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

View File

@ -3,7 +3,8 @@
"other": {
"devices": "Geräte",
"found_central_gateway": ", lokales zentrales Gateway gefunden",
"without_room": "Kein Raum zugewiesen"
"without_room": "Kein Raum zugewiesen",
"no_display": "nicht anzeigen"
},
"control_mode": {
"auto": "automatisch",
@ -53,6 +54,11 @@
"enable": "aktivieren",
"disable": "deaktivieren"
},
"device_state": {
"add": "hinzufügen",
"del": "nicht verfügbar",
"offline": "offline"
},
"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.",
"net_unavailable": "Schnittstelle nicht verfügbar"

View File

@ -3,7 +3,8 @@
"other": {
"devices": "Devices",
"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": {
"auto": "Auto",
@ -53,6 +54,11 @@
"enable": "Enable",
"disable": "Disable"
},
"device_state": {
"add": "Add",
"del": "Unavailable",
"offline": "Offline"
},
"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.",
"net_unavailable": "Interface unavailable"

View File

@ -3,7 +3,8 @@
"other": {
"devices": "dispositivos",
"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": {
"auto": "automático",
@ -53,6 +54,11 @@
"enable": "habilitar",
"disable": "deshabilitar"
},
"device_state": {
"add": "agregar",
"del": "no disponible",
"offline": "fuera de línea"
},
"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.",
"net_unavailable": "Interfaz no disponible"

View File

@ -3,7 +3,8 @@
"other": {
"devices": "appareils",
"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": {
"auto": "automatique",
@ -53,6 +54,11 @@
"enable": "activer",
"disable": "désactiver"
},
"device_state": {
"add": "Ajouter",
"del": "Supprimer",
"offline": "hors ligne"
},
"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.",
"net_unavailable": "Interface non disponible"

View File

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

View File

@ -3,7 +3,8 @@
"other": {
"devices": "Apparaten",
"found_central_gateway": ", Lokale centrale hub-gateway gevonden",
"without_room": "Niet toegewezen kamer"
"without_room": "Niet toegewezen kamer",
"no_display": "Niet weergeven"
},
"control_mode": {
"auto": "Automatisch",
@ -53,6 +54,11 @@
"enable": "Inschakelen",
"disable": "Uitschakelen"
},
"device_state": {
"add": "Toevoegen",
"del": "Niet beschikbaar",
"offline": "Offline"
},
"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.",
"net_unavailable": "Interface niet beschikbaar"

View File

@ -3,7 +3,8 @@
"other": {
"devices": "dispositivos",
"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": {
"auto": "automático",
@ -53,6 +54,11 @@
"enable": "habilitado",
"disable": "desabilitado"
},
"device_state": {
"add": "adicionar",
"del": "indisponível",
"offline": "offline"
},
"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.",
"net_unavailable": "Interface indisponível"

View File

@ -3,7 +3,8 @@
"other": {
"devices": "dispositivos",
"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": {
"auto": "Automático",
@ -53,6 +54,11 @@
"enable": "Habilitar",
"disable": "Desabilitar"
},
"device_state": {
"add": "Adicionar",
"del": "Indisponível",
"offline": "Offline"
},
"lan_ctrl_config": {
"notice_net_dup": "\r\n**[Aviso]** Detectado que várias interfaces podem estar conectadas à mesma rede, escolha com cuidado.",
"net_unavailable": "Interface indisponível"

View File

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

View File

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

View File

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

View File

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