feat: device changed notify logical refinement

This commit is contained in:
topsworld 2024-12-24 15:37:15 +08:00
parent aa0400efda
commit 97e343e1b5
13 changed files with 116 additions and 40 deletions

View File

@ -117,7 +117,7 @@ class XiaomiMihomeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
_area_name_rule: str _area_name_rule: str
_action_debug: bool _action_debug: bool
_hide_non_standard_entities: bool _hide_non_standard_entities: bool
_display_devices_changed_notify: bool _display_devices_changed_notify: list[str]
_auth_info: dict _auth_info: dict
_nick_name: str _nick_name: str
@ -150,7 +150,7 @@ class XiaomiMihomeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self._area_name_rule = self.DEFAULT_AREA_NAME_RULE self._area_name_rule = self.DEFAULT_AREA_NAME_RULE
self._action_debug = False self._action_debug = False
self._hide_non_standard_entities = False self._hide_non_standard_entities = False
self._display_devices_changed_notify = True self._display_devices_changed_notify = ['add', 'del', 'offline']
self._auth_info = {} self._auth_info = {}
self._nick_name = DEFAULT_NICK_NAME self._nick_name = DEFAULT_NICK_NAME
self._home_selected = {} self._home_selected = {}
@ -614,7 +614,8 @@ class XiaomiMihomeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
vol.Required( vol.Required(
'display_devices_changed_notify', 'display_devices_changed_notify',
default=self._display_devices_changed_notify # type: ignore default=self._display_devices_changed_notify # type: ignore
): bool, ): cv.multi_select(
self._miot_i18n.translate(key='config.device_state')),
}), }),
last_step=False, last_step=False,
) )
@ -814,7 +815,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
_home_selected_list: list _home_selected_list: list
_action_debug: bool _action_debug: bool
_hide_non_standard_entities: bool _hide_non_standard_entities: bool
_display_devs_notify: bool _display_devs_notify: list[str]
_oauth_redirect_url_full: str _oauth_redirect_url_full: str
_auth_info: dict _auth_info: dict
@ -861,7 +862,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
self._hide_non_standard_entities = self._entry_data.get( self._hide_non_standard_entities = self._entry_data.get(
'hide_non_standard_entities', False) 'hide_non_standard_entities', False)
self._display_devs_notify = self._entry_data.get( self._display_devs_notify = self._entry_data.get(
'display_devices_changed_notify', True) 'display_devices_changed_notify', ['add', 'del', 'offline'])
self._home_selected_list = list( self._home_selected_list = list(
self._entry_data['home_selected'].keys()) self._entry_data['home_selected'].keys())
@ -1127,7 +1128,8 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
vol.Required( vol.Required(
'display_devices_changed_notify', 'display_devices_changed_notify',
default=self._display_devs_notify # type: ignore default=self._display_devs_notify # type: ignore
): bool, ): cv.multi_select(
self._miot_i18n.translate('config.device_state')),
vol.Required( vol.Required(
'update_trans_rules', 'update_trans_rules',
default=self._update_trans_rules # type: ignore default=self._update_trans_rules # type: ignore
@ -1545,6 +1547,8 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
key='config.option_status.enable') key='config.option_status.enable')
disable_text = self._miot_i18n.translate( disable_text = self._miot_i18n.translate(
key='config.option_status.disable') key='config.option_status.disable')
trans_devs_display: dict = self._miot_i18n.translate(
key='config.device_state')
return self.async_show_form( return self.async_show_form(
step_id='config_confirm', step_id='config_confirm',
data_schema=vol.Schema({ data_schema=vol.Schema({
@ -1566,9 +1570,13 @@ class OptionsFlowHandler(config_entries.OptionsFlow):
'hide_non_standard_entities': ( 'hide_non_standard_entities': (
enable_text if self._hide_non_standard_entities_new enable_text if self._hide_non_standard_entities_new
else disable_text), else disable_text),
'display_devices_changed_notify': ( 'display_devices_changed_notify': (' '.join(
enable_text if self._display_devs_notify trans_devs_display[key]
else disable_text) for key in self._display_devs_notify
if key in trans_devs_display)
if self._display_devs_notify
else self._miot_i18n.translate(
key='config.other.no_display'))
}, # type: ignore }, # type: ignore
errors={'base': 'not_confirm'} if user_input else {}, errors={'base': 'not_confirm'} if user_input else {},
last_step=True last_step=True

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "Geräte", "devices": "Geräte",
"found_central_gateway": ", lokales zentrales Gateway gefunden", "found_central_gateway": ", lokales zentrales Gateway gefunden",
"without_room": "Kein Raum zugewiesen" "without_room": "Kein Raum zugewiesen",
"no_display": "nicht anzeigen"
}, },
"control_mode": { "control_mode": {
"auto": "automatisch", "auto": "automatisch",
@ -53,6 +54,11 @@
"enable": "aktivieren", "enable": "aktivieren",
"disable": "deaktivieren" "disable": "deaktivieren"
}, },
"device_state": {
"add": "hinzufügen",
"del": "nicht verfügbar",
"offline": "offline"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[Hinweis]** Es wurden mehrere Netzwerkkarten erkannt, die möglicherweise mit demselben Netzwerk verbunden sind. Bitte achten Sie auf die Auswahl.", "notice_net_dup": "\r\n**[Hinweis]** Es wurden mehrere Netzwerkkarten erkannt, die möglicherweise mit demselben Netzwerk verbunden sind. Bitte achten Sie auf die Auswahl.",
"net_unavailable": "Schnittstelle nicht verfügbar" "net_unavailable": "Schnittstelle nicht verfügbar"

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "Devices", "devices": "Devices",
"found_central_gateway": ", Found Local Central Hub Gateway", "found_central_gateway": ", Found Local Central Hub Gateway",
"without_room": "No room assigned" "without_room": "No room assigned",
"no_display": "Do not display"
}, },
"control_mode": { "control_mode": {
"auto": "Auto", "auto": "Auto",
@ -53,6 +54,11 @@
"enable": "Enable", "enable": "Enable",
"disable": "Disable" "disable": "Disable"
}, },
"device_state": {
"add": "Add",
"del": "Unavailable",
"offline": "Offline"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[Notice]** Multiple network cards detected that may be connected to the same network. Please pay attention to the selection.", "notice_net_dup": "\r\n**[Notice]** Multiple network cards detected that may be connected to the same network. Please pay attention to the selection.",
"net_unavailable": "Interface unavailable" "net_unavailable": "Interface unavailable"

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "dispositivos", "devices": "dispositivos",
"found_central_gateway": ", se encontró la puerta de enlace central local", "found_central_gateway": ", se encontró la puerta de enlace central local",
"without_room": "Sin habitación asignada" "without_room": "Sin habitación asignada",
"no_display": "no mostrar"
}, },
"control_mode": { "control_mode": {
"auto": "automático", "auto": "automático",
@ -53,6 +54,11 @@
"enable": "habilitar", "enable": "habilitar",
"disable": "deshabilitar" "disable": "deshabilitar"
}, },
"device_state": {
"add": "agregar",
"del": "no disponible",
"offline": "fuera de línea"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[Aviso]** Se detectaron varias tarjetas de red que pueden estar conectadas a la misma red. Por favor, preste atención a la selección.", "notice_net_dup": "\r\n**[Aviso]** Se detectaron varias tarjetas de red que pueden estar conectadas a la misma red. Por favor, preste atención a la selección.",
"net_unavailable": "Interfaz no disponible" "net_unavailable": "Interfaz no disponible"

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "appareils", "devices": "appareils",
"found_central_gateway": ", passerelle centrale locale trouvée", "found_central_gateway": ", passerelle centrale locale trouvée",
"without_room": "Aucune pièce attribuée" "without_room": "Aucune pièce attribuée",
"no_display": "ne pas afficher"
}, },
"control_mode": { "control_mode": {
"auto": "automatique", "auto": "automatique",
@ -53,6 +54,11 @@
"enable": "activer", "enable": "activer",
"disable": "désactiver" "disable": "désactiver"
}, },
"device_state": {
"add": "Ajouter",
"del": "Supprimer",
"offline": "hors ligne"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[Remarque]** Plusieurs cartes réseau détectées qui peuvent être connectées au même réseau. Veuillez faire attention à la sélection.", "notice_net_dup": "\r\n**[Remarque]** Plusieurs cartes réseau détectées qui peuvent être connectées au même réseau. Veuillez faire attention à la sélection.",
"net_unavailable": "Interface non disponible" "net_unavailable": "Interface non disponible"

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "デバイス", "devices": "デバイス",
"found_central_gateway": "、ローカル中央ゲートウェイが見つかりました", "found_central_gateway": "、ローカル中央ゲートウェイが見つかりました",
"without_room": "部屋が割り当てられていません" "without_room": "部屋が割り当てられていません",
"no_display": "表示しない"
}, },
"control_mode": { "control_mode": {
"auto": "自動", "auto": "自動",
@ -53,6 +54,11 @@
"enable": "有効", "enable": "有効",
"disable": "無効" "disable": "無効"
}, },
"device_state": {
"add": "追加",
"del": "利用不可",
"offline": "オフライン"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[注意]** 複数のネットワークカードが同じネットワークに接続されている可能性があります。選択に注意してください。", "notice_net_dup": "\r\n**[注意]** 複数のネットワークカードが同じネットワークに接続されている可能性があります。選択に注意してください。",
"net_unavailable": "インターフェースが利用できません" "net_unavailable": "インターフェースが利用できません"

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "Apparaten", "devices": "Apparaten",
"found_central_gateway": ", Lokale centrale hub-gateway gevonden", "found_central_gateway": ", Lokale centrale hub-gateway gevonden",
"without_room": "Niet toegewezen kamer" "without_room": "Niet toegewezen kamer",
"no_display": "Niet weergeven"
}, },
"control_mode": { "control_mode": {
"auto": "Automatisch", "auto": "Automatisch",
@ -53,6 +54,11 @@
"enable": "Inschakelen", "enable": "Inschakelen",
"disable": "Uitschakelen" "disable": "Uitschakelen"
}, },
"device_state": {
"add": "Toevoegen",
"del": "Niet beschikbaar",
"offline": "Offline"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[Let op]** Meerdere netwerkkaarten gedetecteerd die mogelijk zijn verbonden met hetzelfde netwerk. Let op bij de selectie.", "notice_net_dup": "\r\n**[Let op]** Meerdere netwerkkaarten gedetecteerd die mogelijk zijn verbonden met hetzelfde netwerk. Let op bij de selectie.",
"net_unavailable": "Interface niet beschikbaar" "net_unavailable": "Interface niet beschikbaar"

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "dispositivos", "devices": "dispositivos",
"found_central_gateway": "encontrado o gateway central local", "found_central_gateway": "encontrado o gateway central local",
"without_room": "sem quarto atribuído" "without_room": "sem quarto atribuído",
"no_display": "não exibir"
}, },
"control_mode": { "control_mode": {
"auto": "automático", "auto": "automático",
@ -53,6 +54,11 @@
"enable": "habilitado", "enable": "habilitado",
"disable": "desabilitado" "disable": "desabilitado"
}, },
"device_state": {
"add": "adicionar",
"del": "indisponível",
"offline": "offline"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[Aviso]** Detectado múltiplas interfaces de rede que podem estar conectando à mesma rede, por favor, selecione a correta.", "notice_net_dup": "\r\n**[Aviso]** Detectado múltiplas interfaces de rede que podem estar conectando à mesma rede, por favor, selecione a correta.",
"net_unavailable": "Interface indisponível" "net_unavailable": "Interface indisponível"

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "dispositivos", "devices": "dispositivos",
"found_central_gateway": ", encontrou a central de gateway local", "found_central_gateway": ", encontrou a central de gateway local",
"without_room": "Sem quarto atribuído" "without_room": "Sem quarto atribuído",
"no_display": "Não exibir"
}, },
"control_mode": { "control_mode": {
"auto": "Automático", "auto": "Automático",
@ -53,6 +54,11 @@
"enable": "Habilitar", "enable": "Habilitar",
"disable": "Desabilitar" "disable": "Desabilitar"
}, },
"device_state": {
"add": "Adicionar",
"del": "Indisponível",
"offline": "Offline"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[Aviso]** Detectado que várias interfaces podem estar conectadas à mesma rede, escolha com cuidado.", "notice_net_dup": "\r\n**[Aviso]** Detectado que várias interfaces podem estar conectadas à mesma rede, escolha com cuidado.",
"net_unavailable": "Interface indisponível" "net_unavailable": "Interface indisponível"

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "устройства", "devices": "устройства",
"found_central_gateway": ", найден локальный центральный шлюз", "found_central_gateway": ", найден локальный центральный шлюз",
"without_room": "без комнаты" "without_room": "без комнаты",
"no_display": "не отображать"
}, },
"control_mode": { "control_mode": {
"auto": "автоматический", "auto": "автоматический",
@ -53,6 +54,11 @@
"enable": "Включить", "enable": "Включить",
"disable": "Отключить" "disable": "Отключить"
}, },
"device_state": {
"add": "Добавить",
"del": "Недоступно",
"offline": "Не в сети"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[Уведомление]** Обнаружено несколько сетевых карт, которые могут быть подключены к одной и той же сети. Пожалуйста, обратите внимание на выбор.", "notice_net_dup": "\r\n**[Уведомление]** Обнаружено несколько сетевых карт, которые могут быть подключены к одной и той же сети. Пожалуйста, обратите внимание на выбор.",
"net_unavailable": "Интерфейс недоступен" "net_unavailable": "Интерфейс недоступен"

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "个设备", "devices": "个设备",
"found_central_gateway": ",发现本地中枢网关", "found_central_gateway": ",发现本地中枢网关",
"without_room": "未分配房间" "without_room": "未分配房间",
"no_display": "不显示"
}, },
"control_mode": { "control_mode": {
"auto": "自动", "auto": "自动",
@ -53,6 +54,11 @@
"enable": "启用", "enable": "启用",
"disable": "禁用" "disable": "禁用"
}, },
"device_state": {
"add": "新增",
"del": "不可用",
"offline": "离线"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[提示]** 检测到多个网卡可能连接同一个网络,请注意选择。", "notice_net_dup": "\r\n**[提示]** 检测到多个网卡可能连接同一个网络,请注意选择。",
"net_unavailable": "接口不可用" "net_unavailable": "接口不可用"

View File

@ -3,7 +3,8 @@
"other": { "other": {
"devices": "個設備", "devices": "個設備",
"found_central_gateway": ",發現本地中樞網關", "found_central_gateway": ",發現本地中樞網關",
"without_room": "未分配房間" "without_room": "未分配房間",
"no_display": "不顯示"
}, },
"control_mode": { "control_mode": {
"auto": "自動", "auto": "自動",
@ -53,6 +54,11 @@
"enable": "啟用", "enable": "啟用",
"disable": "禁用" "disable": "禁用"
}, },
"device_state": {
"add": "新增",
"del": "不可用",
"offline": "離線"
},
"lan_ctrl_config": { "lan_ctrl_config": {
"notice_net_dup": "\r\n**[提示]** 檢測到多個網卡可能連接同一個網絡,請注意選擇。", "notice_net_dup": "\r\n**[提示]** 檢測到多個網卡可能連接同一個網絡,請注意選擇。",
"net_unavailable": "接口不可用" "net_unavailable": "接口不可用"

View File

@ -167,8 +167,8 @@ class MIoTClient:
_persistence_notify: Callable[[str, Optional[str], Optional[str]], None] _persistence_notify: Callable[[str, Optional[str], Optional[str]], None]
# Device list changed notify # Device list changed notify
_show_devices_changed_notify_timer: Optional[asyncio.TimerHandle] _show_devices_changed_notify_timer: Optional[asyncio.TimerHandle]
# Display devices changed notify
_display_devs_notify: bool _display_devs_notify: list[str]
def __init__( def __init__(
self, self,
@ -234,7 +234,7 @@ class MIoTClient:
self._show_devices_changed_notify_timer = None self._show_devices_changed_notify_timer = None
self._display_devs_notify = entry_data.get( self._display_devs_notify = entry_data.get(
'display_devices_changed_notify', True) 'display_devices_changed_notify', ['add', 'del', 'offline'])
async def init_async(self) -> None: async def init_async(self) -> None:
# Load user config and check # Load user config and check
@ -465,12 +465,12 @@ class MIoTClient:
'hide_non_standard_entities', False) 'hide_non_standard_entities', False)
@property @property
def display_devices_changed_notify(self) -> bool: def display_devices_changed_notify(self) -> list[str]:
return self._display_devs_notify return self._display_devs_notify
@display_devices_changed_notify.setter @display_devices_changed_notify.setter
def display_devices_changed_notify(self, value: bool) -> None: def display_devices_changed_notify(self, value: list[str]) -> None:
if value == self._display_devs_notify: if set(value) == set(self._display_devs_notify):
return return
self._display_devs_notify = value self._display_devs_notify = value
if value: if value:
@ -1736,15 +1736,16 @@ class MIoTClient:
count_offline: int = 0 count_offline: int = 0
# New devices # New devices
for did, info in { if 'add' in self._display_devs_notify:
**self._device_list_gateway, **self._device_list_cloud for did, info in {
}.items(): **self._device_list_gateway, **self._device_list_cloud
if did in self._device_list_cache: }.items():
continue if did in self._device_list_cache:
count_add += 1 continue
message_add += ( count_add += 1
f'- {info.get("name", "unknown")} ({did}, ' message_add += (
f'{info.get("model", "unknown")})\n') f'- {info.get("name", "unknown")} ({did}, '
f'{info.get("model", "unknown")})\n')
# Get unavailable and offline devices # Get unavailable and offline devices
home_name_del: Optional[str] = None home_name_del: Optional[str] = None
home_name_offline: Optional[str] = None home_name_offline: Optional[str] = None
@ -1754,7 +1755,7 @@ class MIoTClient:
if online: if online:
# Skip online device # Skip online device
continue continue
if online is None: if 'del' in self._display_devs_notify and online is None:
# Device not exist # Device not exist
if home_name_del != home_name_new: if home_name_del != home_name_new:
message_del += f'\n[{home_name_new}]\n' message_del += f'\n[{home_name_new}]\n'
@ -1763,7 +1764,8 @@ class MIoTClient:
message_del += ( message_del += (
f'- {info.get("name", "unknown")} ({did}, ' f'- {info.get("name", "unknown")} ({did}, '
f'{info.get("room_name", "unknown")})\n') f'{info.get("room_name", "unknown")})\n')
else: continue
if 'offline' in self._display_devs_notify:
# Device offline # Device offline
if home_name_offline != home_name_new: if home_name_offline != home_name_new:
message_offline += f'\n[{home_name_new}]\n' message_offline += f'\n[{home_name_new}]\n'
@ -1774,19 +1776,19 @@ class MIoTClient:
f'{info.get("room_name", "unknown")})\n') f'{info.get("room_name", "unknown")})\n')
message = '' message = ''
if count_add: if 'add' in self._display_devs_notify and count_add:
message += self._i18n.translate( message += self._i18n.translate(
key='miot.client.device_list_add', key='miot.client.device_list_add',
replace={ replace={
'count': count_add, 'count': count_add,
'message': message_add}) 'message': message_add})
if count_del: if 'del' in self._display_devs_notify and count_del:
message += self._i18n.translate( message += self._i18n.translate(
key='miot.client.device_list_del', key='miot.client.device_list_del',
replace={ replace={
'count': count_del, 'count': count_del,
'message': message_del}) 'message': message_del})
if count_offline: if 'offline' in self._display_devs_notify and count_offline:
message += self._i18n.translate( message += self._i18n.translate(
key='miot.client.device_list_offline', key='miot.client.device_list_offline',
replace={ replace={