From 1624f340da5db644acf3f6bc6c99cc555d0a87f9 Mon Sep 17 00:00:00 2001 From: sworld Date: Sat, 21 Dec 2024 18:54:12 +0800 Subject: [PATCH 01/24] feat: add devices filter page --- custom_components/xiaomi_home/config_flow.py | 97 +++++++++++++------ .../xiaomi_home/miot/i18n/de.json | 4 + .../xiaomi_home/miot/i18n/en.json | 4 + .../xiaomi_home/miot/i18n/es.json | 4 + .../xiaomi_home/miot/i18n/fr.json | 4 + .../xiaomi_home/miot/i18n/ja.json | 4 + .../xiaomi_home/miot/i18n/nl.json | 6 +- .../xiaomi_home/miot/i18n/pt-BR.json | 4 + .../xiaomi_home/miot/i18n/pt.json | 4 + .../xiaomi_home/miot/i18n/ru.json | 4 + .../xiaomi_home/miot/i18n/zh-Hans.json | 4 + .../xiaomi_home/miot/i18n/zh-Hant.json | 4 + .../xiaomi_home/translations/de.json | 21 +++- .../xiaomi_home/translations/en.json | 29 ++++-- .../xiaomi_home/translations/es.json | 27 ++++-- .../xiaomi_home/translations/fr.json | 29 ++++-- .../xiaomi_home/translations/ja.json | 29 ++++-- .../xiaomi_home/translations/nl.json | 31 ++++-- .../xiaomi_home/translations/pt-BR.json | 31 ++++-- .../xiaomi_home/translations/pt.json | 29 ++++-- .../xiaomi_home/translations/ru.json | 27 ++++-- .../xiaomi_home/translations/zh-Hans.json | 21 +++- .../xiaomi_home/translations/zh-Hant.json | 21 +++- 23 files changed, 341 insertions(+), 97 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index b9f3776..4b69418 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -479,16 +479,11 @@ async def async_step_homes_select(self, user_input=None): if not home_selected: return await self.display_homes_select_form( 'no_family_selected') - self._ctrl_mode = user_input.get('ctrl_mode') for home_id, home_info in self._home_info_buffer[ 'homes']['home_list'].items(): if home_id in home_selected: self._home_selected[home_id] = home_info self._area_name_rule = user_input.get('area_name_rule') - self._action_debug = user_input.get( - 'action_debug', self._action_debug) - self._hide_non_standard_entities = user_input.get( - 'hide_non_standard_entities', self._hide_non_standard_entities) # Storage device list devices_list: dict[str, dict] = { did: dev_info @@ -513,26 +508,9 @@ async def async_step_homes_select(self, user_input=None): 'auth_info': self._auth_info })): raise MIoTError('miot_storage.update_user_config_async error') - return self.async_create_entry( - title=( - f'{self._nick_name}: {self._uid} ' - f'[{CLOUD_SERVERS[self._cloud_server]}]'), - data={ - 'virtual_did': self._virtual_did, - 'uuid': self._uuid, - 'integration_language': self._integration_language, - 'storage_path': self._storage_path, - 'uid': self._uid, - 'nick_name': self._nick_name, - 'cloud_server': self._cloud_server, - 'oauth_redirect_url': self._oauth_redirect_url, - 'ctrl_mode': self._ctrl_mode, - 'home_selected': self._home_selected, - 'area_name_rule': self._area_name_rule, - 'action_debug': self._action_debug, - 'hide_non_standard_entities': - self._hide_non_standard_entities, - }) + if user_input.get('advanced_options', False): + return await self.async_step_advanced_options() + return await self.config_flow_done() except Exception as err: _LOGGER.error( 'async_step_homes_select, %s, %s', @@ -547,15 +525,10 @@ async def display_homes_select_form(self, reason: str): return self.async_show_form( step_id='homes_select', data_schema=vol.Schema({ - vol.Required('ctrl_mode', default=DEFAULT_CTRL_MODE): vol.In( - self._miot_i18n.translate(key='config.control_mode')), vol.Required('home_infos'): cv.multi_select(self._home_list), vol.Required('area_name_rule', default='room'): vol.In( self._miot_i18n.translate(key='config.room_name_rule')), - vol.Required('action_debug', default=self._action_debug): bool, - vol.Required( - 'hide_non_standard_entities', - default=self._hide_non_standard_entities): bool, + vol.Required('advanced_options', default=False): bool, }), errors={'base': reason}, description_placeholders={ @@ -564,6 +537,68 @@ async def display_homes_select_form(self, reason: str): last_step=False, ) + async def async_step_advanced_options(self, user_input: dict = None): + if user_input: + self._ctrl_mode = user_input.get('ctrl_mode', self._ctrl_mode) + self._action_debug = user_input.get( + 'action_debug', self._action_debug) + self._hide_non_standard_entities = user_input.get( + 'hide_non_standard_entities', self._hide_non_standard_entities) + # Device filter + if user_input.get('devices_filter', False): + return await self.async_step_devices_filter() + return await self.config_flow_done() + return self.async_show_form( + step_id='advanced_options', + data_schema=vol.Schema({ + vol.Required('ctrl_mode', default=DEFAULT_CTRL_MODE): vol.In( + self._miot_i18n.translate(key='config.control_mode')), + vol.Required('action_debug', default=self._action_debug): bool, + vol.Required( + 'hide_non_standard_entities', + default=self._hide_non_standard_entities): bool, + vol.Required('devices_filter', default=False): bool, + }), + last_step=False, + ) + + async def async_step_devices_filter(self, user_input: dict = None): + if user_input: + return await self.config_flow_done() + + return self.async_show_form( + step_id='devices_filter', + data_schema=vol.Schema({ + vol.Required('filter_mode', default='include'): vol.In( + self._miot_i18n.translate(key='config.filter_mode')), + vol.Required('filter_mode', default='include'): vol.In( + self._miot_i18n.translate(key='config.filter_mode')) + }), + last_step=False, + ) + + async def config_flow_done(self): + return self.async_create_entry( + title=( + f'{self._nick_name}: {self._uid} ' + f'[{CLOUD_SERVERS[self._cloud_server]}]'), + data={ + 'virtual_did': self._virtual_did, + 'uuid': self._uuid, + 'integration_language': self._integration_language, + 'storage_path': self._storage_path, + 'uid': self._uid, + 'nick_name': self._nick_name, + 'cloud_server': self._cloud_server, + 'oauth_redirect_url': self._oauth_redirect_url, + 'ctrl_mode': self._ctrl_mode, + 'home_selected': self._home_selected, + 'area_name_rule': self._area_name_rule, + 'action_debug': self._action_debug, + 'hide_non_standard_entities': + self._hide_non_standard_entities, + }) + @staticmethod @callback def async_get_options_flow( diff --git a/custom_components/xiaomi_home/miot/i18n/de.json b/custom_components/xiaomi_home/miot/i18n/de.json index afcea1d..04103d6 100644 --- a/custom_components/xiaomi_home/miot/i18n/de.json +++ b/custom_components/xiaomi_home/miot/i18n/de.json @@ -8,6 +8,10 @@ "auto": "automatisch", "cloud": "Cloud" }, + "filter_mode": { + "include": "einschließen", + "exclude": "ausschließen" + }, "room_name_rule": { "none": "nicht synchronisieren", "home_room": "Hausname und Raumname (Xiaomi Home Schlafzimmer)", diff --git a/custom_components/xiaomi_home/miot/i18n/en.json b/custom_components/xiaomi_home/miot/i18n/en.json index 49430b3..d8fb68d 100644 --- a/custom_components/xiaomi_home/miot/i18n/en.json +++ b/custom_components/xiaomi_home/miot/i18n/en.json @@ -8,6 +8,10 @@ "auto": "Auto", "cloud": "Cloud" }, + "filter_mode": { + "include": "Include", + "exclude": "Exclude" + }, "room_name_rule": { "none": "Do not synchronize", "home_room": "Home Name and Room Name (Xiaomi Home Bedroom)", diff --git a/custom_components/xiaomi_home/miot/i18n/es.json b/custom_components/xiaomi_home/miot/i18n/es.json index 5ca9862..8effc97 100644 --- a/custom_components/xiaomi_home/miot/i18n/es.json +++ b/custom_components/xiaomi_home/miot/i18n/es.json @@ -8,6 +8,10 @@ "auto": "automático", "cloud": "nube" }, + "filter_mode": { + "include": "incluir", + "exclude": "excluir" + }, "room_name_rule": { "none": "no sincronizar", "home_room": "nombre de la casa y nombre de la habitación (Xiaomi Home Dormitorio)", diff --git a/custom_components/xiaomi_home/miot/i18n/fr.json b/custom_components/xiaomi_home/miot/i18n/fr.json index 677bf27..f8b6caa 100644 --- a/custom_components/xiaomi_home/miot/i18n/fr.json +++ b/custom_components/xiaomi_home/miot/i18n/fr.json @@ -8,6 +8,10 @@ "auto": "automatique", "cloud": "cloud" }, + "filter_mode": { + "include": "inclure", + "exclude": "exclure" + }, "room_name_rule": { "none": "ne pas synchroniser", "home_room": "nom de la maison et nom de la pièce (Xiaomi Home Chambre)", diff --git a/custom_components/xiaomi_home/miot/i18n/ja.json b/custom_components/xiaomi_home/miot/i18n/ja.json index 3980c1e..c0d51b9 100644 --- a/custom_components/xiaomi_home/miot/i18n/ja.json +++ b/custom_components/xiaomi_home/miot/i18n/ja.json @@ -8,6 +8,10 @@ "auto": "自動", "cloud": "クラウド" }, + "filter_mode": { + "include": "含む", + "exclude": "除外" + }, "room_name_rule": { "none": "同期しない", "home_room": "家の名前と部屋の名前 (Xiaomi Home 寝室)", diff --git a/custom_components/xiaomi_home/miot/i18n/nl.json b/custom_components/xiaomi_home/miot/i18n/nl.json index 03dfc32..bc81b20 100644 --- a/custom_components/xiaomi_home/miot/i18n/nl.json +++ b/custom_components/xiaomi_home/miot/i18n/nl.json @@ -8,6 +8,10 @@ "auto": "Automatisch", "cloud": "Cloud" }, + "filter_mode": { + "include": "Inclusief", + "exclude": "Uitsluiten" + }, "room_name_rule": { "none": "Niet synchroniseren", "home_room": "Huisnaam en Kamernaam (Xiaomi Home Slaapkamer)", @@ -92,4 +96,4 @@ "-706014006": "Apparaatbeschrijving niet gevonden" } } -} +} \ No newline at end of file diff --git a/custom_components/xiaomi_home/miot/i18n/pt-BR.json b/custom_components/xiaomi_home/miot/i18n/pt-BR.json index 8df352b..54ae478 100644 --- a/custom_components/xiaomi_home/miot/i18n/pt-BR.json +++ b/custom_components/xiaomi_home/miot/i18n/pt-BR.json @@ -8,6 +8,10 @@ "auto": "automático", "cloud": "nuvem" }, + "filter_mode": { + "include": "incluir", + "exclude": "excluir" + }, "room_name_rule": { "none": "não sincronizado", "home_room": "Nome da casa e nome do quarto (Xiaomi Home Quarto)", diff --git a/custom_components/xiaomi_home/miot/i18n/pt.json b/custom_components/xiaomi_home/miot/i18n/pt.json index dd30774..0dd732f 100644 --- a/custom_components/xiaomi_home/miot/i18n/pt.json +++ b/custom_components/xiaomi_home/miot/i18n/pt.json @@ -8,6 +8,10 @@ "auto": "Automático", "cloud": "Nuvem" }, + "filter_mode": { + "include": "Incluir", + "exclude": "Excluir" + }, "room_name_rule": { "none": "Não sincronizar", "home_room": "Nome da casa e Nome do quarto (Xiaomi Home Quarto)", diff --git a/custom_components/xiaomi_home/miot/i18n/ru.json b/custom_components/xiaomi_home/miot/i18n/ru.json index 18f8490..c922212 100644 --- a/custom_components/xiaomi_home/miot/i18n/ru.json +++ b/custom_components/xiaomi_home/miot/i18n/ru.json @@ -8,6 +8,10 @@ "auto": "автоматический", "cloud": "облако" }, + "filter_mode": { + "include": "включить", + "exclude": "исключить" + }, "room_name_rule": { "none": "не синхронизировать", "home_room": "название дома и название комнаты (Xiaomi Home Спальня)", diff --git a/custom_components/xiaomi_home/miot/i18n/zh-Hans.json b/custom_components/xiaomi_home/miot/i18n/zh-Hans.json index 1607a5e..b2bca90 100644 --- a/custom_components/xiaomi_home/miot/i18n/zh-Hans.json +++ b/custom_components/xiaomi_home/miot/i18n/zh-Hans.json @@ -8,6 +8,10 @@ "auto": "自动", "cloud": "云端" }, + "filter_mode": { + "include": "包含", + "exclude": "排除" + }, "room_name_rule": { "none": "不同步", "home_room": "家庭名 和 房间名 (米家 卧室)", diff --git a/custom_components/xiaomi_home/miot/i18n/zh-Hant.json b/custom_components/xiaomi_home/miot/i18n/zh-Hant.json index e62b4f9..901e5c0 100644 --- a/custom_components/xiaomi_home/miot/i18n/zh-Hant.json +++ b/custom_components/xiaomi_home/miot/i18n/zh-Hant.json @@ -8,6 +8,10 @@ "auto": "自動", "cloud": "雲端" }, + "filter_mode": { + "include": "包含", + "exclude": "排除" + }, "room_name_rule": { "none": "不同步", "home_room": "家庭名 和 房間名 (米家 臥室)", diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index b06c460..47254b6 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -24,13 +24,28 @@ }, "homes_select": { "title": "Familie und Geräte auswählen", - "description": "## Gebrauchsanweisung\r\n### Steuerungsmodus\r\n- Automatisch: Wenn im lokalen Netzwerk ein verfügbarer Xiaomi-Zentralgateway vorhanden ist, wird Home Assistant bevorzugt Steuerbefehle über den Zentralgateway senden, um eine lokale Steuerung zu ermöglichen. Wenn im lokalen Netzwerk kein Zentralgateway vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden, um eine lokale Steuerung zu ermöglichen. Nur wenn die oben genannten Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Steuerbefehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden nur über die Cloud gesendet.\r\n### Familienimport für importierte Geräte\r\nDie Integration fügt Geräte aus den ausgewählten Familien hinzu.\r\n### Raumnamensynchronisationsmodus\r\nWenn Geräte von der Xiaomi Home App zu Home Assistant synchronisiert werden, wird die Bezeichnung des Bereichs, in dem sich die Geräte in Home Assistant befinden, nach folgenden Regeln benannt. Beachten Sie, dass das Synchronisieren von Geräten den von Xiaomi Home App festgelegten Familien- und Raum-Einstellungen nicht ändert.\r\n- Nicht synchronisieren: Das Gerät wird keinem Bereich hinzugefügt.\r\n- Andere Optionen: Der Bereich, in den das Gerät aufgenommen wird, wird nach dem Namen der Familie oder des Raums in der Xiaomi Home App benannt.\r\n### Action-Debug-Modus\r\nFür von MIoT-Spec-V2 definierte Gerätemethoden wird neben der Benachrichtigungs-Entität auch eine Texteingabe-Entität generiert. Damit können Sie bei der Fehlerbehebung Steuerbefehle an das Gerät senden.\r\n### Verstecke Nicht-Standard-Entitäten\r\nVerstecke Entitäten, die von nicht standardmäßigen MIoT-Spec-V2-Instanzen mit einem Namen beginnen, der mit einem \"*\" beginnt.\r\n\r\n \r\n### Hallo {nick_name}! Bitte wählen Sie den Steuerungsmodus der Integration sowie die Familie aus, in der sich die hinzuzufügenden Geräte befinden.", + "description": "## Gebrauchsanweisung\r\n### Familienimport für importierte Geräte\r\nDie Integration fügt Geräte aus den ausgewählten Familien hinzu.\r\n### Raumnamensynchronisationsmodus\r\nWenn Geräte von der Xiaomi Home App zu Home Assistant synchronisiert werden, wird die Bezeichnung des Bereichs, in dem sich die Geräte in Home Assistant befinden, nach folgenden Regeln benannt. Beachten Sie, dass das Synchronisieren von Geräten den von Xiaomi Home App festgelegten Familien- und Raum-Einstellungen nicht ändert.\r\n- Nicht synchronisieren: Das Gerät wird keinem Bereich hinzugefügt.\r\n- Andere Optionen: Der Bereich, in den das Gerät aufgenommen wird, wird nach dem Namen der Familie oder des Raums in der Xiaomi Home App benannt.\r\n### Erweiterte Einstellungen\r\nZeigen Sie erweiterte Einstellungen an, um die professionellen Konfigurationsoptionen der Integration zu ändern.\r\n\r\n \r\n### {nick_name} Hallo! Bitte wählen Sie die Familie aus, zu der Sie das Gerät hinzufügen möchten.", "data": { - "ctrl_mode": "Steuerungsmodus", "home_infos": "Familienimport für importierte Geräte", "area_name_rule": "Raumnamensynchronisationsmodus", + "advanced_options": "Erweiterte Einstellungen" + } + }, + "advanced_options": { + "title": "Erweiterte Einstellungen", + "description": "## Einführung\r\n### Behalten Sie die Standardeinstellungen bei, es sei denn, Sie verstehen die folgenden Optionen vollständig.\r\n### Steuerungsmodus\r\n- Automatisch: Wenn ein verfügbarer Xiaomi-Hub im lokalen Netzwerk vorhanden ist, priorisiert Home Assistant das Senden von Steuerbefehlen über den Hub, um eine lokale Steuerung zu ermöglichen. Wenn kein Hub vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden. Nur wenn diese Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Befehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden ausschließlich über die Cloud gesendet.\r\n### Gerätefilterung\r\nFiltern Sie unerwünschte Geräte nach Familien.\r\n### Action-Debug-Modus\r\nFür Methoden, die von MIoT-Spec-V2-Geräten definiert werden, wird neben der Benachrichtigungsentität auch eine Texteingabe-Entität erstellt, mit der Sie während des Debuggens Steuerbefehle an das Gerät senden können.\r\n### Nicht standardmäßige Entitäten ausblenden\r\nBlendet Entitäten aus, die von nicht-standardmäßigen MIoT-Spec-V2-Instanzen generiert werden und deren Name mit „*“ beginnt.", + "data": { + "ctrl_mode": "Steuerungsmodus", "action_debug": "Action-Debug-Modus", - "hide_non_standard_entities": "Verstecke Nicht-Standard-Entitäten" + "hide_non_standard_entities": "Nicht standardmäßige Entitäten ausblenden", + "devices_filter": "Gerätefilterung" + } + }, + "devices_filter": { + "title": "Gerätefilterung", + "description": "## Einführung\r\nFiltern Sie unerwünschte Geräte nach Familien.", + "data": { + "filter_mode": "Filtermodus" } } }, diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index ddb424a..d8e11d5 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -23,14 +23,29 @@ "description": "Click NEXT to try again." }, "homes_select": { - "title": "Select Home and Devices", - "description": "## Usage Instructions\r\n### Control mode\r\n- Auto: When there is an available Xiaomi central hub gateway in the local area network, Home Assistant will prioritize sending device control commands through the central hub gateway to achieve local control. If there is no central hub gateway in the local area network, it will attempt to send control commands through Xiaomi LAN control function. Only when the above local control conditions are not met, the device control commands will be sent through the cloud.\r\n- Cloud: All control commands are sent through the cloud.\r\n### Import devices from home\r\nThe integration will add devices from the selected homes.\n### Room name synchronizing mode\nWhen importing devices from Xiaomi Home APP to Home Assistant, the naming convention of the area where the device is added to is as follows. Note that the device synchronizing process does not change the home or room settings in Xiaomi Home APP.\r\n- Do not synchronize: The device will not be added to any area.\r\n- Other options: The device will be added to an area named as the home and/or room name that already exists in Xiaomi Home APP.\r\n### Debug mode for action\r\nFor the action defined in MIoT-Spec-V2 of the device, a Text entity along with a Notify entity will be created, in which you can send control commands to the device for debugging.\r\n### Hide non-standard created entities\r\nHide the entities generated from non-standard MIoT-Spec-V2 instances, whose names begin with \"*\".\r\n\r\n \r\n### Hello {nick_name}, please select the integration control mode and the home where the device you want to import.", + "title": "Select Family and Device", + "description": "## Introduction\r\n### Import Device's Family\r\nThe integration will add devices from the selected family.\r\n### Room Name Sync Mode\r\nWhen syncing devices from the Mi Home APP to Home Assistant, the naming of the area in Home Assistant will follow the rules below. Note that the sync process will not change the family and room settings in the Mi Home APP.\r\n- Do not sync: The device will not be added to any area.\r\n- Other options: The area to which the device is added will be named after the family or room name in the Mi Home APP.\r\n### Advanced Settings\r\nShow advanced settings to modify the professional configuration options of the integration.\r\n\r\n \r\n### {nick_name} Hello! Please select the family to which you want to add the device.", "data": { - "ctrl_mode": "Control mode", - "home_infos": "Import devices from home", - "area_name_rule": "Room name synchronizing mode", - "action_debug": "Debug mode for action", - "hide_non_standard_entities": "Hide non-standard created entities" + "home_infos": "Import Device's Family", + "area_name_rule": "Room Name Sync Mode", + "advanced_options": "Advanced Settings" + } + }, + "advanced_options": { + "title": "Advanced Settings", + "description": "## Introduction\r\n### Keep the default settings unless you fully understand the following options.\r\n### Control Mode\r\n- Auto: When a Xiaomi hub is available on the local network, Home Assistant will prioritize sending device control commands through the hub for local control. If there is no hub, it will attempt to send commands via the Xiaomi OT protocol. Only if those local control conditions are not met will commands be sent through the cloud.\r\n- Cloud: Control commands are sent exclusively through the cloud.\r\n### Device Filtering\r\nFilter out unwanted devices by family.\r\n### Action Debug Mode\r\nFor methods defined by MIoT-Spec-V2 devices, besides generating a notification entity, a text input entity will also be created so you can send control commands to the device during debugging.\r\n### Hide Non-Standard Generated Entities\r\nHide entities generated by non-standard MIoT-Spec-V2 instances whose names start with \"*\".", + "data": { + "ctrl_mode": "Control Mode", + "action_debug": "Action Debug Mode", + "hide_non_standard_entities": "Hide Non-Standard Generated Entities", + "devices_filter": "Device Filtering" + } + }, + "devices_filter": { + "title": "Device Filtering", + "description": "## Introduction\r\nFilter out unwanted devices by family.", + "data": { + "filter_mode": "Filter Mode" } } }, diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index 23ee109..c15adcd 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -23,14 +23,29 @@ "description": "Haga clic en \"Siguiente\" para volver a intentarlo" }, "homes_select": { - "title": "Seleccionar hogares y dispositivos", - "description": "## Instrucciones de uso\r\n### Modo de control\r\n- Automático: Cuando hay un gateway central de Xiaomi disponible en la red local, Home Assistant priorizará el envío de comandos de control de dispositivos a través del gateway central para lograr un control localizado. Si no hay un gateway central en la red local, intentará enviar comandos de control a través del protocolo Xiaomi OT para lograr un control localizado. Solo cuando no se cumplan las condiciones anteriores de control localizado, los comandos de control del dispositivo se enviarán a través de la nube.\r\n- Nube: Los comandos de control solo se envían a través de la nube.\r\n### Hogares de dispositivos importados\r\nLa integración agregará los dispositivos en los hogares seleccionados.\r\n### Modo de sincronización del nombre de la habitación\r\nCuando se sincronizan los dispositivos desde la aplicación Xiaomi Home a Home Assistant, los nombres de las áreas donde se encuentran los dispositivos en Home Assistant seguirán las reglas de nomenclatura a continuación. Tenga en cuenta que el proceso de sincronización de dispositivos no cambiará la configuración de hogares y habitaciones en la aplicación Xiaomi Home.\r\n- Sin sincronización: el dispositivo no se agregará a ninguna área.\r\n- Otras opciones: la zona donde se agrega el dispositivo tendrá el mismo nombre que el hogar o la habitación en la aplicación Xiaomi Home.\r\n### Modo de depuración de Action\r\nPara los métodos definidos por MIoT-Spec-V2, además de generar una entidad de notificación, también se generará una entidad de cuadro de entrada de texto que se puede utilizar para enviar comandos de control al dispositivo durante la depuración.\r\n### Ocultar entidades generadas no estándar\r\nOcultar las entidades generadas por la instancia no estándar MIoT-Spec-V2 que comienzan con \"*\".\r\n\r\n \r\n### ¡Hola, {nick_name}! Seleccione el modo de control de integración y el hogar donde se encuentran los dispositivos que desea agregar.", + "title": "Seleccionar familia y dispositivo", + "description": "## Introducción\r\n### Importar la familia del dispositivo\r\nLa integración añadirá dispositivos de la familia seleccionada.\r\n### Modo de sincronización del nombre de la habitación\r\nAl sincronizar dispositivos desde la APP Mi Home a Home Assistant, el nombre del área en Home Assistant seguirá las siguientes reglas. Tenga en cuenta que el proceso de sincronización no cambiará la configuración de la familia y la habitación en la APP Mi Home.\r\n- No sincronizar: El dispositivo no se añadirá a ninguna área.\r\n- Otras opciones: El área a la que se añade el dispositivo se nombrará según el nombre de la familia o la habitación en la APP Mi Home.\r\n### Configuración avanzada\r\nMostrar configuración avanzada para modificar las opciones de configuración profesional de la integración.\r\n\r\n \r\n### {nick_name} ¡Hola! Por favor, seleccione la familia a la que desea añadir el dispositivo.", "data": { - "ctrl_mode": "Modo de control", - "home_infos": "Hogares de dispositivos importados", + "home_infos": "Importar la familia del dispositivo", "area_name_rule": "Modo de sincronización del nombre de la habitación", - "action_debug": "Modo de depuración de Action", - "hide_non_standard_entities": "Ocultar entidades generadas no estándar" + "advanced_options": "Configuración avanzada" + } + }, + "advanced_options": { + "title": "Opciones Avanzadas", + "description": "## Introducción\r\n### Mantenga la configuración predeterminada a menos que conozca completamente el significado de las siguientes opciones.\r\n### Modo de Control\r\n- Automático: Cuando haya un hub Xiaomi disponible en la red local, Home Assistant priorizará el envío de comandos de control a través del hub para lograr un control local. Si no hay un hub, intentará enviar los comandos a través del protocolo Xiaomi OT. Solo si no se cumplen esas condiciones de control local, los comandos se enviarán a través de la nube.\r\n- Nube: Los comandos se envían exclusivamente a través de la nube.\r\n### Filtrado de Dispositivos\r\nFiltre dispositivos no deseados por familia.\r\n### Modo de Depuración de Acciones\r\nPara los métodos definidos por dispositivos MIoT-Spec-V2, además de generar una entidad de notificación, se creará una entidad de entrada de texto para que pueda enviar comandos de control durante la depuración.\r\n### Ocultar Entidades Generadas No Estándar\r\nOculte entidades generadas por instancias no estándar de MIoT-Spec-V2 cuyos nombres comiencen con \"*\".", + "data": { + "ctrl_mode": "Modo de Control", + "action_debug": "Modo de Depuración de Acciones", + "hide_non_standard_entities": "Ocultar Entidades Generadas No Estándar", + "devices_filter": "Filtrado de Dispositivos" + } + }, + "devices_filter": { + "title": "Filtrado de Dispositivos", + "description": "## Introducción\r\nFiltre dispositivos no deseados por familia.", + "data": { + "filter_mode": "Modo de Filtrado" } } }, diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index 82c8908..2e589b6 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -23,14 +23,29 @@ "description": "Cliquez sur \"Suivant\" pour réessayer" }, "homes_select": { - "title": "Sélectionner une maison et des appareils", - "description": "## Instructions d'utilisation\r\n### Mode de contrôle\r\n- Automatique: Lorsqu'il y a une passerelle centrale Xiaomi disponible dans le réseau local, Home Assistant priorisera l'envoi des commandes de contrôle des appareils via la passerelle centrale pour réaliser un contrôle localisé. S'il n'y a pas de passerelle centrale dans le réseau local, il tentera d'envoyer des commandes de contrôle via le protocole Xiaomi OT pour réaliser un contrôle localisé. Ce n'est que lorsque les conditions de contrôle localisé ci-dessus ne sont pas remplies que les commandes de contrôle des appareils seront envoyées via le cloud.\r\n- Cloud: Les commandes de contrôle ne sont envoyées que via le cloud.\r\n### Importer une maison pour les appareils\r\nL'intégration ajoutera les appareils de la maison sélectionnée.\r\n### Mode de synchronisation des noms de pièces\r\nLors de la synchronisation des appareils de Xiaomi Home à Home Assistant, le nom de la pièce où se trouve l'appareil sera nommé selon les règles suivantes. Notez que le processus de synchronisation des appareils n'affecte pas les paramètres de la maison et de la pièce dans Xiaomi Home APP.\r\n- Ne pas synchroniser: L'appareil ne sera ajouté à aucune zone.\r\n- Autre option: La zone dans laquelle l'appareil est ajouté est nommée en fonction du nom de la maison ou de la pièce de Xiaomi Home APP.\r\n### Mode de débogage d'action\r\nPour les méthodes définies par MIoT-Spec-V2, en plus de générer une entité de notification, une entité de zone de texte sera également générée pour que vous puissiez envoyer des commandes de contrôle à l'appareil lors du débogage.\r\n### Masquer les entités générées non standard\r\nMasquer les entités générées non standard de MIoT-Spec-V2 commençant par \"*\".\r\n\r\n \r\n### {nick_name} Bonjour ! Veuillez sélectionner le mode de contrôle de l'intégration et la maison où se trouvent les appareils à ajouter.", + "title": "Sélectionner la famille et l'appareil", + "description": "## Introduction\r\n### Importer la famille de l'appareil\r\nL'intégration ajoutera des appareils de la famille sélectionnée.\r\n### Mode de synchronisation du nom de la pièce\r\nLors de la synchronisation des appareils de l'application Mi Home avec Home Assistant, le nom de la zone dans Home Assistant suivra les règles ci-dessous. Notez que le processus de synchronisation ne modifiera pas les paramètres de la famille et de la pièce dans l'application Mi Home.\r\n- Ne pas synchroniser : L'appareil ne sera ajouté à aucune zone.\r\n- Autres options : La zone à laquelle l'appareil est ajouté sera nommée d'après le nom de la famille ou de la pièce dans l'application Mi Home.\r\n### Paramètres avancés\r\nAfficher les paramètres avancés pour modifier les options de configuration professionnelle de l'intégration.\r\n\r\n \r\n### {nick_name} Bonjour ! Veuillez sélectionner la famille à laquelle vous souhaitez ajouter l'appareil.", "data": { - "ctrl_mode": "Mode de contrôle", - "home_infos": "Importer une maison pour les appareils", - "area_name_rule": "Mode de synchronisation des noms de pièces", - "action_debug": "Mode de débogage d'action", - "hide_non_standard_entities": "Masquer les entités générées non standard" + "home_infos": "Importer la famille de l'appareil", + "area_name_rule": "Mode de synchronisation du nom de la pièce", + "advanced_options": "Paramètres avancés" + } + }, + "advanced_options": { + "title": "Paramètres Avancés", + "description": "## Introduction\r\n### Conservez les paramètres par défaut à moins de comprendre parfaitement la signification des options ci-dessous.\r\n### Mode de Contrôle\r\n- Automatique : Lorsqu’un hub Xiaomi est disponible sur le réseau local, Home Assistant privilégie l’envoi de commandes via ce hub pour un contrôle local. S’il n’y a pas de hub, il tentera d’envoyer des commandes via le protocole Xiaomi OT. Ce n’est que si les conditions de contrôle local ne sont pas remplies que les commandes seront envoyées via le cloud.\r\n- Cloud : Les commandes sont envoyées exclusivement via le cloud.\r\n### Filtrage des Appareils\r\nFiltrez les appareils indésirables en fonction de la famille.\r\n### Mode de Débogage d’Actions\r\nPour les méthodes définies par les appareils MIoT-Spec-V2, en plus de générer une entité de notification, une entité de saisie de texte sera créée pour envoyer des commandes de contrôle pendant le débogage.\r\n### Masquer les Entités Non Standard\r\nMasquez les entités générées par des instances MIoT-Spec-V2 non standard dont le nom commence par « * ».", + "data": { + "ctrl_mode": "Mode de Contrôle", + "action_debug": "Mode de Débogage d’Actions", + "hide_non_standard_entities": "Masquer les Entités Non Standard", + "devices_filter": "Filtrage des Appareils" + } + }, + "devices_filter": { + "title": "Filtrage des Appareils", + "description": "## Introduction\r\nFiltrez les appareils indésirables en fonction de la famille.", + "data": { + "filter_mode": "Mode de Filtrage" } } }, diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index a8d6b36..bffdaa0 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -23,14 +23,29 @@ "description": "「次へ」をクリックして再試行してください" }, "homes_select": { - "title": "ホームとデバイスを選択", - "description": "## 使用方法\r\n### 制御モード\r\n- 自動: ローカルエリアネットワーク内に利用可能なXiaomi中央ゲートウェイが存在する場合、Home Assistantは中央ゲートウェイを介してデバイス制御コマンドを優先的に送信し、ローカル制御機能を実現します。ローカルエリアネットワーク内に中央ゲートウェイが存在しない場合、Xiaomi OTプロトコルを介して制御コマンドを送信し、ローカル制御機能を実現しようとします。上記のローカル制御条件が満たされない場合にのみ、デバイス制御コマンドはクラウドを介して送信されます。\r\n- クラウド: 制御コマンドはクラウドを介してのみ送信されます。\r\n### 導入されたデバイスのホーム\r\n統合は、選択された家庭にあるデバイスを追加します。\r\n### 部屋名同期モード\r\nXiaomi Home アプリから Home Assistant に同期されるデバイスの場合、デバイスが Home Assistant 内でどのような領域にあるかを示す名前の命名方式は、以下のルールに従います。ただし、デバイスの同期プロセスは、Xiaomi Home アプリで家庭および部屋の設定を変更しないことに注意してください。\r\n- 同期しない:デバイスはどの領域にも追加されません。\r\n- その他のオプション:デバイスが追加される領域は、Xiaomi Home アプリの家庭または部屋の名前に従って命名されます。\r\n### Action デバッグモード\r\nデバイスが MIoT-Spec-V2 で定義された方法を実行する場合、通知エンティティの生成に加えて、テキスト入力ボックスエンティティも生成されます。これを使用して、デバイスに制御命令を送信することができます。\r\n### 非標準生成エンティティを非表示にする\r\n「*」で始まる名前の非標準 MIoT-Spec-V2 インスタンスによって生成されたエンティティを非表示にします。\r\n\r\n \r\n### {nick_name} さん、こんにちは! 統合制御モードと追加するデバイスがあるホームを選択してください。", + "title": "家族とデバイスを選択", + "description": "## 紹介\r\n### デバイスの家族をインポート\r\n統合は選択された家族のデバイスを追加します。\r\n### 部屋の名前の同期モード\r\nMi HomeアプリからHome Assistantにデバイスを同期する際、Home Assistantのエリアの名前は以下のルールに従います。同期プロセスはMi Homeアプリの家族と部屋の設定を変更しないことに注意してください。\r\n- 同期しない:デバイスはどのエリアにも追加されません。\r\n- その他のオプション:デバイスが追加されるエリアはMi Homeアプリの家族または部屋の名前にちなんで命名されます。\r\n### 高度な設定\r\n統合のプロフェッショナルな設定オプションを変更するために高度な設定を表示します。\r\n\r\n \r\n### {nick_name} こんにちは!デバイスを追加したい家族を選択してください。", "data": { - "ctrl_mode": "制御モード", - "home_infos": "導入されたデバイスのホーム", - "area_name_rule": "部屋名同期モード", - "action_debug": "Action デバッグモード", - "hide_non_standard_entities": "非標準生成エンティティを非表示にする" + "home_infos": "デバイスの家族をインポート", + "area_name_rule": "部屋の名前の同期モード", + "advanced_options": "高度な設定" + } + }, + "advanced_options": { + "title": "高度な設定オプション", + "description": "## 紹介\r\n### 以下のオプションの意味を十分に理解していない限り、デフォルト設定のままにしてください。\r\n### コントロールモード\r\n- 自動: ローカルネットワークに利用可能なXiaomiハブがある場合、Home Assistantはローカル制御を実現するためにハブを介してデバイス制御コマンドを優先的に送信します。ハブが存在しない場合は、Xiaomi OTプロトコルを介して制御コマンドを送信しようとします。これらのローカル制御条件が満たされない場合のみ、クラウド経由でコマンドが送信されます。\r\n- クラウド: コマンドはクラウド経由でのみ送信されます。\r\n### デバイスフィルタ\r\n不要なデバイスをファミリー単位でフィルタリングします。\r\n### Actionデバッグモード\r\nMIoT-Spec-V2デバイスで定義されたメソッドについては、通知エンティティに加えてテキスト入力エンティティも生成され、デバッグ時にデバイスへ制御コマンドを送信できます。\r\n### 非標準生成エンティティを隠す\r\n名前が「*」で始まる、非標準のMIoT-Spec-V2インスタンスによって生成されたエンティティを隠します。", + "data": { + "ctrl_mode": "コントロールモード", + "action_debug": "Actionデバッグモード", + "hide_non_standard_entities": "非標準生成エンティティを隠す", + "devices_filter": "デバイスフィルタ" + } + }, + "devices_filter": { + "title": "デバイスフィルタ", + "description": "## 使い方\r\n不要なデバイスをファミリー単位でフィルタリングします。", + "data": { + "filter_mode": "フィルターモード" } } }, diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index a01f845..ad257c3 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -23,14 +23,29 @@ "description": "Klik OP VOLGENDE om het opnieuw te proberen." }, "homes_select": { - "title": "Selecteer Huis en Apparaten", - "description": "## Gebruiksinstructies\r\n### Controlemodus\r\n- Auto: Wanneer er een beschikbare Xiaomi centrale hubgateway in het lokale netwerk is, geeft Home Assistant de voorkeur aan het verzenden van apparaatbedieningscommando's via de centrale hubgateway om lokale controle te bereiken. Als er geen centrale hubgateway in het lokale netwerk is, zal het proberen bedieningscommando's te verzenden via de Xiaomi LAN-controlefunctie. Alleen wanneer de bovenstaande lokale controlevoorwaarden niet zijn vervuld, worden de apparaatbedieningscommando's via de cloud verzonden.\r\n- Cloud: Alle bedieningscommando's worden via de cloud verzonden.\r\n### Apparaten importeren vanuit huis\r\nDe integratie voegt apparaten toe van de geselecteerde huizen.\n### Ruimtenaamsynchronisatiemodus\nBij het importeren van apparaten vanuit de Xiaomi Home APP naar Home Assistant is de naamgevingsconventie van het gebied waarin het apparaat wordt toegevoegd als volgt. Opmerking: het synchronisatieproces van het apparaat verandert de huis- of ruimte-instellingen in de Xiaomi Home APP niet.\r\n- Niet synchroniseren: Het apparaat wordt aan geen enkel gebied toegevoegd.\r\n- Andere opties: Het apparaat wordt toegevoegd aan een gebied dat is genoemd naar de huis- en/of ruimtenamen die al bestaan in de Xiaomi Home APP.\r\n### Debugmodus voor actie\r\nVoor de actie gedefinieerd in MIoT-Spec-V2 van het apparaat, wordt er een Tekstentiteit samen met een Notificatie-entiteit aangemaakt, waarin u bedieningscommando's naar het apparaat kunt sturen voor debugging.\r\n### Verberg niet-standaard gemaakte entiteiten\r\nVerberg de entiteiten die zijn gegenereerd vanuit niet-standaard MIoT-Spec-V2-instanties, waarvan de namen beginnen met \"*\".\r\n\r\n \r\n### Hallo {nick_name}, selecteer alstublieft de integratie controlemethodiek en het huis waar het apparaat dat u wilt importeren zich bevindt.", + "title": "Selecteer Familie en Apparaat", + "description": "## Inleiding\r\n### Importeer de familie van het apparaat\r\nDe integratie voegt apparaten toe uit de geselecteerde familie.\r\n### Kamernaam Synchronisatiemodus\r\nBij het synchroniseren van apparaten van de Mi Home-app naar Home Assistant, wordt de naam van het gebied in Home Assistant volgens de volgende regels genoemd. Houd er rekening mee dat het synchronisatieproces de instellingen van familie en kamer in de Mi Home-app niet zal wijzigen.\r\n- Niet synchroniseren: Het apparaat wordt niet aan een gebied toegevoegd.\r\n- Andere opties: Het gebied waaraan het apparaat wordt toegevoegd, wordt genoemd naar de familie- of kamernaam in de Mi Home-app.\r\n### Geavanceerde instellingen\r\nToon geavanceerde instellingen om de professionele configuratie-opties van de integratie te wijzigen.\r\n\r\n \r\n### {nick_name} Hallo! Selecteer de familie waaraan u het apparaat wilt toevoegen.", "data": { - "ctrl_mode": "Controlemodus", - "home_infos": "Importeer apparaten uit huis", - "area_name_rule": "Ruimtenaamsynchronisatiemodus", - "action_debug": "Debugmodus voor actie", - "hide_non_standard_entities": "Verberg niet-standaard gemaakte entiteiten" + "home_infos": "Importeer de familie van het apparaat", + "area_name_rule": "Kamernaam Synchronisatiemodus", + "advanced_options": "Geavanceerde instellingen" + } + }, + "advanced_options": { + "title": "Geavanceerde Instellingen", + "description": "## Inleiding\r\n### Houd de standaardinstellingen aan, tenzij u de betekenis van de volgende opties volledig begrijpt.\r\n### Besturingsmodus\r\n- Automatisch: Wanneer er een beschikbare Xiaomi-hub in het lokale netwerk is, zal Home Assistant voorrang geven aan het verzenden van besturingsopdrachten via de hub voor lokale besturing. Als er geen hub beschikbaar is, zal het proberen besturingsopdrachten te verzenden via het Xiaomi OT-protocol. Alleen als aan deze lokale besturingsvoorwaarden niet wordt voldaan, worden de opdrachten via de cloud verzonden.\r\n- Cloud: Besturingsopdrachten worden uitsluitend via de cloud verzonden.\r\n### Apparaatfiltering\r\nFilter ongewenste apparaten per familie.\r\n### Actie-debugmodus\r\nVoor methoden gedefinieerd door MIoT-Spec-V2-apparaten wordt, naast een meldingsentiteit, ook een tekstinvoerentiteit gemaakt waarmee u tijdens het debuggen besturingsopdrachten naar het apparaat kunt sturen.\r\n### Niet-standaard entiteiten verbergen\r\nVerberg entiteiten die door niet-standaard MIoT-Spec-V2-instanties worden gegenereerd en waarvan de naam begint met \"*\".", + "data": { + "ctrl_mode": "Besturingsmodus", + "action_debug": "Actie-debugmodus", + "hide_non_standard_entities": "Niet-standaard entiteiten verbergen", + "devices_filter": "Apparaatfiltering" + } + }, + "devices_filter": { + "title": "Apparaatfiltering", + "description": "## Inleiding\r\nFilter ongewenste apparaten per familie.", + "data": { + "filter_mode": "Filtermodus" } } }, @@ -141,4 +156,4 @@ "inconsistent_account": "Accountinformatie is inconsistent. Log in met het juiste account." } } -} +} \ No newline at end of file diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index fca54a5..4fcf47c 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -23,14 +23,29 @@ "description": "Clique em AVANÇAR para tentar novamente." }, "homes_select": { - "title": "Selecione a Casa e os Dispositivos", - "description": "## Instruções de Uso\r\n### Modo de controle\r\n- Auto: Quando houver um gateway central Xiaomi disponível na rede local, o Home Assistant priorizará o envio de comandos de controle do dispositivo através do gateway central, obtendo assim controle local. Se não houver gateway central na rede local, ele tentará enviar comandos através da função de controle LAN da Xiaomi. Somente quando as condições de controle local acima não forem atendidas, os comandos serão enviados pela nuvem.\r\n- Nuvem: Todos os comandos de controle são enviados através da nuvem.\r\n### Importar dispositivos da casa\r\nA integração adicionará dispositivos das casas selecionadas.\n### Modo de sincronização do nome do cômodo\r\nAo importar dispositivos do aplicativo Xiaomi Home para o Home Assistant, a convenção de nomeação da área onde o dispositivo é adicionado é a seguinte. Observe que o processo de sincronização do dispositivo não altera as configurações de casa ou cômodo no aplicativo Xiaomi Home.\r\n- Não sincronizar: O dispositivo não será adicionado a nenhuma área.\r\n- Outras opções: O dispositivo será adicionado a uma área nomeada de acordo com o nome da casa e/ou do cômodo que já existem no aplicativo Xiaomi Home.\r\n### Modo de depuração para ação\r\nPara as ações definidas no MIoT-Spec-V2 do dispositivo, será criada uma entidade de texto juntamente com uma entidade de notificação, nas quais você poderá enviar comandos de controle ao dispositivo para fins de depuração.\r\n### Ocultar entidades criadas não padrão\r\nOculta as entidades geradas a partir de instâncias não padrão do MIoT-Spec-V2, cujos nomes começam com \"*\".\r\n\r\n \r\n### Olá {nick_name}, selecione o modo de controle da integração e a casa onde estão os dispositivos que você deseja importar.", + "title": "Selecionar Família e Dispositivo", + "description": "## Introdução\r\n### Importar a Família do Dispositivo\r\nA integração adicionará dispositivos da família selecionada.\r\n### Modo de Sincronização do Nome da Sala\r\nAo sincronizar dispositivos do APP Mi Home para o Home Assistant, a nomeação da área no Home Assistant seguirá as regras abaixo. Observe que o processo de sincronização não alterará as configurações de família e sala no APP Mi Home.\r\n- Não sincronizar: O dispositivo não será adicionado a nenhuma área.\r\n- Outras opções: A área à qual o dispositivo é adicionado será nomeada de acordo com o nome da família ou da sala no APP Mi Home.\r\n### Configurações Avançadas\r\nMostrar configurações avançadas para modificar as opções de configuração profissional da integração.\r\n\r\n \r\n### {nick_name} Olá! Por favor, selecione a família à qual você deseja adicionar o dispositivo.", "data": { - "ctrl_mode": "Modo de controle", - "home_infos": "Importar dispositivos da casa", - "area_name_rule": "Modo de sincronização do nome do cômodo", - "action_debug": "Modo de depuração para ação", - "hide_non_standard_entities": "Ocultar entidades não padrão criadas" + "home_infos": "Importar a Família do Dispositivo", + "area_name_rule": "Modo de Sincronização do Nome da Sala", + "advanced_options": "Configurações Avançadas" + } + }, + "advanced_options": { + "title": "Configurações Avançadas", + "description": "## Introdução\r\n### Mantenha as configurações padrão, a menos que você entenda completamente o significado das seguintes opções.\r\n### Modo de Controle\r\n- Automático: Quando houver um hub Xiaomi disponível na rede local, o Home Assistant priorizará o envio de comandos de controle através do hub para obter controle local. Se não houver hub, tentará enviar comandos de controle pelo protocolo Xiaomi OT. Somente se essas condições de controle local não forem atendidas, os comandos serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controle são enviados exclusivamente pela nuvem.\r\n### Filtragem de Dispositivos\r\nFiltre dispositivos indesejados por família.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos por dispositivos MIoT-Spec-V2, além de gerar uma entidade de notificação, será criada uma entidade de entrada de texto para que você possa enviar comandos de controle ao dispositivo durante a depuração.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOculte entidades geradas por instâncias não padrão do MIoT-Spec-V2 cujos nomes começam com \"*\".", + "data": { + "ctrl_mode": "Modo de Controle", + "action_debug": "Modo de Depuração de Ações", + "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão", + "devices_filter": "Filtragem de Dispositivos" + } + }, + "devices_filter": { + "title": "Filtragem de Dispositivos", + "description": "## Introdução\r\nFiltre dispositivos indesejados por família.", + "data": { + "filter_mode": "Modo de Filtro" } } }, @@ -141,4 +156,4 @@ "inconsistent_account": "As informações da conta são inconsistentes. Por favor, faça login com a conta correta." } } -} +} \ No newline at end of file diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index 480f59e..02f883d 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -23,14 +23,29 @@ "description": "Clique em SEGUINTE para tentar novamente." }, "homes_select": { - "title": "Selecione a Casa e os Dispositivos", - "description": "## Instruções de Utilização\r\n### Modo de Controlo\r\n- Automático: Quando existir um gateway central Xiaomi disponível na rede local, o Home Assistant dará prioridade ao envio de comandos de controlo através do gateway central, permitindo um controlo local. Caso não exista um gateway central na rede local, tentará enviar comandos através da funcionalidade de controlo LAN. Apenas se estas condições não forem cumpridas, os comandos serão enviados pela nuvem.\r\n- Nuvem: Todos os comandos de controlo são enviados através da nuvem.\r\n### Importar dispositivos da casa\r\nA integração adicionará dispositivos das casas selecionadas.\n### Modo de sincronização do nome da divisão\r\nAo importar dispositivos da aplicação Xiaomi Home para o Home Assistant, a nomeação da área onde o dispositivo é adicionado segue as regras abaixo. Note que o processo de sincronização dos dispositivos não altera as definições de casa ou divisão na aplicação Xiaomi Home.\r\n- Não sincronizar: O dispositivo não será atribuído a qualquer área.\r\n- Outras opções: O dispositivo será adicionado a uma área cujo nome corresponde ao da casa e/ou divisão definida na aplicação Xiaomi Home.\r\n### Modo de depuração de ação\r\nPara as ações definidas no MIoT-Spec-V2 do dispositivo, será criada uma entidade do tipo texto juntamente com uma entidade de notificação, nas quais poderá enviar comandos de controlo ao dispositivo para fins de depuração.\r\n### Ocultar entidades não padrão\r\nOculta as entidades geradas a partir de instâncias não padrão do MIoT-Spec-V2, cujos nomes começam por \"*\".\r\n\r\n \r\n### Olá {nick_name}, selecione o modo de controlo da integração e a casa na qual deseja importar os dispositivos.", + "title": "Selecionar Família e Dispositivo", + "description": "## Introdução\r\n### Importar a Família do Dispositivo\r\nA integração adicionará dispositivos da família selecionada.\r\n### Modo de Sincronização do Nome da Sala\r\nAo sincronizar dispositivos do APP Mi Home para o Home Assistant, a nomeação da área no Home Assistant seguirá as regras abaixo. Observe que o processo de sincronização não alterará as configurações de família e sala no APP Mi Home.\r\n- Não sincronizar: O dispositivo não será adicionado a nenhuma área.\r\n- Outras opções: A área à qual o dispositivo é adicionado será nomeada de acordo com o nome da família ou da sala no APP Mi Home.\r\n### Configurações Avançadas\r\nMostrar configurações avançadas para modificar as opções de configuração profissional da integração.\r\n\r\n \r\n### {nick_name} Olá! Por favor, selecione a família à qual você deseja adicionar o dispositivo.", + "data": { + "home_infos": "Importar a Família do Dispositivo", + "area_name_rule": "Modo de Sincronização do Nome da Sala", + "advanced_options": "Configurações Avançadas" + } + }, + "advanced_options": { + "title": "Opções Avançadas", + "description": "## Introdução\r\n### Mantenha as configurações padrão, a menos que compreenda totalmente o significado das seguintes opções.\r\n### Modo de Controlo\r\n- Automático: Quando existir um hub Xiaomi disponível na rede local, o Home Assistant irá priorizar o envio de comandos de controlo através do hub para permitir controlo local. Se não houver hub na rede local, irá tentar enviar comandos de controlo através do protocolo Xiaomi OT. Apenas quando estas condições de controlo local não forem satisfeitas, os comandos serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controlo são enviados exclusivamente através da nuvem.\r\n### Filtragem de Dispositivos\r\nFiltre dispositivos indesejados por família.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos por dispositivos MIoT-Spec-V2, além de gerar uma entidade de notificação, também será criada uma entidade de entrada de texto para enviar comandos ao dispositivo durante a depuração.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOculte entidades geradas por instâncias não padrão do MIoT-Spec-V2 cujos nomes começam com \"*\".", "data": { "ctrl_mode": "Modo de Controlo", - "home_infos": "Importar dispositivos da casa", - "area_name_rule": "Modo de sincronização do nome da divisão", - "action_debug": "Modo de depuração de ação", - "hide_non_standard_entities": "Ocultar entidades não padrão" + "action_debug": "Modo de Depuração de Ações", + "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão", + "devices_filter": "Filtragem de Dispositivos" + } + }, + "devices_filter": { + "title": "Filtragem de Dispositivos", + "description": "## Introdução\r\nFiltre dispositivos indesejados por família.", + "data": { + "filter_mode": "Modo de Filtro" } } }, @@ -141,4 +156,4 @@ "inconsistent_account": "A informação da conta é inconsistente. Por favor, inicie sessão com a conta correta." } } -} +} \ No newline at end of file diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index 8418f93..4c4fdf9 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -23,14 +23,29 @@ "description": "Нажмите кнопку «Далее», чтобы повторить попытку" }, "homes_select": { - "title": "Выберите дом и устройства", - "description": "## Инструкция по использованию\r\n### Режим управления\r\n- Авто: Когда в локальной сети доступен центральный шлюз Xiaomi, Home Assistant будет в первую очередь отправлять команды управления устройствами через центральный шлюз для достижения локализованного управления. Если в локальной сети нет центрального шлюза, он попытается отправить команды управления через протокол Xiaomi OT для достижения локализованного управления. Только если вышеуказанные условия локализованного управления не выполняются, команды управления устройствами будут отправляться через облако.\r\n- Облако: Команды управления отправляются только через облако.\r\n### Импорт домашнего устройства\r\nИнтеграция добавит устройства из выбранных домов.\r\n### Режим синхронизации имен комнат\r\nПри синхронизации устройств из приложения Xiaomi Home в Home Assistant имена комнат устройств в Home Assistant будут именоваться в соответствии с именами дома или комнаты в приложении Xiaomi Home.\r\n- Не синхронизировать: устройство не будет добавлено в любую область.\r\n- Другие параметры: область, в которую добавляется устройство, называется именем дома или комнаты в приложении Xiaomi Home.\r\n### Режим отладки Action\r\nДля методов, определенных в MIoT-Spec-V2, помимо создания уведомительной сущности будет создана сущность текстового поля ввода, которую можно использовать для отправки команд управления устройством во время отладки.\r\n### Скрыть нестандартные сущности\r\nСкрыть сущности, созданные нестандартными примерами MIoT-Spec-V2, имена которых начинаются с « * ».\r\n\r\n \r\n### {nick_name} Здравствуйте! Выберите режим управления интеграцией и дом, в котором находятся устройства, которые вы хотите добавить.", + "title": "Выберите семью и устройство", + "description": "## Введение\r\n### Импорт семьи устройства\r\nИнтеграция добавит устройства из выбранной семьи.\r\n### Режим синхронизации имени комнаты\r\nПри синхронизации устройств из приложения Mi Home с Home Assistant, название области в Home Assistant будет следовать следующим правилам. Обратите внимание, что процесс синхронизации не изменит настройки семьи и комнаты в приложении Mi Home.\r\n- Не синхронизировать: Устройство не будет добавлено ни в одну область.\r\n- Другие варианты: Область, в которую добавляется устройство, будет названа в честь имени семьи или комнаты в приложении Mi Home.\r\n### Расширенные настройки\r\nПоказать расширенные настройки для изменения профессиональных параметров конфигурации интеграции.\r\n\r\n \r\n### {nick_name} Здравствуйте! Пожалуйста, выберите семью, в которую вы хотите добавить устройство.", + "data": { + "home_infos": "Импорт семьи устройства", + "area_name_rule": "Режим синхронизации имени комнаты", + "advanced_options": "Расширенные настройки" + } + }, + "advanced_options": { + "title": "Расширенные настройки", + "description": "## Введение\r\n### Сохраняйте настройки по умолчанию, если вы не полностью понимаете смысл следующих опций.\r\n### Режим управления\r\n- Авто: Если в локальной сети доступен шлюз Xiaomi, Home Assistant будет в приоритете отправлять команды управления устройствами через этот шлюз, чтобы обеспечить локальное управление. При отсутствии шлюза осуществляется попытка отправить команды управления через протокол Xiaomi OT. Только при несоблюдении указанных условий локального управления команды отправляются через облако.\r\n- Облако: Команды управления отправляются исключительно через облако.\r\n### Фильтрация устройств\r\nФильтруйте ненужные устройства по семьям.\r\n### Режим отладки действий\r\nДля методов, определённых устройствами MIoT-Spec-V2, помимо сущности уведомления, будет создана сущность текстового ввода, которая позволяет отправлять команды управления устройству во время отладки.\r\n### Скрыть нестандартные сущности\r\nСкрывает сущности, созданные нестандартными экземплярами MIoT-Spec-V2, чьи имена начинаются со «*».", "data": { "ctrl_mode": "Режим управления", - "home_infos": "Импорт домашнего устройства", - "area_name_rule": "Режим синхронизации имен комнат", - "action_debug": "Режим отладки Action", - "hide_non_standard_entities": "Скрыть нестандартные сущности" + "action_debug": "Режим отладки действий", + "hide_non_standard_entities": "Скрыть нестандартные сущности", + "devices_filter": "Фильтрация устройств" + } + }, + "devices_filter": { + "title": "Фильтрация устройств", + "description": "## Введение\r\nФильтруйте ненужные устройства по семьям.", + "data": { + "filter_mode": "Режим фильтрации" } } }, diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index 37b905d..1cdd7a2 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -24,13 +24,28 @@ }, "homes_select": { "title": "选择家庭与设备", - "description": "## 使用介绍\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### 导入设备的家庭\r\n集成将添加已选中家庭中的设备。\r\n### 房间名同步模式\r\n将设备从米家APP同步到 Home Assistant 时,设备在 Home Assistant 中所处区域的名称的命名方式将遵循以下规则。注意,设备同步过程不会改变米家APP中家庭和房间的设置。\r\n- 不同步:设备不会被添加至任何区域。\r\n- 其它选项:设备所添加到的区域以米家APP中的家庭或房间名称命名。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。\r\n\r\n \r\n### {nick_name} 您好!请选择集成控制模式以及您想要添加的设备所处的家庭。", + "description": "## 使用介绍\r\n### 导入设备的家庭\r\n集成将添加已选中家庭中的设备。\r\n### 房间名同步模式\r\n将设备从米家APP同步到 Home Assistant 时,设备在 Home Assistant 中所处区域的名称的命名方式将遵循以下规则。注意,设备同步过程不会改变米家APP中家庭和房间的设置。\r\n- 不同步:设备不会被添加至任何区域。\r\n- 其它选项:设备所添加到的区域以米家APP中的家庭或房间名称命名。\r\n### 高级设置选项\r\n展示高级设置选项,对集成的专业配置选项进行修改。\r\n\r\n \r\n### {nick_name} 您好!请选择您想要添加的设备所处家庭。", "data": { - "ctrl_mode": "控制模式", "home_infos": "导入设备的家庭", "area_name_rule": "房间名同步模式", + "advanced_options": "高级设置选项" + } + }, + "advanced_options": { + "title": "高级设置选项", + "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### 设备过滤\r\n按照家庭维度,过滤不需要的设备。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。", + "data": { + "ctrl_mode": "控制模式", "action_debug": "Action 调试模式", - "hide_non_standard_entities": "隐藏非标准生成实体" + "hide_non_standard_entities": "隐藏非标准生成实体", + "devices_filter": "设备过滤" + } + }, + "devices_filter": { + "title": "设备过滤", + "description": "## 使用介绍\r\n按照家庭维度,过滤不需要的设备。", + "data": { + "filter_mode": "过滤模式" } } }, diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index c8551a0..c711ab2 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -24,13 +24,28 @@ }, "homes_select": { "title": "選擇家庭與設備", - "description": "## 使用介紹\r\n### 控制模式\r\n- 自動:本地區域網內存在可用的小米中樞網關時, Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。本地區域網不存在中樞時,會嘗試通過小米OT協議發送控制指令,以實現本地化控制功能。只有當上述本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令僅通過雲端發送。\r\n### 導入設備的家庭\r\n集成將添加已選中家庭中的設備。\r\n### 房間名同步模式\r\n將設備從米家APP同步到 Home Assistant 時,設備在 Home Assistant 中所處區域的名稱的命名方式將遵循以下規則。注意,設備同步過程不會改變米家APP中家庭和房間的設置。\r\n- 不同步:設備不會被添加至任何區域。\r\n- 其它選項:設備所添加到的區域以米家APP中的家庭或房間名稱命名。\r\n### Action 調試模式\r\n對於設備 MIoT-Spec-V2 定義的方法,在生成通知實體之外,還會生成一個文本輸入框實體,您可以在調試時用它向設備發送控制指令。\r\n### 隱藏非標準生成實體\r\n隱藏名稱以“*”開頭的非標準 MIoT-Spec-V2 實例生成的實體。\r\n\r\n \r\n### {nick_name} 您好!請選擇集成控制模式以及您想要添加的設備所處的家庭。", + "description": "## 使用介紹\r\n### 導入設備的家庭\r\n集成將添加已選中家庭中的設備。\r\n### 房間名同步模式\r\n將設備從米家APP同步到 Home Assistant 時,設備在 Home Assistant 中所處區域的名稱的命名方式將遵循以下規則。注意,設備同步過程不會改變米家APP中家庭和房間的設置。\r\n- 不同步:設備不會被添加至任何區域。\r\n- 其它選項:設備所添加到的區域以米家APP中的家庭或房間名稱命名。\r\n### 高級設置選項\r\n展示高級設置選項,對集成的專業配置選項進行修改。\r\n\r\n \r\n### {nick_name} 您好!請選擇您想要添加的設備所處家庭。", "data": { - "ctrl_mode": "控制模式", "home_infos": "導入設備的家庭", "area_name_rule": "房間名同步模式", + "advanced_options": "高級設置選項" + } + }, + "advanced_options": { + "title": "高級設置選項", + "description": "## 使用介紹\r\n### 除非您非常清楚下列選項的含義,否則請保持默認。\r\n### 控制模式\r\n- 自動:本地區域網內存在可用的小米中樞網關時,Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。本地區域網不存在中樞時,會嘗試通過小米OT協議發送控制指令,以實現本地化控制功能。只有當上述本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令僅通過雲端發送。\r\n### 設備過濾\r\n按照家庭維度,過濾不需要的設備。\r\n### Action 調試模式\r\n對於設備 MIoT-Spec-V2 定義的方法,在生成通知實體之外,還會生成一個文本輸入框實體,您可以在調試時用它向設備發送控制指令。\r\n### 隱藏非標準生成實體\r\n隱藏名稱以“*”開頭的非標準 MIoT-Spec-V2 實例生成的實體。", + "data": { + "ctrl_mode": "控制模式", "action_debug": "Action 調試模式", - "hide_non_standard_entities": "隱藏非標準生成實體" + "hide_non_standard_entities": "隱藏非標準生成實體", + "devices_filter": "設備過濾" + } + }, + "devices_filter": { + "title": "設備過濾", + "description": "## 使用介紹\r\n按照家庭維度,過濾不需要的設備。", + "data": { + "filter_mode": "過濾模式" } } }, From 8429899669e0f24d224ff94455c422951203da30 Mon Sep 17 00:00:00 2001 From: sworld Date: Sun, 22 Dec 2024 20:10:13 +0800 Subject: [PATCH 02/24] doc: update translations and i18n --- .../xiaomi_home/miot/i18n/de.json | 7 ++++--- .../xiaomi_home/miot/i18n/en.json | 7 ++++--- .../xiaomi_home/miot/i18n/es.json | 7 ++++--- .../xiaomi_home/miot/i18n/fr.json | 7 ++++--- .../xiaomi_home/miot/i18n/ja.json | 7 ++++--- .../xiaomi_home/miot/i18n/nl.json | 7 ++++--- .../xiaomi_home/miot/i18n/pt-BR.json | 7 ++++--- .../xiaomi_home/miot/i18n/pt.json | 7 ++++--- .../xiaomi_home/miot/i18n/ru.json | 7 ++++--- .../xiaomi_home/miot/i18n/zh-Hans.json | 16 +++++++++++----- .../xiaomi_home/miot/i18n/zh-Hant.json | 7 ++++--- .../xiaomi_home/translations/de.json | 4 ++-- .../xiaomi_home/translations/en.json | 6 +++--- .../xiaomi_home/translations/es.json | 6 +++--- .../xiaomi_home/translations/fr.json | 6 +++--- .../xiaomi_home/translations/ja.json | 6 +++--- .../xiaomi_home/translations/nl.json | 6 +++--- .../xiaomi_home/translations/pt-BR.json | 6 +++--- .../xiaomi_home/translations/pt.json | 6 +++--- .../xiaomi_home/translations/ru.json | 4 ++-- .../xiaomi_home/translations/zh-Hans.json | 19 +++++++++++++------ .../xiaomi_home/translations/zh-Hant.json | 6 +++--- 22 files changed, 92 insertions(+), 69 deletions(-) diff --git a/custom_components/xiaomi_home/miot/i18n/de.json b/custom_components/xiaomi_home/miot/i18n/de.json index 04103d6..66ba583 100644 --- a/custom_components/xiaomi_home/miot/i18n/de.json +++ b/custom_components/xiaomi_home/miot/i18n/de.json @@ -2,15 +2,16 @@ "config": { "other": { "devices": "Geräte", - "found_central_gateway": ", lokales zentrales Gateway gefunden" + "found_central_gateway": ", lokales zentrales Gateway gefunden", + "without_room": "Kein Raum zugewiesen" }, "control_mode": { "auto": "automatisch", "cloud": "Cloud" }, "filter_mode": { - "include": "einschließen", - "exclude": "ausschließen" + "exclude": "ausschließen", + "include": "einschließen" }, "room_name_rule": { "none": "nicht synchronisieren", diff --git a/custom_components/xiaomi_home/miot/i18n/en.json b/custom_components/xiaomi_home/miot/i18n/en.json index d8fb68d..b10a1f3 100644 --- a/custom_components/xiaomi_home/miot/i18n/en.json +++ b/custom_components/xiaomi_home/miot/i18n/en.json @@ -2,15 +2,16 @@ "config": { "other": { "devices": "Devices", - "found_central_gateway": ", Found Local Central Hub Gateway" + "found_central_gateway": ", Found Local Central Hub Gateway", + "without_room": "No room assigned" }, "control_mode": { "auto": "Auto", "cloud": "Cloud" }, "filter_mode": { - "include": "Include", - "exclude": "Exclude" + "exclude": "Exclude", + "include": "Include" }, "room_name_rule": { "none": "Do not synchronize", diff --git a/custom_components/xiaomi_home/miot/i18n/es.json b/custom_components/xiaomi_home/miot/i18n/es.json index 8effc97..e87e86f 100644 --- a/custom_components/xiaomi_home/miot/i18n/es.json +++ b/custom_components/xiaomi_home/miot/i18n/es.json @@ -2,15 +2,16 @@ "config": { "other": { "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" }, "control_mode": { "auto": "automático", "cloud": "nube" }, "filter_mode": { - "include": "incluir", - "exclude": "excluir" + "exclude": "excluir", + "include": "incluir" }, "room_name_rule": { "none": "no sincronizar", diff --git a/custom_components/xiaomi_home/miot/i18n/fr.json b/custom_components/xiaomi_home/miot/i18n/fr.json index f8b6caa..0e6945d 100644 --- a/custom_components/xiaomi_home/miot/i18n/fr.json +++ b/custom_components/xiaomi_home/miot/i18n/fr.json @@ -2,15 +2,16 @@ "config": { "other": { "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" }, "control_mode": { "auto": "automatique", "cloud": "cloud" }, "filter_mode": { - "include": "inclure", - "exclude": "exclure" + "exclude": "exclure", + "include": "inclure" }, "room_name_rule": { "none": "ne pas synchroniser", diff --git a/custom_components/xiaomi_home/miot/i18n/ja.json b/custom_components/xiaomi_home/miot/i18n/ja.json index c0d51b9..70b1477 100644 --- a/custom_components/xiaomi_home/miot/i18n/ja.json +++ b/custom_components/xiaomi_home/miot/i18n/ja.json @@ -2,15 +2,16 @@ "config": { "other": { "devices": "デバイス", - "found_central_gateway": "、ローカル中央ゲートウェイが見つかりました" + "found_central_gateway": "、ローカル中央ゲートウェイが見つかりました", + "without_room": "部屋が割り当てられていません" }, "control_mode": { "auto": "自動", "cloud": "クラウド" }, "filter_mode": { - "include": "含む", - "exclude": "除外" + "exclude": "除外", + "include": "含む" }, "room_name_rule": { "none": "同期しない", diff --git a/custom_components/xiaomi_home/miot/i18n/nl.json b/custom_components/xiaomi_home/miot/i18n/nl.json index bc81b20..7aeb26e 100644 --- a/custom_components/xiaomi_home/miot/i18n/nl.json +++ b/custom_components/xiaomi_home/miot/i18n/nl.json @@ -2,15 +2,16 @@ "config": { "other": { "devices": "Apparaten", - "found_central_gateway": ", Lokale centrale hub-gateway gevonden" + "found_central_gateway": ", Lokale centrale hub-gateway gevonden", + "without_room": "Niet toegewezen kamer" }, "control_mode": { "auto": "Automatisch", "cloud": "Cloud" }, "filter_mode": { - "include": "Inclusief", - "exclude": "Uitsluiten" + "exclude": "Uitsluiten", + "include": "Inclusief" }, "room_name_rule": { "none": "Niet synchroniseren", diff --git a/custom_components/xiaomi_home/miot/i18n/pt-BR.json b/custom_components/xiaomi_home/miot/i18n/pt-BR.json index 54ae478..957b229 100644 --- a/custom_components/xiaomi_home/miot/i18n/pt-BR.json +++ b/custom_components/xiaomi_home/miot/i18n/pt-BR.json @@ -2,15 +2,16 @@ "config": { "other": { "devices": "dispositivos", - "found_central_gateway": "encontrado o gateway central local" + "found_central_gateway": "encontrado o gateway central local", + "without_room": "sem quarto atribuído" }, "control_mode": { "auto": "automático", "cloud": "nuvem" }, "filter_mode": { - "include": "incluir", - "exclude": "excluir" + "exclude": "excluir", + "include": "incluir" }, "room_name_rule": { "none": "não sincronizado", diff --git a/custom_components/xiaomi_home/miot/i18n/pt.json b/custom_components/xiaomi_home/miot/i18n/pt.json index 0dd732f..1620b98 100644 --- a/custom_components/xiaomi_home/miot/i18n/pt.json +++ b/custom_components/xiaomi_home/miot/i18n/pt.json @@ -2,15 +2,16 @@ "config": { "other": { "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" }, "control_mode": { "auto": "Automático", "cloud": "Nuvem" }, "filter_mode": { - "include": "Incluir", - "exclude": "Excluir" + "exclude": "Excluir", + "include": "Incluir" }, "room_name_rule": { "none": "Não sincronizar", diff --git a/custom_components/xiaomi_home/miot/i18n/ru.json b/custom_components/xiaomi_home/miot/i18n/ru.json index c922212..703c048 100644 --- a/custom_components/xiaomi_home/miot/i18n/ru.json +++ b/custom_components/xiaomi_home/miot/i18n/ru.json @@ -2,15 +2,16 @@ "config": { "other": { "devices": "устройства", - "found_central_gateway": ", найден локальный центральный шлюз" + "found_central_gateway": ", найден локальный центральный шлюз", + "without_room": "без комнаты" }, "control_mode": { "auto": "автоматический", "cloud": "облако" }, "filter_mode": { - "include": "включить", - "exclude": "исключить" + "exclude": "исключить", + "include": "включить" }, "room_name_rule": { "none": "не синхронизировать", diff --git a/custom_components/xiaomi_home/miot/i18n/zh-Hans.json b/custom_components/xiaomi_home/miot/i18n/zh-Hans.json index b2bca90..f8f3c40 100644 --- a/custom_components/xiaomi_home/miot/i18n/zh-Hans.json +++ b/custom_components/xiaomi_home/miot/i18n/zh-Hans.json @@ -2,22 +2,28 @@ "config": { "other": { "devices": "个设备", - "found_central_gateway": ",发现本地中枢网关" + "found_central_gateway": ",发现本地中枢网关", + "without_room": "未分配房间" }, "control_mode": { "auto": "自动", "cloud": "云端" }, - "filter_mode": { - "include": "包含", - "exclude": "排除" - }, "room_name_rule": { "none": "不同步", "home_room": "家庭名 和 房间名 (米家 卧室)", "room": "房间名 (卧室)", "home": "家庭名 (米家)" }, + "filter_mode": { + "exclude": "排除", + "include": "包含" + }, + "connect_type": { + "0": "WiFi设备", + "1": "蓝牙设备", + "2": "其它类型" + }, "option_status": { "enable": "启用", "disable": "禁用" diff --git a/custom_components/xiaomi_home/miot/i18n/zh-Hant.json b/custom_components/xiaomi_home/miot/i18n/zh-Hant.json index 901e5c0..5c7ef79 100644 --- a/custom_components/xiaomi_home/miot/i18n/zh-Hant.json +++ b/custom_components/xiaomi_home/miot/i18n/zh-Hant.json @@ -2,15 +2,16 @@ "config": { "other": { "devices": "個設備", - "found_central_gateway": ",發現本地中樞網關" + "found_central_gateway": ",發現本地中樞網關", + "without_room": "未分配房間" }, "control_mode": { "auto": "自動", "cloud": "雲端" }, "filter_mode": { - "include": "包含", - "exclude": "排除" + "exclude": "排除", + "include": "包含" }, "room_name_rule": { "none": "不同步", diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index 47254b6..05d8293 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -35,10 +35,10 @@ "title": "Erweiterte Einstellungen", "description": "## Einführung\r\n### Behalten Sie die Standardeinstellungen bei, es sei denn, Sie verstehen die folgenden Optionen vollständig.\r\n### Steuerungsmodus\r\n- Automatisch: Wenn ein verfügbarer Xiaomi-Hub im lokalen Netzwerk vorhanden ist, priorisiert Home Assistant das Senden von Steuerbefehlen über den Hub, um eine lokale Steuerung zu ermöglichen. Wenn kein Hub vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden. Nur wenn diese Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Befehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden ausschließlich über die Cloud gesendet.\r\n### Gerätefilterung\r\nFiltern Sie unerwünschte Geräte nach Familien.\r\n### Action-Debug-Modus\r\nFür Methoden, die von MIoT-Spec-V2-Geräten definiert werden, wird neben der Benachrichtigungsentität auch eine Texteingabe-Entität erstellt, mit der Sie während des Debuggens Steuerbefehle an das Gerät senden können.\r\n### Nicht standardmäßige Entitäten ausblenden\r\nBlendet Entitäten aus, die von nicht-standardmäßigen MIoT-Spec-V2-Instanzen generiert werden und deren Name mit „*“ beginnt.", "data": { + "devices_filter": "Gerätefilterung", "ctrl_mode": "Steuerungsmodus", "action_debug": "Action-Debug-Modus", - "hide_non_standard_entities": "Nicht standardmäßige Entitäten ausblenden", - "devices_filter": "Gerätefilterung" + "hide_non_standard_entities": "Nicht standardmäßige Entitäten ausblenden" } }, "devices_filter": { diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index d8e11d5..7e1dcd8 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -35,14 +35,14 @@ "title": "Advanced Settings", "description": "## Introduction\r\n### Keep the default settings unless you fully understand the following options.\r\n### Control Mode\r\n- Auto: When a Xiaomi hub is available on the local network, Home Assistant will prioritize sending device control commands through the hub for local control. If there is no hub, it will attempt to send commands via the Xiaomi OT protocol. Only if those local control conditions are not met will commands be sent through the cloud.\r\n- Cloud: Control commands are sent exclusively through the cloud.\r\n### Device Filtering\r\nFilter out unwanted devices by family.\r\n### Action Debug Mode\r\nFor methods defined by MIoT-Spec-V2 devices, besides generating a notification entity, a text input entity will also be created so you can send control commands to the device during debugging.\r\n### Hide Non-Standard Generated Entities\r\nHide entities generated by non-standard MIoT-Spec-V2 instances whose names start with \"*\".", "data": { + "devices_filter": "Filter Devices", "ctrl_mode": "Control Mode", "action_debug": "Action Debug Mode", - "hide_non_standard_entities": "Hide Non-Standard Generated Entities", - "devices_filter": "Device Filtering" + "hide_non_standard_entities": "Hide Non-Standard Generated Entities" } }, "devices_filter": { - "title": "Device Filtering", + "title": "Filter Devices", "description": "## Introduction\r\nFilter out unwanted devices by family.", "data": { "filter_mode": "Filter Mode" diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index c15adcd..4adc364 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -35,14 +35,14 @@ "title": "Opciones Avanzadas", "description": "## Introducción\r\n### Mantenga la configuración predeterminada a menos que conozca completamente el significado de las siguientes opciones.\r\n### Modo de Control\r\n- Automático: Cuando haya un hub Xiaomi disponible en la red local, Home Assistant priorizará el envío de comandos de control a través del hub para lograr un control local. Si no hay un hub, intentará enviar los comandos a través del protocolo Xiaomi OT. Solo si no se cumplen esas condiciones de control local, los comandos se enviarán a través de la nube.\r\n- Nube: Los comandos se envían exclusivamente a través de la nube.\r\n### Filtrado de Dispositivos\r\nFiltre dispositivos no deseados por familia.\r\n### Modo de Depuración de Acciones\r\nPara los métodos definidos por dispositivos MIoT-Spec-V2, además de generar una entidad de notificación, se creará una entidad de entrada de texto para que pueda enviar comandos de control durante la depuración.\r\n### Ocultar Entidades Generadas No Estándar\r\nOculte entidades generadas por instancias no estándar de MIoT-Spec-V2 cuyos nombres comiencen con \"*\".", "data": { + "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Control", "action_debug": "Modo de Depuración de Acciones", - "hide_non_standard_entities": "Ocultar Entidades Generadas No Estándar", - "devices_filter": "Filtrado de Dispositivos" + "hide_non_standard_entities": "Ocultar Entidades Generadas No Estándar" } }, "devices_filter": { - "title": "Filtrado de Dispositivos", + "title": "Filtrar Dispositivos", "description": "## Introducción\r\nFiltre dispositivos no deseados por familia.", "data": { "filter_mode": "Modo de Filtrado" diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index 2e589b6..362968c 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -35,14 +35,14 @@ "title": "Paramètres Avancés", "description": "## Introduction\r\n### Conservez les paramètres par défaut à moins de comprendre parfaitement la signification des options ci-dessous.\r\n### Mode de Contrôle\r\n- Automatique : Lorsqu’un hub Xiaomi est disponible sur le réseau local, Home Assistant privilégie l’envoi de commandes via ce hub pour un contrôle local. S’il n’y a pas de hub, il tentera d’envoyer des commandes via le protocole Xiaomi OT. Ce n’est que si les conditions de contrôle local ne sont pas remplies que les commandes seront envoyées via le cloud.\r\n- Cloud : Les commandes sont envoyées exclusivement via le cloud.\r\n### Filtrage des Appareils\r\nFiltrez les appareils indésirables en fonction de la famille.\r\n### Mode de Débogage d’Actions\r\nPour les méthodes définies par les appareils MIoT-Spec-V2, en plus de générer une entité de notification, une entité de saisie de texte sera créée pour envoyer des commandes de contrôle pendant le débogage.\r\n### Masquer les Entités Non Standard\r\nMasquez les entités générées par des instances MIoT-Spec-V2 non standard dont le nom commence par « * ».", "data": { + "devices_filter": "Filtrer les Appareils", "ctrl_mode": "Mode de Contrôle", "action_debug": "Mode de Débogage d’Actions", - "hide_non_standard_entities": "Masquer les Entités Non Standard", - "devices_filter": "Filtrage des Appareils" + "hide_non_standard_entities": "Masquer les Entités Non Standard" } }, "devices_filter": { - "title": "Filtrage des Appareils", + "title": "Filtrer les Appareils", "description": "## Introduction\r\nFiltrez les appareils indésirables en fonction de la famille.", "data": { "filter_mode": "Mode de Filtrage" diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index bffdaa0..8c343c8 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -35,14 +35,14 @@ "title": "高度な設定オプション", "description": "## 紹介\r\n### 以下のオプションの意味を十分に理解していない限り、デフォルト設定のままにしてください。\r\n### コントロールモード\r\n- 自動: ローカルネットワークに利用可能なXiaomiハブがある場合、Home Assistantはローカル制御を実現するためにハブを介してデバイス制御コマンドを優先的に送信します。ハブが存在しない場合は、Xiaomi OTプロトコルを介して制御コマンドを送信しようとします。これらのローカル制御条件が満たされない場合のみ、クラウド経由でコマンドが送信されます。\r\n- クラウド: コマンドはクラウド経由でのみ送信されます。\r\n### デバイスフィルタ\r\n不要なデバイスをファミリー単位でフィルタリングします。\r\n### Actionデバッグモード\r\nMIoT-Spec-V2デバイスで定義されたメソッドについては、通知エンティティに加えてテキスト入力エンティティも生成され、デバッグ時にデバイスへ制御コマンドを送信できます。\r\n### 非標準生成エンティティを隠す\r\n名前が「*」で始まる、非標準のMIoT-Spec-V2インスタンスによって生成されたエンティティを隠します。", "data": { + "devices_filter": "デバイスをフィルタリング", "ctrl_mode": "コントロールモード", "action_debug": "Actionデバッグモード", - "hide_non_standard_entities": "非標準生成エンティティを隠す", - "devices_filter": "デバイスフィルタ" + "hide_non_standard_entities": "非標準生成エンティティを隠す" } }, "devices_filter": { - "title": "デバイスフィルタ", + "title": "デバイスをフィルタリング", "description": "## 使い方\r\n不要なデバイスをファミリー単位でフィルタリングします。", "data": { "filter_mode": "フィルターモード" diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index ad257c3..b67f408 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -35,14 +35,14 @@ "title": "Geavanceerde Instellingen", "description": "## Inleiding\r\n### Houd de standaardinstellingen aan, tenzij u de betekenis van de volgende opties volledig begrijpt.\r\n### Besturingsmodus\r\n- Automatisch: Wanneer er een beschikbare Xiaomi-hub in het lokale netwerk is, zal Home Assistant voorrang geven aan het verzenden van besturingsopdrachten via de hub voor lokale besturing. Als er geen hub beschikbaar is, zal het proberen besturingsopdrachten te verzenden via het Xiaomi OT-protocol. Alleen als aan deze lokale besturingsvoorwaarden niet wordt voldaan, worden de opdrachten via de cloud verzonden.\r\n- Cloud: Besturingsopdrachten worden uitsluitend via de cloud verzonden.\r\n### Apparaatfiltering\r\nFilter ongewenste apparaten per familie.\r\n### Actie-debugmodus\r\nVoor methoden gedefinieerd door MIoT-Spec-V2-apparaten wordt, naast een meldingsentiteit, ook een tekstinvoerentiteit gemaakt waarmee u tijdens het debuggen besturingsopdrachten naar het apparaat kunt sturen.\r\n### Niet-standaard entiteiten verbergen\r\nVerberg entiteiten die door niet-standaard MIoT-Spec-V2-instanties worden gegenereerd en waarvan de naam begint met \"*\".", "data": { + "devices_filter": "Apparaten filteren", "ctrl_mode": "Besturingsmodus", "action_debug": "Actie-debugmodus", - "hide_non_standard_entities": "Niet-standaard entiteiten verbergen", - "devices_filter": "Apparaatfiltering" + "hide_non_standard_entities": "Niet-standaard entiteiten verbergen" } }, "devices_filter": { - "title": "Apparaatfiltering", + "title": "Apparaten filteren", "description": "## Inleiding\r\nFilter ongewenste apparaten per familie.", "data": { "filter_mode": "Filtermodus" diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index 4fcf47c..ceef23f 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -35,14 +35,14 @@ "title": "Configurações Avançadas", "description": "## Introdução\r\n### Mantenha as configurações padrão, a menos que você entenda completamente o significado das seguintes opções.\r\n### Modo de Controle\r\n- Automático: Quando houver um hub Xiaomi disponível na rede local, o Home Assistant priorizará o envio de comandos de controle através do hub para obter controle local. Se não houver hub, tentará enviar comandos de controle pelo protocolo Xiaomi OT. Somente se essas condições de controle local não forem atendidas, os comandos serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controle são enviados exclusivamente pela nuvem.\r\n### Filtragem de Dispositivos\r\nFiltre dispositivos indesejados por família.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos por dispositivos MIoT-Spec-V2, além de gerar uma entidade de notificação, será criada uma entidade de entrada de texto para que você possa enviar comandos de controle ao dispositivo durante a depuração.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOculte entidades geradas por instâncias não padrão do MIoT-Spec-V2 cujos nomes começam com \"*\".", "data": { + "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Controle", "action_debug": "Modo de Depuração de Ações", - "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão", - "devices_filter": "Filtragem de Dispositivos" + "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão" } }, "devices_filter": { - "title": "Filtragem de Dispositivos", + "title": "Filtrar Dispositivos", "description": "## Introdução\r\nFiltre dispositivos indesejados por família.", "data": { "filter_mode": "Modo de Filtro" diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index 02f883d..5784a6f 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -35,14 +35,14 @@ "title": "Opções Avançadas", "description": "## Introdução\r\n### Mantenha as configurações padrão, a menos que compreenda totalmente o significado das seguintes opções.\r\n### Modo de Controlo\r\n- Automático: Quando existir um hub Xiaomi disponível na rede local, o Home Assistant irá priorizar o envio de comandos de controlo através do hub para permitir controlo local. Se não houver hub na rede local, irá tentar enviar comandos de controlo através do protocolo Xiaomi OT. Apenas quando estas condições de controlo local não forem satisfeitas, os comandos serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controlo são enviados exclusivamente através da nuvem.\r\n### Filtragem de Dispositivos\r\nFiltre dispositivos indesejados por família.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos por dispositivos MIoT-Spec-V2, além de gerar uma entidade de notificação, também será criada uma entidade de entrada de texto para enviar comandos ao dispositivo durante a depuração.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOculte entidades geradas por instâncias não padrão do MIoT-Spec-V2 cujos nomes começam com \"*\".", "data": { + "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Controlo", "action_debug": "Modo de Depuração de Ações", - "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão", - "devices_filter": "Filtragem de Dispositivos" + "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão" } }, "devices_filter": { - "title": "Filtragem de Dispositivos", + "title": "Filtrar Dispositivos", "description": "## Introdução\r\nFiltre dispositivos indesejados por família.", "data": { "filter_mode": "Modo de Filtro" diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index 4c4fdf9..32b8def 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -35,10 +35,10 @@ "title": "Расширенные настройки", "description": "## Введение\r\n### Сохраняйте настройки по умолчанию, если вы не полностью понимаете смысл следующих опций.\r\n### Режим управления\r\n- Авто: Если в локальной сети доступен шлюз Xiaomi, Home Assistant будет в приоритете отправлять команды управления устройствами через этот шлюз, чтобы обеспечить локальное управление. При отсутствии шлюза осуществляется попытка отправить команды управления через протокол Xiaomi OT. Только при несоблюдении указанных условий локального управления команды отправляются через облако.\r\n- Облако: Команды управления отправляются исключительно через облако.\r\n### Фильтрация устройств\r\nФильтруйте ненужные устройства по семьям.\r\n### Режим отладки действий\r\nДля методов, определённых устройствами MIoT-Spec-V2, помимо сущности уведомления, будет создана сущность текстового ввода, которая позволяет отправлять команды управления устройству во время отладки.\r\n### Скрыть нестандартные сущности\r\nСкрывает сущности, созданные нестандартными экземплярами MIoT-Spec-V2, чьи имена начинаются со «*».", "data": { + "devices_filter": "Фильтрация устройств", "ctrl_mode": "Режим управления", "action_debug": "Режим отладки действий", - "hide_non_standard_entities": "Скрыть нестандартные сущности", - "devices_filter": "Фильтрация устройств" + "hide_non_standard_entities": "Скрыть нестандартные сущности" } }, "devices_filter": { diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index 1cdd7a2..732bd10 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -33,19 +33,26 @@ }, "advanced_options": { "title": "高级设置选项", - "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### 设备过滤\r\n按照家庭维度,过滤不需要的设备。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。", + "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n###筛选设备\r\n支持按照房间名称和设备类型筛选设备,同时也支持设备维度筛选。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### 设备过滤\r\n按照家庭维度,过滤不需要的设备。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。", "data": { + "devices_filter": "筛选设备", "ctrl_mode": "控制模式", "action_debug": "Action 调试模式", - "hide_non_standard_entities": "隐藏非标准生成实体", - "devices_filter": "设备过滤" + "hide_non_standard_entities": "隐藏非标准生成实体" } }, "devices_filter": { - "title": "设备过滤", - "description": "## 使用介绍\r\n按照家庭维度,过滤不需要的设备。", + "title": "筛选设备", + "description": "## 使用介绍\r\n#### 支持按照房间名称和设备类型筛选设备,同时也支持设备维度筛选。您也可以进入对应集成项【配置】页面重新筛选。", "data": { - "filter_mode": "过滤模式" + "room_filter_mode": "筛选家庭房间", + "room_list": "家庭房间", + "type_filter_mode": "筛选设备类型", + "type_list": "设备类型", + "model_filter_mode": "筛选设备型号", + "model_list": "设备型号", + "devices_filter_mode": "筛选设备", + "device_list": "设备列表" } } }, diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index c711ab2..f05dc1f 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -35,14 +35,14 @@ "title": "高級設置選項", "description": "## 使用介紹\r\n### 除非您非常清楚下列選項的含義,否則請保持默認。\r\n### 控制模式\r\n- 自動:本地區域網內存在可用的小米中樞網關時,Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。本地區域網不存在中樞時,會嘗試通過小米OT協議發送控制指令,以實現本地化控制功能。只有當上述本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令僅通過雲端發送。\r\n### 設備過濾\r\n按照家庭維度,過濾不需要的設備。\r\n### Action 調試模式\r\n對於設備 MIoT-Spec-V2 定義的方法,在生成通知實體之外,還會生成一個文本輸入框實體,您可以在調試時用它向設備發送控制指令。\r\n### 隱藏非標準生成實體\r\n隱藏名稱以“*”開頭的非標準 MIoT-Spec-V2 實例生成的實體。", "data": { + "devices_filter": "篩選設備", "ctrl_mode": "控制模式", "action_debug": "Action 調試模式", - "hide_non_standard_entities": "隱藏非標準生成實體", - "devices_filter": "設備過濾" + "hide_non_standard_entities": "隱藏非標準生成實體" } }, "devices_filter": { - "title": "設備過濾", + "title": "篩選設備", "description": "## 使用介紹\r\n按照家庭維度,過濾不需要的設備。", "data": { "filter_mode": "過濾模式" From 4e8361d18acb494b92c0d76471b6876b3ce9bb6c Mon Sep 17 00:00:00 2001 From: sworld Date: Sun, 22 Dec 2024 20:11:05 +0800 Subject: [PATCH 03/24] fix: cancel miot http timer --- custom_components/xiaomi_home/miot/miot_cloud.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/custom_components/xiaomi_home/miot/miot_cloud.py b/custom_components/xiaomi_home/miot/miot_cloud.py index 036ea57..4632a6c 100644 --- a/custom_components/xiaomi_home/miot/miot_cloud.py +++ b/custom_components/xiaomi_home/miot/miot_cloud.py @@ -254,6 +254,13 @@ def __init__( self._session = aiohttp.ClientSession(loop=self._main_loop) async def deinit_async(self) -> None: + if self._get_prop_timer: + self._get_prop_timer.cancel() + self._get_prop_timer = None + for item in self._get_prop_list.values(): + fut: asyncio.Future = item.get('fut') + fut.cancel() + self._get_prop_list.clear() if self._session and not self._session.closed: await self._session.close() From b54ec9bff45db21d510611b16d774b45e1dc255a Mon Sep 17 00:00:00 2001 From: sworld Date: Sun, 22 Dec 2024 20:11:38 +0800 Subject: [PATCH 04/24] feat: improve devices filter --- custom_components/xiaomi_home/config_flow.py | 95 +++++++++++++++++--- 1 file changed, 82 insertions(+), 13 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index 358432a..a940b1f 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -121,6 +121,7 @@ class XiaomiMihomeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): _home_selected: Optional[dict] _home_info_buffer: Optional[dict[str, str | dict[str, dict]]] _home_list: Optional[dict] + _device_list_sorted: Optional[dict] _cloud_server: Optional[str] _oauth_redirect_url: Optional[str] @@ -155,6 +156,7 @@ def __init__(self) -> None: self._home_selected = {} self._home_info_buffer = None self._home_list = None + self._device_list_sorted = None self._cloud_server = None self._oauth_redirect_url = None @@ -503,23 +505,19 @@ async def async_step_homes_select(self, user_input=None): if dev_info['home_id'] in home_selected} if not devices_list: return await self.display_homes_select_form('no_devices') - devices_list_sort = dict(sorted( + self._device_list_sorted = dict(sorted( devices_list.items(), key=lambda item: item[1].get('home_id', '')+item[1].get('room_id', ''))) + if not await self._miot_storage.save_async( domain='miot_devices', name=f'{self._uid}_{self._cloud_server}', - data=devices_list_sort): + data=self._device_list_sorted): _LOGGER.error( 'save devices async failed, %s, %s', self._uid, self._cloud_server) return await self.display_homes_select_form( 'devices_storage_failed') - if not (await self._miot_storage.update_user_config_async( - uid=self._uid, cloud_server=self._cloud_server, config={ - 'auth_info': self._auth_info - })): - raise MIoTError('miot_storage.update_user_config_async error') if user_input.get('advanced_options', False): return await self.async_step_advanced_options() return await self.config_flow_done() @@ -563,33 +561,104 @@ async def async_step_advanced_options(self, user_input: dict = None): return self.async_show_form( step_id='advanced_options', data_schema=vol.Schema({ + vol.Required('devices_filter', default=False): bool, vol.Required('ctrl_mode', default=DEFAULT_CTRL_MODE): vol.In( self._miot_i18n.translate(key='config.control_mode')), vol.Required('action_debug', default=self._action_debug): bool, vol.Required( 'hide_non_standard_entities', default=self._hide_non_standard_entities): bool, - vol.Required('devices_filter', default=False): bool, + }), last_step=False, ) async def async_step_devices_filter(self, user_input: dict = None): if user_input: + room_list_in: list = user_input.get('room_list', []) + if room_list_in: + room_filter_mode: str = user_input.get('room_filter_mode') + + type_list_in: list = user_input.get('type_list', []) + if type_list_in: + type_filter_mode: str = user_input.get('type_filter_mode') + + model_list_in: list = user_input.get('model_list', []) + if model_list_in: + model_filter_mode: str = user_input.get('model_filter_mode') + + device_list_in: list = user_input.get('device_list', []) + if device_list_in: + devices_filter_mode: str = user_input.get( + 'devices_filter_mode') + return await self.config_flow_done() + tip_devices: str = self._miot_i18n.translate( + key='config.other.devices') + tip_filter_mode: str = self._miot_i18n.translate( + key='config.filter_mode') + tip_connect_type: dict = self._miot_i18n.translate( + key='config.connect_type') + tip_without_room: str = self._miot_i18n.translate( + key='config.other.without_room') + + room_device_count: dict = {} + model_device_count: dict = {} + device_list: dict = {} + for did, info in self._device_list_sorted.items(): + device_list[did] = ( + f'{info["home_name"]} {info["room_name"]} - ' + + f'{info["name"]} - {did}') + room_device_count.setdefault(info['room_id'], 0) + room_device_count[info['room_id']] += 1 + model_device_count.setdefault(info['model'], 0) + model_device_count[info['model']] += 1 + + model_list: dict = {} + for model, count in model_device_count.items(): + model_list[model] = f'{model} [ {count}{tip_devices} ]' + + room_list: dict = {} + for home_id, home_info in self._home_selected.items(): + for room_id, room_name in home_info['room_info'].items(): + if room_id not in room_device_count: + continue + room_list[room_id] = ( + f'{home_info["home_name"]} {room_name}' + f' [ {room_device_count[room_id]}{tip_devices} ]') + if home_id in room_device_count: + room_list[home_id] = ( + f'{home_info["home_name"]} {tip_without_room}' + f' [ {room_device_count[home_id]}{tip_devices} ]') + return self.async_show_form( step_id='devices_filter', data_schema=vol.Schema({ - vol.Required('filter_mode', default='include'): vol.In( - self._miot_i18n.translate(key='config.filter_mode')), - vol.Required('filter_mode', default='include'): vol.In( - self._miot_i18n.translate(key='config.filter_mode')) + vol.Required('room_filter_mode', default='exclude'): + vol.In(tip_filter_mode), + vol.Optional('room_list'): cv.multi_select(room_list), + vol.Required('type_filter_mode', default='exclude'): + vol.In(tip_filter_mode), + vol.Optional('type_list'): cv.multi_select(tip_connect_type), + vol.Required('model_filter_mode', default='exclude'): + vol.In(tip_filter_mode), + vol.Optional('model_list'): cv.multi_select(dict(sorted( + model_list.items(), key=lambda item: item[0]))), + vol.Required('devices_filter_mode', default='exclude'): + vol.In(tip_filter_mode), + vol.Optional('device_list'): cv.multi_select(dict(sorted( + device_list.items(), key=lambda device: device[1]))) }), - last_step=False, + last_step=False ) async def config_flow_done(self): + if not (await self._miot_storage.update_user_config_async( + uid=self._uid, cloud_server=self._cloud_server, config={ + 'auth_info': self._auth_info + })): + raise MIoTError('miot_storage.update_user_config_async error') return self.async_create_entry( title=( f'{self._nick_name}: {self._uid} ' From e0a0b6d22e585ccef1bcb36d64f21a88b4f21b24 Mon Sep 17 00:00:00 2001 From: sworld Date: Sun, 22 Dec 2024 20:12:38 +0800 Subject: [PATCH 05/24] doc: update translations/de --- custom_components/xiaomi_home/translations/de.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index 05d8293..ad1f045 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -35,14 +35,14 @@ "title": "Erweiterte Einstellungen", "description": "## Einführung\r\n### Behalten Sie die Standardeinstellungen bei, es sei denn, Sie verstehen die folgenden Optionen vollständig.\r\n### Steuerungsmodus\r\n- Automatisch: Wenn ein verfügbarer Xiaomi-Hub im lokalen Netzwerk vorhanden ist, priorisiert Home Assistant das Senden von Steuerbefehlen über den Hub, um eine lokale Steuerung zu ermöglichen. Wenn kein Hub vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden. Nur wenn diese Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Befehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden ausschließlich über die Cloud gesendet.\r\n### Gerätefilterung\r\nFiltern Sie unerwünschte Geräte nach Familien.\r\n### Action-Debug-Modus\r\nFür Methoden, die von MIoT-Spec-V2-Geräten definiert werden, wird neben der Benachrichtigungsentität auch eine Texteingabe-Entität erstellt, mit der Sie während des Debuggens Steuerbefehle an das Gerät senden können.\r\n### Nicht standardmäßige Entitäten ausblenden\r\nBlendet Entitäten aus, die von nicht-standardmäßigen MIoT-Spec-V2-Instanzen generiert werden und deren Name mit „*“ beginnt.", "data": { - "devices_filter": "Gerätefilterung", + "devices_filter": "Geräte filtern", "ctrl_mode": "Steuerungsmodus", "action_debug": "Action-Debug-Modus", "hide_non_standard_entities": "Nicht standardmäßige Entitäten ausblenden" } }, "devices_filter": { - "title": "Gerätefilterung", + "title": "Geräte filtern", "description": "## Einführung\r\nFiltern Sie unerwünschte Geräte nach Familien.", "data": { "filter_mode": "Filtermodus" From 96b508409236f49ef5336f48e0e9be5e5f7b8261 Mon Sep 17 00:00:00 2001 From: sworld Date: Sun, 22 Dec 2024 22:23:50 +0800 Subject: [PATCH 06/24] fix: i18n type error --- custom_components/xiaomi_home/miot/miot_i18n.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/custom_components/xiaomi_home/miot/miot_i18n.py b/custom_components/xiaomi_home/miot/miot_i18n.py index 5f11694..152bc08 100644 --- a/custom_components/xiaomi_home/miot/miot_i18n.py +++ b/custom_components/xiaomi_home/miot/miot_i18n.py @@ -71,7 +71,7 @@ def __init__( ) -> None: self._main_loop = loop or asyncio.get_event_loop() self._lang = lang - self._data = None + self._data = {} async def init_async(self) -> None: if self._data: @@ -94,7 +94,7 @@ async def init_async(self) -> None: self._data = data async def deinit_async(self) -> None: - self._data = None + self._data = {} def translate( self, key: str, replace: Optional[dict[str, str]] = None From 4e3fcc9705b8d46a067793089d9b2734e93b5612 Mon Sep 17 00:00:00 2001 From: sworld Date: Sun, 22 Dec 2024 22:33:07 +0800 Subject: [PATCH 07/24] feat: config flow support device filter --- custom_components/xiaomi_home/config_flow.py | 82 ++++++++++++++++--- .../xiaomi_home/translations/de.json | 13 ++- .../xiaomi_home/translations/en.json | 11 ++- .../xiaomi_home/translations/es.json | 11 ++- .../xiaomi_home/translations/fr.json | 11 ++- .../xiaomi_home/translations/ja.json | 11 ++- .../xiaomi_home/translations/nl.json | 11 ++- .../xiaomi_home/translations/pt-BR.json | 11 ++- .../xiaomi_home/translations/pt.json | 11 ++- .../xiaomi_home/translations/ru.json | 11 ++- .../xiaomi_home/translations/zh-Hans.json | 2 +- .../xiaomi_home/translations/zh-Hant.json | 11 ++- 12 files changed, 164 insertions(+), 32 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index a940b1f..9f54207 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -121,7 +121,8 @@ class XiaomiMihomeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): _home_selected: Optional[dict] _home_info_buffer: Optional[dict[str, str | dict[str, dict]]] _home_list: Optional[dict] - _device_list_sorted: Optional[dict] + _device_list_sorted: dict + _device_list_filter: dict _cloud_server: Optional[str] _oauth_redirect_url: Optional[str] @@ -573,25 +574,86 @@ async def async_step_advanced_options(self, user_input: dict = None): last_step=False, ) - async def async_step_devices_filter(self, user_input: dict = None): + async def async_step_devices_filter( + self, user_input: Optional[dict] = None + ): if user_input: + # Room filter room_list_in: list = user_input.get('room_list', []) if room_list_in: - room_filter_mode: str = user_input.get('room_filter_mode') - + room_filter_mode: str = user_input.get( + 'room_filter_mode', None) + if room_filter_mode == 'exclude': + self._device_list_filter = { + did: dev_info + for did, dev_info in self._device_list_sorted.items() + if dev_info['room_id'] not in room_list_in} + elif room_filter_mode == 'include': + self._device_list_filter = { + did: dev_info + for did, dev_info in self._device_list_sorted.items() + if dev_info['room_id'] in room_list_in} + # Type filter type_list_in: list = user_input.get('type_list', []) if type_list_in: - type_filter_mode: str = user_input.get('type_filter_mode') - + type_filter_mode: str = user_input.get( + 'type_filter_mode', None) + if type_filter_mode == 'exclude': + self._device_list_filter = { + did: dev_info + for did, dev_info in self._device_list_sorted.items() + if dev_info['connect_type'] not in type_list_in} + elif type_filter_mode == 'include': + self._device_list_filter = { + did: dev_info + for did, dev_info in self._device_list_sorted.items() + if dev_info['connect_type'] in type_list_in} + # Model filter model_list_in: list = user_input.get('model_list', []) if model_list_in: - model_filter_mode: str = user_input.get('model_filter_mode') - + model_filter_mode: str = user_input.get( + 'model_filter_mode', None) + if model_filter_mode == 'exclude': + self._device_list_filter = { + did: dev_info + for did, dev_info in self._device_list_sorted.items() + if dev_info['model'] not in model_list_in} + elif model_filter_mode == 'include': + self._device_list_filter = { + did: dev_info + for did, dev_info in self._device_list_sorted.items() + if dev_info['model'] in model_list_in} + # Device filter device_list_in: list = user_input.get('device_list', []) if device_list_in: devices_filter_mode: str = user_input.get( - 'devices_filter_mode') - + 'devices_filter_mode', None) + if devices_filter_mode == 'exclude': + self._device_list_filter = { + did: dev_info + for did, dev_info in self._device_list_sorted.items() + if did not in device_list_in} + elif devices_filter_mode == 'include': + self._device_list_filter = { + did: dev_info + for did, dev_info in self._device_list_sorted.items() + if did in device_list_in} + else: + raise MIoTError('invalid devices_filter_mode') + self._device_list_sorted = dict(sorted( + self._device_list_filter.items(), key=lambda item: + item[1].get('home_id', '')+item[1].get('room_id', ''))) + if not await self._miot_storage.save_async( + domain='miot_devices', + name=f'{self._uid}_{self._cloud_server}', + data=self._device_list_sorted): + _LOGGER.error( + 'save devices async failed, %s, %s', + self._uid, self._cloud_server) + raise AbortFlow( + reason='config_flow_error', + description_placeholders={ + 'error': 'save devices failed'}) return await self.config_flow_done() tip_devices: str = self._miot_i18n.translate( diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index ad1f045..2342d24 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Erweiterte Einstellungen", - "description": "## Einführung\r\n### Behalten Sie die Standardeinstellungen bei, es sei denn, Sie verstehen die folgenden Optionen vollständig.\r\n### Steuerungsmodus\r\n- Automatisch: Wenn ein verfügbarer Xiaomi-Hub im lokalen Netzwerk vorhanden ist, priorisiert Home Assistant das Senden von Steuerbefehlen über den Hub, um eine lokale Steuerung zu ermöglichen. Wenn kein Hub vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden. Nur wenn diese Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Befehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden ausschließlich über die Cloud gesendet.\r\n### Gerätefilterung\r\nFiltern Sie unerwünschte Geräte nach Familien.\r\n### Action-Debug-Modus\r\nFür Methoden, die von MIoT-Spec-V2-Geräten definiert werden, wird neben der Benachrichtigungsentität auch eine Texteingabe-Entität erstellt, mit der Sie während des Debuggens Steuerbefehle an das Gerät senden können.\r\n### Nicht standardmäßige Entitäten ausblenden\r\nBlendet Entitäten aus, die von nicht-standardmäßigen MIoT-Spec-V2-Instanzen generiert werden und deren Name mit „*“ beginnt.", + "description": "## Gebrauchsanweisung\r\n### Behalten Sie die Standardeinstellungen bei, es sei denn, Sie verstehen die folgenden Optionen vollständig.\r\n### Steuerungsmodus\r\n- Automatisch: Wenn ein verfügbarer Xiaomi-Hub im lokalen Netzwerk vorhanden ist, priorisiert Home Assistant das Senden von Steuerbefehlen über den Hub, um eine lokale Steuerung zu ermöglichen. Wenn kein Hub vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden. Nur wenn diese Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Befehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden ausschließlich über die Cloud gesendet.\r\n### Gerätefilterung\r\nFiltern Sie unerwünschte Geräte nach Familien.\r\n### Action-Debug-Modus\r\nFür Methoden, die von MIoT-Spec-V2-Geräten definiert werden, wird neben der Benachrichtigungsentität auch eine Texteingabe-Entität erstellt, mit der Sie während des Debuggens Steuerbefehle an das Gerät senden können.\r\n### Nicht standardmäßige Entitäten ausblenden\r\nBlendet Entitäten aus, die von nicht-standardmäßigen MIoT-Spec-V2-Instanzen generiert werden und deren Name mit „*“ beginnt.", "data": { "devices_filter": "Geräte filtern", "ctrl_mode": "Steuerungsmodus", @@ -43,9 +43,16 @@ }, "devices_filter": { "title": "Geräte filtern", - "description": "## Einführung\r\nFiltern Sie unerwünschte Geräte nach Familien.", + "description": "## Gebrauchsanweisung\r\n- Unterstützt das Filtern von Geräten nach Raumnamen und Gerätetypen sowie das Filtern nach Gerätedimensionen.\r\n- Sie können auch die entsprechende Integrationsoption \"Konfiguration> Geräteliste aktualisieren\" aufrufen, um die Filterung erneut durchzuführen.", "data": { - "filter_mode": "Filtermodus" + "room_filter_mode": "Familienraum filtern", + "room_list": "Familienraum", + "type_filter_mode": "Gerätetyp filtern", + "type_list": "Gerätetyp", + "model_filter_mode": "Gerätemodell filtern", + "model_list": "Gerätemodell", + "devices_filter_mode": "Geräte filtern", + "device_list": "Geräteliste" } } }, diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index 7e1dcd8..391bd47 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -43,9 +43,16 @@ }, "devices_filter": { "title": "Filter Devices", - "description": "## Introduction\r\nFilter out unwanted devices by family.", + "description": "## Introduction\r\n- Supports filtering devices by room name and device type, and also supports device dimension filtering.\r\n- You can also re-filter on the corresponding integration page [Configuration>Update Device List].", "data": { - "filter_mode": "Filter Mode" + "room_filter_mode": "Filter Family Rooms", + "room_list": "Family Rooms", + "type_filter_mode": "Filter Device Type", + "type_list": "Device Type", + "model_filter_mode": "Filter Device Model", + "model_list": "Device Model", + "devices_filter_mode": "Filter Devices", + "device_list": "Device List" } } }, diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index 4adc364..27b9fdc 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -43,9 +43,16 @@ }, "devices_filter": { "title": "Filtrar Dispositivos", - "description": "## Introducción\r\nFiltre dispositivos no deseados por familia.", + "description": "## Introducción\r\n- Admite la filtración de dispositivos por nombre de habitación y tipo de dispositivo, y también admite la filtración por familia.\r\n- También puede volver a filtrar en la página correspondiente de la integración [Configuración>Actualizar lista de dispositivos].", "data": { - "filter_mode": "Modo de Filtrado" + "room_filter_mode": "Filtrar Habitaciones de la Familia", + "room_list": "Habitaciones de la Familia", + "type_filter_mode": "Filtrar Tipo de Dispositivo", + "type_list": "Tipo de Dispositivo", + "model_filter_mode": "Filtrar Modelo de Dispositivo", + "model_list": "Modelo de Dispositivo", + "devices_filter_mode": "Filtrar Dispositivos", + "device_list": "Lista de Dispositivos" } } }, diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index 362968c..ef33855 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -43,9 +43,16 @@ }, "devices_filter": { "title": "Filtrer les Appareils", - "description": "## Introduction\r\nFiltrez les appareils indésirables en fonction de la famille.", + "description": "## Introduction\r\n- Prend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n- Vous pouvez également accéder à la page de filtrage correspondante de l'intégration [Configuration> Mettre à jour la liste des appareils] pour refiltrer.", "data": { - "filter_mode": "Mode de Filtrage" + "room_filter_mode": "Filtrer les Pièces", + "room_list": "Pièces", + "type_filter_mode": "Filtrer les Types d'Appareils", + "type_list": "Types d'Appareils", + "model_filter_mode": "Filtrer les Modèles d'Appareils", + "model_list": "Modèles d'Appareils", + "devices_filter_mode": "Filtrer les Appareils", + "device_list": "Liste des Appareils" } } }, diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index 8c343c8..88a75c5 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -43,9 +43,16 @@ }, "devices_filter": { "title": "デバイスをフィルタリング", - "description": "## 使い方\r\n不要なデバイスをファミリー単位でフィルタリングします。", + "description": "## 紹介\r\n- 部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n- 対応する統合項目【設定>デバイスリストの更新】ページに移動して再度フィルタリングすることもできます。", "data": { - "filter_mode": "フィルターモード" + "room_filter_mode": "家族の部屋をフィルタリング", + "room_list": "家族の部屋", + "type_filter_mode": "デバイスタイプをフィルタリング", + "type_list": "デバイスタイプ", + "model_filter_mode": "デバイスモデルをフィルタリング", + "model_list": "デバイスモデル", + "devices_filter_mode": "デバイスをフィルタリング", + "device_list": "デバイスリスト" } } }, diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index b67f408..d476be2 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -43,9 +43,16 @@ }, "devices_filter": { "title": "Apparaten filteren", - "description": "## Inleiding\r\nFilter ongewenste apparaten per familie.", + "description": "## Inleiding\r\n- Ondersteunt het filteren van apparaten op basis van kamer- en apparaattypen, en ondersteunt ook apparaatdimensiefiltering.\r\n- U kunt ook naar de overeenkomstige integratie-item [Configuratie>Apparaatlijst bijwerken] pagina gaan om opnieuw te filteren.", "data": { - "filter_mode": "Filtermodus" + "room_filter_mode": "Kamerfiltermodus", + "room_list": "Kamers", + "type_filter_mode": "Apparaattypen filteren", + "type_list": "Apparaattypen", + "model_filter_mode": "Apparaatmodel filteren", + "model_list": "Apparaatmodellen", + "devices_filter_mode": "Apparaten filteren", + "device_list": "Apparaatlijst" } } }, diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index ceef23f..7d0e237 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -43,9 +43,16 @@ }, "devices_filter": { "title": "Filtrar Dispositivos", - "description": "## Introdução\r\nFiltre dispositivos indesejados por família.", + "description": "## Introdução\r\n- Suporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n- Você também pode acessar a página correspondente da integração [Configuração>Atualizar Lista de Dispositivos] para refiltrar.", "data": { - "filter_mode": "Modo de Filtro" + "room_filter_mode": "Filtrar por Sala", + "room_list": "Salas", + "type_filter_mode": "Filtrar por Tipo de Dispositivo", + "type_list": "Tipos de Dispositivo", + "model_filter_mode": "Filtrar por Modelo de Dispositivo", + "model_list": "Modelos de Dispositivo", + "devices_filter_mode": "Filtrar Dispositivos", + "device_list": "Lista de Dispositivos" } } }, diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index 5784a6f..aef3aa5 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -43,9 +43,16 @@ }, "devices_filter": { "title": "Filtrar Dispositivos", - "description": "## Introdução\r\nFiltre dispositivos indesejados por família.", + "description": "## Introdução\r\n- Suporta a filtragem de dispositivos por nome de sala e tipo de dispositivo, bem como a filtragem por família.\r\n- Pode também aceder à página de configuração correspondente da integração [Configuração > Atualizar Lista de Dispositivos] para refazer a filtragem.", "data": { - "filter_mode": "Modo de Filtro" + "room_filter_mode": "Filtrar por Sala", + "room_list": "Salas", + "type_filter_mode": "Filtrar por Tipo de Dispositivo", + "type_list": "Tipos de Dispositivo", + "model_filter_mode": "Filtrar por Modelo de Dispositivo", + "model_list": "Modelos de Dispositivo", + "devices_filter_mode": "Filtrar Dispositivos", + "device_list": "Lista de Dispositivos" } } }, diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index 32b8def..e26f80e 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -43,9 +43,16 @@ }, "devices_filter": { "title": "Фильтрация устройств", - "description": "## Введение\r\nФильтруйте ненужные устройства по семьям.", + "description": "## Введение\r\n- Поддерживает фильтрацию устройств по названию комнаты и типу устройства, а также фильтрацию по уровню устройства.\r\n- Вы также можете перейти на соответствующую страницу интеграции [Настройки> Обновить список устройств], чтобы перефильтровать.", "data": { - "filter_mode": "Режим фильтрации" + "room_filter_mode": "Фильтрация по комнатам семьи", + "room_list": "Комнаты семьи", + "type_filter_mode": "Фильтрация по типу устройства", + "type_list": "Типы устройств", + "model_filter_mode": "Фильтрация по модели устройства", + "model_list": "Модели устройств", + "devices_filter_mode": "Фильтрация устройств", + "device_list": "Список устройств" } } }, diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index 732bd10..2d85447 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -43,7 +43,7 @@ }, "devices_filter": { "title": "筛选设备", - "description": "## 使用介绍\r\n#### 支持按照房间名称和设备类型筛选设备,同时也支持设备维度筛选。您也可以进入对应集成项【配置】页面重新筛选。", + "description": "## 使用介绍\r\n- 支持按照房间名称和设备类型筛选设备,同时也支持设备维度筛选。\r\n- 您也可以进入对应集成项【配置>更新设备列表】页面重新筛选。", "data": { "room_filter_mode": "筛选家庭房间", "room_list": "家庭房间", diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index f05dc1f..3dbc33f 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -43,9 +43,16 @@ }, "devices_filter": { "title": "篩選設備", - "description": "## 使用介紹\r\n按照家庭維度,過濾不需要的設備。", + "description": "## 使用介紹\r\n- 支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n- 您也可以進入對應集成項【配置>更新設備列表】頁面重新篩選。", "data": { - "filter_mode": "過濾模式" + "room_filter_mode": "篩選家庭房間", + "room_list": "家庭房間", + "type_filter_mode": "篩選設備類型", + "type_list": "設備類型", + "model_filter_mode": "篩選設備型號", + "model_list": "設備型號", + "devices_filter_mode": "篩選設備", + "device_list": "設備列表" } } }, From 8c0461e88c7737e072985aa7e7fb3f5622f3091c Mon Sep 17 00:00:00 2001 From: sworld Date: Sun, 22 Dec 2024 22:56:25 +0800 Subject: [PATCH 08/24] fix: fix mdns type error --- .../xiaomi_home/miot/miot_mdns.py | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/custom_components/xiaomi_home/miot/miot_mdns.py b/custom_components/xiaomi_home/miot/miot_mdns.py index 4f13649..a6b3002 100644 --- a/custom_components/xiaomi_home/miot/miot_mdns.py +++ b/custom_components/xiaomi_home/miot/miot_mdns.py @@ -50,7 +50,7 @@ import binascii import copy from enum import Enum -from typing import Callable, Optional +from typing import Callable, Coroutine, Optional import logging from zeroconf import ( @@ -98,8 +98,8 @@ class MipsServiceData: def __init__(self, service_info: AsyncServiceInfo) -> None: if service_info is None: raise MipsServiceError('invalid params') - properties = service_info.decoded_properties - if properties is None: + properties: dict = service_info.decoded_properties + if not properties: raise MipsServiceError('invalid service properties') self.profile = properties.get('profile', None) if self.profile is None: @@ -111,9 +111,11 @@ def __init__(self, service_info: AsyncServiceInfo) -> None: if not self.addresses: raise MipsServiceError('invalid addresses') self.addresses.sort() + if not service_info.port: + raise MipsServiceError('invalid port') self.port = service_info.port self.type = service_info.type - self.server = service_info.server + self.server = service_info.server or '' # Parse profile self.did = str(int.from_bytes(self.profile_bin[1:9])) self.group_id = binascii.hexlify( @@ -150,8 +152,8 @@ class MipsService: _aio_browser: AsyncServiceBrowser _services: dict[str, dict] # key = (key, group_id) - _sub_list: dict[(str, str), Callable[[ - str, MipsServiceState, dict], asyncio.Future]] + _sub_list: dict[tuple[str, str], Callable[[ + str, MipsServiceState, dict], Coroutine]] def __init__( self, aiozc: AsyncZeroconf, @@ -159,7 +161,6 @@ def __init__( ) -> None: self._aiozc = aiozc self._main_loop = loop or asyncio.get_running_loop() - self._aio_browser = None self._services = {} self._sub_list = {} @@ -207,7 +208,7 @@ def get_services(self, group_id: Optional[str] = None) -> dict[str, dict]: def sub_service_change( self, key: str, group_id: str, - handler: Callable[[str, MipsServiceState, dict], asyncio.Future] + handler: Callable[[str, MipsServiceState, dict], Coroutine] ) -> None: if key is None or group_id is None or handler is None: raise MipsServiceError('invalid params') @@ -232,7 +233,7 @@ def __on_service_state_change( for item in list(self._services.values()): if item['name'] != name: continue - service_data = self._services.pop(item['group_id'], None) + service_data = self._services.pop(item['group_id'], {}) self.__call_service_change( state=MipsServiceState.REMOVED, data=service_data) return @@ -275,10 +276,10 @@ async def __request_service_info_async( _LOGGER.error('invalid mips service, %s, %s', error, info) def __call_service_change( - self, state: MipsServiceState, data: dict = None + self, state: MipsServiceState, data: dict ) -> None: _LOGGER.info('call service change, %s, %s', state, data) for keys in list(self._sub_list.keys()): - if keys[1] in [data['group_id'], '*']: + if keys[1] in [data.get('group_id', None), '*']: self._main_loop.create_task( self._sub_list[keys](data['group_id'], state, data)) From ff5e4c7ab1449be014bc7d67c9a29e47d16c984c Mon Sep 17 00:00:00 2001 From: sworld Date: Sun, 22 Dec 2024 23:40:45 +0800 Subject: [PATCH 09/24] fix: fix miot client i18n logic --- custom_components/xiaomi_home/miot/miot_client.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/custom_components/xiaomi_home/miot/miot_client.py b/custom_components/xiaomi_home/miot/miot_client.py index da8e2b6..1346b63 100644 --- a/custom_components/xiaomi_home/miot/miot_client.py +++ b/custom_components/xiaomi_home/miot/miot_client.py @@ -239,14 +239,14 @@ async def init_async(self) -> None: # Integration need to be add again raise MIoTClientError('load_user_config_async error') _LOGGER.debug('user config, %s', json.dumps(self._user_config)) - # Load cache device list - await self.__load_cache_device_async() # MIoT i18n client self._i18n = MIoTI18n( lang=self._entry_data.get( 'integration_language', DEFAULT_INTEGRATION_LANGUAGE), loop=self._main_loop) await self._i18n.init_async() + # Load cache device list + await self.__load_cache_device_async() # MIoT oauth client instance self._oauth = MIoTOauthClient( client_id=OAUTH2_CLIENT_ID, From 23cb4bf7433bac3a2e9cda6b8cb705c6fe1fe1df Mon Sep 17 00:00:00 2001 From: sworld Date: Mon, 23 Dec 2024 00:03:55 +0800 Subject: [PATCH 10/24] feat: add connect type --- custom_components/xiaomi_home/config_flow.py | 32 ++++++++++++-------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index 9f54207..46b6a64 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -423,7 +423,7 @@ async def __check_oauth_async(self) -> None: home_info['central_did'] = mips_list[group_id].get('did', None) home_list[home_id] = ( f'{home_info["home_name"]} ' - f'[ {len(dev_list)} {tip_devices}{tip_central} ]') + f'[ {len(dev_list)} {tip_devices} {tip_central} ]') self._home_list = dict(sorted(home_list.items())) @@ -658,15 +658,16 @@ async def async_step_devices_filter( tip_devices: str = self._miot_i18n.translate( key='config.other.devices') - tip_filter_mode: str = self._miot_i18n.translate( - key='config.filter_mode') - tip_connect_type: dict = self._miot_i18n.translate( - key='config.connect_type') tip_without_room: str = self._miot_i18n.translate( key='config.other.without_room') + trans_filter_mode: dict = self._miot_i18n.translate( + key='config.filter_mode') + trans_connect_type: dict = self._miot_i18n.translate( + key='config.connect_type') room_device_count: dict = {} model_device_count: dict = {} + connect_type_count: dict = {} device_list: dict = {} for did, info in self._device_list_sorted.items(): device_list[did] = ( @@ -676,10 +677,17 @@ async def async_step_devices_filter( room_device_count[info['room_id']] += 1 model_device_count.setdefault(info['model'], 0) model_device_count[info['model']] += 1 + connect_type_count.setdefault(str(info['connect_type']), 0) + connect_type_count[str(info['connect_type'])] += 1 model_list: dict = {} for model, count in model_device_count.items(): - model_list[model] = f'{model} [ {count}{tip_devices} ]' + model_list[model] = f'{model} [ {count} {tip_devices} ]' + + type_list: dict = { + k: f'{trans_connect_type.get(k, f"Connect Type ({k})")} ' + f'[ {v} {tip_devices} ]' + for k, v in connect_type_count.items()} room_list: dict = {} for home_id, home_info in self._home_selected.items(): @@ -698,17 +706,17 @@ async def async_step_devices_filter( step_id='devices_filter', data_schema=vol.Schema({ vol.Required('room_filter_mode', default='exclude'): - vol.In(tip_filter_mode), + vol.In(trans_filter_mode), vol.Optional('room_list'): cv.multi_select(room_list), vol.Required('type_filter_mode', default='exclude'): - vol.In(tip_filter_mode), - vol.Optional('type_list'): cv.multi_select(tip_connect_type), + vol.In(trans_filter_mode), + vol.Optional('type_list'): cv.multi_select(type_list), vol.Required('model_filter_mode', default='exclude'): - vol.In(tip_filter_mode), + vol.In(trans_filter_mode), vol.Optional('model_list'): cv.multi_select(dict(sorted( model_list.items(), key=lambda item: item[0]))), vol.Required('devices_filter_mode', default='exclude'): - vol.In(tip_filter_mode), + vol.In(trans_filter_mode), vol.Optional('device_list'): cv.multi_select(dict(sorted( device_list.items(), key=lambda device: device[1]))) }), @@ -1183,7 +1191,7 @@ async def async_step_homes_select(self, user_input=None): 'did', None) home_list[home_id] = ( f'{home_info["home_name"]} ' - f'[ {len(did_list)} {tip_devices}{tip_central} ]') + f'[ {len(did_list)} {tip_devices} {tip_central} ]') # Remove deleted item self._home_selected_list = [ home_id for home_id in self._home_selected_list From f93c3302b334aa461ebbfedd552e680e171d5efe Mon Sep 17 00:00:00 2001 From: topsworld Date: Mon, 23 Dec 2024 09:50:05 +0800 Subject: [PATCH 11/24] doc: update translations and i18n --- .../xiaomi_home/miot/i18n/de.json | 26 ++++++++++++++++++ .../xiaomi_home/miot/i18n/en.json | 26 ++++++++++++++++++ .../xiaomi_home/miot/i18n/es.json | 26 ++++++++++++++++++ .../xiaomi_home/miot/i18n/fr.json | 26 ++++++++++++++++++ .../xiaomi_home/miot/i18n/ja.json | 26 ++++++++++++++++++ .../xiaomi_home/miot/i18n/nl.json | 26 ++++++++++++++++++ .../xiaomi_home/miot/i18n/pt-BR.json | 26 ++++++++++++++++++ .../xiaomi_home/miot/i18n/pt.json | 26 ++++++++++++++++++ .../xiaomi_home/miot/i18n/ru.json | 26 ++++++++++++++++++ .../xiaomi_home/miot/i18n/zh-Hans.json | 27 ++++++++++++++++--- .../xiaomi_home/miot/i18n/zh-Hant.json | 26 ++++++++++++++++++ .../xiaomi_home/translations/de.json | 2 +- .../xiaomi_home/translations/en.json | 6 ++--- .../xiaomi_home/translations/es.json | 2 +- .../xiaomi_home/translations/fr.json | 2 +- .../xiaomi_home/translations/ja.json | 2 +- .../xiaomi_home/translations/nl.json | 2 +- .../xiaomi_home/translations/pt-BR.json | 2 +- .../xiaomi_home/translations/pt.json | 2 +- .../xiaomi_home/translations/ru.json | 2 +- .../xiaomi_home/translations/zh-Hans.json | 6 ++--- .../xiaomi_home/translations/zh-Hant.json | 6 ++--- 22 files changed, 301 insertions(+), 20 deletions(-) diff --git a/custom_components/xiaomi_home/miot/i18n/de.json b/custom_components/xiaomi_home/miot/i18n/de.json index 66ba583..78005a6 100644 --- a/custom_components/xiaomi_home/miot/i18n/de.json +++ b/custom_components/xiaomi_home/miot/i18n/de.json @@ -13,6 +13,32 @@ "exclude": "ausschließen", "include": "einschließen" }, + "connect_type": { + "0": "WiFi", + "1": "yunyi-Gerät", + "2": "Cloud-Gerät", + "3": "ZigBee", + "4": "webSocket", + "5": "virtuelles Gerät", + "6": "BLE", + "7": "lokaler AP", + "8": "WiFi+BLE", + "9": "andere", + "10": "Funktions-Plug-in", + "11": "Zellnetz", + "12": "Kabel", + "13": "NB-IoT", + "14": "Drittanbieter-Cloud-Zugriff", + "15": "Infrarot-Fernbedienungsgerät", + "16": "BLE-Mesh", + "17": "virtuelle Gerätegruppe", + "18": "Gateway-Untergerät", + "19": "Sicherheitsstufe Gateway-Untergerät", + "22": "PLC", + "23": "nur Kabel", + "24": "Matter", + "25": "WiFi+Zellnetz" + }, "room_name_rule": { "none": "nicht synchronisieren", "home_room": "Hausname und Raumname (Xiaomi Home Schlafzimmer)", diff --git a/custom_components/xiaomi_home/miot/i18n/en.json b/custom_components/xiaomi_home/miot/i18n/en.json index b10a1f3..f79a20e 100644 --- a/custom_components/xiaomi_home/miot/i18n/en.json +++ b/custom_components/xiaomi_home/miot/i18n/en.json @@ -13,6 +13,32 @@ "exclude": "Exclude", "include": "Include" }, + "connect_type": { + "0": "WiFi", + "1": "yunyi device", + "2": "Cloud device", + "3": "ZigBee", + "4": "webSocket", + "5": "Virtual device", + "6": "BLE", + "7": "Local AP", + "8": "WiFi+BLE", + "9": "Other", + "10": "Function plug-in", + "11": "Cellular network", + "12": "Cable", + "13": "NB-IoT", + "14": "Third-party cloud access", + "15": "Infrared remote control device", + "16": "BLE-Mesh", + "17": "Virtual device group", + "18": "Gateway sub-device", + "19": "Security level gateway sub-device", + "22": "PLC", + "23": "Cable only", + "24": "Matter", + "25": "WiFi+Cellular network" + }, "room_name_rule": { "none": "Do not synchronize", "home_room": "Home Name and Room Name (Xiaomi Home Bedroom)", diff --git a/custom_components/xiaomi_home/miot/i18n/es.json b/custom_components/xiaomi_home/miot/i18n/es.json index e87e86f..b94c950 100644 --- a/custom_components/xiaomi_home/miot/i18n/es.json +++ b/custom_components/xiaomi_home/miot/i18n/es.json @@ -13,6 +13,32 @@ "exclude": "excluir", "include": "incluir" }, + "connect_type": { + "0": "WiFi", + "1": "dispositivo yunyi", + "2": "dispositivo de nube", + "3": "ZigBee", + "4": "webSocket", + "5": "dispositivo virtual", + "6": "BLE", + "7": "AP local", + "8": "WiFi+BLE", + "9": "otro", + "10": "complemento de función", + "11": "red celular", + "12": "cable", + "13": "NB-IoT", + "14": "acceso a la nube de terceros", + "15": "dispositivo de control remoto infrarrojo", + "16": "BLE-Mesh", + "17": "grupo de dispositivos virtuales", + "18": "subdispositivo de puerta de enlace", + "19": "subdispositivo de puerta de enlace de nivel de seguridad", + "22": "PLC", + "23": "solo cable", + "24": "Matter", + "25": "WiFi+red celular" + }, "room_name_rule": { "none": "no sincronizar", "home_room": "nombre de la casa y nombre de la habitación (Xiaomi Home Dormitorio)", diff --git a/custom_components/xiaomi_home/miot/i18n/fr.json b/custom_components/xiaomi_home/miot/i18n/fr.json index 0e6945d..dbe481f 100644 --- a/custom_components/xiaomi_home/miot/i18n/fr.json +++ b/custom_components/xiaomi_home/miot/i18n/fr.json @@ -13,6 +13,32 @@ "exclude": "exclure", "include": "inclure" }, + "connect_type": { + "0": "WiFi", + "1": "appareil yunyi", + "2": "appareil cloud", + "3": "ZigBee", + "4": "webSocket", + "5": "appareil virtuel", + "6": "BLE", + "7": "AP local", + "8": "WiFi+BLE", + "9": "autre", + "10": "plug-in de fonction", + "11": "réseau cellulaire", + "12": "câble", + "13": "NB-IoT", + "14": "accès cloud tiers", + "15": "appareil de télécommande infrarouge", + "16": "BLE-Mesh", + "17": "groupe d'appareils virtuels", + "18": "sous-appareil de passerelle", + "19": "niveau de sécurité sous-appareil de passerelle", + "22": "PLC", + "23": "câble uniquement", + "24": "Matter", + "25": "WiFi+réseau cellulaire" + }, "room_name_rule": { "none": "ne pas synchroniser", "home_room": "nom de la maison et nom de la pièce (Xiaomi Home Chambre)", diff --git a/custom_components/xiaomi_home/miot/i18n/ja.json b/custom_components/xiaomi_home/miot/i18n/ja.json index 70b1477..529e05e 100644 --- a/custom_components/xiaomi_home/miot/i18n/ja.json +++ b/custom_components/xiaomi_home/miot/i18n/ja.json @@ -13,6 +13,32 @@ "exclude": "除外", "include": "含む" }, + "connect_type": { + "0": "WiFi", + "1": "yunyiデバイス", + "2": "クラウドデバイス", + "3": "ZigBee", + "4": "webSocket", + "5": "仮想デバイス", + "6": "BLE", + "7": "ローカルAP", + "8": "WiFi+BLE", + "9": "その他", + "10": "機能プラグイン", + "11": "セルラーネットワーク", + "12": "ケーブル", + "13": "NB-IoT", + "14": "サードパーティクラウドアクセス", + "15": "赤外線リモコンデバイス", + "16": "BLE-Mesh", + "17": "仮想デバイスグループ", + "18": "ゲートウェイサブデバイス", + "19": "セキュリティレベルゲートウェイサブデバイス", + "22": "PLC", + "23": "ケーブルのみ", + "24": "Matter", + "25": "WiFi+セルラーネットワーク" + }, "room_name_rule": { "none": "同期しない", "home_room": "家の名前と部屋の名前 (Xiaomi Home 寝室)", diff --git a/custom_components/xiaomi_home/miot/i18n/nl.json b/custom_components/xiaomi_home/miot/i18n/nl.json index 7aeb26e..c3a4776 100644 --- a/custom_components/xiaomi_home/miot/i18n/nl.json +++ b/custom_components/xiaomi_home/miot/i18n/nl.json @@ -13,6 +13,32 @@ "exclude": "Uitsluiten", "include": "Inclusief" }, + "connect_type": { + "0": "WiFi", + "1": "yunyi-apparaat", + "2": "Cloudapparaat", + "3": "ZigBee", + "4": "webSocket", + "5": "Virtueel apparaat", + "6": "BLE", + "7": "Lokaal AP", + "8": "WiFi+BLE", + "9": "Andere", + "10": "Functieplug-in", + "11": "Cellulair netwerk", + "12": "Kabel", + "13": "NB-IoT", + "14": "Toegang van derden tot de cloud", + "15": "Infrarood afstandsbedieningsapparaat", + "16": "BLE-Mesh", + "17": "Virtuele apparaatgroep", + "18": "Gateway sub-apparaat", + "19": "Beveiligingsniveau gateway sub-apparaat", + "22": "PLC", + "23": "Alleen kabel", + "24": "Matter", + "25": "WiFi+Cellulair netwerk" + }, "room_name_rule": { "none": "Niet synchroniseren", "home_room": "Huisnaam en Kamernaam (Xiaomi Home Slaapkamer)", diff --git a/custom_components/xiaomi_home/miot/i18n/pt-BR.json b/custom_components/xiaomi_home/miot/i18n/pt-BR.json index 957b229..5cc6048 100644 --- a/custom_components/xiaomi_home/miot/i18n/pt-BR.json +++ b/custom_components/xiaomi_home/miot/i18n/pt-BR.json @@ -13,6 +13,32 @@ "exclude": "excluir", "include": "incluir" }, + "connect_type": { + "0": "WiFi", + "1": "dispositivo yunyi", + "2": "dispositivo de nuvem", + "3": "ZigBee", + "4": "webSocket", + "5": "dispositivo virtual", + "6": "BLE", + "7": "AP local", + "8": "WiFi+BLE", + "9": "outro", + "10": "plug-in de função", + "11": "rede celular", + "12": "cabo", + "13": "NB-IoT", + "14": "acesso à nuvem de terceiros", + "15": "dispositivo de controle remoto infravermelho", + "16": "BLE-Mesh", + "17": "grupo de dispositivos virtuais", + "18": "subdispositivo de gateway", + "19": "subdispositivo de gateway de nível de segurança", + "22": "PLC", + "23": "somente cabo", + "24": "Matter", + "25": "WiFi+rede celular" + }, "room_name_rule": { "none": "não sincronizado", "home_room": "Nome da casa e nome do quarto (Xiaomi Home Quarto)", diff --git a/custom_components/xiaomi_home/miot/i18n/pt.json b/custom_components/xiaomi_home/miot/i18n/pt.json index 1620b98..d072dda 100644 --- a/custom_components/xiaomi_home/miot/i18n/pt.json +++ b/custom_components/xiaomi_home/miot/i18n/pt.json @@ -13,6 +13,32 @@ "exclude": "Excluir", "include": "Incluir" }, + "connect_type": { + "0": "WiFi", + "1": "dispositivo yunyi", + "2": "dispositivo de nuvem", + "3": "ZigBee", + "4": "webSocket", + "5": "dispositivo virtual", + "6": "BLE", + "7": "AP local", + "8": "WiFi+BLE", + "9": "outro", + "10": "plug-in de função", + "11": "rede celular", + "12": "cabo", + "13": "NB-IoT", + "14": "acesso à nuvem de terceiros", + "15": "dispositivo de controle remoto infravermelho", + "16": "BLE-Mesh", + "17": "grupo de dispositivos virtuais", + "18": "subdispositivo de gateway", + "19": "subdispositivo de gateway de nível de segurança", + "22": "PLC", + "23": "somente cabo", + "24": "Matter", + "25": "WiFi+rede celular" + }, "room_name_rule": { "none": "Não sincronizar", "home_room": "Nome da casa e Nome do quarto (Xiaomi Home Quarto)", diff --git a/custom_components/xiaomi_home/miot/i18n/ru.json b/custom_components/xiaomi_home/miot/i18n/ru.json index 703c048..0763cc1 100644 --- a/custom_components/xiaomi_home/miot/i18n/ru.json +++ b/custom_components/xiaomi_home/miot/i18n/ru.json @@ -13,6 +13,32 @@ "exclude": "исключить", "include": "включить" }, + "connect_type": { + "0": "WiFi", + "1": "yunyi устройство", + "2": "Облачное устройство", + "3": "ZigBee", + "4": "webSocket", + "5": "Виртуальное устройство", + "6": "BLE", + "7": "Локальный AP", + "8": "WiFi+BLE", + "9": "Другое", + "10": "Плагин функции", + "11": "Сотовая сеть", + "12": "Кабель", + "13": "NB-IoT", + "14": "Доступ к стороннему облаку", + "15": "Устройство с ИК-пультом дистанционного управления", + "16": "BLE-Mesh", + "17": "Группа виртуальных устройств", + "18": "Подустройство шлюза", + "19": "Подустройство шлюза уровня безопасности", + "22": "PLC", + "23": "Только кабель", + "24": "Matter", + "25": "WiFi+Сотовая сеть" + }, "room_name_rule": { "none": "не синхронизировать", "home_room": "название дома и название комнаты (Xiaomi Home Спальня)", diff --git a/custom_components/xiaomi_home/miot/i18n/zh-Hans.json b/custom_components/xiaomi_home/miot/i18n/zh-Hans.json index f8f3c40..c4d1bfc 100644 --- a/custom_components/xiaomi_home/miot/i18n/zh-Hans.json +++ b/custom_components/xiaomi_home/miot/i18n/zh-Hans.json @@ -20,9 +20,30 @@ "include": "包含" }, "connect_type": { - "0": "WiFi设备", - "1": "蓝牙设备", - "2": "其它类型" + "0": "WiFi", + "1": "yunyi设备", + "2": "云接入设备", + "3": "ZigBee", + "4": "webSocket", + "5": "虚拟设备", + "6": "BLE", + "7": "本地AP", + "8": "WiFi+BLE", + "9": "其他", + "10": "功能插件", + "11": "蜂窝网", + "12": "网线", + "13": "NB-IoT", + "14": "第三方云接入", + "15": "红外遥控器子设备", + "16": "BLE-Mesh", + "17": "虚拟设备组", + "18": "代理网关子设备", + "19": "安全级代理网关子设备", + "22": "PLC", + "23": "仅网线", + "24": "Matter", + "25": "WiFi+蜂窝网" }, "option_status": { "enable": "启用", diff --git a/custom_components/xiaomi_home/miot/i18n/zh-Hant.json b/custom_components/xiaomi_home/miot/i18n/zh-Hant.json index 5c7ef79..4251a51 100644 --- a/custom_components/xiaomi_home/miot/i18n/zh-Hant.json +++ b/custom_components/xiaomi_home/miot/i18n/zh-Hant.json @@ -13,6 +13,32 @@ "exclude": "排除", "include": "包含" }, + "connect_type": { + "0": "WiFi", + "1": "yunyi設備", + "2": "雲接入設備", + "3": "ZigBee", + "4": "webSocket", + "5": "虛擬設備", + "6": "BLE", + "7": "本地AP", + "8": "WiFi+BLE", + "9": "其他", + "10": "功能插件", + "11": "蜂窩網", + "12": "網線", + "13": "NB-IoT", + "14": "第三方雲接入", + "15": "紅外遙控器子設備", + "16": "BLE-Mesh", + "17": "虛擬設備組", + "18": "代理網關子設備", + "19": "安全級代理網關子設備", + "22": "PLC", + "23": "僅網線", + "24": "Matter", + "25": "WiFi+蜂窩網" + }, "room_name_rule": { "none": "不同步", "home_room": "家庭名 和 房間名 (米家 臥室)", diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index 2342d24..58357e7 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Erweiterte Einstellungen", - "description": "## Gebrauchsanweisung\r\n### Behalten Sie die Standardeinstellungen bei, es sei denn, Sie verstehen die folgenden Optionen vollständig.\r\n### Steuerungsmodus\r\n- Automatisch: Wenn ein verfügbarer Xiaomi-Hub im lokalen Netzwerk vorhanden ist, priorisiert Home Assistant das Senden von Steuerbefehlen über den Hub, um eine lokale Steuerung zu ermöglichen. Wenn kein Hub vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden. Nur wenn diese Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Befehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden ausschließlich über die Cloud gesendet.\r\n### Gerätefilterung\r\nFiltern Sie unerwünschte Geräte nach Familien.\r\n### Action-Debug-Modus\r\nFür Methoden, die von MIoT-Spec-V2-Geräten definiert werden, wird neben der Benachrichtigungsentität auch eine Texteingabe-Entität erstellt, mit der Sie während des Debuggens Steuerbefehle an das Gerät senden können.\r\n### Nicht standardmäßige Entitäten ausblenden\r\nBlendet Entitäten aus, die von nicht-standardmäßigen MIoT-Spec-V2-Instanzen generiert werden und deren Name mit „*“ beginnt.", + "description": "## Gebrauchsanweisung\r\n### Wenn Sie die Bedeutung der folgenden Optionen nicht genau kennen, belassen Sie sie bitte auf den Standardeinstellungen.\r\n### Geräte filtern\r\nUnterstützt das Filtern von Geräten nach Raumnamen und Gerätetypen sowie das Filtern nach Gerätedimensionen.\r\n\r\n### Steuerungsmodus\r\n- Automatisch: Wenn ein verfügbarer Xiaomi-Hub im lokalen Netzwerk vorhanden ist, priorisiert Home Assistant das Senden von Steuerbefehlen über den Hub, um eine lokale Steuerung zu ermöglichen. Wenn kein Hub vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden. Nur wenn diese Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Befehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden ausschließlich über die Cloud gesendet.\r\n### Action-Debug-Modus\r\nFür Methoden, die von MIoT-Spec-V2-Geräten definiert werden, wird neben der Benachrichtigungsentität auch eine Texteingabe-Entität erstellt, mit der Sie während des Debuggens Steuerbefehle an das Gerät senden können.\r\n### Nicht standardmäßige Entitäten ausblenden\r\nBlendet Entitäten aus, die von nicht-standardmäßigen MIoT-Spec-V2-Instanzen generiert werden und deren Name mit „*“ beginnt.", "data": { "devices_filter": "Geräte filtern", "ctrl_mode": "Steuerungsmodus", diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index 391bd47..8a2dc40 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Advanced Settings", - "description": "## Introduction\r\n### Keep the default settings unless you fully understand the following options.\r\n### Control Mode\r\n- Auto: When a Xiaomi hub is available on the local network, Home Assistant will prioritize sending device control commands through the hub for local control. If there is no hub, it will attempt to send commands via the Xiaomi OT protocol. Only if those local control conditions are not met will commands be sent through the cloud.\r\n- Cloud: Control commands are sent exclusively through the cloud.\r\n### Device Filtering\r\nFilter out unwanted devices by family.\r\n### Action Debug Mode\r\nFor methods defined by MIoT-Spec-V2 devices, besides generating a notification entity, a text input entity will also be created so you can send control commands to the device during debugging.\r\n### Hide Non-Standard Generated Entities\r\nHide entities generated by non-standard MIoT-Spec-V2 instances whose names start with \"*\".", + "description": "## Introduction\r\n### Unless you are very clear about the meaning of the following options, please keep the default settings.\r\n### Filter Devices\r\nSupports filtering devices by room name and device type, and also supports device dimension filtering.\r\n### Control Mode\r\n- Auto: When there is an available Xiaomi central hub gateway in the local area network, Home Assistant will prioritize sending device control commands through the central hub gateway to achieve local control. If there is no central hub gateway in the local area network, it will attempt to send control commands through Xiaomi OT protocol to achieve local control. Only when the above local control conditions are not met, the device control commands will be sent through the cloud.\r\n- Cloud: All control commands are sent through the cloud.\r\n### Action Debug Mode\r\nFor the methods defined by the device MIoT-Spec-V2, in addition to generating notification entities, a text input box entity will also be generated. You can use it to send control commands to the device during debugging.\r\n### Hide Non-Standard Generated Entities\r\nHide entities generated by non-standard MIoT-Spec-V2 instances with names starting with \"*\".", "data": { "devices_filter": "Filter Devices", "ctrl_mode": "Control Mode", @@ -47,8 +47,8 @@ "data": { "room_filter_mode": "Filter Family Rooms", "room_list": "Family Rooms", - "type_filter_mode": "Filter Device Type", - "type_list": "Device Type", + "type_filter_mode": "Filter Device Connect Type", + "type_list": "Device Connect Type", "model_filter_mode": "Filter Device Model", "model_list": "Device Model", "devices_filter_mode": "Filter Devices", diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index 27b9fdc..1332e44 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Opciones Avanzadas", - "description": "## Introducción\r\n### Mantenga la configuración predeterminada a menos que conozca completamente el significado de las siguientes opciones.\r\n### Modo de Control\r\n- Automático: Cuando haya un hub Xiaomi disponible en la red local, Home Assistant priorizará el envío de comandos de control a través del hub para lograr un control local. Si no hay un hub, intentará enviar los comandos a través del protocolo Xiaomi OT. Solo si no se cumplen esas condiciones de control local, los comandos se enviarán a través de la nube.\r\n- Nube: Los comandos se envían exclusivamente a través de la nube.\r\n### Filtrado de Dispositivos\r\nFiltre dispositivos no deseados por familia.\r\n### Modo de Depuración de Acciones\r\nPara los métodos definidos por dispositivos MIoT-Spec-V2, además de generar una entidad de notificación, se creará una entidad de entrada de texto para que pueda enviar comandos de control durante la depuración.\r\n### Ocultar Entidades Generadas No Estándar\r\nOculte entidades generadas por instancias no estándar de MIoT-Spec-V2 cuyos nombres comiencen con \"*\".", + "description": "## Introducción\r\n### A menos que entienda claramente el significado de las siguientes opciones, manténgalas en su configuración predeterminada.\r\n### Filtrar dispositivos\r\nAdmite la filtración de dispositivos por nombre de habitación y tipo de dispositivo, y también admite la filtración por familia.\r\n### Modo de Control\r\n- Automático: Cuando hay una puerta de enlace central de Xiaomi disponible en la red local, Home Assistant enviará comandos de control de dispositivos a través de la puerta de enlace central para lograr la función de control local. Cuando no hay una puerta de enlace central en la red local, intentará enviar comandos de control a través del protocolo OT de Xiaomi para lograr la función de control local. Solo cuando no se cumplan las condiciones de control local anteriores, los comandos de control de dispositivos se enviarán a través de la nube.\r\n- Nube: Los comandos de control solo se envían a través de la nube.\r\n### Modo de Depuración de Acciones\r\nPara los métodos definidos por el dispositivo MIoT-Spec-V2, además de generar una entidad de notificación, también se generará una entidad de cuadro de texto que se puede utilizar para enviar comandos de control al dispositivo durante la depuración.\r\n### Ocultar Entidades Generadas No Estándar\r\nOcultar entidades generadas por instancias MIoT-Spec-V2 no estándar que comienzan con \"*\".", "data": { "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Control", diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index ef33855..49b0a95 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Paramètres Avancés", - "description": "## Introduction\r\n### Conservez les paramètres par défaut à moins de comprendre parfaitement la signification des options ci-dessous.\r\n### Mode de Contrôle\r\n- Automatique : Lorsqu’un hub Xiaomi est disponible sur le réseau local, Home Assistant privilégie l’envoi de commandes via ce hub pour un contrôle local. S’il n’y a pas de hub, il tentera d’envoyer des commandes via le protocole Xiaomi OT. Ce n’est que si les conditions de contrôle local ne sont pas remplies que les commandes seront envoyées via le cloud.\r\n- Cloud : Les commandes sont envoyées exclusivement via le cloud.\r\n### Filtrage des Appareils\r\nFiltrez les appareils indésirables en fonction de la famille.\r\n### Mode de Débogage d’Actions\r\nPour les méthodes définies par les appareils MIoT-Spec-V2, en plus de générer une entité de notification, une entité de saisie de texte sera créée pour envoyer des commandes de contrôle pendant le débogage.\r\n### Masquer les Entités Non Standard\r\nMasquez les entités générées par des instances MIoT-Spec-V2 non standard dont le nom commence par « * ».", + "description": "## Introduction\r\n### Sauf si vous comprenez très bien la signification des options suivantes, veuillez les laisser par défaut.\r\n###Filtrer les appareils\r\nPrend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n### Mode de Contrôle\r\n- Automatique : Lorsqu'une passerelle Xiaomi est disponible dans le réseau local, Home Assistant enverra les commandes de contrôle des appareils via la passerelle pour permettre le contrôle local. Si aucune passerelle n'est disponible dans le réseau local, Home Assistant essaiera d'envoyer les commandes de contrôle des appareils via le protocole OT Xiaomi pour permettre le contrôle local. Seules si les conditions de contrôle local ci-dessus ne sont pas remplies, les commandes de contrôle des appareils seront envoyées via le cloud.\r\n- Cloud : Les commandes de contrôle des appareils sont envoyées uniquement via le cloud.\r\n### Mode de Débogage d’Actions\r\nPour les méthodes définies par les appareils MIoT-Spec-V2, en plus de générer une entité de notification, une entité de champ de texte sera également générée pour vous permettre d'envoyer des commandes de contrôle aux appareils lors du débogage.\r\n### Masquer les Entités Non Standard\r\nMasquer les entités générées par des instances MIoT-Spec-V2 non standard et commençant par \"*\".", "data": { "devices_filter": "Filtrer les Appareils", "ctrl_mode": "Mode de Contrôle", diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index 88a75c5..59e2cae 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "高度な設定オプション", - "description": "## 紹介\r\n### 以下のオプションの意味を十分に理解していない限り、デフォルト設定のままにしてください。\r\n### コントロールモード\r\n- 自動: ローカルネットワークに利用可能なXiaomiハブがある場合、Home Assistantはローカル制御を実現するためにハブを介してデバイス制御コマンドを優先的に送信します。ハブが存在しない場合は、Xiaomi OTプロトコルを介して制御コマンドを送信しようとします。これらのローカル制御条件が満たされない場合のみ、クラウド経由でコマンドが送信されます。\r\n- クラウド: コマンドはクラウド経由でのみ送信されます。\r\n### デバイスフィルタ\r\n不要なデバイスをファミリー単位でフィルタリングします。\r\n### Actionデバッグモード\r\nMIoT-Spec-V2デバイスで定義されたメソッドについては、通知エンティティに加えてテキスト入力エンティティも生成され、デバッグ時にデバイスへ制御コマンドを送信できます。\r\n### 非標準生成エンティティを隠す\r\n名前が「*」で始まる、非標準のMIoT-Spec-V2インスタンスによって生成されたエンティティを隠します。", + "description": "## 紹介\r\n### 以下のオプションの意味がよくわからない場合は、デフォルトのままにしてください。\r\n###デバイスのフィルタリング\r\n部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n### コントロールモード\r\n- 自動:ローカルネットワーク内に利用可能なXiaomi中央ゲートウェイがある場合、Home Assistantはデバイス制御命令を送信するために優先的に中央ゲートウェイを使用します。ローカルネットワークに中央ゲートウェイがない場合、Xiaomi OTプロトコルを使用してデバイス制御命令を送信し、ローカル制御機能を実現します。上記のローカル制御条件が満たされない場合のみ、デバイス制御命令はクラウドを介して送信されます。\r\n- クラウド:制御命令はクラウドを介してのみ送信されます。\r\n### Actionデバッグモード\r\nデバイスが定義するMIoT-Spec-V2のメソッドに対して、通知エンティティを生成するだけでなく、デバイスに制御命令を送信するためのテキスト入力ボックスエンティティも生成されます。デバッグ時にデバイスに制御命令を送信するために使用できます。\r\n### 非標準生成エンティティを隠す\r\n「*」で始まる名前の非標準MIoT-Spec-V2インスタンスによって生成されたエンティティを非表示にします。", "data": { "devices_filter": "デバイスをフィルタリング", "ctrl_mode": "コントロールモード", diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index d476be2..079071f 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Geavanceerde Instellingen", - "description": "## Inleiding\r\n### Houd de standaardinstellingen aan, tenzij u de betekenis van de volgende opties volledig begrijpt.\r\n### Besturingsmodus\r\n- Automatisch: Wanneer er een beschikbare Xiaomi-hub in het lokale netwerk is, zal Home Assistant voorrang geven aan het verzenden van besturingsopdrachten via de hub voor lokale besturing. Als er geen hub beschikbaar is, zal het proberen besturingsopdrachten te verzenden via het Xiaomi OT-protocol. Alleen als aan deze lokale besturingsvoorwaarden niet wordt voldaan, worden de opdrachten via de cloud verzonden.\r\n- Cloud: Besturingsopdrachten worden uitsluitend via de cloud verzonden.\r\n### Apparaatfiltering\r\nFilter ongewenste apparaten per familie.\r\n### Actie-debugmodus\r\nVoor methoden gedefinieerd door MIoT-Spec-V2-apparaten wordt, naast een meldingsentiteit, ook een tekstinvoerentiteit gemaakt waarmee u tijdens het debuggen besturingsopdrachten naar het apparaat kunt sturen.\r\n### Niet-standaard entiteiten verbergen\r\nVerberg entiteiten die door niet-standaard MIoT-Spec-V2-instanties worden gegenereerd en waarvan de naam begint met \"*\".", + "description": "## Inleiding\r\n### Tenzij u zeer goed op de hoogte bent van de betekenis van de volgende opties, houdt u de standaardinstellingen.\r\n### Apparaten filteren\r\nOndersteunt het filteren van apparaten op basis van kamer- en apparaattypen, en ondersteunt ook apparaatdimensiefiltering.\r\n### Besturingsmodus\r\n- Automatisch: Wanneer er een beschikbare Xiaomi centrale hubgateway in het lokale netwerk is, zal Home Assistant eerst apparaatbesturingsinstructies via de centrale hubgateway verzenden om lokale controlefunctionaliteit te bereiken. Als er geen centrale hub in het lokale netwerk is, zal het proberen om besturingsinstructies via het Xiaomi OT-protocol te verzenden om lokale controlefunctionaliteit te bereiken. Alleen als de bovenstaande lokale controlevoorwaarden niet worden vervuld, worden apparaatbesturingsinstructies via de cloud verzonden.\r\n- Cloud: Besturingsinstructies worden alleen via de cloud verzonden.\r\n### Actie-debugmodus\r\nVoor methoden die zijn gedefinieerd in de MIoT-Spec-V2 van het apparaat, wordt naast het genereren van een meldingsentiteit ook een tekstinvoerveldentiteit gegenereerd. U kunt dit gebruiken om besturingsinstructies naar het apparaat te sturen tijdens het debuggen.\r\n### Niet-standaard entiteiten verbergen\r\nVerberg entiteiten die zijn gegenereerd door niet-standaard MIoT-Spec-V2-instanties die beginnen met \"*\".", "data": { "devices_filter": "Apparaten filteren", "ctrl_mode": "Besturingsmodus", diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index 7d0e237..c89fc0d 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Configurações Avançadas", - "description": "## Introdução\r\n### Mantenha as configurações padrão, a menos que você entenda completamente o significado das seguintes opções.\r\n### Modo de Controle\r\n- Automático: Quando houver um hub Xiaomi disponível na rede local, o Home Assistant priorizará o envio de comandos de controle através do hub para obter controle local. Se não houver hub, tentará enviar comandos de controle pelo protocolo Xiaomi OT. Somente se essas condições de controle local não forem atendidas, os comandos serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controle são enviados exclusivamente pela nuvem.\r\n### Filtragem de Dispositivos\r\nFiltre dispositivos indesejados por família.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos por dispositivos MIoT-Spec-V2, além de gerar uma entidade de notificação, será criada uma entidade de entrada de texto para que você possa enviar comandos de controle ao dispositivo durante a depuração.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOculte entidades geradas por instâncias não padrão do MIoT-Spec-V2 cujos nomes começam com \"*\".", + "description": "## Introdução\r\n### A menos que você entenda claramente o significado das opções a seguir, mantenha as configurações padrão.\r\n### Filtrar Dispositivos\r\nSuporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n### Modo de Controle\r\n- Automático: Quando um gateway central Xiaomi disponível na rede local está disponível, o Home Assistant enviará comandos de controle de dispositivo através do gateway central para realizar a função de controle local. Quando não há gateway central na rede local, ele tentará enviar comandos de controle através do protocolo OT da Xiaomi para realizar a função de controle local. Somente quando as condições de controle local acima não forem atendidas, os comandos de controle do dispositivo serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controle são enviados apenas através da nuvem.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos pelo MIoT-Spec-V2 do dispositivo, além de gerar uma entidade de notificação, também será gerada uma entidade de caixa de texto para você enviar comandos de controle ao dispositivo durante a depuração.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOcultar entidades geradas por instâncias MIoT-Spec-V2 não padrão que começam com \"*\".", "data": { "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Controle", diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index aef3aa5..761a8c7 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Opções Avançadas", - "description": "## Introdução\r\n### Mantenha as configurações padrão, a menos que compreenda totalmente o significado das seguintes opções.\r\n### Modo de Controlo\r\n- Automático: Quando existir um hub Xiaomi disponível na rede local, o Home Assistant irá priorizar o envio de comandos de controlo através do hub para permitir controlo local. Se não houver hub na rede local, irá tentar enviar comandos de controlo através do protocolo Xiaomi OT. Apenas quando estas condições de controlo local não forem satisfeitas, os comandos serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controlo são enviados exclusivamente através da nuvem.\r\n### Filtragem de Dispositivos\r\nFiltre dispositivos indesejados por família.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos por dispositivos MIoT-Spec-V2, além de gerar uma entidade de notificação, também será criada uma entidade de entrada de texto para enviar comandos ao dispositivo durante a depuração.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOculte entidades geradas por instâncias não padrão do MIoT-Spec-V2 cujos nomes começam com \"*\".", + "description": "## Introdução\r\n### A menos que você entenda claramente o significado das opções abaixo, mantenha as configurações padrão.\r\n### Filtrar Dispositivos\r\nSuporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n### Modo de Controle\r\n- Automático: Quando um gateway central Xiaomi está disponível na rede local, o Home Assistant enviará comandos de controlo de dispositivos através do gateway central para realizar o controlo local. Quando não há gateway central na rede local, tentará enviar comandos de controlo através do protocolo Xiaomi OT para realizar o controlo local. Apenas quando as condições de controlo local acima não são atendidas, os comandos de controlo de dispositivos serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controlo são enviados apenas através da nuvem.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos pelo MIoT-Spec-V2, além de gerar uma entidade de notificação, também será gerada uma entidade de caixa de texto para depuração de controlo de dispositivos.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOcultar entidades geradas por instâncias MIoT-Spec-V2 não padrão, cujos nomes começam com \"*\".", "data": { "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Controlo", diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index e26f80e..3d7b3a3 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Расширенные настройки", - "description": "## Введение\r\n### Сохраняйте настройки по умолчанию, если вы не полностью понимаете смысл следующих опций.\r\n### Режим управления\r\n- Авто: Если в локальной сети доступен шлюз Xiaomi, Home Assistant будет в приоритете отправлять команды управления устройствами через этот шлюз, чтобы обеспечить локальное управление. При отсутствии шлюза осуществляется попытка отправить команды управления через протокол Xiaomi OT. Только при несоблюдении указанных условий локального управления команды отправляются через облако.\r\n- Облако: Команды управления отправляются исключительно через облако.\r\n### Фильтрация устройств\r\nФильтруйте ненужные устройства по семьям.\r\n### Режим отладки действий\r\nДля методов, определённых устройствами MIoT-Spec-V2, помимо сущности уведомления, будет создана сущность текстового ввода, которая позволяет отправлять команды управления устройству во время отладки.\r\n### Скрыть нестандартные сущности\r\nСкрывает сущности, созданные нестандартными экземплярами MIoT-Spec-V2, чьи имена начинаются со «*».", + "description": "## Введение\r\n### Если вы не очень хорошо понимаете значение следующих параметров, оставьте их по умолчанию.\r\n### Фильтрация устройств\r\nПоддерживает фильтрацию устройств по названию комнаты и типу устройства, а также фильтрацию по уровню устройства.\r\n### Режим управления\r\n- Автоматически: при наличии доступного центрального шлюза Xiaomi в локальной сети Home Assistant Home Assistant будет отправлять команды управления устройствами через центральный шлюз для локального управления. Если центрального шлюза нет в локальной сети, Home Assistant попытается отправить команды управления устройствами через протокол OT Xiaomi для локального управления. Только если вышеуказанные условия локального управления не выполняются, команды управления устройствами будут отправляться через облако.\r\n- Облако: команды управления отправляются только через облако.\r\n### Режим отладки действий\r\nДля методов, определенных устройством MIoT-Spec-V2, помимо создания уведомления, будет создана сущность текстового поля, которую вы можете использовать для отправки команд управления устройством во время отладки.\r\n### Скрыть нестандартные сущности\r\nСкрыть сущности, созданные нестандартными экземплярами MIoT-Spec-V2, имена которых начинаются с «*».", "data": { "devices_filter": "Фильтрация устройств", "ctrl_mode": "Режим управления", diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index 2d85447..90fe7bc 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "高级设置选项", - "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n###筛选设备\r\n支持按照房间名称和设备类型筛选设备,同时也支持设备维度筛选。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### 设备过滤\r\n按照家庭维度,过滤不需要的设备。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。", + "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n###筛选设备\r\n支持按照房间名称和设备类型筛选设备,同时也支持设备维度筛选。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。", "data": { "devices_filter": "筛选设备", "ctrl_mode": "控制模式", @@ -47,8 +47,8 @@ "data": { "room_filter_mode": "筛选家庭房间", "room_list": "家庭房间", - "type_filter_mode": "筛选设备类型", - "type_list": "设备类型", + "type_filter_mode": "筛选设备接入类型", + "type_list": "设备接入类型", "model_filter_mode": "筛选设备型号", "model_list": "设备型号", "devices_filter_mode": "筛选设备", diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index 3dbc33f..9ac4108 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "高級設置選項", - "description": "## 使用介紹\r\n### 除非您非常清楚下列選項的含義,否則請保持默認。\r\n### 控制模式\r\n- 自動:本地區域網內存在可用的小米中樞網關時,Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。本地區域網不存在中樞時,會嘗試通過小米OT協議發送控制指令,以實現本地化控制功能。只有當上述本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令僅通過雲端發送。\r\n### 設備過濾\r\n按照家庭維度,過濾不需要的設備。\r\n### Action 調試模式\r\n對於設備 MIoT-Spec-V2 定義的方法,在生成通知實體之外,還會生成一個文本輸入框實體,您可以在調試時用它向設備發送控制指令。\r\n### 隱藏非標準生成實體\r\n隱藏名稱以“*”開頭的非標準 MIoT-Spec-V2 實例生成的實體。", + "description": "## 使用介紹\r\n### 除非您非常清楚下列選項的含義,否則請保持默認。\r\n###篩選設備\r\n支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n### 控制模式\r\n- 自動:本地局域網內存在可用的小米中樞網關時, Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。本地局域網不存在中樞時,會嘗試通過小米OT協議發送控制指令,以實現本地化控制功能。只有當上述本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令僅通過雲端發送。\r\n### Action 調試模式\r\n對於設備 MIoT-Spec-V2 定義的方法,在生成通知實體之外,還會生成一個文本輸入框實體,您可以在調試時用它向設備發送控制指令。\r\n### 隱藏非標準生成實體\r\n隱藏名稱以“*”開頭的非標準 MIoT-Spec-V2 實例生成的實體。", "data": { "devices_filter": "篩選設備", "ctrl_mode": "控制模式", @@ -47,8 +47,8 @@ "data": { "room_filter_mode": "篩選家庭房間", "room_list": "家庭房間", - "type_filter_mode": "篩選設備類型", - "type_list": "設備類型", + "type_filter_mode": "篩選設備接入類型", + "type_list": "設備接入類型", "model_filter_mode": "篩選設備型號", "model_list": "設備型號", "devices_filter_mode": "篩選設備", From 5d9a00d0b7dfc06ac80e8bff526e479a6ad72904 Mon Sep 17 00:00:00 2001 From: topsworld Date: Mon, 23 Dec 2024 10:11:37 +0800 Subject: [PATCH 12/24] feat: update auth info save logic --- custom_components/xiaomi_home/config_flow.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index 46b6a64..747e2b8 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -365,6 +365,13 @@ async def __check_oauth_async(self) -> None: except (MIoTOauthError, json.JSONDecodeError): self._nick_name = DEFAULT_NICK_NAME _LOGGER.error('get nick name failed') + # Save auth_info + if not (await self._miot_storage.update_user_config_async( + uid=self._uid, cloud_server=self._cloud_server, config={ + 'auth_info': self._auth_info + })): + raise MIoTError( + 'miot_storage.update_user_config_async error') except Exception as err: _LOGGER.error( 'get_access_token, %s, %s', err, traceback.format_exc()) @@ -607,7 +614,7 @@ async def async_step_devices_filter( self._device_list_filter = { did: dev_info for did, dev_info in self._device_list_sorted.items() - if dev_info['connect_type'] in type_list_in} + if str(dev_info['connect_type']) in type_list_in} # Model filter model_list_in: list = user_input.get('model_list', []) if model_list_in: @@ -640,9 +647,15 @@ async def async_step_devices_filter( if did in device_list_in} else: raise MIoTError('invalid devices_filter_mode') + if self._device_list_filter: + raise AbortFlow( + reason='config_flow_error', + description_placeholders={ + 'error': 'invalid devices_filter'}) self._device_list_sorted = dict(sorted( self._device_list_filter.items(), key=lambda item: item[1].get('home_id', '')+item[1].get('room_id', ''))) + # Save devices if not await self._miot_storage.save_async( domain='miot_devices', name=f'{self._uid}_{self._cloud_server}', @@ -724,11 +737,6 @@ async def async_step_devices_filter( ) async def config_flow_done(self): - if not (await self._miot_storage.update_user_config_async( - uid=self._uid, cloud_server=self._cloud_server, config={ - 'auth_info': self._auth_info - })): - raise MIoTError('miot_storage.update_user_config_async error') return self.async_create_entry( title=( f'{self._nick_name}: {self._uid} ' From 13d76b66defb0adcd1adea2f27edbb81ca62002e Mon Sep 17 00:00:00 2001 From: topsworld Date: Mon, 23 Dec 2024 15:07:24 +0800 Subject: [PATCH 13/24] feat: improve config flow devices filter --- custom_components/xiaomi_home/config_flow.py | 199 +++++++++--------- .../xiaomi_home/miot/i18n/de.json | 4 + .../xiaomi_home/miot/i18n/en.json | 4 + .../xiaomi_home/miot/i18n/es.json | 4 + .../xiaomi_home/miot/i18n/fr.json | 4 + .../xiaomi_home/miot/i18n/ja.json | 4 + .../xiaomi_home/miot/i18n/nl.json | 4 + .../xiaomi_home/miot/i18n/pt-BR.json | 4 + .../xiaomi_home/miot/i18n/pt.json | 4 + .../xiaomi_home/miot/i18n/ru.json | 4 + .../xiaomi_home/miot/i18n/zh-Hans.json | 4 + .../xiaomi_home/miot/i18n/zh-Hant.json | 4 + .../xiaomi_home/translations/de.json | 1 + .../xiaomi_home/translations/en.json | 1 + .../xiaomi_home/translations/es.json | 1 + .../xiaomi_home/translations/fr.json | 3 +- .../xiaomi_home/translations/ja.json | 3 +- .../xiaomi_home/translations/nl.json | 1 + .../xiaomi_home/translations/pt-BR.json | 1 + .../xiaomi_home/translations/pt.json | 1 + .../xiaomi_home/translations/ru.json | 1 + .../xiaomi_home/translations/zh-Hans.json | 5 +- .../xiaomi_home/translations/zh-Hant.json | 3 +- 23 files changed, 164 insertions(+), 100 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index 747e2b8..46bab14 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -50,7 +50,7 @@ import json import secrets import traceback -from typing import Optional +from typing import Optional, Set from aiohttp import web from aiohttp.hdrs import METH_GET import voluptuous as vol @@ -116,9 +116,10 @@ class XiaomiMihomeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): _area_name_rule: Optional[str] _action_debug: bool _hide_non_standard_entities: bool + _display_devices_changed_notify: bool _auth_info: Optional[dict] _nick_name: Optional[str] - _home_selected: Optional[dict] + _home_selected: dict _home_info_buffer: Optional[dict[str, str | dict[str, dict]]] _home_list: Optional[dict] _device_list_sorted: dict @@ -152,6 +153,7 @@ def __init__(self) -> None: self._area_name_rule = None self._action_debug = False self._hide_non_standard_entities = False + self._display_devices_changed_notify = True self._auth_info = None self._nick_name = None self._home_selected = {} @@ -365,13 +367,6 @@ async def __check_oauth_async(self) -> None: except (MIoTOauthError, json.JSONDecodeError): self._nick_name = DEFAULT_NICK_NAME _LOGGER.error('get nick name failed') - # Save auth_info - if not (await self._miot_storage.update_user_config_async( - uid=self._uid, cloud_server=self._cloud_server, config={ - 'auth_info': self._auth_info - })): - raise MIoTError( - 'miot_storage.update_user_config_async error') except Exception as err: _LOGGER.error( 'get_access_token, %s, %s', err, traceback.format_exc()) @@ -385,6 +380,12 @@ async def __check_oauth_async(self) -> None: self._uid = self._home_info_buffer['uid'] if self._uid == self._nick_name: self._nick_name = DEFAULT_NICK_NAME + # Save auth_info + if not (await self._miot_storage.update_user_config_async( + uid=self._uid, cloud_server=self._cloud_server, config={ + 'auth_info': self._auth_info + })): + raise MIoTError('miot_storage.update_user_config_async error') except Exception as err: _LOGGER.error( 'get_homeinfos error, %s, %s', err, traceback.format_exc()) @@ -495,11 +496,11 @@ async def async_step_homes_select(self, user_input=None): _LOGGER.debug('async_step_homes_select') try: if user_input is None: - return await self.display_homes_select_form('') + return await self.__display_homes_select_form('') home_selected: list = user_input.get('home_infos', []) if not home_selected: - return await self.display_homes_select_form( + return await self.__display_homes_select_form( 'no_family_selected') for home_id, home_info in self._home_info_buffer[ 'homes']['home_list'].items(): @@ -512,7 +513,7 @@ async def async_step_homes_select(self, user_input=None): for did, dev_info in self._home_info_buffer['devices'].items() if dev_info['home_id'] in home_selected} if not devices_list: - return await self.display_homes_select_form('no_devices') + return await self.__display_homes_select_form('no_devices') self._device_list_sorted = dict(sorted( devices_list.items(), key=lambda item: item[1].get('home_id', '')+item[1].get('room_id', ''))) @@ -524,7 +525,7 @@ async def async_step_homes_select(self, user_input=None): _LOGGER.error( 'save devices async failed, %s, %s', self._uid, self._cloud_server) - return await self.display_homes_select_form( + return await self.__display_homes_select_form( 'devices_storage_failed') if user_input.get('advanced_options', False): return await self.async_step_advanced_options() @@ -539,7 +540,7 @@ async def async_step_homes_select(self, user_input=None): 'error': f'config_flow error, {err}'} ) from err - async def display_homes_select_form(self, reason: str): + async def __display_homes_select_form(self, reason: str): return self.async_show_form( step_id='homes_select', data_schema=vol.Schema({ @@ -576,7 +577,9 @@ async def async_step_advanced_options(self, user_input: dict = None): vol.Required( 'hide_non_standard_entities', default=self._hide_non_standard_entities): bool, - + vol.Required( + 'display_devices_changed_notify', + default=self._display_devices_changed_notify): bool, }), last_step=False, ) @@ -586,93 +589,68 @@ async def async_step_devices_filter( ): if user_input: # Room filter + include_items: dict = {} + exclude_items: dict = {} room_list_in: list = user_input.get('room_list', []) if room_list_in: - room_filter_mode: str = user_input.get( - 'room_filter_mode', None) - if room_filter_mode == 'exclude': - self._device_list_filter = { - did: dev_info - for did, dev_info in self._device_list_sorted.items() - if dev_info['room_id'] not in room_list_in} - elif room_filter_mode == 'include': - self._device_list_filter = { - did: dev_info - for did, dev_info in self._device_list_sorted.items() - if dev_info['room_id'] in room_list_in} - # Type filter + if user_input.get( + 'room_filter_mode', 'include') == 'include': + include_items['room_id'] = room_list_in + else: + exclude_items['room_id'] = room_list_in + # Connect Type filter type_list_in: list = user_input.get('type_list', []) if type_list_in: - type_filter_mode: str = user_input.get( - 'type_filter_mode', None) - if type_filter_mode == 'exclude': - self._device_list_filter = { - did: dev_info - for did, dev_info in self._device_list_sorted.items() - if dev_info['connect_type'] not in type_list_in} - elif type_filter_mode == 'include': - self._device_list_filter = { - did: dev_info - for did, dev_info in self._device_list_sorted.items() - if str(dev_info['connect_type']) in type_list_in} + if user_input.get( + 'type_filter_mode', 'include') == 'include': + include_items['connect_type'] = type_list_in + else: + exclude_items['connect_type'] = type_list_in # Model filter model_list_in: list = user_input.get('model_list', []) if model_list_in: - model_filter_mode: str = user_input.get( - 'model_filter_mode', None) - if model_filter_mode == 'exclude': - self._device_list_filter = { - did: dev_info - for did, dev_info in self._device_list_sorted.items() - if dev_info['model'] not in model_list_in} - elif model_filter_mode == 'include': - self._device_list_filter = { - did: dev_info - for did, dev_info in self._device_list_sorted.items() - if dev_info['model'] in model_list_in} + if user_input.get( + 'model_filter_mode', 'include') == 'include': + include_items['model'] = model_list_in + else: + exclude_items['model'] = model_list_in # Device filter device_list_in: list = user_input.get('device_list', []) if device_list_in: - devices_filter_mode: str = user_input.get( - 'devices_filter_mode', None) - if devices_filter_mode == 'exclude': - self._device_list_filter = { - did: dev_info - for did, dev_info in self._device_list_sorted.items() - if did not in device_list_in} - elif devices_filter_mode == 'include': - self._device_list_filter = { - did: dev_info - for did, dev_info in self._device_list_sorted.items() - if did in device_list_in} + if user_input.get( + 'devices_filter_mode', 'include') == 'include': + include_items['did'] = device_list_in else: - raise MIoTError('invalid devices_filter_mode') - if self._device_list_filter: + exclude_items['did'] = device_list_in + device_filter_list = self.__devices_filter( + devices=self._device_list_sorted, + logic_or=(user_input.get('statistics_logic', 'or') == 'or'), + item_in=include_items, item_ex=exclude_items) + if not device_filter_list: raise AbortFlow( reason='config_flow_error', description_placeholders={ 'error': 'invalid devices_filter'}) self._device_list_sorted = dict(sorted( - self._device_list_filter.items(), key=lambda item: + device_filter_list.items(), key=lambda item: item[1].get('home_id', '')+item[1].get('room_id', ''))) # Save devices if not await self._miot_storage.save_async( domain='miot_devices', name=f'{self._uid}_{self._cloud_server}', data=self._device_list_sorted): - _LOGGER.error( - 'save devices async failed, %s, %s', - self._uid, self._cloud_server) - raise AbortFlow( - reason='config_flow_error', - description_placeholders={ - 'error': 'save devices failed'}) + return await self.__display_devices_filter_form( + reason='no_devices_selected') return await self.config_flow_done() + return await self.__display_devices_filter_form(reason='') + async def __display_devices_filter_form(self, reason: str): tip_devices: str = self._miot_i18n.translate( key='config.other.devices') tip_without_room: str = self._miot_i18n.translate( key='config.other.without_room') + trans_statistics_logic: dict = self._miot_i18n.translate( + key='config.statistics_logic') trans_filter_mode: dict = self._miot_i18n.translate( key='config.filter_mode') trans_connect_type: dict = self._miot_i18n.translate( @@ -684,24 +662,21 @@ async def async_step_devices_filter( device_list: dict = {} for did, info in self._device_list_sorted.items(): device_list[did] = ( - f'{info["home_name"]} {info["room_name"]} - ' + - f'{info["name"]} - {did}') + f'[ {info["home_name"]} {info["room_name"]} ] ' + + f'{info["name"]}, {did}') room_device_count.setdefault(info['room_id'], 0) room_device_count[info['room_id']] += 1 model_device_count.setdefault(info['model'], 0) model_device_count[info['model']] += 1 connect_type_count.setdefault(str(info['connect_type']), 0) connect_type_count[str(info['connect_type'])] += 1 - model_list: dict = {} for model, count in model_device_count.items(): model_list[model] = f'{model} [ {count} {tip_devices} ]' - type_list: dict = { k: f'{trans_connect_type.get(k, f"Connect Type ({k})")} ' f'[ {v} {tip_devices} ]' for k, v in connect_type_count.items()} - room_list: dict = {} for home_id, home_info in self._home_selected.items(): for room_id, room_name in home_info['room_info'].items(): @@ -714,7 +689,6 @@ async def async_step_devices_filter( room_list[home_id] = ( f'{home_info["home_name"]} {tip_without_room}' f' [ {room_device_count[home_id]}{tip_devices} ]') - return self.async_show_form( step_id='devices_filter', data_schema=vol.Schema({ @@ -731,11 +705,47 @@ async def async_step_devices_filter( vol.Required('devices_filter_mode', default='exclude'): vol.In(trans_filter_mode), vol.Optional('device_list'): cv.multi_select(dict(sorted( - device_list.items(), key=lambda device: device[1]))) + device_list.items(), key=lambda device: device[1]))), + vol.Required('statistics_logic', default='or'): + vol.In(trans_statistics_logic), }), + errors={'base': reason}, last_step=False ) + def __devices_filter( + self, devices: dict, logic_or: bool, item_in: dict, item_ex: dict + ) -> dict: + include_set: Set = set([]) + if not item_in: + include_set = set(devices.keys()) + else: + filter_item: list[set] = [] + for key, value in item_in.items(): + filter_item.append(set([ + did for did, info in devices.items() + if str(info[key]) in value])) + include_set = ( + set.union(*filter_item) + if logic_or else set.intersection(*filter_item)) + if not include_set: + return {} + if item_ex: + filter_item: list[set] = [] + for key, value in item_ex.items(): + filter_item.append(set([ + did for did, info in devices.items() + if str(info[key]) in value])) + exclude_set: Set = ( + set.union(*filter_item) + if logic_or else set.intersection(*filter_item)) + if exclude_set: + include_set = include_set-exclude_set + if not include_set: + return {} + return { + did: info for did, info in devices.items() if did in include_set} + async def config_flow_done(self): return self.async_create_entry( title=( @@ -755,11 +765,13 @@ async def config_flow_done(self): 'area_name_rule': self._area_name_rule, 'action_debug': self._action_debug, 'hide_non_standard_entities': - self._hide_non_standard_entities, + self._hide_non_standard_entities, + 'display_devices_changed_notify': + self._display_devices_changed_notify }) - @staticmethod - @callback + @ staticmethod + @ callback def async_get_options_flow( config_entry: config_entries.ConfigEntry, ) -> config_entries.OptionsFlow: @@ -1206,11 +1218,11 @@ async def async_step_homes_select(self, user_input=None): if home_id in home_list] self._home_list = dict(sorted(home_list.items())) - return await self.display_homes_select_form('') + return await self.__display_homes_select_form('') self._home_selected_list = user_input.get('home_infos', []) if not self._home_selected_list: - return await self.display_homes_select_form('no_family_selected') + return await self.__display_homes_select_form('no_family_selected') self._ctrl_mode = user_input.get('ctrl_mode') self._home_selected_dict = {} for home_id, home_info in self._home_info_buffer[ @@ -1223,7 +1235,7 @@ async def async_step_homes_select(self, user_input=None): for did, dev_info in self._home_info_buffer['devices'].items() if dev_info['home_id'] in self._home_selected_list} if not self._device_list: - return await self.display_homes_select_form('no_devices') + return await self.__display_homes_select_form('no_devices') # Statistics devices changed self._devices_add = [] self._devices_remove = [] @@ -1241,17 +1253,14 @@ async def async_step_homes_select(self, user_input=None): self._devices_add, self._devices_remove) return await self.async_step_update_trans_rules() - async def display_homes_select_form(self, reason: str): + async def __display_homes_select_form(self, reason: str): return self.async_show_form( step_id='homes_select', data_schema=vol.Schema({ - vol.Required( - 'ctrl_mode', default=self._ctrl_mode - ): vol.In(self._miot_i18n.translate(key='config.control_mode')), - vol.Required( - 'home_infos', - default=self._home_selected_list - ): cv.multi_select(self._home_list), + vol.Required('home_infos', default=self._home_selected_list): + cv.multi_select(self._home_list), + vol.Required('ctrl_mode', default=self._ctrl_mode): vol.In( + self._miot_i18n.translate(key='config.control_mode')), }), errors={'base': reason}, description_placeholders={ diff --git a/custom_components/xiaomi_home/miot/i18n/de.json b/custom_components/xiaomi_home/miot/i18n/de.json index 78005a6..74fe7dc 100644 --- a/custom_components/xiaomi_home/miot/i18n/de.json +++ b/custom_components/xiaomi_home/miot/i18n/de.json @@ -9,6 +9,10 @@ "auto": "automatisch", "cloud": "Cloud" }, + "statistics_logic": { + "or": "ODER-Logik", + "and": "UND-Logik" + }, "filter_mode": { "exclude": "ausschließen", "include": "einschließen" diff --git a/custom_components/xiaomi_home/miot/i18n/en.json b/custom_components/xiaomi_home/miot/i18n/en.json index f79a20e..e3afb45 100644 --- a/custom_components/xiaomi_home/miot/i18n/en.json +++ b/custom_components/xiaomi_home/miot/i18n/en.json @@ -9,6 +9,10 @@ "auto": "Auto", "cloud": "Cloud" }, + "statistics_logic": { + "or": "OR logic", + "and": "AND logic" + }, "filter_mode": { "exclude": "Exclude", "include": "Include" diff --git a/custom_components/xiaomi_home/miot/i18n/es.json b/custom_components/xiaomi_home/miot/i18n/es.json index b94c950..0524e2c 100644 --- a/custom_components/xiaomi_home/miot/i18n/es.json +++ b/custom_components/xiaomi_home/miot/i18n/es.json @@ -9,6 +9,10 @@ "auto": "automático", "cloud": "nube" }, + "statistics_logic": { + "or": "lógica OR", + "and": "lógica AND" + }, "filter_mode": { "exclude": "excluir", "include": "incluir" diff --git a/custom_components/xiaomi_home/miot/i18n/fr.json b/custom_components/xiaomi_home/miot/i18n/fr.json index dbe481f..0f0cec0 100644 --- a/custom_components/xiaomi_home/miot/i18n/fr.json +++ b/custom_components/xiaomi_home/miot/i18n/fr.json @@ -9,6 +9,10 @@ "auto": "automatique", "cloud": "cloud" }, + "statistics_logic": { + "or": "ou logique", + "and": "et logique" + }, "filter_mode": { "exclude": "exclure", "include": "inclure" diff --git a/custom_components/xiaomi_home/miot/i18n/ja.json b/custom_components/xiaomi_home/miot/i18n/ja.json index 529e05e..d714539 100644 --- a/custom_components/xiaomi_home/miot/i18n/ja.json +++ b/custom_components/xiaomi_home/miot/i18n/ja.json @@ -9,6 +9,10 @@ "auto": "自動", "cloud": "クラウド" }, + "statistics_logic": { + "or": "ORロジック", + "and": "ANDロジック" + }, "filter_mode": { "exclude": "除外", "include": "含む" diff --git a/custom_components/xiaomi_home/miot/i18n/nl.json b/custom_components/xiaomi_home/miot/i18n/nl.json index c3a4776..01ada51 100644 --- a/custom_components/xiaomi_home/miot/i18n/nl.json +++ b/custom_components/xiaomi_home/miot/i18n/nl.json @@ -9,6 +9,10 @@ "auto": "Automatisch", "cloud": "Cloud" }, + "statistics_logic": { + "or": "OF-logica", + "and": "EN-logica" + }, "filter_mode": { "exclude": "Uitsluiten", "include": "Inclusief" diff --git a/custom_components/xiaomi_home/miot/i18n/pt-BR.json b/custom_components/xiaomi_home/miot/i18n/pt-BR.json index 5cc6048..109837e 100644 --- a/custom_components/xiaomi_home/miot/i18n/pt-BR.json +++ b/custom_components/xiaomi_home/miot/i18n/pt-BR.json @@ -9,6 +9,10 @@ "auto": "automático", "cloud": "nuvem" }, + "statistics_logic": { + "or": "lógica OU", + "and": "lógica E" + }, "filter_mode": { "exclude": "excluir", "include": "incluir" diff --git a/custom_components/xiaomi_home/miot/i18n/pt.json b/custom_components/xiaomi_home/miot/i18n/pt.json index d072dda..1ff075e 100644 --- a/custom_components/xiaomi_home/miot/i18n/pt.json +++ b/custom_components/xiaomi_home/miot/i18n/pt.json @@ -9,6 +9,10 @@ "auto": "Automático", "cloud": "Nuvem" }, + "statistics_logic": { + "or": "Ou lógica", + "and": "E lógica" + }, "filter_mode": { "exclude": "Excluir", "include": "Incluir" diff --git a/custom_components/xiaomi_home/miot/i18n/ru.json b/custom_components/xiaomi_home/miot/i18n/ru.json index 0763cc1..acd66f4 100644 --- a/custom_components/xiaomi_home/miot/i18n/ru.json +++ b/custom_components/xiaomi_home/miot/i18n/ru.json @@ -9,6 +9,10 @@ "auto": "автоматический", "cloud": "облако" }, + "statistics_logic": { + "or": "логика ИЛИ", + "and": "логика И" + }, "filter_mode": { "exclude": "исключить", "include": "включить" diff --git a/custom_components/xiaomi_home/miot/i18n/zh-Hans.json b/custom_components/xiaomi_home/miot/i18n/zh-Hans.json index c4d1bfc..bb5f742 100644 --- a/custom_components/xiaomi_home/miot/i18n/zh-Hans.json +++ b/custom_components/xiaomi_home/miot/i18n/zh-Hans.json @@ -15,6 +15,10 @@ "room": "房间名 (卧室)", "home": "家庭名 (米家)" }, + "statistics_logic": { + "or": "或逻辑", + "and": "与逻辑" + }, "filter_mode": { "exclude": "排除", "include": "包含" diff --git a/custom_components/xiaomi_home/miot/i18n/zh-Hant.json b/custom_components/xiaomi_home/miot/i18n/zh-Hant.json index 4251a51..aec5293 100644 --- a/custom_components/xiaomi_home/miot/i18n/zh-Hant.json +++ b/custom_components/xiaomi_home/miot/i18n/zh-Hant.json @@ -9,6 +9,10 @@ "auto": "自動", "cloud": "雲端" }, + "statistics_logic": { + "or": "或邏輯", + "and": "與邏輯" + }, "filter_mode": { "exclude": "排除", "include": "包含" diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index 58357e7..6090368 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -45,6 +45,7 @@ "title": "Geräte filtern", "description": "## Gebrauchsanweisung\r\n- Unterstützt das Filtern von Geräten nach Raumnamen und Gerätetypen sowie das Filtern nach Gerätedimensionen.\r\n- Sie können auch die entsprechende Integrationsoption \"Konfiguration> Geräteliste aktualisieren\" aufrufen, um die Filterung erneut durchzuführen.", "data": { + "statistics_logic": "Statistiklogik", "room_filter_mode": "Familienraum filtern", "room_list": "Familienraum", "type_filter_mode": "Gerätetyp filtern", diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index 8a2dc40..1931c5f 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -45,6 +45,7 @@ "title": "Filter Devices", "description": "## Introduction\r\n- Supports filtering devices by room name and device type, and also supports device dimension filtering.\r\n- You can also re-filter on the corresponding integration page [Configuration>Update Device List].", "data": { + "statistics_logic": "Statistics Logic", "room_filter_mode": "Filter Family Rooms", "room_list": "Family Rooms", "type_filter_mode": "Filter Device Connect Type", diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index 1332e44..057d114 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -45,6 +45,7 @@ "title": "Filtrar Dispositivos", "description": "## Introducción\r\n- Admite la filtración de dispositivos por nombre de habitación y tipo de dispositivo, y también admite la filtración por familia.\r\n- También puede volver a filtrar en la página correspondiente de la integración [Configuración>Actualizar lista de dispositivos].", "data": { + "statistics_logic": "Lógica de Estadísticas", "room_filter_mode": "Filtrar Habitaciones de la Familia", "room_list": "Habitaciones de la Familia", "type_filter_mode": "Filtrar Tipo de Dispositivo", diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index 49b0a95..a072ac0 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Paramètres Avancés", - "description": "## Introduction\r\n### Sauf si vous comprenez très bien la signification des options suivantes, veuillez les laisser par défaut.\r\n###Filtrer les appareils\r\nPrend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n### Mode de Contrôle\r\n- Automatique : Lorsqu'une passerelle Xiaomi est disponible dans le réseau local, Home Assistant enverra les commandes de contrôle des appareils via la passerelle pour permettre le contrôle local. Si aucune passerelle n'est disponible dans le réseau local, Home Assistant essaiera d'envoyer les commandes de contrôle des appareils via le protocole OT Xiaomi pour permettre le contrôle local. Seules si les conditions de contrôle local ci-dessus ne sont pas remplies, les commandes de contrôle des appareils seront envoyées via le cloud.\r\n- Cloud : Les commandes de contrôle des appareils sont envoyées uniquement via le cloud.\r\n### Mode de Débogage d’Actions\r\nPour les méthodes définies par les appareils MIoT-Spec-V2, en plus de générer une entité de notification, une entité de champ de texte sera également générée pour vous permettre d'envoyer des commandes de contrôle aux appareils lors du débogage.\r\n### Masquer les Entités Non Standard\r\nMasquer les entités générées par des instances MIoT-Spec-V2 non standard et commençant par \"*\".", + "description": "## Introduction\r\n### Sauf si vous comprenez très bien la signification des options suivantes, veuillez les laisser par défaut.\r\n### Filtrer les appareils\r\nPrend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n### Mode de Contrôle\r\n- Automatique : Lorsqu'une passerelle Xiaomi est disponible dans le réseau local, Home Assistant enverra les commandes de contrôle des appareils via la passerelle pour permettre le contrôle local. Si aucune passerelle n'est disponible dans le réseau local, Home Assistant essaiera d'envoyer les commandes de contrôle des appareils via le protocole OT Xiaomi pour permettre le contrôle local. Seules si les conditions de contrôle local ci-dessus ne sont pas remplies, les commandes de contrôle des appareils seront envoyées via le cloud.\r\n- Cloud : Les commandes de contrôle des appareils sont envoyées uniquement via le cloud.\r\n### Mode de Débogage d’Actions\r\nPour les méthodes définies par les appareils MIoT-Spec-V2, en plus de générer une entité de notification, une entité de champ de texte sera également générée pour vous permettre d'envoyer des commandes de contrôle aux appareils lors du débogage.\r\n### Masquer les Entités Non Standard\r\nMasquer les entités générées par des instances MIoT-Spec-V2 non standard et commençant par \"*\".", "data": { "devices_filter": "Filtrer les Appareils", "ctrl_mode": "Mode de Contrôle", @@ -45,6 +45,7 @@ "title": "Filtrer les Appareils", "description": "## Introduction\r\n- Prend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n- Vous pouvez également accéder à la page de filtrage correspondante de l'intégration [Configuration> Mettre à jour la liste des appareils] pour refiltrer.", "data": { + "statistics_logic": "Logique de Statistiques", "room_filter_mode": "Filtrer les Pièces", "room_list": "Pièces", "type_filter_mode": "Filtrer les Types d'Appareils", diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index 59e2cae..0d6acc4 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "高度な設定オプション", - "description": "## 紹介\r\n### 以下のオプションの意味がよくわからない場合は、デフォルトのままにしてください。\r\n###デバイスのフィルタリング\r\n部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n### コントロールモード\r\n- 自動:ローカルネットワーク内に利用可能なXiaomi中央ゲートウェイがある場合、Home Assistantはデバイス制御命令を送信するために優先的に中央ゲートウェイを使用します。ローカルネットワークに中央ゲートウェイがない場合、Xiaomi OTプロトコルを使用してデバイス制御命令を送信し、ローカル制御機能を実現します。上記のローカル制御条件が満たされない場合のみ、デバイス制御命令はクラウドを介して送信されます。\r\n- クラウド:制御命令はクラウドを介してのみ送信されます。\r\n### Actionデバッグモード\r\nデバイスが定義するMIoT-Spec-V2のメソッドに対して、通知エンティティを生成するだけでなく、デバイスに制御命令を送信するためのテキスト入力ボックスエンティティも生成されます。デバッグ時にデバイスに制御命令を送信するために使用できます。\r\n### 非標準生成エンティティを隠す\r\n「*」で始まる名前の非標準MIoT-Spec-V2インスタンスによって生成されたエンティティを非表示にします。", + "description": "## 紹介\r\n### 以下のオプションの意味がよくわからない場合は、デフォルトのままにしてください。\r\n### デバイスのフィルタリング\r\n部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n### コントロールモード\r\n- 自動:ローカルネットワーク内に利用可能なXiaomi中央ゲートウェイがある場合、Home Assistantはデバイス制御命令を送信するために優先的に中央ゲートウェイを使用します。ローカルネットワークに中央ゲートウェイがない場合、Xiaomi OTプロトコルを使用してデバイス制御命令を送信し、ローカル制御機能を実現します。上記のローカル制御条件が満たされない場合のみ、デバイス制御命令はクラウドを介して送信されます。\r\n- クラウド:制御命令はクラウドを介してのみ送信されます。\r\n### Actionデバッグモード\r\nデバイスが定義するMIoT-Spec-V2のメソッドに対して、通知エンティティを生成するだけでなく、デバイスに制御命令を送信するためのテキスト入力ボックスエンティティも生成されます。デバッグ時にデバイスに制御命令を送信するために使用できます。\r\n### 非標準生成エンティティを隠す\r\n「*」で始まる名前の非標準MIoT-Spec-V2インスタンスによって生成されたエンティティを非表示にします。", "data": { "devices_filter": "デバイスをフィルタリング", "ctrl_mode": "コントロールモード", @@ -45,6 +45,7 @@ "title": "デバイスをフィルタリング", "description": "## 紹介\r\n- 部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n- 対応する統合項目【設定>デバイスリストの更新】ページに移動して再度フィルタリングすることもできます。", "data": { + "statistics_logic": "統計ロジック", "room_filter_mode": "家族の部屋をフィルタリング", "room_list": "家族の部屋", "type_filter_mode": "デバイスタイプをフィルタリング", diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index 079071f..53079be 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -45,6 +45,7 @@ "title": "Apparaten filteren", "description": "## Inleiding\r\n- Ondersteunt het filteren van apparaten op basis van kamer- en apparaattypen, en ondersteunt ook apparaatdimensiefiltering.\r\n- U kunt ook naar de overeenkomstige integratie-item [Configuratie>Apparaatlijst bijwerken] pagina gaan om opnieuw te filteren.", "data": { + "statistics_logic": "Statistische logica", "room_filter_mode": "Kamerfiltermodus", "room_list": "Kamers", "type_filter_mode": "Apparaattypen filteren", diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index c89fc0d..5454e5b 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -45,6 +45,7 @@ "title": "Filtrar Dispositivos", "description": "## Introdução\r\n- Suporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n- Você também pode acessar a página correspondente da integração [Configuração>Atualizar Lista de Dispositivos] para refiltrar.", "data": { + "statistics_logic": "Lógica de Estatísticas", "room_filter_mode": "Filtrar por Sala", "room_list": "Salas", "type_filter_mode": "Filtrar por Tipo de Dispositivo", diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index 761a8c7..892843b 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -45,6 +45,7 @@ "title": "Filtrar Dispositivos", "description": "## Introdução\r\n- Suporta a filtragem de dispositivos por nome de sala e tipo de dispositivo, bem como a filtragem por família.\r\n- Pode também aceder à página de configuração correspondente da integração [Configuração > Atualizar Lista de Dispositivos] para refazer a filtragem.", "data": { + "statistics_logic": "Lógica de Estatísticas", "room_filter_mode": "Filtrar por Sala", "room_list": "Salas", "type_filter_mode": "Filtrar por Tipo de Dispositivo", diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index 3d7b3a3..8965c72 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -45,6 +45,7 @@ "title": "Фильтрация устройств", "description": "## Введение\r\n- Поддерживает фильтрацию устройств по названию комнаты и типу устройства, а также фильтрацию по уровню устройства.\r\n- Вы также можете перейти на соответствующую страницу интеграции [Настройки> Обновить список устройств], чтобы перефильтровать.", "data": { + "statistics_logic": "Логика статистики", "room_filter_mode": "Фильтрация по комнатам семьи", "room_list": "Комнаты семьи", "type_filter_mode": "Фильтрация по типу устройства", diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index 90fe7bc..cf3e141 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "高级设置选项", - "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n###筛选设备\r\n支持按照房间名称和设备类型筛选设备,同时也支持设备维度筛选。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。", + "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n### 筛选设备\r\n支持按照房间名称和设备类型筛选设备,同时也支持设备维度筛选。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。", "data": { "devices_filter": "筛选设备", "ctrl_mode": "控制模式", @@ -43,8 +43,9 @@ }, "devices_filter": { "title": "筛选设备", - "description": "## 使用介绍\r\n- 支持按照房间名称和设备类型筛选设备,同时也支持设备维度筛选。\r\n- 您也可以进入对应集成项【配置>更新设备列表】页面重新筛选。", + "description": "## 使用介绍\r\n支持按照房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n- 统计优先级:排除优先级高于包含优先级,会先取包含项,然后再排除。\r\n- 筛选优先级:筛选设备>筛选设备型号>筛选设备接入类型>筛选家庭房间\r\n### 统计逻辑\r\n- 与逻辑:取所有同模式筛选项的交集。\r\n- 或逻辑:取所有同模式筛选项的并集。\r\n### 筛选模式\r\n- 排除:移除不需要的项。\r\n- 包含:包含需要的项。\r\n- 您也可以进入对应集成项【配置>更新设备列表】页面重新筛选。", "data": { + "statistics_logic": "统计逻辑", "room_filter_mode": "筛选家庭房间", "room_list": "家庭房间", "type_filter_mode": "筛选设备接入类型", diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index 9ac4108..2c7300a 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "高級設置選項", - "description": "## 使用介紹\r\n### 除非您非常清楚下列選項的含義,否則請保持默認。\r\n###篩選設備\r\n支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n### 控制模式\r\n- 自動:本地局域網內存在可用的小米中樞網關時, Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。本地局域網不存在中樞時,會嘗試通過小米OT協議發送控制指令,以實現本地化控制功能。只有當上述本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令僅通過雲端發送。\r\n### Action 調試模式\r\n對於設備 MIoT-Spec-V2 定義的方法,在生成通知實體之外,還會生成一個文本輸入框實體,您可以在調試時用它向設備發送控制指令。\r\n### 隱藏非標準生成實體\r\n隱藏名稱以“*”開頭的非標準 MIoT-Spec-V2 實例生成的實體。", + "description": "## 使用介紹\r\n### 除非您非常清楚下列選項的含義,否則請保持默認。\r\n### 篩選設備\r\n支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n### 控制模式\r\n- 自動:本地局域網內存在可用的小米中樞網關時, Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。本地局域網不存在中樞時,會嘗試通過小米OT協議發送控制指令,以實現本地化控制功能。只有當上述本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令僅通過雲端發送。\r\n### Action 調試模式\r\n對於設備 MIoT-Spec-V2 定義的方法,在生成通知實體之外,還會生成一個文本輸入框實體,您可以在調試時用它向設備發送控制指令。\r\n### 隱藏非標準生成實體\r\n隱藏名稱以“*”開頭的非標準 MIoT-Spec-V2 實例生成的實體。", "data": { "devices_filter": "篩選設備", "ctrl_mode": "控制模式", @@ -45,6 +45,7 @@ "title": "篩選設備", "description": "## 使用介紹\r\n- 支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n- 您也可以進入對應集成項【配置>更新設備列表】頁面重新篩選。", "data": { + "statistics_logic": "統計邏輯", "room_filter_mode": "篩選家庭房間", "room_list": "家庭房間", "type_filter_mode": "篩選設備接入類型", From ab5fac9f4590f1a67078aeec0e09af17e19dd077 Mon Sep 17 00:00:00 2001 From: topsworld Date: Mon, 23 Dec 2024 22:01:06 +0800 Subject: [PATCH 14/24] fix: fix some type error --- custom_components/xiaomi_home/config_flow.py | 369 +++++++++++++------ 1 file changed, 247 insertions(+), 122 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index 46bab14..79517a4 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -101,37 +101,39 @@ class XiaomiMihomeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): # pylint: disable=unused-argument, inconsistent-quotes VERSION = 1 MINOR_VERSION = 1 + DEFAULT_AREA_NAME_RULE = 'room' _main_loop: asyncio.AbstractEventLoop - _mips_service: Optional[MipsService] - _miot_storage: Optional[MIoTStorage] - _miot_network: Optional[MIoTNetwork] - _miot_i18n: Optional[MIoTI18n] - - _integration_language: Optional[str] - _storage_path: Optional[str] - _virtual_did: Optional[str] - _uid: Optional[str] - _uuid: Optional[str] - _ctrl_mode: Optional[str] - _area_name_rule: Optional[str] + _miot_network: MIoTNetwork + _mips_service: MipsService + _miot_storage: MIoTStorage + _miot_i18n: MIoTI18n + + _integration_language: str + _storage_path: str + _virtual_did: str + _uid: str + _uuid: str + _ctrl_mode: str + _area_name_rule: str _action_debug: bool _hide_non_standard_entities: bool _display_devices_changed_notify: bool - _auth_info: Optional[dict] - _nick_name: Optional[str] + + _auth_info: dict + _nick_name: str _home_selected: dict - _home_info_buffer: Optional[dict[str, str | dict[str, dict]]] - _home_list: Optional[dict] + _home_info_buffer: dict + _home_list_show: dict _device_list_sorted: dict _device_list_filter: dict - _cloud_server: Optional[str] - _oauth_redirect_url: Optional[str] + _cloud_server: str + _oauth_redirect_url_full: str _miot_oauth: Optional[MIoTOauthClient] _miot_http: Optional[MIoTHttpClient] _user_cert_state: bool - _oauth_auth_url: Optional[str] + _oauth_auth_url: str _task_oauth: Optional[asyncio.Task[None]] _config_error_reason: Optional[str] @@ -139,70 +141,65 @@ class XiaomiMihomeConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): def __init__(self) -> None: self._main_loop = asyncio.get_running_loop() - self._mips_service = None - self._miot_storage = None - self._miot_network = None - self._miot_i18n = None - - self._integration_language = None - self._storage_path = None - self._virtual_did = None - self._uid = None - self._uuid = None # MQTT client id - self._ctrl_mode = None - self._area_name_rule = None + self._integration_language = DEFAULT_INTEGRATION_LANGUAGE + self._storage_path = '' + self._virtual_did = '' + self._uid = '' + self._uuid = '' # MQTT client id + self._ctrl_mode = DEFAULT_CTRL_MODE + 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._auth_info = None - self._nick_name = None + self._auth_info = {} + self._nick_name = DEFAULT_NICK_NAME self._home_selected = {} - self._home_info_buffer = None - self._home_list = None - self._device_list_sorted = None + self._home_info_buffer = {} + self._home_list_show = {} + self._device_list_sorted = {} - self._cloud_server = None - self._oauth_redirect_url = None + self._cloud_server = DEFAULT_CLOUD_SERVER + self._oauth_redirect_url_full = '' self._miot_oauth = None self._miot_http = None - self._user_cert_state = False - self._oauth_auth_url = None + self._user_cert_state = False + self._oauth_auth_url = '' self._task_oauth = None self._config_error_reason = None self._fut_oauth_code = None - async def async_step_user(self, user_input=None): + async def async_step_user( + self, user_input: Optional[dict] = None + ): self.hass.data.setdefault(DOMAIN, {}) - loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() - - if self._virtual_did is None: + if not self._virtual_did: self._virtual_did = str(secrets.randbits(64)) self.hass.data[DOMAIN].setdefault(self._virtual_did, {}) - if self._storage_path is None: + if not self._storage_path: self._storage_path = self.hass.config.path('.storage', DOMAIN) # MIoT network self._miot_network = self.hass.data[DOMAIN].get('miot_network', None) - if self._miot_network is None: - self._miot_network = MIoTNetwork(loop=loop) + if not self._miot_network: + self._miot_network = MIoTNetwork(loop=self._main_loop) self.hass.data[DOMAIN]['miot_network'] = self._miot_network await self._miot_network.init_async( refresh_interval=NETWORK_REFRESH_INTERVAL) _LOGGER.info('async_step_user, create miot network') # Mips server self._mips_service = self.hass.data[DOMAIN].get('mips_service', None) - if self._mips_service is None: + if not self._mips_service: aiozc: HaAsyncZeroconf = await zeroconf.async_get_async_instance( self.hass) - self._mips_service = MipsService(aiozc=aiozc, loop=loop) + self._mips_service = MipsService(aiozc=aiozc, loop=self._main_loop) self.hass.data[DOMAIN]['mips_service'] = self._mips_service await self._mips_service.init_async() _LOGGER.info('async_step_user, create mips service') # MIoT storage self._miot_storage = self.hass.data[DOMAIN].get('miot_storage', None) - if self._miot_storage is None: + if not self._miot_storage: self._miot_storage = MIoTStorage( - root_path=self._storage_path, loop=loop) + root_path=self._storage_path, loop=self._main_loop) self.hass.data[DOMAIN]['miot_storage'] = self._miot_storage _LOGGER.info( 'async_step_user, create miot storage, %s', self._storage_path) @@ -214,7 +211,9 @@ async def async_step_user(self, user_input=None): return await self.async_step_eula(user_input) - async def async_step_eula(self, user_input=None): + async def async_step_eula( + self, user_input: Optional[dict] = None + ): if user_input: if user_input.get('eula', None) is True: return await self.async_step_auth_config() @@ -225,16 +224,18 @@ async def __display_eula(self, reason: str): return self.async_show_form( step_id='eula', data_schema=vol.Schema({ - vol.Required('eula', default=False): bool, + vol.Required('eula', default=False): bool, # type: ignore }), last_step=False, errors={'base': reason}, ) - async def async_step_auth_config(self, user_input=None): + async def async_step_auth_config( + self, user_input: Optional[dict] = None + ): if user_input: self._cloud_server = user_input.get( - 'cloud_server', DEFAULT_CLOUD_SERVER) + 'cloud_server', self._cloud_server) self._integration_language = user_input.get( 'integration_language', DEFAULT_INTEGRATION_LANGUAGE) self._miot_i18n = MIoTI18n( @@ -242,7 +243,7 @@ async def async_step_auth_config(self, user_input=None): await self._miot_i18n.init_async() webhook_path = webhook_async_generate_path( webhook_id=self._virtual_did) - self._oauth_redirect_url = ( + self._oauth_redirect_url_full = ( f'{user_input.get("oauth_redirect_url")}{webhook_path}') return await self.async_step_oauth(user_input) # Generate default language from HomeAssistant config (not user config) @@ -257,33 +258,38 @@ async def async_step_auth_config(self, user_input=None): data_schema=vol.Schema({ vol.Required( 'cloud_server', - default=DEFAULT_CLOUD_SERVER): vol.In(CLOUD_SERVERS), + default=self._cloud_server # type: ignore + ): vol.In(CLOUD_SERVERS), vol.Required( 'integration_language', - default=default_language): vol.In(INTEGRATION_LANGUAGES), + default=default_language # type: ignore + ): vol.In(INTEGRATION_LANGUAGES), vol.Required( 'oauth_redirect_url', - default=OAUTH_REDIRECT_URL): vol.In([OAUTH_REDIRECT_URL]), + default=OAUTH_REDIRECT_URL # type: ignore + ): vol.In([OAUTH_REDIRECT_URL]), }), last_step=False, ) - async def async_step_oauth(self, user_input=None): + async def async_step_oauth( + self, user_input: Optional[dict] = None + ): # 1: Init miot_oauth, generate auth url try: - if self._miot_oauth is None: + if not self._miot_oauth: _LOGGER.info( 'async_step_oauth, redirect_url: %s', - self._oauth_redirect_url) + self._oauth_redirect_url_full) miot_oauth = MIoTOauthClient( client_id=OAUTH2_CLIENT_ID, - redirect_url=self._oauth_redirect_url, + redirect_url=self._oauth_redirect_url_full, cloud_server=self._cloud_server ) state = str(secrets.randbits(64)) self.hass.data[DOMAIN][self._virtual_did]['oauth_state'] = state self._oauth_auth_url = miot_oauth.gen_auth_url( - redirect_url=self._oauth_redirect_url, state=state) + redirect_url=self._oauth_redirect_url_full, state=state) _LOGGER.info( 'async_step_oauth, oauth_url: %s', self._oauth_auth_url) webhook_async_unregister( @@ -298,7 +304,7 @@ async def async_step_oauth(self, user_input=None): ) self._fut_oauth_code = self.hass.data[DOMAIN][ self._virtual_did].get('fut_oauth_code', None) - if self._fut_oauth_code is None: + if not self._fut_oauth_code: self._fut_oauth_code = self._main_loop.create_future() self.hass.data[DOMAIN][self._virtual_did][ 'fut_oauth_code'] = self._fut_oauth_code @@ -337,11 +343,16 @@ async def async_step_oauth(self, user_input=None): async def __check_oauth_async(self) -> None: # TASK 1: Get oauth code + if not self._fut_oauth_code: + raise MIoTConfigError('oauth_code_fut_error') oauth_code: Optional[str] = await self._fut_oauth_code - + if not oauth_code: + raise MIoTConfigError('oauth_code_error') # TASK 2: Get access_token and user_info from miot_oauth if not self._auth_info: try: + if not self._miot_oauth: + raise MIoTConfigError('oauth_client_error') auth_info = await self._miot_oauth.get_access_token_async( code=oauth_code) if not self._miot_http: @@ -363,7 +374,7 @@ async def __check_oauth_async(self) -> None: try: self._nick_name = ( await self._miot_http.get_user_info_async() or {} - ).get('miliaoNick', DEFAULT_NICK_NAME) + ).get('miliaoNick', self._nick_name) except (MIoTOauthError, json.JSONDecodeError): self._nick_name = DEFAULT_NICK_NAME _LOGGER.error('get nick name failed') @@ -374,6 +385,8 @@ async def __check_oauth_async(self) -> None: # TASK 3: Get home info try: + if not self._miot_http: + raise MIoTConfigError('http_client_error') self._home_info_buffer = ( await self._miot_http.get_devices_async()) _LOGGER.info('get_homeinfos response: %s', self._home_info_buffer) @@ -433,7 +446,7 @@ async def __check_oauth_async(self) -> None: f'{home_info["home_name"]} ' f'[ {len(dev_list)} {tip_devices} {tip_central} ]') - self._home_list = dict(sorted(home_list.items())) + self._home_list_show = dict(sorted(home_list.items())) # TASK 7: Get user's MiHome certificate if self._cloud_server in SUPPORT_CENTRAL_GATEWAY_CTRL: @@ -454,6 +467,8 @@ async def __check_oauth_async(self) -> None: user_key=user_key, did=self._virtual_did) crt_str = await self._miot_http.get_central_cert_async( csr_str) + if not crt_str: + raise MIoTError('get_central_cert_async failed') if not await miot_cert.update_user_cert_async( cert=crt_str): raise MIoTError('update_user_cert_async failed') @@ -492,10 +507,12 @@ async def async_step_oauth_error(self, user_input=None): errors={'base': error_reason}, ) - async def async_step_homes_select(self, user_input=None): + async def async_step_homes_select( + self, user_input: Optional[dict] = None + ): _LOGGER.debug('async_step_homes_select') try: - if user_input is None: + if not user_input: return await self.__display_homes_select_form('') home_selected: list = user_input.get('home_infos', []) @@ -506,7 +523,8 @@ async def async_step_homes_select(self, user_input=None): 'homes']['home_list'].items(): if home_id in home_selected: self._home_selected[home_id] = home_info - self._area_name_rule = user_input.get('area_name_rule') + self._area_name_rule = user_input.get( + 'area_name_rule', self._area_name_rule) # Storage device list devices_list: dict[str, dict] = { did: dev_info @@ -544,10 +562,16 @@ async def __display_homes_select_form(self, reason: str): return self.async_show_form( step_id='homes_select', data_schema=vol.Schema({ - vol.Required('home_infos'): cv.multi_select(self._home_list), - vol.Required('area_name_rule', default='room'): vol.In( - self._miot_i18n.translate(key='config.room_name_rule')), - vol.Required('advanced_options', default=False): bool, + vol.Required('home_infos'): cv.multi_select( + self._home_list_show), + vol.Required( + 'area_name_rule', + default=self._area_name_rule # type: ignore + ): vol.In(self._miot_i18n.translate( + key='config.room_name_rule')), + vol.Required( + 'advanced_options', default=False # type: ignore + ): bool, }), errors={'base': reason}, description_placeholders={ @@ -556,7 +580,9 @@ async def __display_homes_select_form(self, reason: str): last_step=False, ) - async def async_step_advanced_options(self, user_input: dict = None): + async def async_step_advanced_options( + self, user_input: Optional[dict] = None + ): if user_input: self._ctrl_mode = user_input.get('ctrl_mode', self._ctrl_mode) self._action_debug = user_input.get( @@ -570,16 +596,22 @@ async def async_step_advanced_options(self, user_input: dict = None): return self.async_show_form( step_id='advanced_options', data_schema=vol.Schema({ - vol.Required('devices_filter', default=False): bool, - vol.Required('ctrl_mode', default=DEFAULT_CTRL_MODE): vol.In( - self._miot_i18n.translate(key='config.control_mode')), - vol.Required('action_debug', default=self._action_debug): bool, + vol.Required( + 'devices_filter', default=False): bool, # type: ignore + vol.Required( + 'ctrl_mode', default=self._ctrl_mode # type: ignore + ): vol.In(self._miot_i18n.translate(key='config.control_mode')), + vol.Required( + 'action_debug', default=self._action_debug # type: ignore + ): bool, vol.Required( 'hide_non_standard_entities', - default=self._hide_non_standard_entities): bool, + default=self._hide_non_standard_entities # type: ignore + ): bool, vol.Required( 'display_devices_changed_notify', - default=self._display_devices_changed_notify): bool, + default=self._display_devices_changed_notify # type: ignore + ): bool, }), last_step=False, ) @@ -645,16 +677,17 @@ async def async_step_devices_filter( return await self.__display_devices_filter_form(reason='') async def __display_devices_filter_form(self, reason: str): + tip_devices: str = self._miot_i18n.translate( - key='config.other.devices') + key='config.other.devices') # type: ignore tip_without_room: str = self._miot_i18n.translate( - key='config.other.without_room') + key='config.other.without_room') # type: ignore trans_statistics_logic: dict = self._miot_i18n.translate( - key='config.statistics_logic') + key='config.statistics_logic') # type: ignore trans_filter_mode: dict = self._miot_i18n.translate( - key='config.filter_mode') + key='config.filter_mode') # type: ignore trans_connect_type: dict = self._miot_i18n.translate( - key='config.connect_type') + key='config.connect_type') # type: ignore room_device_count: dict = {} model_device_count: dict = {} @@ -692,22 +725,27 @@ async def __display_devices_filter_form(self, reason: str): return self.async_show_form( step_id='devices_filter', data_schema=vol.Schema({ - vol.Required('room_filter_mode', default='exclude'): - vol.In(trans_filter_mode), + vol.Required( + 'room_filter_mode', default='exclude' # type: ignore + ): vol.In(trans_filter_mode), vol.Optional('room_list'): cv.multi_select(room_list), - vol.Required('type_filter_mode', default='exclude'): - vol.In(trans_filter_mode), + vol.Required( + 'type_filter_mode', default='exclude' # type: ignore + ): vol.In(trans_filter_mode), vol.Optional('type_list'): cv.multi_select(type_list), - vol.Required('model_filter_mode', default='exclude'): - vol.In(trans_filter_mode), + vol.Required( + 'model_filter_mode', default='exclude' # type: ignore + ): vol.In(trans_filter_mode), vol.Optional('model_list'): cv.multi_select(dict(sorted( model_list.items(), key=lambda item: item[0]))), - vol.Required('devices_filter_mode', default='exclude'): - vol.In(trans_filter_mode), + vol.Required( + 'devices_filter_mode', default='exclude' # type: ignore + ): vol.In(trans_filter_mode), vol.Optional('device_list'): cv.multi_select(dict(sorted( device_list.items(), key=lambda device: device[1]))), - vol.Required('statistics_logic', default='or'): - vol.In(trans_statistics_logic), + vol.Required( + 'statistics_logic', default='or' # type: ignore + ): vol.In(trans_statistics_logic), }), errors={'base': reason}, last_step=False @@ -759,7 +797,7 @@ async def config_flow_done(self): 'uid': self._uid, 'nick_name': self._nick_name, 'cloud_server': self._cloud_server, - 'oauth_redirect_url': self._oauth_redirect_url, + 'oauth_redirect_url': self._oauth_redirect_url_full, 'ctrl_mode': self._ctrl_mode, 'home_selected': self._home_selected, 'area_name_rule': self._area_name_rule, @@ -784,7 +822,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow): # pylint: disable=inconsistent-quotes _config_entry: config_entries.ConfigEntry _main_loop: asyncio.AbstractEventLoop - _miot_client: Optional[MIoTClient] + _miot_client: MIoTClient _miot_network: Optional[MIoTNetwork] _miot_storage: Optional[MIoTStorage] @@ -799,7 +837,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow): _uid: Optional[str] _storage_path: Optional[str] _cloud_server: Optional[str] - _oauth_redirect_url: Optional[str] + _oauth_redirect_url_full: str _integration_language: Optional[str] _ctrl_mode: Optional[str] _nick_name: Optional[str] @@ -811,7 +849,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow): _home_selected_dict: Optional[dict] _home_info_buffer: Optional[dict[str, str | dict[str, dict]]] _home_list: Optional[dict] - _device_list: Optional[dict[str, dict]] + _device_list: dict[str, dict] _devices_add: list[str] _devices_remove: list[str] @@ -851,7 +889,7 @@ def __init__(self, config_entry: config_entries.ConfigEntry): self._uid = self._entry_data['uid'] self._storage_path = self._entry_data['storage_path'] self._cloud_server = self._entry_data['cloud_server'] - self._oauth_redirect_url = self._entry_data['oauth_redirect_url'] + self._oauth_redirect_url_full = '' self._ctrl_mode = self._entry_data['ctrl_mode'] self._integration_language = self._entry_data['integration_language'] self._nick_name = self._entry_data['nick_name'] @@ -959,7 +997,7 @@ async def async_step_auth_config(self, user_input=None): if user_input: webhook_path = webhook_async_generate_path( webhook_id=self._virtual_did) - self._oauth_redirect_url = ( + self._oauth_redirect_url_full = ( f'{user_input.get("oauth_redirect_url")}{webhook_path}') return await self.async_step_oauth(user_input) return self.async_show_form( @@ -981,9 +1019,9 @@ async def async_step_oauth(self, user_input=None): state = str(secrets.randbits(64)) self.hass.data[DOMAIN][self._virtual_did]['oauth_state'] = state self._miot_oauth.set_redirect_url( - redirect_url=self._oauth_redirect_url) + redirect_url=self._oauth_redirect_url_full) self._oauth_auth_url = self._miot_oauth.gen_auth_url( - redirect_url=self._oauth_redirect_url, state=state) + redirect_url=self._oauth_redirect_url_full, state=state) _LOGGER.info( 'async_step_oauth, oauth_url: %s', self._oauth_auth_url) @@ -1166,7 +1204,9 @@ async def async_step_update_user_info(self, user_input=None): self._nick_name_new = user_input.get('nick_name') return await self.async_step_homes_select() - async def async_step_homes_select(self, user_input=None): + async def async_step_homes_select( + self, user_input: Optional[dict] = None + ): if not self._update_devices: return await self.async_step_update_trans_rules() if not user_input: @@ -1236,27 +1276,19 @@ async def async_step_homes_select(self, user_input=None): if dev_info['home_id'] in self._home_selected_list} if not self._device_list: return await self.__display_homes_select_form('no_devices') - # Statistics devices changed - self._devices_add = [] - self._devices_remove = [] - local_devices = await self._miot_storage.load_async( - domain='miot_devices', - name=f'{self._uid}_{self._cloud_server}', - type_=dict) or {} + self._device_list_sorted = dict(sorted( + self._device_list.items(), key=lambda item: + item[1].get('home_id', '')+item[1].get('room_id', ''))) - self._devices_add = [ - did for did in self._device_list.keys() if did not in local_devices] - self._devices_remove = [ - did for did in local_devices.keys() if did not in self._device_list] - _LOGGER.debug( - 'devices update, add->%s, remove->%s', - self._devices_add, self._devices_remove) - return await self.async_step_update_trans_rules() + if user_input.get('devices_filter', False): + return await self.async_step_devices_filter() + return await self.update_devices_done_async() async def __display_homes_select_form(self, reason: str): return self.async_show_form( step_id='homes_select', data_schema=vol.Schema({ + vol.Required('devices_filter', default=False): bool, vol.Required('home_infos', default=self._home_selected_list): cv.multi_select(self._home_list), vol.Required('ctrl_mode', default=self._ctrl_mode): vol.In( @@ -1269,6 +1301,100 @@ async def __display_homes_select_form(self, reason: str): last_step=False ) + async def async_step_devices_filter( + self, user_input: Optional[dict] = None + ): + if user_input: + return await self.update_devices_done_async() + return await self.__display_devices_filter_form(reason='') + + async def __display_devices_filter_form(self, reason: str): + tip_devices: str = self._miot_i18n.translate( + key='config.other.devices') + tip_without_room: str = self._miot_i18n.translate( + key='config.other.without_room') + trans_statistics_logic: dict = self._miot_i18n.translate( + key='config.statistics_logic') + trans_filter_mode: dict = self._miot_i18n.translate( + key='config.filter_mode') + trans_connect_type: dict = self._miot_i18n.translate( + key='config.connect_type') + + room_device_count: dict = {} + model_device_count: dict = {} + connect_type_count: dict = {} + device_list: dict = {} + for did, info in self._device_list_sorted.items(): + device_list[did] = ( + f'[ {info["home_name"]} {info["room_name"]} ] ' + + f'{info["name"]}, {did}') + room_device_count.setdefault(info['room_id'], 0) + room_device_count[info['room_id']] += 1 + model_device_count.setdefault(info['model'], 0) + model_device_count[info['model']] += 1 + connect_type_count.setdefault(str(info['connect_type']), 0) + connect_type_count[str(info['connect_type'])] += 1 + model_list: dict = {} + for model, count in model_device_count.items(): + model_list[model] = f'{model} [ {count} {tip_devices} ]' + type_list: dict = { + k: f'{trans_connect_type.get(k, f"Connect Type ({k})")} ' + f'[ {v} {tip_devices} ]' + for k, v in connect_type_count.items()} + room_list: dict = {} + for home_id, home_info in self._home_selected_dict.items(): + for room_id, room_name in home_info['room_info'].items(): + if room_id not in room_device_count: + continue + room_list[room_id] = ( + f'{home_info["home_name"]} {room_name}' + f' [ {room_device_count[room_id]}{tip_devices} ]') + if home_id in room_device_count: + room_list[home_id] = ( + f'{home_info["home_name"]} {tip_without_room}' + f' [ {room_device_count[home_id]}{tip_devices} ]') + return self.async_show_form( + step_id='devices_filter', + data_schema=vol.Schema({ + vol.Required('room_filter_mode', default='exclude'): + vol.In(trans_filter_mode), + vol.Optional('room_list'): cv.multi_select(room_list), + vol.Required('type_filter_mode', default='exclude'): + vol.In(trans_filter_mode), + vol.Optional('type_list'): cv.multi_select(type_list), + vol.Required('model_filter_mode', default='exclude'): + vol.In(trans_filter_mode), + vol.Optional('model_list'): cv.multi_select(dict(sorted( + model_list.items(), key=lambda item: item[0]))), + vol.Required('devices_filter_mode', default='exclude'): + vol.In(trans_filter_mode), + vol.Optional('device_list'): cv.multi_select(dict(sorted( + device_list.items(), key=lambda device: device[1]))), + vol.Required('statistics_logic', default='or'): + vol.In(trans_statistics_logic), + }), + errors={'base': reason}, + last_step=False + ) + + async def update_devices_done_async(self): + # Statistics devices changed + self._devices_add = [] + self._devices_remove = [] + local_devices: dict = await self._miot_storage.load_async( + domain='miot_devices', + name=f'{self._uid}_{self._cloud_server}', + type_=dict) or {} # type: ignore + + self._devices_add = [ + did for did in self._device_list.keys() if did not in local_devices] + self._devices_remove = [ + did for did in local_devices.keys() if did not in self._device_list] + _LOGGER.debug( + 'devices update, add->%s, remove->%s', + self._devices_add, self._devices_remove) + return await self.async_step_update_trans_rules() + async def async_step_update_trans_rules(self, user_input=None): if not self._update_trans_rules: return await self.async_step_update_lan_ctrl_config() @@ -1397,7 +1523,6 @@ async def async_step_config_confirm(self, user_input=None): last_step=True ) - self._entry_data['oauth_redirect_url'] = self._oauth_redirect_url if self._lang_new != self._integration_language: self._entry_data['integration_language'] = self._lang_new self._need_reload = True From 043ac142375f6d3fdea960aa7a77ff78ed3eb08b Mon Sep 17 00:00:00 2001 From: topsworld Date: Mon, 23 Dec 2024 22:11:51 +0800 Subject: [PATCH 15/24] doc: update translations for option flow --- .../xiaomi_home/translations/de.json | 20 +++++++++++++++++-- .../xiaomi_home/translations/en.json | 20 +++++++++++++++++-- .../xiaomi_home/translations/es.json | 20 +++++++++++++++++-- .../xiaomi_home/translations/fr.json | 20 +++++++++++++++++-- .../xiaomi_home/translations/ja.json | 20 +++++++++++++++++-- .../xiaomi_home/translations/nl.json | 20 +++++++++++++++++-- .../xiaomi_home/translations/pt-BR.json | 20 +++++++++++++++++-- .../xiaomi_home/translations/pt.json | 20 +++++++++++++++++-- .../xiaomi_home/translations/ru.json | 20 +++++++++++++++++-- .../xiaomi_home/translations/zh-Hans.json | 20 +++++++++++++++++-- .../xiaomi_home/translations/zh-Hant.json | 20 +++++++++++++++++-- 11 files changed, 198 insertions(+), 22 deletions(-) diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index 6090368..3ef34ce 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -114,8 +114,24 @@ "title": "Familie und Geräte neu auswählen", "description": "## Gebrauchsanweisung\r\n### Steuerungsmodus\r\n- Automatisch: Wenn im lokalen Netzwerk ein verfügbarer Xiaomi-Zentralgateway vorhanden ist, wird Home Assistant bevorzugt Steuerbefehle über den Zentralgateway senden, um eine lokale Steuerung zu ermöglichen. Wenn im lokalen Netzwerk kein Zentralgateway vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden, um eine lokale Steuerung zu ermöglichen. Nur wenn die oben genannten Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Steuerbefehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden nur über die Cloud gesendet.\r\n### Familienimport für importierte Geräte\r\nDie Integration fügt Geräte aus den ausgewählten Familien hinzu.\r\n \r\n### Hallo {nick_name}! Bitte wählen Sie den Steuerungsmodus der Integration sowie die Familie aus, in der sich die hinzuzufügenden Geräte befinden.", "data": { - "ctrl_mode": "Steuerungsmodus", - "home_infos": "Familienimport für importierte Geräte" + "home_infos": "Familienimport für importierte Geräte", + "devices_filter": "Geräte filtern", + "ctrl_mode": "Steuerungsmodus" + } + }, + "devices_filter": { + "title": "Geräte filtern", + "description": "## Gebrauchsanweisung\r\n- Unterstützt das Filtern von Geräten nach Raumnamen und Gerätetypen sowie das Filtern nach Gerätedimensionen.\r\n- Sie können auch die entsprechende Integrationsoption \"Konfiguration> Geräteliste aktualisieren\" aufrufen, um die Filterung erneut durchzuführen.", + "data": { + "statistics_logic": "Statistiklogik", + "room_filter_mode": "Familienraum filtern", + "room_list": "Familienraum", + "type_filter_mode": "Gerätetyp filtern", + "type_list": "Gerätetyp", + "model_filter_mode": "Gerätemodell filtern", + "model_list": "Gerätemodell", + "devices_filter_mode": "Geräte filtern", + "device_list": "Geräteliste" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index 1931c5f..d16c67c 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -114,8 +114,24 @@ "title": "Re-select Home and Devices", "description": "## Usage Instructions\r\n### Control mode\r\n- Auto: When there is an available Xiaomi central hub gateway in the local area network, Home Assistant will prioritize sending device control commands through the central hub gateway to achieve local control. If there is no central hub gateway in the local area network, it will attempt to send control commands through Xiaomi LAN control function. Only when the above local control conditions are not met, the device control commands will be sent through the cloud.\r\n- Cloud: All control commands are sent through the cloud.\r\n### Import devices from home\r\nThe integration will add devices from the selected homes.\r\n \r\n### Hello {nick_name}, please select the integration control mode and the home where the device you want to import.", "data": { - "ctrl_mode": "Control mode", - "home_infos": "Import devices from home" + "home_infos": "Import devices from home", + "devices_filter": "Filter devices", + "ctrl_mode": "Control mode" + } + }, + "devices_filter": { + "title": "Filter Devices", + "description": "## Introduction\r\n- Supports filtering devices by room name and device type, and also supports device dimension filtering.\r\n- You can also re-filter on the corresponding integration page [Configuration>Update Device List].", + "data": { + "statistics_logic": "Statistics Logic", + "room_filter_mode": "Filter Family Rooms", + "room_list": "Family Rooms", + "type_filter_mode": "Filter Device Connect Type", + "type_list": "Device Connect Type", + "model_filter_mode": "Filter Device Model", + "model_list": "Device Model", + "devices_filter_mode": "Filter Devices", + "device_list": "Device List" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index 057d114..a92524c 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -114,8 +114,24 @@ "title": "Recomendar hogares y dispositivos", "description": "## Instrucciones de uso\r\n### Modo de control\r\n- Automático: Cuando hay un gateway central de Xiaomi disponible en la red local, Home Assistant priorizará el envío de comandos de control de dispositivos a través del gateway central para lograr un control localizado. Si no hay un gateway central en la red local, intentará enviar comandos de control a través del protocolo Xiaomi OT para lograr un control localizado. Solo cuando no se cumplan las condiciones anteriores de control localizado, los comandos de control del dispositivo se enviarán a través de la nube.\r\n- Nube: Los comandos de control solo se envían a través de la nube.\r\n### Hogares de dispositivos importados\r\nLa integración agregará los dispositivos en los hogares seleccionados.\r\n \r\n### ¡Hola, {nick_name}! Seleccione el modo de control de integración y el hogar donde se encuentran los dispositivos que desea agregar.", "data": { - "ctrl_mode": "Modo de control", - "home_infos": "Hogares de dispositivos importados" + "home_infos": "Hogares de dispositivos importados", + "devices_filter": "Filtrar Dispositivos", + "ctrl_mode": "Modo de control" + } + }, + "devices_filter": { + "title": "Filtrar Dispositivos", + "description": "## Introducción\r\n- Admite la filtración de dispositivos por nombre de habitación y tipo de dispositivo, y también admite la filtración por familia.\r\n- También puede volver a filtrar en la página correspondiente de la integración [Configuración>Actualizar lista de dispositivos].", + "data": { + "statistics_logic": "Lógica de Estadísticas", + "room_filter_mode": "Filtrar Habitaciones de la Familia", + "room_list": "Habitaciones de la Familia", + "type_filter_mode": "Filtrar Tipo de Dispositivo", + "type_list": "Tipo de Dispositivo", + "model_filter_mode": "Filtrar Modelo de Dispositivo", + "model_list": "Modelo de Dispositivo", + "devices_filter_mode": "Filtrar Dispositivos", + "device_list": "Lista de Dispositivos" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index a072ac0..e068456 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -114,8 +114,24 @@ "title": "Re-sélectionner une maison et des appareils", "description": "## Instructions d'utilisation\r\n### Mode de contrôle\r\n- Automatique: Lorsqu'il y a une passerelle centrale Xiaomi disponible dans le réseau local, Home Assistant priorisera l'envoi des commandes de contrôle des appareils via la passerelle centrale pour réaliser un contrôle localisé. S'il n'y a pas de passerelle centrale dans le réseau local, il tentera d'envoyer des commandes de contrôle via le protocole Xiaomi OT pour réaliser un contrôle localisé. Ce n'est que lorsque les conditions de contrôle localisé ci-dessus ne sont pas remplies que les commandes de contrôle des appareils seront envoyées via le cloud.\r\n- Cloud: Les commandes de contrôle ne sont envoyées que via le cloud.\r\n### Importer une maison pour les appareils\r\nL'intégration ajoutera les appareils de la maison sélectionnée.\r\n \r\n### {nick_name} Bonjour ! Veuillez sélectionner le mode de contrôle de l'intégration et la maison où se trouvent les appareils à ajouter.", "data": { - "ctrl_mode": "Mode de contrôle", - "home_infos": "Importer une maison pour les appareils" + "home_infos": "Importer une maison pour les appareils", + "devices_filter": "Filtrer les Appareils", + "ctrl_mode": "Mode de contrôle" + } + }, + "devices_filter": { + "title": "Filtrer les Appareils", + "description": "## Introduction\r\n- Prend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n- Vous pouvez également accéder à la page de filtrage correspondante de l'intégration [Configuration> Mettre à jour la liste des appareils] pour refiltrer.", + "data": { + "statistics_logic": "Logique de Statistiques", + "room_filter_mode": "Filtrer les Pièces", + "room_list": "Pièces", + "type_filter_mode": "Filtrer les Types d'Appareils", + "type_list": "Types d'Appareils", + "model_filter_mode": "Filtrer les Modèles d'Appareils", + "model_list": "Modèles d'Appareils", + "devices_filter_mode": "Filtrer les Appareils", + "device_list": "Liste des Appareils" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index 0d6acc4..19d39a7 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -114,8 +114,24 @@ "title": "ホームとデバイスを再度選択", "description": "## 使用方法\r\n### 制御モード\r\n- 自動: ローカルエリアネットワーク内に利用可能なXiaomi中央ゲートウェイが存在する場合、Home Assistantは中央ゲートウェイを介してデバイス制御コマンドを優先的に送信し、ローカル制御機能を実現します。ローカルエリアネットワーク内に中央ゲートウェイが存在しない場合、Xiaomi OTプロトコルを介して制御コマンドを送信し、ローカル制御機能を実現しようとします。上記のローカル制御条件が満たされない場合にのみ、デバイス制御コマンドはクラウドを介して送信されます。\r\n- クラウド: 制御コマンドはクラウドを介してのみ送信されます。\r\n### 導入されたデバイスのホーム\r\n統合は、選択された家庭にあるデバイスを追加します。\r\n \r\n### {nick_name} さん、こんにちは! 統合制御モードと追加するデバイスがあるホームを選択してください。", "data": { - "ctrl_mode": "制御モード", - "home_infos": "導入されたデバイスのホーム" + "home_infos": "導入されたデバイスのホーム", + "devices_filter": "デバイスをフィルタリング", + "ctrl_mode": "制御モード" + } + }, + "devices_filter": { + "title": "デバイスをフィルタリング", + "description": "## 紹介\r\n- 部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n- 対応する統合項目【設定>デバイスリストの更新】ページに移動して再度フィルタリングすることもできます。", + "data": { + "statistics_logic": "統計ロジック", + "room_filter_mode": "家族の部屋をフィルタリング", + "room_list": "家族の部屋", + "type_filter_mode": "デバイスタイプをフィルタリング", + "type_list": "デバイスタイプ", + "model_filter_mode": "デバイスモデルをフィルタリング", + "model_list": "デバイスモデル", + "devices_filter_mode": "デバイスをフィルタリング", + "device_list": "デバイスリスト" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index 53079be..719e6b9 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -114,8 +114,24 @@ "title": "Huis en Apparaten opnieuw selecteren", "description": "## Gebruiksinstructies\r\n### Controlemodus\r\n- Auto: Wanneer er een beschikbare Xiaomi centrale hubgateway in het lokale netwerk is, geeft Home Assistant de voorkeur aan het verzenden van apparaatbedieningscommando's via de centrale hubgateway om lokale controle te bereiken. Als er geen centrale hubgateway in het lokale netwerk is, zal het proberen bedieningscommando's te verzenden via de Xiaomi LAN-controlefunctie. Alleen wanneer de bovenstaande lokale controlevoorwaarden niet zijn vervuld, worden de apparaatbedieningscommando's via de cloud verzonden.\r\n- Cloud: Alle bedieningscommando's worden via de cloud verzonden.\r\n### Apparaten importeren vanuit huis\r\nDe integratie voegt apparaten toe van de geselecteerde huizen.\r\n \r\n### Hallo {nick_name}, selecteer alstublieft de integratie controlemethodiek en het huis waar het apparaat dat u wilt importeren zich bevindt.", "data": { - "ctrl_mode": "Controlemodus", - "home_infos": "Importeer apparaten uit huis" + "home_infos": "Importeer apparaten uit huis", + "devices_filter": "Apparaten filteren", + "ctrl_mode": "Controlemodus" + } + }, + "devices_filter": { + "title": "Apparaten filteren", + "description": "## Inleiding\r\n- Ondersteunt het filteren van apparaten op basis van kamer- en apparaattypen, en ondersteunt ook apparaatdimensiefiltering.\r\n- U kunt ook naar de overeenkomstige integratie-item [Configuratie>Apparaatlijst bijwerken] pagina gaan om opnieuw te filteren.", + "data": { + "statistics_logic": "Statistische logica", + "room_filter_mode": "Kamerfiltermodus", + "room_list": "Kamers", + "type_filter_mode": "Apparaattypen filteren", + "type_list": "Apparaattypen", + "model_filter_mode": "Apparaatmodel filteren", + "model_list": "Apparaatmodellen", + "devices_filter_mode": "Apparaten filteren", + "device_list": "Apparaatlijst" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index 5454e5b..9662bb8 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -114,8 +114,24 @@ "title": "Selecionar novamente Casa e Dispositivos", "description": "## Instruções de Uso\r\n### Modo de controle\r\n- Auto: Quando houver um gateway central Xiaomi disponível na rede local, o Home Assistant priorizará o envio de comandos através dele para obter controle local. Caso não haja, tentará enviar comandos através da função de controle LAN da Xiaomi. Somente se as condições anteriores não forem atendidas, o controle será feito pela nuvem.\r\n- Nuvem: Todos os comandos de controle são enviados pela nuvem.\r\n### Importar dispositivos da casa\r\nA integração adicionará dispositivos das casas selecionadas.\r\n \r\n### Olá {nick_name}, selecione o modo de controle da integração e a casa de onde deseja importar dispositivos.", "data": { - "ctrl_mode": "Modo de controle", - "home_infos": "Importar dispositivos da casa" + "home_infos": "Importar dispositivos da casa", + "devices_filter": "Filtrar Dispositivos", + "ctrl_mode": "Modo de controle" + } + }, + "devices_filter": { + "title": "Filtrar Dispositivos", + "description": "## Introdução\r\n- Suporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n- Você também pode acessar a página correspondente da integração [Configuração>Atualizar Lista de Dispositivos] para refiltrar.", + "data": { + "statistics_logic": "Lógica de Estatísticas", + "room_filter_mode": "Filtrar por Sala", + "room_list": "Salas", + "type_filter_mode": "Filtrar por Tipo de Dispositivo", + "type_list": "Tipos de Dispositivo", + "model_filter_mode": "Filtrar por Modelo de Dispositivo", + "model_list": "Modelos de Dispositivo", + "devices_filter_mode": "Filtrar Dispositivos", + "device_list": "Lista de Dispositivos" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index 892843b..f505022 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -114,8 +114,24 @@ "title": "Selecionar novamente a Casa e os Dispositivos", "description": "## Instruções de Utilização\r\n### Modo de Controlo\r\n- Automático: Quando houver um gateway central Xiaomi disponível na rede local, o Home Assistant priorizará o envio de comandos através dele para obter controlo local. Se não existir um gateway central, tentará enviar comandos através da função de controlo LAN da Xiaomi. Apenas se estas condições não forem satisfeitas, os comandos serão enviados pela nuvem.\r\n- Nuvem: Todos os comandos de controlo são enviados através da nuvem.\r\n### Importar dispositivos da casa\r\nA integração adicionará dispositivos das casas selecionadas.\r\n \r\n### Olá {nick_name}, selecione o modo de controlo da integração e a casa da qual pretende importar dispositivos.", "data": { - "ctrl_mode": "Modo de Controlo", - "home_infos": "Importar dispositivos da casa" + "home_infos": "Importar dispositivos da casa", + "devices_filter": "Filtrar Dispositivos", + "ctrl_mode": "Modo de Controlo" + } + }, + "devices_filter": { + "title": "Filtrar Dispositivos", + "description": "## Introdução\r\n- Suporta a filtragem de dispositivos por nome de sala e tipo de dispositivo, bem como a filtragem por família.\r\n- Pode também aceder à página de configuração correspondente da integração [Configuração > Atualizar Lista de Dispositivos] para refazer a filtragem.", + "data": { + "statistics_logic": "Lógica de Estatísticas", + "room_filter_mode": "Filtrar por Sala", + "room_list": "Salas", + "type_filter_mode": "Filtrar por Tipo de Dispositivo", + "type_list": "Tipos de Dispositivo", + "model_filter_mode": "Filtrar por Modelo de Dispositivo", + "model_list": "Modelos de Dispositivo", + "devices_filter_mode": "Filtrar Dispositivos", + "device_list": "Lista de Dispositivos" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index 8965c72..081bcf9 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -114,8 +114,24 @@ "title": "Выберите дом и устройства", "description": "## Инструкция по использованию\r\n### Режим управления\r\n- Авто: Когда в локальной сети доступен центральный шлюз Xiaomi, Home Assistant будет в первую очередь отправлять команды управления устройствами через центральный шлюз для достижения локализованного управления. Если в локальной сети нет центрального шлюза, он попытается отправить команды управления через протокол Xiaomi OT для достижения локализованного управления. Только если вышеуказанные условия локализованного управления не выполняются, команды управления устройствами будут отправляться через облако.\r\n- Облако: Команды управления отправляются только через облако.\r\n### Импорт домашнего устройства\r\nИнтеграция добавит устройства из выбранных домов.\r\n \r\n### {nick_name} Здравствуйте! Выберите режим управления интеграцией и дом, в котором находятся устройства, которые вы хотите добавить.", "data": { - "ctrl_mode": "Режим управления", - "home_infos": "Импорт домашнего устройства" + "home_infos": "Импорт домашнего устройства", + "devices_filter": "Фильтрация устройств", + "ctrl_mode": "Режим управления" + } + }, + "devices_filter": { + "title": "Фильтрация устройств", + "description": "## Введение\r\n- Поддерживает фильтрацию устройств по названию комнаты и типу устройства, а также фильтрацию по уровню устройства.\r\n- Вы также можете перейти на соответствующую страницу интеграции [Настройки> Обновить список устройств], чтобы перефильтровать.", + "data": { + "statistics_logic": "Логика статистики", + "room_filter_mode": "Фильтрация по комнатам семьи", + "room_list": "Комнаты семьи", + "type_filter_mode": "Фильтрация по типу устройства", + "type_list": "Типы устройств", + "model_filter_mode": "Фильтрация по модели устройства", + "model_list": "Модели устройств", + "devices_filter_mode": "Фильтрация устройств", + "device_list": "Список устройств" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index cf3e141..dfc067f 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -114,8 +114,24 @@ "title": "重新选择家庭与设备", "description": "## 使用介绍\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### 导入设备的家庭\r\n集成将添加已选中家庭中的设备。\r\n \r\n### {nick_name} 您好!请选择集成控制模式以及您想要添加的设备所处的家庭。", "data": { - "ctrl_mode": "控制模式", - "home_infos": "导入设备的家庭" + "home_infos": "导入设备的家庭", + "devices_filter": "筛选设备", + "ctrl_mode": "控制模式" + } + }, + "devices_filter": { + "title": "筛选设备", + "description": "## 使用介绍\r\n支持按照房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n- 统计优先级:排除优先级高于包含优先级,会先取包含项,然后再排除。\r\n- 筛选优先级:筛选设备>筛选设备型号>筛选设备接入类型>筛选家庭房间\r\n### 统计逻辑\r\n- 与逻辑:取所有同模式筛选项的交集。\r\n- 或逻辑:取所有同模式筛选项的并集。\r\n### 筛选模式\r\n- 排除:移除不需要的项。\r\n- 包含:包含需要的项。\r\n- 您也可以进入对应集成项【配置>更新设备列表】页面重新筛选。", + "data": { + "statistics_logic": "统计逻辑", + "room_filter_mode": "筛选家庭房间", + "room_list": "家庭房间", + "type_filter_mode": "筛选设备接入类型", + "type_list": "设备接入类型", + "model_filter_mode": "筛选设备型号", + "model_list": "设备型号", + "devices_filter_mode": "筛选设备", + "device_list": "设备列表" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index 2c7300a..fc132b0 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -114,8 +114,24 @@ "title": "重新選擇家庭與設備", "description": "\r\n## 使用介紹\r\n### 控制模式\r\n- 自動:本地局域網內存在可用的小米中樞網關時, Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。只有當本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令強制通過雲端發送。\r\n### 導入設備的家庭\r\n集成將添加已選中家庭中的設備。\r\n \r\n### {nick_name} 您好!請選擇集成控制模式以及您想要添加的設備所處的家庭。", "data": { - "ctrl_mode": "控制模式", - "home_infos": "導入設備的家庭" + "home_infos": "導入設備的家庭", + "devices_filter": "篩選設備", + "ctrl_mode": "控制模式" + } + }, + "devices_filter": { + "title": "篩選設備", + "description": "## 使用介紹\r\n- 支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n- 您也可以進入對應集成項【配置>更新設備列表】頁面重新篩選。", + "data": { + "statistics_logic": "統計邏輯", + "room_filter_mode": "篩選家庭房間", + "room_list": "家庭房間", + "type_filter_mode": "篩選設備接入類型", + "type_list": "設備接入類型", + "model_filter_mode": "篩選設備型號", + "model_list": "設備型號", + "devices_filter_mode": "篩選設備", + "device_list": "設備列表" } }, "update_trans_rules": { From 24e85b358a8e8fae44d354a6ee6f8bd1ae4c0484 Mon Sep 17 00:00:00 2001 From: topsworld Date: Mon, 23 Dec 2024 22:40:04 +0800 Subject: [PATCH 16/24] fix: fix option flow type error --- custom_components/xiaomi_home/config_flow.py | 209 ++++++++++--------- 1 file changed, 112 insertions(+), 97 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index 79517a4..7040869 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -824,32 +824,33 @@ class OptionsFlowHandler(config_entries.OptionsFlow): _main_loop: asyncio.AbstractEventLoop _miot_client: MIoTClient - _miot_network: Optional[MIoTNetwork] - _miot_storage: Optional[MIoTStorage] - _mips_service: Optional[MipsService] - _miot_oauth: Optional[MIoTOauthClient] - _miot_http: Optional[MIoTHttpClient] - _miot_i18n: Optional[MIoTI18n] - _miot_lan: Optional[MIoTLan] + _miot_network: MIoTNetwork + _miot_storage: MIoTStorage + _mips_service: MipsService + _miot_oauth: MIoTOauthClient + _miot_http: MIoTHttpClient + _miot_i18n: MIoTI18n + _miot_lan: MIoTLan _entry_data: dict - _virtual_did: Optional[str] - _uid: Optional[str] - _storage_path: Optional[str] - _cloud_server: Optional[str] - _oauth_redirect_url_full: str - _integration_language: Optional[str] - _ctrl_mode: Optional[str] - _nick_name: Optional[str] - _home_selected_list: Optional[list] + _virtual_did: str + _uid: str + _storage_path: str + _cloud_server: str + + _integration_language: str + _ctrl_mode: str + _nick_name: str + _home_selected_list: list _action_debug: bool _hide_non_standard_entities: bool - _auth_info: Optional[dict] - _home_selected_dict: Optional[dict] - _home_info_buffer: Optional[dict[str, str | dict[str, dict]]] - _home_list: Optional[dict] - _device_list: dict[str, dict] + _oauth_redirect_url_full: str + _auth_info: dict + _home_selected: dict + _home_info_buffer: dict + _home_list_show: dict + _device_list_sorted: dict _devices_add: list[str] _devices_remove: list[str] @@ -858,7 +859,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow): _config_error_reason: Optional[str] _fut_oauth_code: Optional[asyncio.Future] # Config options - _lang_new: Optional[str] + _lang_new: str _nick_name_new: Optional[str] _action_debug_new: bool _hide_non_standard_entities_new: bool @@ -873,37 +874,29 @@ class OptionsFlowHandler(config_entries.OptionsFlow): def __init__(self, config_entry: config_entries.ConfigEntry): self._config_entry = config_entry - self._main_loop = None - self._miot_client = None - - self._miot_network = None - self._miot_storage = None - self._mips_service = None - self._miot_oauth = None - self._miot_http = None - self._miot_i18n = None - self._miot_lan = None + self._main_loop = asyncio.get_event_loop() self._entry_data = dict(config_entry.data) self._virtual_did = self._entry_data['virtual_did'] self._uid = self._entry_data['uid'] self._storage_path = self._entry_data['storage_path'] self._cloud_server = self._entry_data['cloud_server'] - self._oauth_redirect_url_full = '' - self._ctrl_mode = self._entry_data['ctrl_mode'] - self._integration_language = self._entry_data['integration_language'] - self._nick_name = self._entry_data['nick_name'] + self._ctrl_mode = self._entry_data.get('ctrl_mode', DEFAULT_CTRL_MODE) + self._integration_language = self._entry_data.get( + 'integration_language', DEFAULT_INTEGRATION_LANGUAGE) + self._nick_name = self._entry_data.get('nick_name', DEFAULT_NICK_NAME) self._action_debug = self._entry_data.get('action_debug', False) self._hide_non_standard_entities = self._entry_data.get( 'hide_non_standard_entities', False) self._home_selected_list = list( self._entry_data['home_selected'].keys()) - self._auth_info = None - self._home_selected_dict = {} - self._home_info_buffer = None - self._home_list = None - self._device_list = None + self._oauth_redirect_url_full = '' + self._auth_info = {} + self._home_selected = {} + self._home_info_buffer = {} + self._home_list_show = {} + self._device_list_sorted = {} self._devices_add = [] self._devices_remove = [] @@ -912,7 +905,7 @@ def __init__(self, config_entry: config_entries.ConfigEntry): self._config_error_reason = None self._fut_oauth_code = None - self._lang_new = None + self._lang_new = self._integration_language self._nick_name_new = None self._action_debug_new = False self._hide_non_standard_entities_new = False @@ -933,8 +926,6 @@ async def async_step_init(self, user_input=None): self.hass.data.setdefault(DOMAIN, {}) self.hass.data[DOMAIN].setdefault(self._virtual_did, {}) try: - # main loop - self._main_loop = asyncio.get_running_loop() # MIoT client self._miot_client: MIoTClient = await get_miot_instance_async( hass=self.hass, entry_id=self._config_entry.entry_id) @@ -1005,7 +996,8 @@ async def async_step_auth_config(self, user_input=None): data_schema=vol.Schema({ vol.Required( 'oauth_redirect_url', - default=OAUTH_REDIRECT_URL): vol.In([OAUTH_REDIRECT_URL]), + default=OAUTH_REDIRECT_URL # type: ignore + ): vol.In([OAUTH_REDIRECT_URL]), }), description_placeholders={ 'cloud_server': CLOUD_SERVERS[self._cloud_server], @@ -1076,11 +1068,15 @@ async def async_step_oauth(self, user_input=None): async def __check_oauth_async(self) -> None: # Get oauth code - oauth_code: Optional[str] = await self._fut_oauth_code + if not self._fut_oauth_code: + raise MIoTConfigError('oauth_code_fut_error') + oauth_code: str = await self._fut_oauth_code + if not oauth_code: + raise MIoTConfigError('oauth_code_error') _LOGGER.debug('options flow __check_oauth_async, %s', oauth_code) # Get access_token and user_info from miot_oauth - if self._auth_info is None: - auth_info: dict = None + if not self._auth_info: + auth_info: dict = {} try: auth_info = await self._miot_oauth.get_access_token_async( code=oauth_code) @@ -1135,24 +1131,32 @@ async def async_step_config_options(self, user_input=None): data_schema=vol.Schema({ vol.Required( 'integration_language', - default=self._integration_language + default=self._integration_language # type: ignore ): vol.In(INTEGRATION_LANGUAGES), vol.Required( 'update_user_info', - default=self._update_user_info): bool, + default=self._update_user_info # type: ignore + ): bool, vol.Required( - 'update_devices', default=self._update_devices): bool, + 'update_devices', + default=self._update_devices # type: ignore + ): bool, vol.Required( - 'action_debug', default=self._action_debug): bool, + 'action_debug', + default=self._action_debug # type: ignore + ): bool, vol.Required( 'hide_non_standard_entities', - default=self._hide_non_standard_entities): bool, + default=self._hide_non_standard_entities # type: ignore + ): bool, vol.Required( 'update_trans_rules', - default=self._update_trans_rules): bool, + default=self._update_trans_rules # type: ignore + ): bool, vol.Required( 'update_lan_ctrl_config', - default=self._update_lan_ctrl_config): bool + default=self._update_lan_ctrl_config # type: ignore + ): bool }), errors={}, description_placeholders={ @@ -1257,27 +1261,27 @@ async def async_step_homes_select( home_id for home_id in self._home_selected_list if home_id in home_list] - self._home_list = dict(sorted(home_list.items())) + self._home_list_show = dict(sorted(home_list.items())) return await self.__display_homes_select_form('') self._home_selected_list = user_input.get('home_infos', []) if not self._home_selected_list: return await self.__display_homes_select_form('no_family_selected') - self._ctrl_mode = user_input.get('ctrl_mode') - self._home_selected_dict = {} + self._ctrl_mode = user_input.get('ctrl_mode', self._ctrl_mode) + self._home_selected = {} for home_id, home_info in self._home_info_buffer[ 'homes']['home_list'].items(): if home_id in self._home_selected_list: - self._home_selected_dict[home_id] = home_info + self._home_selected[home_id] = home_info # Get device list - self._device_list: dict[str, dict] = { + device_list: dict = { did: dev_info for did, dev_info in self._home_info_buffer['devices'].items() if dev_info['home_id'] in self._home_selected_list} - if not self._device_list: + if not device_list: return await self.__display_homes_select_form('no_devices') self._device_list_sorted = dict(sorted( - self._device_list.items(), key=lambda item: + device_list.items(), key=lambda item: item[1].get('home_id', '')+item[1].get('room_id', ''))) if user_input.get('devices_filter', False): @@ -1288,11 +1292,16 @@ async def __display_homes_select_form(self, reason: str): return self.async_show_form( step_id='homes_select', data_schema=vol.Schema({ - vol.Required('devices_filter', default=False): bool, - vol.Required('home_infos', default=self._home_selected_list): - cv.multi_select(self._home_list), - vol.Required('ctrl_mode', default=self._ctrl_mode): vol.In( - self._miot_i18n.translate(key='config.control_mode')), + vol.Required( + 'devices_filter', default=False # type: ignore + ): bool, + vol.Required( + 'home_infos', + default=self._home_selected_list # type: ignore + ): cv.multi_select(self._home_list_show), + vol.Required( + 'ctrl_mode', default=self._ctrl_mode # type: ignore + ): vol.In(self._miot_i18n.translate(key='config.control_mode')), }), errors={'base': reason}, description_placeholders={ @@ -1310,15 +1319,15 @@ async def async_step_devices_filter( async def __display_devices_filter_form(self, reason: str): tip_devices: str = self._miot_i18n.translate( - key='config.other.devices') + key='config.other.devices') # type: ignore tip_without_room: str = self._miot_i18n.translate( - key='config.other.without_room') + key='config.other.without_room') # type: ignore trans_statistics_logic: dict = self._miot_i18n.translate( - key='config.statistics_logic') + key='config.statistics_logic') # type: ignore trans_filter_mode: dict = self._miot_i18n.translate( - key='config.filter_mode') + key='config.filter_mode') # type: ignore trans_connect_type: dict = self._miot_i18n.translate( - key='config.connect_type') + key='config.connect_type') # type: ignore room_device_count: dict = {} model_device_count: dict = {} @@ -1342,7 +1351,7 @@ async def __display_devices_filter_form(self, reason: str): f'[ {v} {tip_devices} ]' for k, v in connect_type_count.items()} room_list: dict = {} - for home_id, home_info in self._home_selected_dict.items(): + for home_id, home_info in self._home_selected.items(): for room_id, room_name in home_info['room_info'].items(): if room_id not in room_device_count: continue @@ -1356,22 +1365,27 @@ async def __display_devices_filter_form(self, reason: str): return self.async_show_form( step_id='devices_filter', data_schema=vol.Schema({ - vol.Required('room_filter_mode', default='exclude'): - vol.In(trans_filter_mode), + vol.Required( + 'room_filter_mode', default='exclude' # type: ignore + ): vol.In(trans_filter_mode), vol.Optional('room_list'): cv.multi_select(room_list), - vol.Required('type_filter_mode', default='exclude'): - vol.In(trans_filter_mode), + vol.Required( + 'type_filter_mode', default='exclude' # type: ignore + ): vol.In(trans_filter_mode), vol.Optional('type_list'): cv.multi_select(type_list), - vol.Required('model_filter_mode', default='exclude'): - vol.In(trans_filter_mode), + vol.Required( + 'model_filter_mode', default='exclude' # type: ignore + ): vol.In(trans_filter_mode), vol.Optional('model_list'): cv.multi_select(dict(sorted( model_list.items(), key=lambda item: item[0]))), - vol.Required('devices_filter_mode', default='exclude'): - vol.In(trans_filter_mode), + vol.Required( + 'devices_filter_mode', default='exclude' # type: ignore + ): vol.In(trans_filter_mode), vol.Optional('device_list'): cv.multi_select(dict(sorted( device_list.items(), key=lambda device: device[1]))), - vol.Required('statistics_logic', default='or'): - vol.In(trans_statistics_logic), + vol.Required( + 'statistics_logic', default='or' # type: ignore + ): vol.In(trans_statistics_logic), }), errors={'base': reason}, last_step=False @@ -1385,11 +1399,12 @@ async def update_devices_done_async(self): domain='miot_devices', name=f'{self._uid}_{self._cloud_server}', type_=dict) or {} # type: ignore - self._devices_add = [ - did for did in self._device_list.keys() if did not in local_devices] + did for did in list(self._device_list_sorted.keys()) + if did not in local_devices] self._devices_remove = [ - did for did in local_devices.keys() if did not in self._device_list] + did for did in local_devices.keys() + if did not in self._device_list_sorted] _LOGGER.debug( 'devices update, add->%s, remove->%s', self._devices_add, self._devices_remove) @@ -1407,10 +1422,12 @@ async def async_step_update_trans_rules(self, user_input=None): return self.async_show_form( step_id='update_trans_rules', data_schema=vol.Schema({ - vol.Required('confirm', default=False): bool + vol.Required( + 'confirm', default=False # type: ignore + ): bool }), description_placeholders={ - 'urn_count': self._trans_rules_count, + 'urn_count': str(self._trans_rules_count), }, last_step=False ) @@ -1450,8 +1467,8 @@ async def async_step_update_lan_ctrl_config(self, user_input=None): f'{if_name} ({info.ip}/{info.netmask})') net_segs.add(info.net_seg) if len(net_segs) != len(net_info): - notice_net_dup = self._miot_i18n.translate( - key='config.lan_ctrl_config.notice_net_dup') + notice_net_dup: str = self._miot_i18n.translate( + key='config.lan_ctrl_config.notice_net_dup') # type: ignore return self.async_show_form( step_id='update_lan_ctrl_config', data_schema=vol.Schema({ @@ -1501,7 +1518,8 @@ async def async_step_config_confirm(self, user_input=None): return self.async_show_form( step_id='config_confirm', data_schema=vol.Schema({ - vol.Required('confirm', default=False): bool + vol.Required( + 'confirm', default=False): bool # type: ignore }), description_placeholders={ 'nick_name': self._nick_name, @@ -1518,7 +1536,7 @@ async def async_step_config_confirm(self, user_input=None): 'hide_non_standard_entities': ( enable_text if self._hide_non_standard_entities_new else disable_text), - }, + }, # type: ignore errors={'base': 'not_confirm'} if user_input else {}, last_step=True ) @@ -1530,14 +1548,11 @@ async def async_step_config_confirm(self, user_input=None): self._entry_data['nick_name'] = self._nick_name_new if self._update_devices: self._entry_data['ctrl_mode'] = self._ctrl_mode - self._entry_data['home_selected'] = self._home_selected_dict - devices_list_sort = dict(sorted( - self._device_list.items(), key=lambda item: - item[1].get('home_id', '')+item[1].get('room_id', ''))) + self._entry_data['home_selected'] = self._home_selected if not await self._miot_storage.save_async( domain='miot_devices', name=f'{self._uid}_{self._cloud_server}', - data=devices_list_sort): + data=self._device_list_sorted): _LOGGER.error( 'save devices async failed, %s, %s', self._uid, self._cloud_server) From cd0b13e49e9bd0061b2b94dd7c68bcce5a8e68d5 Mon Sep 17 00:00:00 2001 From: topsworld Date: Mon, 23 Dec 2024 23:15:13 +0800 Subject: [PATCH 17/24] feat: support option flow devices filter --- custom_components/xiaomi_home/config_flow.py | 125 ++++++++++++------ .../xiaomi_home/translations/zh-Hans.json | 4 +- 2 files changed, 90 insertions(+), 39 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index 7040869..9a7b876 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -654,7 +654,7 @@ async def async_step_devices_filter( include_items['did'] = device_list_in else: exclude_items['did'] = device_list_in - device_filter_list = self.__devices_filter( + device_filter_list = _handle_devices_filter( devices=self._device_list_sorted, logic_or=(user_input.get('statistics_logic', 'or') == 'or'), item_in=include_items, item_ex=exclude_items) @@ -751,39 +751,6 @@ async def __display_devices_filter_form(self, reason: str): last_step=False ) - def __devices_filter( - self, devices: dict, logic_or: bool, item_in: dict, item_ex: dict - ) -> dict: - include_set: Set = set([]) - if not item_in: - include_set = set(devices.keys()) - else: - filter_item: list[set] = [] - for key, value in item_in.items(): - filter_item.append(set([ - did for did, info in devices.items() - if str(info[key]) in value])) - include_set = ( - set.union(*filter_item) - if logic_or else set.intersection(*filter_item)) - if not include_set: - return {} - if item_ex: - filter_item: list[set] = [] - for key, value in item_ex.items(): - filter_item.append(set([ - did for did, info in devices.items() - if str(info[key]) in value])) - exclude_set: Set = ( - set.union(*filter_item) - if logic_or else set.intersection(*filter_item)) - if exclude_set: - include_set = include_set-exclude_set - if not include_set: - return {} - return { - did: info for did, info in devices.items() if did in include_set} - async def config_flow_done(self): return self.async_create_entry( title=( @@ -1292,13 +1259,13 @@ async def __display_homes_select_form(self, reason: str): return self.async_show_form( step_id='homes_select', data_schema=vol.Schema({ - vol.Required( - 'devices_filter', default=False # type: ignore - ): bool, vol.Required( 'home_infos', default=self._home_selected_list # type: ignore ): cv.multi_select(self._home_list_show), + vol.Required( + 'devices_filter', default=False # type: ignore + ): bool, vol.Required( 'ctrl_mode', default=self._ctrl_mode # type: ignore ): vol.In(self._miot_i18n.translate(key='config.control_mode')), @@ -1314,6 +1281,52 @@ async def async_step_devices_filter( self, user_input: Optional[dict] = None ): if user_input: + # Room filter + include_items: dict = {} + exclude_items: dict = {} + room_list_in: list = user_input.get('room_list', []) + if room_list_in: + if user_input.get( + 'room_filter_mode', 'include') == 'include': + include_items['room_id'] = room_list_in + else: + exclude_items['room_id'] = room_list_in + # Connect Type filter + type_list_in: list = user_input.get('type_list', []) + if type_list_in: + if user_input.get( + 'type_filter_mode', 'include') == 'include': + include_items['connect_type'] = type_list_in + else: + exclude_items['connect_type'] = type_list_in + # Model filter + model_list_in: list = user_input.get('model_list', []) + if model_list_in: + if user_input.get( + 'model_filter_mode', 'include') == 'include': + include_items['model'] = model_list_in + else: + exclude_items['model'] = model_list_in + # Device filter + device_list_in: list = user_input.get('device_list', []) + if device_list_in: + if user_input.get( + 'devices_filter_mode', 'include') == 'include': + include_items['did'] = device_list_in + else: + exclude_items['did'] = device_list_in + device_filter_list = _handle_devices_filter( + devices=self._device_list_sorted, + logic_or=(user_input.get('statistics_logic', 'or') == 'or'), + item_in=include_items, item_ex=exclude_items) + if not device_filter_list: + raise AbortFlow( + reason='config_flow_error', + description_placeholders={ + 'error': 'invalid devices_filter'}) + self._device_list_sorted = dict(sorted( + device_filter_list.items(), key=lambda item: + item[1].get('home_id', '')+item[1].get('room_id', ''))) return await self.update_devices_done_async() return await self.__display_devices_filter_form(reason='') @@ -1388,6 +1401,8 @@ async def __display_devices_filter_form(self, reason: str): ): vol.In(trans_statistics_logic), }), errors={'base': reason}, + description_placeholders={ + 'devices_count': str(len(self._device_list_sorted))}, last_step=False ) @@ -1598,6 +1613,7 @@ async def async_step_config_confirm(self, user_input=None): async def handle_oauth_webhook(hass, webhook_id, request): + """Webhook to handle oauth2 callback.""" # pylint: disable=inconsistent-quotes try: data = dict(request.query) @@ -1623,3 +1639,38 @@ async def handle_oauth_webhook(hass, webhook_id, request): return web.Response( body=oauth_redirect_page(hass.config.language, 'fail'), content_type='text/html') + + +def _handle_devices_filter( + devices: dict, logic_or: bool, item_in: dict, item_ex: dict +) -> dict: + """Private method to filter devices.""" + include_set: Set = set([]) + if not item_in: + include_set = set(devices.keys()) + else: + filter_item: list[set] = [] + for key, value in item_in.items(): + filter_item.append(set([ + did for did, info in devices.items() + if str(info[key]) in value])) + include_set = ( + set.union(*filter_item) + if logic_or else set.intersection(*filter_item)) + if not include_set: + return {} + if item_ex: + filter_item: list[set] = [] + for key, value in item_ex.items(): + filter_item.append(set([ + did for did, info in devices.items() + if str(info[key]) in value])) + exclude_set: Set = ( + set.union(*filter_item) + if logic_or else set.intersection(*filter_item)) + if exclude_set: + include_set = include_set-exclude_set + if not include_set: + return {} + return { + did: info for did, info in devices.items() if did in include_set} diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index dfc067f..dd19a5a 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -43,7 +43,7 @@ }, "devices_filter": { "title": "筛选设备", - "description": "## 使用介绍\r\n支持按照房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n- 统计优先级:排除优先级高于包含优先级,会先取包含项,然后再排除。\r\n- 筛选优先级:筛选设备>筛选设备型号>筛选设备接入类型>筛选家庭房间\r\n### 统计逻辑\r\n- 与逻辑:取所有同模式筛选项的交集。\r\n- 或逻辑:取所有同模式筛选项的并集。\r\n### 筛选模式\r\n- 排除:移除不需要的项。\r\n- 包含:包含需要的项。\r\n- 您也可以进入对应集成项【配置>更新设备列表】页面重新筛选。", + "description": "## 使用介绍\r\n支持按照房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n- 统计优先级:排除优先级高于包含优先级,会先取包含项,然后再排除。\r\n- 筛选优先级:筛选设备>筛选设备型号>筛选设备接入类型>筛选家庭房间\r\n### 统计逻辑\r\n- 与逻辑:取所有同模式筛选项的交集。\r\n- 或逻辑:取所有同模式筛选项的并集。\r\n### 筛选模式\r\n- 排除:移除不需要的项。\r\n- 包含:包含需要的项。\r\n\r\n您也可以进入对应集成项【配置>更新设备列表】页面重新筛选。", "data": { "statistics_logic": "统计逻辑", "room_filter_mode": "筛选家庭房间", @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "筛选设备", - "description": "## 使用介绍\r\n支持按照房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n- 统计优先级:排除优先级高于包含优先级,会先取包含项,然后再排除。\r\n- 筛选优先级:筛选设备>筛选设备型号>筛选设备接入类型>筛选家庭房间\r\n### 统计逻辑\r\n- 与逻辑:取所有同模式筛选项的交集。\r\n- 或逻辑:取所有同模式筛选项的并集。\r\n### 筛选模式\r\n- 排除:移除不需要的项。\r\n- 包含:包含需要的项。\r\n- 您也可以进入对应集成项【配置>更新设备列表】页面重新筛选。", + "description": "## 使用介绍\r\n支持按照房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n- 统计优先级:排除优先级高于包含优先级,会先取包含项,然后再排除。\r\n- 筛选优先级:筛选设备>筛选设备型号>筛选设备接入类型>筛选家庭房间\r\n### 统计逻辑\r\n- 与逻辑:取所有同模式筛选项的交集。\r\n- 或逻辑:取所有同模式筛选项的并集。\r\n### 筛选模式\r\n- 排除:移除不需要的项。\r\n- 包含:包含需要的项。\r\n\r\n您也可以进入对应集成项【配置>更新设备列表】页面重新筛选。", "data": { "statistics_logic": "统计逻辑", "room_filter_mode": "筛选家庭房间", From 6504441d968c2bbe5f233420aceda6acaedf90c2 Mon Sep 17 00:00:00 2001 From: topsworld Date: Tue, 24 Dec 2024 10:20:33 +0800 Subject: [PATCH 18/24] doc: update option flow tranlations --- custom_components/xiaomi_home/config_flow.py | 23 +++++++++++-------- .../xiaomi_home/translations/de.json | 6 ++--- .../xiaomi_home/translations/en.json | 6 ++--- .../xiaomi_home/translations/es.json | 8 +++---- .../xiaomi_home/translations/fr.json | 6 ++--- .../xiaomi_home/translations/ja.json | 6 ++--- .../xiaomi_home/translations/nl.json | 6 ++--- .../xiaomi_home/translations/pt-BR.json | 6 ++--- .../xiaomi_home/translations/pt.json | 6 ++--- .../xiaomi_home/translations/ru.json | 6 ++--- .../xiaomi_home/translations/zh-Hans.json | 16 ++++++------- .../xiaomi_home/translations/zh-Hant.json | 12 +++++----- 12 files changed, 55 insertions(+), 52 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index 9a7b876..e6b3627 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -818,6 +818,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow): _home_info_buffer: dict _home_list_show: dict _device_list_sorted: dict + _devices_local: dict _devices_add: list[str] _devices_remove: list[str] @@ -864,6 +865,7 @@ def __init__(self, config_entry: config_entries.ConfigEntry): self._home_info_buffer = {} self._home_list_show = {} self._device_list_sorted = {} + self._devices_local = {} self._devices_add = [] self._devices_remove = [] @@ -1227,8 +1229,13 @@ async def async_step_homes_select( self._home_selected_list = [ home_id for home_id in self._home_selected_list if home_id in home_list] - self._home_list_show = dict(sorted(home_list.items())) + # Get local devices + self._devices_local: dict = await self._miot_storage.load_async( + domain='miot_devices', + name=f'{self._uid}_{self._cloud_server}', + type_=dict) or {} # type: ignore + return await self.__display_homes_select_form('') self._home_selected_list = user_input.get('home_infos', []) @@ -1256,6 +1263,7 @@ async def async_step_homes_select( return await self.update_devices_done_async() async def __display_homes_select_form(self, reason: str): + devices_local_count: str = str(len(self._devices_local)) return self.async_show_form( step_id='homes_select', data_schema=vol.Schema({ @@ -1272,7 +1280,7 @@ async def __display_homes_select_form(self, reason: str): }), errors={'base': reason}, description_placeholders={ - 'nick_name': self._nick_name + 'local_count': devices_local_count }, last_step=False ) @@ -1401,8 +1409,6 @@ async def __display_devices_filter_form(self, reason: str): ): vol.In(trans_statistics_logic), }), errors={'base': reason}, - description_placeholders={ - 'devices_count': str(len(self._device_list_sorted))}, last_step=False ) @@ -1410,15 +1416,12 @@ async def update_devices_done_async(self): # Statistics devices changed self._devices_add = [] self._devices_remove = [] - local_devices: dict = await self._miot_storage.load_async( - domain='miot_devices', - name=f'{self._uid}_{self._cloud_server}', - type_=dict) or {} # type: ignore + self._devices_add = [ did for did in list(self._device_list_sorted.keys()) - if did not in local_devices] + if did not in self._devices_local] self._devices_remove = [ - did for did in local_devices.keys() + did for did in self._devices_local.keys() if did not in self._device_list_sorted] _LOGGER.debug( 'devices update, add->%s, remove->%s', diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index 3ef34ce..60d2095 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -112,7 +112,7 @@ }, "homes_select": { "title": "Familie und Geräte neu auswählen", - "description": "## Gebrauchsanweisung\r\n### Steuerungsmodus\r\n- Automatisch: Wenn im lokalen Netzwerk ein verfügbarer Xiaomi-Zentralgateway vorhanden ist, wird Home Assistant bevorzugt Steuerbefehle über den Zentralgateway senden, um eine lokale Steuerung zu ermöglichen. Wenn im lokalen Netzwerk kein Zentralgateway vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden, um eine lokale Steuerung zu ermöglichen. Nur wenn die oben genannten Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Steuerbefehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden nur über die Cloud gesendet.\r\n### Familienimport für importierte Geräte\r\nDie Integration fügt Geräte aus den ausgewählten Familien hinzu.\r\n \r\n### Hallo {nick_name}! Bitte wählen Sie den Steuerungsmodus der Integration sowie die Familie aus, in der sich die hinzuzufügenden Geräte befinden.", + "description": "## Gebrauchsanweisung\r\n### Familienimport für importierte Geräte\r\nDie Integration fügt Geräte aus den ausgewählten Familien hinzu.\r\n### Geräte filtern\r\nUnterstützt das Filtern von Geräten nach Raumnamen, Gerätezugriffstyp und Gerätemodell, und unterstützt auch das Filtern nach Gerätegröße. Es wurden **{local_count}** Geräte gefiltert.\r\n### Steuerungsmodus\r\n- Automatisch: Wenn im lokalen Netzwerk ein verfügbarer Xiaomi-Zentralgateway vorhanden ist, wird Home Assistant bevorzugt Steuerbefehle über den Zentralgateway senden, um eine lokale Steuerung zu ermöglichen. Wenn im lokalen Netzwerk kein Zentralgateway vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden, um eine lokale Steuerung zu ermöglichen. Nur wenn die oben genannten Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Steuerbefehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden nur über die Cloud gesendet.", "data": { "home_infos": "Familienimport für importierte Geräte", "devices_filter": "Geräte filtern", @@ -123,7 +123,6 @@ "title": "Geräte filtern", "description": "## Gebrauchsanweisung\r\n- Unterstützt das Filtern von Geräten nach Raumnamen und Gerätetypen sowie das Filtern nach Gerätedimensionen.\r\n- Sie können auch die entsprechende Integrationsoption \"Konfiguration> Geräteliste aktualisieren\" aufrufen, um die Filterung erneut durchzuführen.", "data": { - "statistics_logic": "Statistiklogik", "room_filter_mode": "Familienraum filtern", "room_list": "Familienraum", "type_filter_mode": "Gerätetyp filtern", @@ -131,7 +130,8 @@ "model_filter_mode": "Gerätemodell filtern", "model_list": "Gerätemodell", "devices_filter_mode": "Geräte filtern", - "device_list": "Geräteliste" + "device_list": "Geräteliste", + "statistics_logic": "Statistiklogik" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index d16c67c..da99634 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -112,7 +112,7 @@ }, "homes_select": { "title": "Re-select Home and Devices", - "description": "## Usage Instructions\r\n### Control mode\r\n- Auto: When there is an available Xiaomi central hub gateway in the local area network, Home Assistant will prioritize sending device control commands through the central hub gateway to achieve local control. If there is no central hub gateway in the local area network, it will attempt to send control commands through Xiaomi LAN control function. Only when the above local control conditions are not met, the device control commands will be sent through the cloud.\r\n- Cloud: All control commands are sent through the cloud.\r\n### Import devices from home\r\nThe integration will add devices from the selected homes.\r\n \r\n### Hello {nick_name}, please select the integration control mode and the home where the device you want to import.", + "description": "## Usage Instructions\r\n### Import devices from home\r\nThe integration will add devices from the selected homes.\r\n### Filter Devices\r\nSupports filtering devices by home room name, device access type, and device model, and also supports device dimension filtering. **{local_count}** devices have been filtered.\r\n### Control mode\r\n- Auto: When there is an available Xiaomi central hub gateway in the local area network, Home Assistant will prioritize sending device control commands through the central hub gateway to achieve local control. If there is no central hub gateway in the local area network, it will attempt to send control commands through Xiaomi LAN control function. Only when the above local control conditions are not met, the device control commands will be sent through the cloud.\r\n- Cloud: All control commands are sent through the cloud.", "data": { "home_infos": "Import devices from home", "devices_filter": "Filter devices", @@ -123,7 +123,6 @@ "title": "Filter Devices", "description": "## Introduction\r\n- Supports filtering devices by room name and device type, and also supports device dimension filtering.\r\n- You can also re-filter on the corresponding integration page [Configuration>Update Device List].", "data": { - "statistics_logic": "Statistics Logic", "room_filter_mode": "Filter Family Rooms", "room_list": "Family Rooms", "type_filter_mode": "Filter Device Connect Type", @@ -131,7 +130,8 @@ "model_filter_mode": "Filter Device Model", "model_list": "Device Model", "devices_filter_mode": "Filter Devices", - "device_list": "Device List" + "device_list": "Device List", + "statistics_logic": "Statistics Logic" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index a92524c..8acdccb 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -112,10 +112,10 @@ }, "homes_select": { "title": "Recomendar hogares y dispositivos", - "description": "## Instrucciones de uso\r\n### Modo de control\r\n- Automático: Cuando hay un gateway central de Xiaomi disponible en la red local, Home Assistant priorizará el envío de comandos de control de dispositivos a través del gateway central para lograr un control localizado. Si no hay un gateway central en la red local, intentará enviar comandos de control a través del protocolo Xiaomi OT para lograr un control localizado. Solo cuando no se cumplan las condiciones anteriores de control localizado, los comandos de control del dispositivo se enviarán a través de la nube.\r\n- Nube: Los comandos de control solo se envían a través de la nube.\r\n### Hogares de dispositivos importados\r\nLa integración agregará los dispositivos en los hogares seleccionados.\r\n \r\n### ¡Hola, {nick_name}! Seleccione el modo de control de integración y el hogar donde se encuentran los dispositivos que desea agregar.", + "description": "## Instrucciones de uso\r\n### Hogares de dispositivos importados\r\nLa integración agregará los dispositivos en los hogares seleccionados.\r\n### Filtrar dispositivos\r\nAdmite la filtración de dispositivos por nombre de habitación, tipo de acceso del dispositivo y modelo de dispositivo, y también admite la filtración por dimensión del dispositivo. Se han filtrado **{local_count}** dispositivos.\r\n### Modo de control\r\n- Automático: Cuando hay un gateway central de Xiaomi disponible en la red local, Home Assistant priorizará el envío de comandos de control de dispositivos a través del gateway central para lograr un control localizado. Si no hay un gateway central en la red local, intentará enviar comandos de control a través del protocolo Xiaomi OT para lograr un control localizado. Solo cuando no se cumplan las condiciones anteriores de control localizado, los comandos de control del dispositivo se enviarán a través de la nube.\r\n- Nube: Los comandos de control solo se envían a través de la nube.", "data": { "home_infos": "Hogares de dispositivos importados", - "devices_filter": "Filtrar Dispositivos", + "devices_filter": "Filtrar dispositivos", "ctrl_mode": "Modo de control" } }, @@ -123,7 +123,6 @@ "title": "Filtrar Dispositivos", "description": "## Introducción\r\n- Admite la filtración de dispositivos por nombre de habitación y tipo de dispositivo, y también admite la filtración por familia.\r\n- También puede volver a filtrar en la página correspondiente de la integración [Configuración>Actualizar lista de dispositivos].", "data": { - "statistics_logic": "Lógica de Estadísticas", "room_filter_mode": "Filtrar Habitaciones de la Familia", "room_list": "Habitaciones de la Familia", "type_filter_mode": "Filtrar Tipo de Dispositivo", @@ -131,7 +130,8 @@ "model_filter_mode": "Filtrar Modelo de Dispositivo", "model_list": "Modelo de Dispositivo", "devices_filter_mode": "Filtrar Dispositivos", - "device_list": "Lista de Dispositivos" + "device_list": "Lista de Dispositivos", + "statistics_logic": "Lógica de Estadísticas" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index e068456..ad6e9ee 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -112,7 +112,7 @@ }, "homes_select": { "title": "Re-sélectionner une maison et des appareils", - "description": "## Instructions d'utilisation\r\n### Mode de contrôle\r\n- Automatique: Lorsqu'il y a une passerelle centrale Xiaomi disponible dans le réseau local, Home Assistant priorisera l'envoi des commandes de contrôle des appareils via la passerelle centrale pour réaliser un contrôle localisé. S'il n'y a pas de passerelle centrale dans le réseau local, il tentera d'envoyer des commandes de contrôle via le protocole Xiaomi OT pour réaliser un contrôle localisé. Ce n'est que lorsque les conditions de contrôle localisé ci-dessus ne sont pas remplies que les commandes de contrôle des appareils seront envoyées via le cloud.\r\n- Cloud: Les commandes de contrôle ne sont envoyées que via le cloud.\r\n### Importer une maison pour les appareils\r\nL'intégration ajoutera les appareils de la maison sélectionnée.\r\n \r\n### {nick_name} Bonjour ! Veuillez sélectionner le mode de contrôle de l'intégration et la maison où se trouvent les appareils à ajouter.", + "description": "## Instructions d'utilisation\r\n### Importer une maison pour les appareils\r\nL'intégration ajoutera les appareils de la maison sélectionnée.\r\n### Filtrer les appareils\r\nPrend en charge le filtrage des appareils par nom de pièce de la maison, type d'accès de l'appareil et modèle d'appareil, et prend également en charge le filtrage par dimension de l'appareil. **{local_count}** appareils ont été filtrés.\r\n### Mode de contrôle\r\n- Automatique: Lorsqu'il y a une passerelle centrale Xiaomi disponible dans le réseau local, Home Assistant priorisera l'envoi des commandes de contrôle des appareils via la passerelle centrale pour réaliser un contrôle localisé. S'il n'y a pas de passerelle centrale dans le réseau local, il tentera d'envoyer des commandes de contrôle via le protocole Xiaomi OT pour réaliser un contrôle localisé. Ce n'est que lorsque les conditions de contrôle localisé ci-dessus ne sont pas remplies que les commandes de contrôle des appareils seront envoyées via le cloud.\r\n- Cloud: Les commandes de contrôle ne sont envoyées que via le cloud.", "data": { "home_infos": "Importer une maison pour les appareils", "devices_filter": "Filtrer les Appareils", @@ -123,7 +123,6 @@ "title": "Filtrer les Appareils", "description": "## Introduction\r\n- Prend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n- Vous pouvez également accéder à la page de filtrage correspondante de l'intégration [Configuration> Mettre à jour la liste des appareils] pour refiltrer.", "data": { - "statistics_logic": "Logique de Statistiques", "room_filter_mode": "Filtrer les Pièces", "room_list": "Pièces", "type_filter_mode": "Filtrer les Types d'Appareils", @@ -131,7 +130,8 @@ "model_filter_mode": "Filtrer les Modèles d'Appareils", "model_list": "Modèles d'Appareils", "devices_filter_mode": "Filtrer les Appareils", - "device_list": "Liste des Appareils" + "device_list": "Liste des Appareils", + "statistics_logic": "Logique de Statistiques" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index 19d39a7..c8fd97d 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -112,7 +112,7 @@ }, "homes_select": { "title": "ホームとデバイスを再度選択", - "description": "## 使用方法\r\n### 制御モード\r\n- 自動: ローカルエリアネットワーク内に利用可能なXiaomi中央ゲートウェイが存在する場合、Home Assistantは中央ゲートウェイを介してデバイス制御コマンドを優先的に送信し、ローカル制御機能を実現します。ローカルエリアネットワーク内に中央ゲートウェイが存在しない場合、Xiaomi OTプロトコルを介して制御コマンドを送信し、ローカル制御機能を実現しようとします。上記のローカル制御条件が満たされない場合にのみ、デバイス制御コマンドはクラウドを介して送信されます。\r\n- クラウド: 制御コマンドはクラウドを介してのみ送信されます。\r\n### 導入されたデバイスのホーム\r\n統合は、選択された家庭にあるデバイスを追加します。\r\n \r\n### {nick_name} さん、こんにちは! 統合制御モードと追加するデバイスがあるホームを選択してください。", + "description": "## 使用方法\r\n### 導入されたデバイスのホーム\r\n統合は、選択された家庭にあるデバイスを追加します。\r\n### デバイスをフィルタリング\r\n家庭の部屋の名前、デバイスの接続タイプ、デバイスのモデルでデバイスをフィルタリングすることをサポートし、デバイスの次元フィルタリングもサポートします。**{local_count}** 個のデバイスがフィルタリングされました。\r\n### 制御モード\r\n- 自動: ローカルエリアネットワーク内に利用可能なXiaomi中央ゲートウェイが存在する場合、Home Assistantは中央ゲートウェイを介してデバイス制御コマンドを優先的に送信し、ローカル制御機能を実現します。ローカルエリアネットワーク内に中央ゲートウェイが存在しない場合、Xiaomi OTプロトコルを介して制御コマンドを送信し、ローカル制御機能を実現しようとします。上記のローカル制御条件が満たされない場合にのみ、デバイス制御コマンドはクラウドを介して送信されます。\r\n- クラウド: 制御コマンドはクラウドを介してのみ送信されます。", "data": { "home_infos": "導入されたデバイスのホーム", "devices_filter": "デバイスをフィルタリング", @@ -123,7 +123,6 @@ "title": "デバイスをフィルタリング", "description": "## 紹介\r\n- 部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n- 対応する統合項目【設定>デバイスリストの更新】ページに移動して再度フィルタリングすることもできます。", "data": { - "statistics_logic": "統計ロジック", "room_filter_mode": "家族の部屋をフィルタリング", "room_list": "家族の部屋", "type_filter_mode": "デバイスタイプをフィルタリング", @@ -131,7 +130,8 @@ "model_filter_mode": "デバイスモデルをフィルタリング", "model_list": "デバイスモデル", "devices_filter_mode": "デバイスをフィルタリング", - "device_list": "デバイスリスト" + "device_list": "デバイスリスト", + "statistics_logic": "統計ロジック" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index 719e6b9..bbbfe1c 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -112,7 +112,7 @@ }, "homes_select": { "title": "Huis en Apparaten opnieuw selecteren", - "description": "## Gebruiksinstructies\r\n### Controlemodus\r\n- Auto: Wanneer er een beschikbare Xiaomi centrale hubgateway in het lokale netwerk is, geeft Home Assistant de voorkeur aan het verzenden van apparaatbedieningscommando's via de centrale hubgateway om lokale controle te bereiken. Als er geen centrale hubgateway in het lokale netwerk is, zal het proberen bedieningscommando's te verzenden via de Xiaomi LAN-controlefunctie. Alleen wanneer de bovenstaande lokale controlevoorwaarden niet zijn vervuld, worden de apparaatbedieningscommando's via de cloud verzonden.\r\n- Cloud: Alle bedieningscommando's worden via de cloud verzonden.\r\n### Apparaten importeren vanuit huis\r\nDe integratie voegt apparaten toe van de geselecteerde huizen.\r\n \r\n### Hallo {nick_name}, selecteer alstublieft de integratie controlemethodiek en het huis waar het apparaat dat u wilt importeren zich bevindt.", + "description": "## Gebruiksinstructies\r\n### Importeer apparaten uit huis\r\nDe integratie voegt apparaten toe van de geselecteerde huizen.\r\n### Apparaten filteren\r\nOndersteunt het filteren van apparaten op kamernaam, apparaattoegangstype en apparaattype, en ondersteunt ook het filteren op apparaatdimensie. **{local_count}** apparaten zijn gefilterd.\r\n### Controlemodus\r\n- Auto: Wanneer er een beschikbare Xiaomi centrale hubgateway in het lokale netwerk is, geeft Home Assistant de voorkeur aan het verzenden van apparaatbedieningscommando's via de centrale hubgateway om lokale controle te bereiken. Als er geen centrale hubgateway in het lokale netwerk is, zal het proberen bedieningscommando's te verzenden via de Xiaomi LAN-controlefunctie. Alleen wanneer de bovenstaande lokale controlevoorwaarden niet zijn vervuld, worden de apparaatbedieningscommando's via de cloud verzonden.\r\n- Cloud: Alle bedieningscommando's worden via de cloud verzonden.", "data": { "home_infos": "Importeer apparaten uit huis", "devices_filter": "Apparaten filteren", @@ -123,7 +123,6 @@ "title": "Apparaten filteren", "description": "## Inleiding\r\n- Ondersteunt het filteren van apparaten op basis van kamer- en apparaattypen, en ondersteunt ook apparaatdimensiefiltering.\r\n- U kunt ook naar de overeenkomstige integratie-item [Configuratie>Apparaatlijst bijwerken] pagina gaan om opnieuw te filteren.", "data": { - "statistics_logic": "Statistische logica", "room_filter_mode": "Kamerfiltermodus", "room_list": "Kamers", "type_filter_mode": "Apparaattypen filteren", @@ -131,7 +130,8 @@ "model_filter_mode": "Apparaatmodel filteren", "model_list": "Apparaatmodellen", "devices_filter_mode": "Apparaten filteren", - "device_list": "Apparaatlijst" + "device_list": "Apparaatlijst", + "statistics_logic": "Statistische logica" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index 9662bb8..51f762e 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -112,7 +112,7 @@ }, "homes_select": { "title": "Selecionar novamente Casa e Dispositivos", - "description": "## Instruções de Uso\r\n### Modo de controle\r\n- Auto: Quando houver um gateway central Xiaomi disponível na rede local, o Home Assistant priorizará o envio de comandos através dele para obter controle local. Caso não haja, tentará enviar comandos através da função de controle LAN da Xiaomi. Somente se as condições anteriores não forem atendidas, o controle será feito pela nuvem.\r\n- Nuvem: Todos os comandos de controle são enviados pela nuvem.\r\n### Importar dispositivos da casa\r\nA integração adicionará dispositivos das casas selecionadas.\r\n \r\n### Olá {nick_name}, selecione o modo de controle da integração e a casa de onde deseja importar dispositivos.", + "description": "## Instruções de Uso\r\n### Importar dispositivos da casa\r\nA integração adicionará dispositivos das casas selecionadas.\r\n### Filtrar Dispositivos\r\nSuporta a filtragem de dispositivos por nome da sala, tipo de acesso do dispositivo e modelo do dispositivo, e também suporta a filtragem por dimensão do dispositivo. **{local_count}** dispositivos foram filtrados.\r\n### Modo de controle\r\n- Auto: Quando houver um gateway central Xiaomi disponível na rede local, o Home Assistant priorizará o envio de comandos através dele para obter controle local. Caso não haja, tentará enviar comandos através da função de controle LAN da Xiaomi. Somente se as condições anteriores não forem atendidas, o controle será feito pela nuvem.\r\n- Nuvem: Todos os comandos de controle são enviados pela nuvem.", "data": { "home_infos": "Importar dispositivos da casa", "devices_filter": "Filtrar Dispositivos", @@ -123,7 +123,6 @@ "title": "Filtrar Dispositivos", "description": "## Introdução\r\n- Suporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n- Você também pode acessar a página correspondente da integração [Configuração>Atualizar Lista de Dispositivos] para refiltrar.", "data": { - "statistics_logic": "Lógica de Estatísticas", "room_filter_mode": "Filtrar por Sala", "room_list": "Salas", "type_filter_mode": "Filtrar por Tipo de Dispositivo", @@ -131,7 +130,8 @@ "model_filter_mode": "Filtrar por Modelo de Dispositivo", "model_list": "Modelos de Dispositivo", "devices_filter_mode": "Filtrar Dispositivos", - "device_list": "Lista de Dispositivos" + "device_list": "Lista de Dispositivos", + "statistics_logic": "Lógica de Estatísticas" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index f505022..a22fcdf 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -112,7 +112,7 @@ }, "homes_select": { "title": "Selecionar novamente a Casa e os Dispositivos", - "description": "## Instruções de Utilização\r\n### Modo de Controlo\r\n- Automático: Quando houver um gateway central Xiaomi disponível na rede local, o Home Assistant priorizará o envio de comandos através dele para obter controlo local. Se não existir um gateway central, tentará enviar comandos através da função de controlo LAN da Xiaomi. Apenas se estas condições não forem satisfeitas, os comandos serão enviados pela nuvem.\r\n- Nuvem: Todos os comandos de controlo são enviados através da nuvem.\r\n### Importar dispositivos da casa\r\nA integração adicionará dispositivos das casas selecionadas.\r\n \r\n### Olá {nick_name}, selecione o modo de controlo da integração e a casa da qual pretende importar dispositivos.", + "description": "## Instruções de Utilização\r\n### Importar dispositivos da casa\r\nA integração adicionará dispositivos das casas selecionadas.\r\n### Filtrar Dispositivos\r\nSuporta a filtragem de dispositivos por nome da sala, tipo de acesso do dispositivo e modelo do dispositivo, e também suporta a filtragem por dimensão do dispositivo. **{local_count}** dispositivos foram filtrados.\r\n### Modo de Controlo\r\n- Automático: Quando houver um gateway central Xiaomi disponível na rede local, o Home Assistant priorizará o envio de comandos através dele para obter controlo local. Se não existir um gateway central, tentará enviar comandos através da função de controlo LAN da Xiaomi. Apenas se estas condições não forem satisfeitas, os comandos serão enviados pela nuvem.\r\n- Nuvem: Todos os comandos de controlo são enviados através da nuvem.", "data": { "home_infos": "Importar dispositivos da casa", "devices_filter": "Filtrar Dispositivos", @@ -123,7 +123,6 @@ "title": "Filtrar Dispositivos", "description": "## Introdução\r\n- Suporta a filtragem de dispositivos por nome de sala e tipo de dispositivo, bem como a filtragem por família.\r\n- Pode também aceder à página de configuração correspondente da integração [Configuração > Atualizar Lista de Dispositivos] para refazer a filtragem.", "data": { - "statistics_logic": "Lógica de Estatísticas", "room_filter_mode": "Filtrar por Sala", "room_list": "Salas", "type_filter_mode": "Filtrar por Tipo de Dispositivo", @@ -131,7 +130,8 @@ "model_filter_mode": "Filtrar por Modelo de Dispositivo", "model_list": "Modelos de Dispositivo", "devices_filter_mode": "Filtrar Dispositivos", - "device_list": "Lista de Dispositivos" + "device_list": "Lista de Dispositivos", + "statistics_logic": "Lógica de Estatísticas" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index 081bcf9..7f76288 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -112,7 +112,7 @@ }, "homes_select": { "title": "Выберите дом и устройства", - "description": "## Инструкция по использованию\r\n### Режим управления\r\n- Авто: Когда в локальной сети доступен центральный шлюз Xiaomi, Home Assistant будет в первую очередь отправлять команды управления устройствами через центральный шлюз для достижения локализованного управления. Если в локальной сети нет центрального шлюза, он попытается отправить команды управления через протокол Xiaomi OT для достижения локализованного управления. Только если вышеуказанные условия локализованного управления не выполняются, команды управления устройствами будут отправляться через облако.\r\n- Облако: Команды управления отправляются только через облако.\r\n### Импорт домашнего устройства\r\nИнтеграция добавит устройства из выбранных домов.\r\n \r\n### {nick_name} Здравствуйте! Выберите режим управления интеграцией и дом, в котором находятся устройства, которые вы хотите добавить.", + "description": "## Инструкция по использованию\r\n### Импорт домашнего устройства\r\nИнтеграция добавит устройства из выбранных домов.\r\n### Фильтрация устройств\r\nПоддерживает фильтрацию устройств по названию комнаты, типу доступа устройства и модели устройства, а также поддерживает фильтрацию по размеру устройства. Отфильтровано **{local_count}** устройств.\r\n### Режим управления\r\n- Авто: Когда в локальной сети доступен центральный шлюз Xiaomi, Home Assistant будет в первую очередь отправлять команды управления устройствами через центральный шлюз для достижения локализованного управления. Если в локальной сети нет центрального шлюза, он попытается отправить команды управления через протокол Xiaomi OT для достижения локализованного управления. Только если вышеуказанные условия локализованного управления не выполняются, команды управления устройствами будут отправляться через облако.\r\n- Облако: Команды управления отправляются только через облако.", "data": { "home_infos": "Импорт домашнего устройства", "devices_filter": "Фильтрация устройств", @@ -123,7 +123,6 @@ "title": "Фильтрация устройств", "description": "## Введение\r\n- Поддерживает фильтрацию устройств по названию комнаты и типу устройства, а также фильтрацию по уровню устройства.\r\n- Вы также можете перейти на соответствующую страницу интеграции [Настройки> Обновить список устройств], чтобы перефильтровать.", "data": { - "statistics_logic": "Логика статистики", "room_filter_mode": "Фильтрация по комнатам семьи", "room_list": "Комнаты семьи", "type_filter_mode": "Фильтрация по типу устройства", @@ -131,7 +130,8 @@ "model_filter_mode": "Фильтрация по модели устройства", "model_list": "Модели устройств", "devices_filter_mode": "Фильтрация устройств", - "device_list": "Список устройств" + "device_list": "Список устройств", + "statistics_logic": "Логика статистики" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index dd19a5a..be3034e 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "高级设置选项", - "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n### 筛选设备\r\n支持按照房间名称和设备类型筛选设备,同时也支持设备维度筛选。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。", + "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n### 筛选设备\r\n支持按照家庭房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。", "data": { "devices_filter": "筛选设备", "ctrl_mode": "控制模式", @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "筛选设备", - "description": "## 使用介绍\r\n支持按照房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n- 统计优先级:排除优先级高于包含优先级,会先取包含项,然后再排除。\r\n- 筛选优先级:筛选设备>筛选设备型号>筛选设备接入类型>筛选家庭房间\r\n### 统计逻辑\r\n- 与逻辑:取所有同模式筛选项的交集。\r\n- 或逻辑:取所有同模式筛选项的并集。\r\n### 筛选模式\r\n- 排除:移除不需要的项。\r\n- 包含:包含需要的项。\r\n\r\n您也可以进入对应集成项【配置>更新设备列表】页面重新筛选。", + "description": "## 使用介绍\r\n支持按照家庭房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选,筛选逻辑如下:\r\n- 会先根据统计逻辑获取所有包含项的并集或者交集,然后再获取排除项的交集或者并集,最后将【包含汇总结果】减去【排除汇总结果】得到【筛选结果】\r\n- 如未选择包含项,表示包含全部。\r\n### 筛选模式\r\n- 排除:移除不需要的项。\r\n- 包含:包含需要的项。\r\n### 统计逻辑\r\n- 与逻辑:取所有同模式筛选项的交集。\r\n- 或逻辑:取所有同模式筛选项的并集。\r\n\r\n您也可以进入集成项的【配置>更新设备列表】页面,勾选【筛选设备】重新筛选。", "data": { - "statistics_logic": "统计逻辑", "room_filter_mode": "筛选家庭房间", "room_list": "家庭房间", "type_filter_mode": "筛选设备接入类型", @@ -53,7 +52,8 @@ "model_filter_mode": "筛选设备型号", "model_list": "设备型号", "devices_filter_mode": "筛选设备", - "device_list": "设备列表" + "device_list": "设备列表", + "statistics_logic": "统计逻辑" } } }, @@ -112,7 +112,7 @@ }, "homes_select": { "title": "重新选择家庭与设备", - "description": "## 使用介绍\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### 导入设备的家庭\r\n集成将添加已选中家庭中的设备。\r\n \r\n### {nick_name} 您好!请选择集成控制模式以及您想要添加的设备所处的家庭。", + "description": "## 使用介绍\r\n### 导入设备的家庭\r\n集成将添加已选中家庭中的设备。\r\n### 筛选设备\r\n支持按照家庭房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选,已筛选出 **{local_count}** 个设备。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。", "data": { "home_infos": "导入设备的家庭", "devices_filter": "筛选设备", @@ -121,9 +121,8 @@ }, "devices_filter": { "title": "筛选设备", - "description": "## 使用介绍\r\n支持按照房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n- 统计优先级:排除优先级高于包含优先级,会先取包含项,然后再排除。\r\n- 筛选优先级:筛选设备>筛选设备型号>筛选设备接入类型>筛选家庭房间\r\n### 统计逻辑\r\n- 与逻辑:取所有同模式筛选项的交集。\r\n- 或逻辑:取所有同模式筛选项的并集。\r\n### 筛选模式\r\n- 排除:移除不需要的项。\r\n- 包含:包含需要的项。\r\n\r\n您也可以进入对应集成项【配置>更新设备列表】页面重新筛选。", + "description": "## 使用介绍\r\n支持按照家庭房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选,筛选逻辑如下:\r\n- 会先根据统计逻辑获取所有包含项的并集或者交集,然后再获取排除项的交集或者并集,最后将【包含汇总结果】减去【排除汇总结果】得到【筛选结果】\r\n- 如未选择包含项,表示包含全部。\r\n### 筛选模式\r\n- 排除:移除不需要的项。\r\n- 包含:包含需要的项。\r\n### 统计逻辑\r\n- 与逻辑:取所有同模式筛选项的交集。\r\n- 或逻辑:取所有同模式筛选项的并集。\r\n\r\n您也可以进入集成项的【配置>更新设备列表】页面,勾选【筛选设备】重新筛选。", "data": { - "statistics_logic": "统计逻辑", "room_filter_mode": "筛选家庭房间", "room_list": "家庭房间", "type_filter_mode": "筛选设备接入类型", @@ -131,7 +130,8 @@ "model_filter_mode": "筛选设备型号", "model_list": "设备型号", "devices_filter_mode": "筛选设备", - "device_list": "设备列表" + "device_list": "设备列表", + "statistics_logic": "统计逻辑" } }, "update_trans_rules": { diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index fc132b0..6287fda 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "篩選設備", - "description": "## 使用介紹\r\n- 支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n- 您也可以進入對應集成項【配置>更新設備列表】頁面重新篩選。", + "description": "", "data": { - "statistics_logic": "統計邏輯", "room_filter_mode": "篩選家庭房間", "room_list": "家庭房間", "type_filter_mode": "篩選設備接入類型", @@ -53,7 +52,8 @@ "model_filter_mode": "篩選設備型號", "model_list": "設備型號", "devices_filter_mode": "篩選設備", - "device_list": "設備列表" + "device_list": "設備列表", + "statistics_logic": "統計邏輯" } } }, @@ -112,7 +112,7 @@ }, "homes_select": { "title": "重新選擇家庭與設備", - "description": "\r\n## 使用介紹\r\n### 控制模式\r\n- 自動:本地局域網內存在可用的小米中樞網關時, Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。只有當本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令強制通過雲端發送。\r\n### 導入設備的家庭\r\n集成將添加已選中家庭中的設備。\r\n \r\n### {nick_name} 您好!請選擇集成控制模式以及您想要添加的設備所處的家庭。", + "description": "## 使用介紹\r\n### 導入設備的家庭\r\n集成將添加已選中家庭中的設備。\r\n### 篩選設備\r\n支持按照家庭房間名稱、設備接入類型、設備型號篩選設備,同時也支持設備維度篩選,已篩選出 **{local_count}** 個設備。\r\n### 控制模式\r\n- 自動:本地局域網內存在可用的小米中樞網關時, Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。只有當本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令強制通過雲端發送。", "data": { "home_infos": "導入設備的家庭", "devices_filter": "篩選設備", @@ -123,7 +123,6 @@ "title": "篩選設備", "description": "## 使用介紹\r\n- 支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n- 您也可以進入對應集成項【配置>更新設備列表】頁面重新篩選。", "data": { - "statistics_logic": "統計邏輯", "room_filter_mode": "篩選家庭房間", "room_list": "家庭房間", "type_filter_mode": "篩選設備接入類型", @@ -131,7 +130,8 @@ "model_filter_mode": "篩選設備型號", "model_list": "設備型號", "devices_filter_mode": "篩選設備", - "device_list": "設備列表" + "device_list": "設備列表", + "statistics_logic": "統計邏輯" } }, "update_trans_rules": { From c24db455bde8d27d46bbaeab646215fc1c524ac4 Mon Sep 17 00:00:00 2001 From: topsworld Date: Tue, 24 Dec 2024 10:38:46 +0800 Subject: [PATCH 19/24] feat: update webhook handle func to private --- custom_components/xiaomi_home/config_flow.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index e6b3627..cc4a97d 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -299,7 +299,7 @@ async def async_step_oauth( domain=DOMAIN, name='oauth redirect url webhook', webhook_id=self._virtual_did, - handler=handle_oauth_webhook, + handler=_handle_oauth_webhook, allowed_methods=(METH_GET,), ) self._fut_oauth_code = self.hass.data[DOMAIN][ @@ -993,7 +993,7 @@ async def async_step_oauth(self, user_input=None): domain=DOMAIN, name='oauth redirect url webhook', webhook_id=self._virtual_did, - handler=handle_oauth_webhook, + handler=_handle_oauth_webhook, allowed_methods=(METH_GET,), ) self._fut_oauth_code = self.hass.data[DOMAIN][ @@ -1615,7 +1615,7 @@ async def async_step_config_confirm(self, user_input=None): return self.async_create_entry(title='', data={}) -async def handle_oauth_webhook(hass, webhook_id, request): +async def _handle_oauth_webhook(hass, webhook_id, request): """Webhook to handle oauth2 callback.""" # pylint: disable=inconsistent-quotes try: From d3a5702f831022812a5d354646c8c8849bf7b186 Mon Sep 17 00:00:00 2001 From: topsworld Date: Tue, 24 Dec 2024 10:39:38 +0800 Subject: [PATCH 20/24] feat: update config flow translations --- custom_components/xiaomi_home/translations/de.json | 8 ++++---- custom_components/xiaomi_home/translations/en.json | 8 ++++---- custom_components/xiaomi_home/translations/es.json | 8 ++++---- custom_components/xiaomi_home/translations/fr.json | 8 ++++---- custom_components/xiaomi_home/translations/ja.json | 8 ++++---- custom_components/xiaomi_home/translations/nl.json | 8 ++++---- custom_components/xiaomi_home/translations/pt-BR.json | 8 ++++---- custom_components/xiaomi_home/translations/pt.json | 8 ++++---- custom_components/xiaomi_home/translations/ru.json | 8 ++++---- custom_components/xiaomi_home/translations/zh-Hant.json | 4 ++-- 10 files changed, 38 insertions(+), 38 deletions(-) diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index 60d2095..8740ea2 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "Geräte filtern", - "description": "## Gebrauchsanweisung\r\n- Unterstützt das Filtern von Geräten nach Raumnamen und Gerätetypen sowie das Filtern nach Gerätedimensionen.\r\n- Sie können auch die entsprechende Integrationsoption \"Konfiguration> Geräteliste aktualisieren\" aufrufen, um die Filterung erneut durchzuführen.", + "description": "## Gebrauchsanweisung\r\nUnterstützt das Filtern von Geräten nach Raumnamen, Gerätezugriffstyp und Gerätemodell, und unterstützt auch das Filtern nach Gerätegröße. Die Filterlogik ist wie folgt:\r\n- Zuerst wird gemäß der statistischen Logik die Vereinigung oder der Schnittpunkt aller eingeschlossenen Elemente ermittelt, dann der Schnittpunkt oder die Vereinigung der ausgeschlossenen Elemente, und schließlich wird das [eingeschlossene Gesamtergebnis] vom [ausgeschlossenen Gesamtergebnis] subtrahiert, um das [Filterergebnis] zu erhalten.\r\n- Wenn keine eingeschlossenen Elemente ausgewählt sind, bedeutet dies, dass alle eingeschlossen sind.\r\n### Filtermodus\r\n- Ausschließen: Unerwünschte Elemente entfernen.\r\n- Einschließen: Gewünschte Elemente einschließen.\r\n### Statistische Logik\r\n- UND-Logik: Den Schnittpunkt aller Elemente im gleichen Modus nehmen.\r\n- ODER-Logik: Die Vereinigung aller Elemente im gleichen Modus nehmen.\r\n\r\nSie können auch zur Seite [Konfiguration > Geräteliste aktualisieren] des Integrationselements gehen, [Geräte filtern] auswählen, um erneut zu filtern.", "data": { - "statistics_logic": "Statistiklogik", "room_filter_mode": "Familienraum filtern", "room_list": "Familienraum", "type_filter_mode": "Gerätetyp filtern", @@ -53,7 +52,8 @@ "model_filter_mode": "Gerätemodell filtern", "model_list": "Gerätemodell", "devices_filter_mode": "Geräte filtern", - "device_list": "Geräteliste" + "device_list": "Geräteliste", + "statistics_logic": "Statistiklogik" } } }, @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "Geräte filtern", - "description": "## Gebrauchsanweisung\r\n- Unterstützt das Filtern von Geräten nach Raumnamen und Gerätetypen sowie das Filtern nach Gerätedimensionen.\r\n- Sie können auch die entsprechende Integrationsoption \"Konfiguration> Geräteliste aktualisieren\" aufrufen, um die Filterung erneut durchzuführen.", + "description": "## Gebrauchsanweisung\r\nUnterstützt das Filtern von Geräten nach Raumnamen, Gerätezugriffstyp und Gerätemodell, und unterstützt auch das Filtern nach Gerätegröße. Die Filterlogik ist wie folgt:\r\n- Zuerst wird gemäß der statistischen Logik die Vereinigung oder der Schnittpunkt aller eingeschlossenen Elemente ermittelt, dann der Schnittpunkt oder die Vereinigung der ausgeschlossenen Elemente, und schließlich wird das [eingeschlossene Gesamtergebnis] vom [ausgeschlossenen Gesamtergebnis] subtrahiert, um das [Filterergebnis] zu erhalten.\r\n- Wenn keine eingeschlossenen Elemente ausgewählt sind, bedeutet dies, dass alle eingeschlossen sind.\r\n### Filtermodus\r\n- Ausschließen: Unerwünschte Elemente entfernen.\r\n- Einschließen: Gewünschte Elemente einschließen.\r\n### Statistische Logik\r\n- UND-Logik: Den Schnittpunkt aller Elemente im gleichen Modus nehmen.\r\n- ODER-Logik: Die Vereinigung aller Elemente im gleichen Modus nehmen.\r\n\r\nSie können auch zur Seite [Konfiguration > Geräteliste aktualisieren] des Integrationselements gehen, [Geräte filtern] auswählen, um erneut zu filtern.", "data": { "room_filter_mode": "Familienraum filtern", "room_list": "Familienraum", diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index da99634..2db6753 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "Filter Devices", - "description": "## Introduction\r\n- Supports filtering devices by room name and device type, and also supports device dimension filtering.\r\n- You can also re-filter on the corresponding integration page [Configuration>Update Device List].", + "description": "## Usage Instructions\r\nSupports filtering devices by home room name, device access type, and device model, and also supports device dimension filtering. The filtering logic is as follows:\r\n- First, according to the statistical logic, get the union or intersection of all included items, then get the intersection or union of the excluded items, and finally subtract the [included summary result] from the [excluded summary result] to get the [filter result].\r\n- If no included items are selected, it means all are included.\r\n### Filter Mode\r\n- Exclude: Remove unwanted items.\r\n- Include: Include desired items.\r\n### Statistical Logic\r\n- AND logic: Take the intersection of all items in the same mode.\r\n- OR logic: Take the union of all items in the same mode.\r\n\r\nYou can also go to the [Configuration > Update Device List] page of the integration item, check [Filter Devices] to re-filter.", "data": { - "statistics_logic": "Statistics Logic", "room_filter_mode": "Filter Family Rooms", "room_list": "Family Rooms", "type_filter_mode": "Filter Device Connect Type", @@ -53,7 +52,8 @@ "model_filter_mode": "Filter Device Model", "model_list": "Device Model", "devices_filter_mode": "Filter Devices", - "device_list": "Device List" + "device_list": "Device List", + "statistics_logic": "Statistics Logic" } } }, @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "Filter Devices", - "description": "## Introduction\r\n- Supports filtering devices by room name and device type, and also supports device dimension filtering.\r\n- You can also re-filter on the corresponding integration page [Configuration>Update Device List].", + "description": "## Usage Instructions\r\nSupports filtering devices by home room name, device access type, and device model, and also supports device dimension filtering. The filtering logic is as follows:\r\n- First, according to the statistical logic, get the union or intersection of all included items, then get the intersection or union of the excluded items, and finally subtract the [included summary result] from the [excluded summary result] to get the [filter result].\r\n- If no included items are selected, it means all are included.\r\n### Filter Mode\r\n- Exclude: Remove unwanted items.\r\n- Include: Include desired items.\r\n### Statistical Logic\r\n- AND logic: Take the intersection of all items in the same mode.\r\n- OR logic: Take the union of all items in the same mode.\r\n\r\nYou can also go to the [Configuration > Update Device List] page of the integration item, check [Filter Devices] to re-filter.", "data": { "room_filter_mode": "Filter Family Rooms", "room_list": "Family Rooms", diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index 8acdccb..20ee29c 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "Filtrar Dispositivos", - "description": "## Introducción\r\n- Admite la filtración de dispositivos por nombre de habitación y tipo de dispositivo, y también admite la filtración por familia.\r\n- También puede volver a filtrar en la página correspondiente de la integración [Configuración>Actualizar lista de dispositivos].", + "description": "## Instrucciones de uso\r\nAdmite la filtración de dispositivos por nombre de habitación, tipo de acceso del dispositivo y modelo de dispositivo, y también admite la filtración por dimensión del dispositivo. La lógica de filtración es la siguiente:\r\n- Primero, de acuerdo con la lógica estadística, obtenga la unión o intersección de todos los elementos incluidos, luego obtenga la intersección o unión de los elementos excluidos, y finalmente reste el [resultado del resumen incluido] del [resultado del resumen excluido] para obtener el [resultado del filtro].\r\n- Si no se seleccionan elementos incluidos, significa que todos están incluidos.\r\n### Modo de Filtración\r\n- Excluir: Eliminar elementos no deseados.\r\n- Incluir: Incluir elementos deseados.\r\n### Lógica Estadística\r\n- Lógica Y: Tomar la intersección de todos los elementos en el mismo modo.\r\n- Lógica O: Tomar la unión de todos los elementos en el mismo modo.\r\n\r\nTambién puede ir a la página [Configuración > Actualizar lista de dispositivos] del elemento de integración, marcar [Filtrar dispositivos] para volver a filtrar.", "data": { - "statistics_logic": "Lógica de Estadísticas", "room_filter_mode": "Filtrar Habitaciones de la Familia", "room_list": "Habitaciones de la Familia", "type_filter_mode": "Filtrar Tipo de Dispositivo", @@ -53,7 +52,8 @@ "model_filter_mode": "Filtrar Modelo de Dispositivo", "model_list": "Modelo de Dispositivo", "devices_filter_mode": "Filtrar Dispositivos", - "device_list": "Lista de Dispositivos" + "device_list": "Lista de Dispositivos", + "statistics_logic": "Lógica de Estadísticas" } } }, @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "Filtrar Dispositivos", - "description": "## Introducción\r\n- Admite la filtración de dispositivos por nombre de habitación y tipo de dispositivo, y también admite la filtración por familia.\r\n- También puede volver a filtrar en la página correspondiente de la integración [Configuración>Actualizar lista de dispositivos].", + "description": "## Instrucciones de uso\r\nAdmite la filtración de dispositivos por nombre de habitación, tipo de acceso del dispositivo y modelo de dispositivo, y también admite la filtración por dimensión del dispositivo. La lógica de filtración es la siguiente:\r\n- Primero, de acuerdo con la lógica estadística, obtenga la unión o intersección de todos los elementos incluidos, luego obtenga la intersección o unión de los elementos excluidos, y finalmente reste el [resultado del resumen incluido] del [resultado del resumen excluido] para obtener el [resultado del filtro].\r\n- Si no se seleccionan elementos incluidos, significa que todos están incluidos.\r\n### Modo de Filtración\r\n- Excluir: Eliminar elementos no deseados.\r\n- Incluir: Incluir elementos deseados.\r\n### Lógica Estadística\r\n- Lógica Y: Tomar la intersección de todos los elementos en el mismo modo.\r\n- Lógica O: Tomar la unión de todos los elementos en el mismo modo.\r\n\r\nTambién puede ir a la página [Configuración > Actualizar lista de dispositivos] del elemento de integración, marcar [Filtrar dispositivos] para volver a filtrar.", "data": { "room_filter_mode": "Filtrar Habitaciones de la Familia", "room_list": "Habitaciones de la Familia", diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index ad6e9ee..b6b87d9 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "Filtrer les Appareils", - "description": "## Introduction\r\n- Prend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n- Vous pouvez également accéder à la page de filtrage correspondante de l'intégration [Configuration> Mettre à jour la liste des appareils] pour refiltrer.", + "description": "## Instructions d'utilisation\r\nPrend en charge le filtrage des appareils par nom de pièce de la maison, type d'accès de l'appareil et modèle d'appareil, et prend également en charge le filtrage par dimension de l'appareil. La logique de filtrage est la suivante :\r\n- Tout d'abord, selon la logique statistique, obtenez l'union ou l'intersection de tous les éléments inclus, puis obtenez l'intersection ou l'union des éléments exclus, et enfin soustrayez le [résultat du résumé inclus] du [résultat du résumé exclu] pour obtenir le [résultat du filtre].\r\n- Si aucun élément inclus n'est sélectionné, cela signifie que tous sont inclus.\r\n### Mode de Filtrage\r\n- Exclure : Supprimer les éléments indésirables.\r\n- Inclure : Inclure les éléments souhaités.\r\n### Logique Statistique\r\n- Logique ET : Prendre l'intersection de tous les éléments dans le même mode.\r\n- Logique OU : Prendre l'union de tous les éléments dans le même mode.\r\n\r\nVous pouvez également aller à la page [Configuration > Mettre à jour la liste des appareils] de l'élément d'intégration, cocher [Filtrer les appareils] pour re-filtrer.", "data": { - "statistics_logic": "Logique de Statistiques", "room_filter_mode": "Filtrer les Pièces", "room_list": "Pièces", "type_filter_mode": "Filtrer les Types d'Appareils", @@ -53,7 +52,8 @@ "model_filter_mode": "Filtrer les Modèles d'Appareils", "model_list": "Modèles d'Appareils", "devices_filter_mode": "Filtrer les Appareils", - "device_list": "Liste des Appareils" + "device_list": "Liste des Appareils", + "statistics_logic": "Logique de Statistiques" } } }, @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "Filtrer les Appareils", - "description": "## Introduction\r\n- Prend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n- Vous pouvez également accéder à la page de filtrage correspondante de l'intégration [Configuration> Mettre à jour la liste des appareils] pour refiltrer.", + "description": "## Instructions d'utilisation\r\nPrend en charge le filtrage des appareils par nom de pièce de la maison, type d'accès de l'appareil et modèle d'appareil, et prend également en charge le filtrage par dimension de l'appareil. La logique de filtrage est la suivante :\r\n- Tout d'abord, selon la logique statistique, obtenez l'union ou l'intersection de tous les éléments inclus, puis obtenez l'intersection ou l'union des éléments exclus, et enfin soustrayez le [résultat du résumé inclus] du [résultat du résumé exclu] pour obtenir le [résultat du filtre].\r\n- Si aucun élément inclus n'est sélectionné, cela signifie que tous sont inclus.\r\n### Mode de Filtrage\r\n- Exclure : Supprimer les éléments indésirables.\r\n- Inclure : Inclure les éléments souhaités.\r\n### Logique Statistique\r\n- Logique ET : Prendre l'intersection de tous les éléments dans le même mode.\r\n- Logique OU : Prendre l'union de tous les éléments dans le même mode.\r\n\r\nVous pouvez également aller à la page [Configuration > Mettre à jour la liste des appareils] de l'élément d'intégration, cocher [Filtrer les appareils] pour re-filtrer.", "data": { "room_filter_mode": "Filtrer les Pièces", "room_list": "Pièces", diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index c8fd97d..65401f4 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "デバイスをフィルタリング", - "description": "## 紹介\r\n- 部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n- 対応する統合項目【設定>デバイスリストの更新】ページに移動して再度フィルタリングすることもできます。", + "description": "## 使用方法\r\n家庭の部屋の名前、デバイスの接続タイプ、デバイスのモデルでデバイスをフィルタリングすることをサポートし、デバイスの次元フィルタリングもサポートします。フィルタリングロジックは次のとおりです:\r\n- まず、統計ロジックに従って、すべての含まれる項目の和集合または交差を取得し、次に除外される項目の交差または和集合を取得し、最後に[含まれる集計結果]から[除外される集計結果]を引いて[フィルタ結果]を取得します。\r\n- 含まれる項目が選択されていない場合、すべてが含まれることを意味します。\r\n### フィルターモード\r\n- 除外:不要な項目を削除します。\r\n- 含む:必要な項目を含めます。\r\n### 統計ロジック\r\n- ANDロジック:同じモードのすべての項目の交差を取ります。\r\n- ORロジック:同じモードのすべての項目の和集合を取ります。\r\n\r\n統合項目の[設定 > デバイスリストの更新]ページに移動し、[デバイスをフィルタリング]を選択して再フィルタリングすることもできます。", "data": { - "statistics_logic": "統計ロジック", "room_filter_mode": "家族の部屋をフィルタリング", "room_list": "家族の部屋", "type_filter_mode": "デバイスタイプをフィルタリング", @@ -53,7 +52,8 @@ "model_filter_mode": "デバイスモデルをフィルタリング", "model_list": "デバイスモデル", "devices_filter_mode": "デバイスをフィルタリング", - "device_list": "デバイスリスト" + "device_list": "デバイスリスト", + "statistics_logic": "統計ロジック" } } }, @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "デバイスをフィルタリング", - "description": "## 紹介\r\n- 部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n- 対応する統合項目【設定>デバイスリストの更新】ページに移動して再度フィルタリングすることもできます。", + "description": "## 使用方法\r\n家庭の部屋の名前、デバイスの接続タイプ、デバイスのモデルでデバイスをフィルタリングすることをサポートし、デバイスの次元フィルタリングもサポートします。フィルタリングロジックは次のとおりです:\r\n- まず、統計ロジックに従って、すべての含まれる項目の和集合または交差を取得し、次に除外される項目の交差または和集合を取得し、最後に[含まれる集計結果]から[除外される集計結果]を引いて[フィルタ結果]を取得します。\r\n- 含まれる項目が選択されていない場合、すべてが含まれることを意味します。\r\n### フィルターモード\r\n- 除外:不要な項目を削除します。\r\n- 含む:必要な項目を含めます。\r\n### 統計ロジック\r\n- ANDロジック:同じモードのすべての項目の交差を取ります。\r\n- ORロジック:同じモードのすべての項目の和集合を取ります。\r\n\r\n統合項目の[設定 > デバイスリストの更新]ページに移動し、[デバイスをフィルタリング]を選択して再フィルタリングすることもできます。", "data": { "room_filter_mode": "家族の部屋をフィルタリング", "room_list": "家族の部屋", diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index bbbfe1c..1a52cfa 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "Apparaten filteren", - "description": "## Inleiding\r\n- Ondersteunt het filteren van apparaten op basis van kamer- en apparaattypen, en ondersteunt ook apparaatdimensiefiltering.\r\n- U kunt ook naar de overeenkomstige integratie-item [Configuratie>Apparaatlijst bijwerken] pagina gaan om opnieuw te filteren.", + "description": "## Gebruiksinstructies\r\nOndersteunt het filteren van apparaten op kamernaam, apparaattoegangstype en apparaattype, en ondersteunt ook het filteren op apparaatdimensie. De filterlogica is als volgt:\r\n- Eerst, volgens de statistische logica, de vereniging of doorsnede van alle opgenomen items verkrijgen, vervolgens de doorsnede of vereniging van de uitgesloten items verkrijgen, en ten slotte het [opgenomen samenvattingsresultaat] aftrekken van het [uitgesloten samenvattingsresultaat] om het [filterresultaat] te verkrijgen.\r\n- Als er geen opgenomen items zijn geselecteerd, betekent dit dat alles is opgenomen.\r\n### Filtermodus\r\n- Uitsluiten: Ongewenste items verwijderen.\r\n- Opnemen: Gewenste items opnemen.\r\n### Statistische Logica\r\n- EN-logica: Neem de doorsnede van alle items in dezelfde modus.\r\n- OF-logica: Neem de vereniging van alle items in dezelfde modus.\r\n\r\nU kunt ook naar de pagina [Configuratie > Apparaatlijst bijwerken] van het integratie-item gaan, [Apparaten filteren] aanvinken om opnieuw te filteren.", "data": { - "statistics_logic": "Statistische logica", "room_filter_mode": "Kamerfiltermodus", "room_list": "Kamers", "type_filter_mode": "Apparaattypen filteren", @@ -53,7 +52,8 @@ "model_filter_mode": "Apparaatmodel filteren", "model_list": "Apparaatmodellen", "devices_filter_mode": "Apparaten filteren", - "device_list": "Apparaatlijst" + "device_list": "Apparaatlijst", + "statistics_logic": "Statistische logica" } } }, @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "Apparaten filteren", - "description": "## Inleiding\r\n- Ondersteunt het filteren van apparaten op basis van kamer- en apparaattypen, en ondersteunt ook apparaatdimensiefiltering.\r\n- U kunt ook naar de overeenkomstige integratie-item [Configuratie>Apparaatlijst bijwerken] pagina gaan om opnieuw te filteren.", + "description": "## Gebruiksinstructies\r\nOndersteunt het filteren van apparaten op kamernaam, apparaattoegangstype en apparaattype, en ondersteunt ook het filteren op apparaatdimensie. De filterlogica is als volgt:\r\n- Eerst, volgens de statistische logica, de vereniging of doorsnede van alle opgenomen items verkrijgen, vervolgens de doorsnede of vereniging van de uitgesloten items verkrijgen, en ten slotte het [opgenomen samenvattingsresultaat] aftrekken van het [uitgesloten samenvattingsresultaat] om het [filterresultaat] te verkrijgen.\r\n- Als er geen opgenomen items zijn geselecteerd, betekent dit dat alles is opgenomen.\r\n### Filtermodus\r\n- Uitsluiten: Ongewenste items verwijderen.\r\n- Opnemen: Gewenste items opnemen.\r\n### Statistische Logica\r\n- EN-logica: Neem de doorsnede van alle items in dezelfde modus.\r\n- OF-logica: Neem de vereniging van alle items in dezelfde modus.\r\n\r\nU kunt ook naar de pagina [Configuratie > Apparaatlijst bijwerken] van het integratie-item gaan, [Apparaten filteren] aanvinken om opnieuw te filteren.", "data": { "room_filter_mode": "Kamerfiltermodus", "room_list": "Kamers", diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index 51f762e..4285387 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "Filtrar Dispositivos", - "description": "## Introdução\r\n- Suporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n- Você também pode acessar a página correspondente da integração [Configuração>Atualizar Lista de Dispositivos] para refiltrar.", + "description": "## Instruções de Uso\r\nSuporta a filtragem de dispositivos por nome da sala, tipo de acesso do dispositivo e modelo do dispositivo, e também suporta a filtragem por dimensão do dispositivo. A lógica de filtragem é a seguinte:\r\n- Primeiro, de acordo com a lógica estatística, obtenha a união ou interseção de todos os itens incluídos, depois obtenha a interseção ou união dos itens excluídos, e finalmente subtraia o [resultado do resumo incluído] do [resultado do resumo excluído] para obter o [resultado do filtro].\r\n- Se nenhum item incluído for selecionado, significa que todos estão incluídos.\r\n### Modo de Filtragem\r\n- Excluir: Remover itens indesejados.\r\n- Incluir: Incluir itens desejados.\r\n### Lógica Estatística\r\n- Lógica E: Pegue a interseção de todos os itens no mesmo modo.\r\n- Lógica OU: Pegue a união de todos os itens no mesmo modo.\r\n\r\nVocê também pode ir para a página [Configuração > Atualizar Lista de Dispositivos] do item de integração, marcar [Filtrar Dispositivos] para refiltrar.", "data": { - "statistics_logic": "Lógica de Estatísticas", "room_filter_mode": "Filtrar por Sala", "room_list": "Salas", "type_filter_mode": "Filtrar por Tipo de Dispositivo", @@ -53,7 +52,8 @@ "model_filter_mode": "Filtrar por Modelo de Dispositivo", "model_list": "Modelos de Dispositivo", "devices_filter_mode": "Filtrar Dispositivos", - "device_list": "Lista de Dispositivos" + "device_list": "Lista de Dispositivos", + "statistics_logic": "Lógica de Estatísticas" } } }, @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "Filtrar Dispositivos", - "description": "## Introdução\r\n- Suporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n- Você também pode acessar a página correspondente da integração [Configuração>Atualizar Lista de Dispositivos] para refiltrar.", + "description": "## Instruções de Uso\r\nSuporta a filtragem de dispositivos por nome da sala, tipo de acesso do dispositivo e modelo do dispositivo, e também suporta a filtragem por dimensão do dispositivo. A lógica de filtragem é a seguinte:\r\n- Primeiro, de acordo com a lógica estatística, obtenha a união ou interseção de todos os itens incluídos, depois obtenha a interseção ou união dos itens excluídos, e finalmente subtraia o [resultado do resumo incluído] do [resultado do resumo excluído] para obter o [resultado do filtro].\r\n- Se nenhum item incluído for selecionado, significa que todos estão incluídos.\r\n### Modo de Filtragem\r\n- Excluir: Remover itens indesejados.\r\n- Incluir: Incluir itens desejados.\r\n### Lógica Estatística\r\n- Lógica E: Pegue a interseção de todos os itens no mesmo modo.\r\n- Lógica OU: Pegue a união de todos os itens no mesmo modo.\r\n\r\nVocê também pode ir para a página [Configuração > Atualizar Lista de Dispositivos] do item de integração, marcar [Filtrar Dispositivos] para refiltrar.", "data": { "room_filter_mode": "Filtrar por Sala", "room_list": "Salas", diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index a22fcdf..78c2762 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "Filtrar Dispositivos", - "description": "## Introdução\r\n- Suporta a filtragem de dispositivos por nome de sala e tipo de dispositivo, bem como a filtragem por família.\r\n- Pode também aceder à página de configuração correspondente da integração [Configuração > Atualizar Lista de Dispositivos] para refazer a filtragem.", + "description": "## Instruções de Utilização\r\nSuporta a filtragem de dispositivos por nome da sala, tipo de acesso do dispositivo e modelo do dispositivo, e também suporta a filtragem por dimensão do dispositivo. A lógica de filtragem é a seguinte:\r\n- Primeiro, de acordo com a lógica estatística, obtenha a união ou interseção de todos os itens incluídos, depois obtenha a interseção ou união dos itens excluídos, e finalmente subtraia o [resultado do resumo incluído] do [resultado do resumo excluído] para obter o [resultado do filtro].\r\n- Se nenhum item incluído for selecionado, significa que todos estão incluídos.\r\n### Modo de Filtragem\r\n- Excluir: Remover itens indesejados.\r\n- Incluir: Incluir itens desejados.\r\n### Lógica Estatística\r\n- Lógica E: Pegue a interseção de todos os itens no mesmo modo.\r\n- Lógica OU: Pegue a união de todos os itens no mesmo modo.\r\n\r\nVocê também pode ir para a página [Configuração > Atualizar Lista de Dispositivos] do item de integração, marcar [Filtrar Dispositivos] para refiltrar.", "data": { - "statistics_logic": "Lógica de Estatísticas", "room_filter_mode": "Filtrar por Sala", "room_list": "Salas", "type_filter_mode": "Filtrar por Tipo de Dispositivo", @@ -53,7 +52,8 @@ "model_filter_mode": "Filtrar por Modelo de Dispositivo", "model_list": "Modelos de Dispositivo", "devices_filter_mode": "Filtrar Dispositivos", - "device_list": "Lista de Dispositivos" + "device_list": "Lista de Dispositivos", + "statistics_logic": "Lógica de Estatísticas" } } }, @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "Filtrar Dispositivos", - "description": "## Introdução\r\n- Suporta a filtragem de dispositivos por nome de sala e tipo de dispositivo, bem como a filtragem por família.\r\n- Pode também aceder à página de configuração correspondente da integração [Configuração > Atualizar Lista de Dispositivos] para refazer a filtragem.", + "description": "## Instruções de Utilização\r\nSuporta a filtragem de dispositivos por nome da sala, tipo de acesso do dispositivo e modelo do dispositivo, e também suporta a filtragem por dimensão do dispositivo. A lógica de filtragem é a seguinte:\r\n- Primeiro, de acordo com a lógica estatística, obtenha a união ou interseção de todos os itens incluídos, depois obtenha a interseção ou união dos itens excluídos, e finalmente subtraia o [resultado do resumo incluído] do [resultado do resumo excluído] para obter o [resultado do filtro].\r\n- Se nenhum item incluído for selecionado, significa que todos estão incluídos.\r\n### Modo de Filtragem\r\n- Excluir: Remover itens indesejados.\r\n- Incluir: Incluir itens desejados.\r\n### Lógica Estatística\r\n- Lógica E: Pegue a interseção de todos os itens no mesmo modo.\r\n- Lógica OU: Pegue a união de todos os itens no mesmo modo.\r\n\r\nVocê também pode ir para a página [Configuração > Atualizar Lista de Dispositivos] do item de integração, marcar [Filtrar Dispositivos] para refiltrar.", "data": { "room_filter_mode": "Filtrar por Sala", "room_list": "Salas", diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index 7f76288..fc7d0f5 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -43,9 +43,8 @@ }, "devices_filter": { "title": "Фильтрация устройств", - "description": "## Введение\r\n- Поддерживает фильтрацию устройств по названию комнаты и типу устройства, а также фильтрацию по уровню устройства.\r\n- Вы также можете перейти на соответствующую страницу интеграции [Настройки> Обновить список устройств], чтобы перефильтровать.", + "description": "## Инструкция по использованию\r\nПоддерживает фильтрацию устройств по названию комнаты, типу доступа устройства и модели устройства, а также поддерживает фильтрацию по размеру устройства. Логика фильтрации следующая:\r\n- Сначала, согласно статистической логике, получите объединение или пересечение всех включенных элементов, затем получите пересечение или объединение исключенных элементов, и, наконец, вычтите [включенный итоговый результат] из [исключенного итогового результата], чтобы получить [результат фильтрации].\r\n- Если не выбраны включенные элементы, это означает, что все включены.\r\n### Режим фильтрации\r\n- Исключить: Удалить ненужные элементы.\r\n- Включить: Включить нужные элементы.\r\n### Статистическая логика\r\n- Логика И: Взять пересечение всех элементов в одном режиме.\r\n- Логика ИЛИ: Взять объединение всех элементов в одном режиме.\r\n\r\nВы также можете перейти на страницу [Конфигурация > Обновить список устройств] элемента интеграции, установить флажок [Фильтровать устройства], чтобы повторно отфильтровать.", "data": { - "statistics_logic": "Логика статистики", "room_filter_mode": "Фильтрация по комнатам семьи", "room_list": "Комнаты семьи", "type_filter_mode": "Фильтрация по типу устройства", @@ -53,7 +52,8 @@ "model_filter_mode": "Фильтрация по модели устройства", "model_list": "Модели устройств", "devices_filter_mode": "Фильтрация устройств", - "device_list": "Список устройств" + "device_list": "Список устройств", + "statistics_logic": "Логика статистики" } } }, @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "Фильтрация устройств", - "description": "## Введение\r\n- Поддерживает фильтрацию устройств по названию комнаты и типу устройства, а также фильтрацию по уровню устройства.\r\n- Вы также можете перейти на соответствующую страницу интеграции [Настройки> Обновить список устройств], чтобы перефильтровать.", + "description": "## Инструкция по использованию\r\nПоддерживает фильтрацию устройств по названию комнаты, типу доступа устройства и модели устройства, а также поддерживает фильтрацию по размеру устройства. Логика фильтрации следующая:\r\n- Сначала, согласно статистической логике, получите объединение или пересечение всех включенных элементов, затем получите пересечение или объединение исключенных элементов, и, наконец, вычтите [включенный итоговый результат] из [исключенного итогового результата], чтобы получить [результат фильтрации].\r\n- Если не выбраны включенные элементы, это означает, что все включены.\r\n### Режим фильтрации\r\n- Исключить: Удалить ненужные элементы.\r\n- Включить: Включить нужные элементы.\r\n### Статистическая логика\r\n- Логика И: Взять пересечение всех элементов в одном режиме.\r\n- Логика ИЛИ: Взять объединение всех элементов в одном режиме.\r\n\r\nВы также можете перейти на страницу [Конфигурация > Обновить список устройств] элемента интеграции, установить флажок [Фильтровать устройства], чтобы повторно отфильтровать.", "data": { "room_filter_mode": "Фильтрация по комнатам семьи", "room_list": "Комнаты семьи", diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index 6287fda..295c32b 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -43,7 +43,7 @@ }, "devices_filter": { "title": "篩選設備", - "description": "", + "description": "## 使用介紹\r\n支持按照家庭房間名稱、設備接入類型、設備型號篩選設備,同時也支持設備維度篩選,篩選邏輯如下:\r\n- 會先根據統計邏輯獲取所有包含項的並集或者交集,然後再獲取排除項的交集或者並集,最後將【包含匯總結果】減去【排除匯總結果】得到【篩選結果】\r\n- 如未選擇包含項,表示包含全部。\r\n### 篩選模式\r\n- 排除:移除不需要的項。\r\n- 包含:包含需要的項。\r\n### 統計邏輯\r\n- 與邏輯:取所有同模式篩選項的交集。\r\n- 或邏輯:取所有同模式篩選項的並集。\r\n\r\n您也可以進入集成項的【配置>更新設備列表】頁面,勾選【篩選設備】重新篩選。", "data": { "room_filter_mode": "篩選家庭房間", "room_list": "家庭房間", @@ -121,7 +121,7 @@ }, "devices_filter": { "title": "篩選設備", - "description": "## 使用介紹\r\n- 支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n- 您也可以進入對應集成項【配置>更新設備列表】頁面重新篩選。", + "description": "## 使用介紹\r\n支持按照家庭房間名稱、設備接入類型、設備型號篩選設備,同時也支持設備維度篩選,篩選邏輯如下:\r\n- 會先根據統計邏輯獲取所有包含項的並集或者交集,然後再獲取排除項的交集或者並集,最後將【包含匯總結果】減去【排除匯總結果】得到【篩選結果】\r\n- 如未選擇包含項,表示包含全部。\r\n### 篩選模式\r\n- 排除:移除不需要的項。\r\n- 包含:包含需要的項。\r\n### 統計邏輯\r\n- 與邏輯:取所有同模式篩選項的交集。\r\n- 或邏輯:取所有同模式篩選項的並集。\r\n\r\n您也可以進入集成項的【配置>更新設備列表】頁面,勾選【篩選設備】重新篩選。", "data": { "room_filter_mode": "篩選家庭房間", "room_list": "家庭房間", From 9eaa1e2677393d7d48f1889696ee99e11669e1a7 Mon Sep 17 00:00:00 2001 From: topsworld Date: Tue, 24 Dec 2024 11:25:21 +0800 Subject: [PATCH 21/24] doc: update tranlations text --- custom_components/xiaomi_home/translations/de.json | 8 +++++--- custom_components/xiaomi_home/translations/en.json | 4 +++- custom_components/xiaomi_home/translations/es.json | 8 +++++--- custom_components/xiaomi_home/translations/fr.json | 8 +++++--- custom_components/xiaomi_home/translations/ja.json | 8 +++++--- custom_components/xiaomi_home/translations/nl.json | 4 +++- custom_components/xiaomi_home/translations/pt-BR.json | 4 +++- custom_components/xiaomi_home/translations/pt.json | 4 +++- custom_components/xiaomi_home/translations/ru.json | 8 +++++--- custom_components/xiaomi_home/translations/zh-Hans.json | 4 +++- custom_components/xiaomi_home/translations/zh-Hant.json | 4 +++- 11 files changed, 43 insertions(+), 21 deletions(-) diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index 8740ea2..fba9229 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -38,7 +38,8 @@ "devices_filter": "Geräte filtern", "ctrl_mode": "Steuerungsmodus", "action_debug": "Action-Debug-Modus", - "hide_non_standard_entities": "Nicht standardmäßige Entitäten ausblenden" + "hide_non_standard_entities": "Nicht standardmäßige Entitäten ausblenden", + "display_devices_changed_notify": "Gerätestatusänderungen anzeigen" } }, "devices_filter": { @@ -99,8 +100,9 @@ "update_devices": "Geräteliste aktualisieren", "action_debug": "Action-Debug-Modus", "hide_non_standard_entities": "Verstecke Nicht-Standard-Entitäten", - "update_trans_rules": "Entitätskonvertierungsregeln aktualisieren (globale konfiguration)", - "update_lan_ctrl_config": "LAN-Steuerungskonfiguration aktualisieren (globale Konfiguration)" + "display_devices_changed_notify": "Gerätestatusänderungen anzeigen", + "update_trans_rules": "Entitätskonvertierungsregeln aktualisieren", + "update_lan_ctrl_config": "LAN-Steuerungskonfiguration aktualisieren" } }, "update_user_info": { diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index 2db6753..2e47a24 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -38,7 +38,8 @@ "devices_filter": "Filter Devices", "ctrl_mode": "Control Mode", "action_debug": "Action Debug Mode", - "hide_non_standard_entities": "Hide Non-Standard Generated Entities" + "hide_non_standard_entities": "Hide Non-Standard Generated Entities", + "display_devices_changed_notify": "Display Device Status Change Notification" } }, "devices_filter": { @@ -99,6 +100,7 @@ "update_devices": "Update device list", "action_debug": "Debug mode for action", "hide_non_standard_entities": "Hide non-standard created entities", + "display_devices_changed_notify": "Display device status change notifications", "update_trans_rules": "Update entity conversion rules", "update_lan_ctrl_config": "Update LAN control configuration" } diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index 20ee29c..11d6f2f 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -38,7 +38,8 @@ "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Control", "action_debug": "Modo de Depuración de Acciones", - "hide_non_standard_entities": "Ocultar Entidades Generadas No Estándar" + "hide_non_standard_entities": "Ocultar Entidades Generadas No Estándar", + "display_devices_changed_notify": "Mostrar notificaciones de cambio de estado del dispositivo" } }, "devices_filter": { @@ -99,8 +100,9 @@ "update_devices": "Actualizar lista de dispositivos", "action_debug": "Modo de depuración de Action", "hide_non_standard_entities": "Ocultar entidades generadas no estándar", - "update_trans_rules": "Actualizar reglas de conversión de entidad (configuración global)", - "update_lan_ctrl_config": "Actualizar configuración de control LAN (configuración global)" + "display_devices_changed_notify": "Mostrar notificaciones de cambio de estado del dispositivo", + "update_trans_rules": "Actualizar reglas de conversión de entidad", + "update_lan_ctrl_config": "Actualizar configuración de control LAN" } }, "update_user_info": { diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index b6b87d9..d035c62 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -38,7 +38,8 @@ "devices_filter": "Filtrer les Appareils", "ctrl_mode": "Mode de Contrôle", "action_debug": "Mode de Débogage d’Actions", - "hide_non_standard_entities": "Masquer les Entités Non Standard" + "hide_non_standard_entities": "Masquer les Entités Non Standard", + "display_devices_changed_notify": "Afficher les notifications de changement d'état de l'appareil" } }, "devices_filter": { @@ -99,8 +100,9 @@ "update_devices": "Mettre à jour la liste des appareils", "action_debug": "Mode de débogage d'action", "hide_non_standard_entities": "Masquer les entités générées non standard", - "update_trans_rules": "Mettre à jour les règles de conversion d'entités (configuration globale)", - "update_lan_ctrl_config": "Mettre à jour la configuration de contrôle LAN (configuration globale)" + "display_devices_changed_notify": "Afficher les notifications de changement d'état de l'appareil", + "update_trans_rules": "Mettre à jour les règles de conversion d'entités", + "update_lan_ctrl_config": "Mettre à jour la configuration de contrôle LAN" } }, "update_user_info": { diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index 65401f4..be0d668 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -38,7 +38,8 @@ "devices_filter": "デバイスをフィルタリング", "ctrl_mode": "コントロールモード", "action_debug": "Actionデバッグモード", - "hide_non_standard_entities": "非標準生成エンティティを隠す" + "hide_non_standard_entities": "非標準生成エンティティを隠す", + "display_devices_changed_notify": "デバイスの状態変化通知を表示" } }, "devices_filter": { @@ -99,8 +100,9 @@ "update_devices": "デバイスリストを更新する", "action_debug": "Action デバッグモード", "hide_non_standard_entities": "非標準生成エンティティを非表示にする", - "update_trans_rules": "エンティティ変換ルールを更新する (グローバル設定)", - "update_lan_ctrl_config": "LAN制御構成を更新する(グローバル設定)" + "display_devices_changed_notify": "デバイスの状態変化通知を表示", + "update_trans_rules": "エンティティ変換ルールを更新する", + "update_lan_ctrl_config": "LAN制御構成を更新する" } }, "update_user_info": { diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index 1a52cfa..13cf9a0 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -38,7 +38,8 @@ "devices_filter": "Apparaten filteren", "ctrl_mode": "Besturingsmodus", "action_debug": "Actie-debugmodus", - "hide_non_standard_entities": "Niet-standaard entiteiten verbergen" + "hide_non_standard_entities": "Niet-standaard entiteiten verbergen", + "display_devices_changed_notify": "Apparaatstatuswijzigingen weergeven" } }, "devices_filter": { @@ -99,6 +100,7 @@ "update_devices": "Werk apparatenlijst bij", "action_debug": "Debugmodus voor actie", "hide_non_standard_entities": "Verberg niet-standaard gemaakte entiteiten", + "display_devices_changed_notify": "Apparaatstatuswijzigingen weergeven", "update_trans_rules": "Werk entiteitsconversieregels bij", "update_lan_ctrl_config": "Werk LAN controleconfiguratie bij" } diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index 4285387..8d58aa6 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -38,7 +38,8 @@ "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Controle", "action_debug": "Modo de Depuração de Ações", - "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão" + "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão", + "display_devices_changed_notify": "Exibir notificações de mudança de status do dispositivo", } }, "devices_filter": { @@ -99,6 +100,7 @@ "update_devices": "Atualizar lista de dispositivos", "action_debug": "Modo de depuração para ação", "hide_non_standard_entities": "Ocultar entidades não padrão criadas", + "display_devices_changed_notify": "Exibir notificações de mudança de status do dispositivo", "update_trans_rules": "Atualizar regras de conversão de entidades", "update_lan_ctrl_config": "Atualizar configuração de controle LAN" } diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index 78c2762..a8c681f 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -38,7 +38,8 @@ "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Controlo", "action_debug": "Modo de Depuração de Ações", - "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão" + "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão", + "display_devices_changed_notify": "Exibir notificações de mudança de status do dispositivo" } }, "devices_filter": { @@ -99,6 +100,7 @@ "update_devices": "Atualizar lista de dispositivos", "action_debug": "Modo de depuração de ação", "hide_non_standard_entities": "Ocultar entidades não padrão", + "display_devices_changed_notify": "Exibir notificações de mudança de status do dispositivo", "update_trans_rules": "Atualizar regras de conversão de entidades", "update_lan_ctrl_config": "Atualizar configuração de controlo LAN" } diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index fc7d0f5..0eec2e8 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -38,7 +38,8 @@ "devices_filter": "Фильтрация устройств", "ctrl_mode": "Режим управления", "action_debug": "Режим отладки действий", - "hide_non_standard_entities": "Скрыть нестандартные сущности" + "hide_non_standard_entities": "Скрыть нестандартные сущности", + "display_devices_changed_notify": "Отображать уведомления о изменении состояния устройства" } }, "devices_filter": { @@ -99,8 +100,9 @@ "update_devices": "Обновить список устройств", "action_debug": "Режим отладки Action", "hide_non_standard_entities": "Скрыть нестандартные сущности", - "update_trans_rules": "Обновить правила преобразования сущностей (глобальная настройка)", - "update_lan_ctrl_config": "Обновить конфигурацию управления LAN (глобальная настройка)" + "display_devices_changed_notify": "Отображать уведомления о изменении состояния устройства", + "update_trans_rules": "Обновить правила преобразования сущностей", + "update_lan_ctrl_config": "Обновить конфигурацию управления LAN" } }, "update_user_info": { diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index be3034e..be981fa 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -38,7 +38,8 @@ "devices_filter": "筛选设备", "ctrl_mode": "控制模式", "action_debug": "Action 调试模式", - "hide_non_standard_entities": "隐藏非标准生成实体" + "hide_non_standard_entities": "隐藏非标准生成实体", + "display_devices_changed_notify": "显示设备状态变化通知" } }, "devices_filter": { @@ -99,6 +100,7 @@ "update_devices": "更新设备列表", "action_debug": "Action 调试模式", "hide_non_standard_entities": "隐藏非标准生成实体", + "display_devices_changed_notify": "显示设备状态变化通知", "update_trans_rules": "更新实体转换规则", "update_lan_ctrl_config": "更新局域网控制配置" } diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index 295c32b..d956011 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -38,7 +38,8 @@ "devices_filter": "篩選設備", "ctrl_mode": "控制模式", "action_debug": "Action 調試模式", - "hide_non_standard_entities": "隱藏非標準生成實體" + "hide_non_standard_entities": "隱藏非標準生成實體", + "display_devices_changed_notify": "顯示設備狀態變化通知" } }, "devices_filter": { @@ -99,6 +100,7 @@ "update_devices": "更新設備列表", "action_debug": "Action 調試模式", "hide_non_standard_entities": "隱藏非標準生成實體", + "display_devices_changed_notify": "顯示設備狀態變化通知", "update_trans_rules": "更新實體轉換規則", "update_lan_ctrl_config": "更新局域網控制配置" } From aa0400efda800e3ef7bfa5668a4ed9517af60157 Mon Sep 17 00:00:00 2001 From: topsworld Date: Tue, 24 Dec 2024 13:08:34 +0800 Subject: [PATCH 22/24] feat: custom display device changed notify --- custom_components/xiaomi_home/config_flow.py | 20 ++++++++++++++++ .../xiaomi_home/miot/miot_client.py | 24 ++++++++++++++++++- .../xiaomi_home/translations/de.json | 2 +- .../xiaomi_home/translations/en.json | 4 ++-- .../xiaomi_home/translations/es.json | 2 +- .../xiaomi_home/translations/fr.json | 2 +- .../xiaomi_home/translations/ja.json | 2 +- .../xiaomi_home/translations/nl.json | 2 +- .../xiaomi_home/translations/pt-BR.json | 4 ++-- .../xiaomi_home/translations/pt.json | 2 +- .../xiaomi_home/translations/ru.json | 2 +- .../xiaomi_home/translations/zh-Hans.json | 2 +- .../xiaomi_home/translations/zh-Hant.json | 2 +- 13 files changed, 56 insertions(+), 14 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index cc4a97d..820de47 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -589,6 +589,9 @@ async def async_step_advanced_options( 'action_debug', self._action_debug) self._hide_non_standard_entities = user_input.get( 'hide_non_standard_entities', self._hide_non_standard_entities) + self._display_devices_changed_notify = user_input.get( + 'display_devices_changed_notify', + self._display_devices_changed_notify) # Device filter if user_input.get('devices_filter', False): return await self.async_step_devices_filter() @@ -811,6 +814,7 @@ class OptionsFlowHandler(config_entries.OptionsFlow): _home_selected_list: list _action_debug: bool _hide_non_standard_entities: bool + _display_devs_notify: bool _oauth_redirect_url_full: str _auth_info: dict @@ -856,6 +860,8 @@ def __init__(self, config_entry: config_entries.ConfigEntry): self._action_debug = self._entry_data.get('action_debug', False) 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) self._home_selected_list = list( self._entry_data['home_selected'].keys()) @@ -1118,6 +1124,10 @@ async def async_step_config_options(self, user_input=None): 'hide_non_standard_entities', default=self._hide_non_standard_entities # type: ignore ): bool, + vol.Required( + 'display_devices_changed_notify', + default=self._display_devs_notify # type: ignore + ): bool, vol.Required( 'update_trans_rules', default=self._update_trans_rules # type: ignore @@ -1149,6 +1159,8 @@ async def async_step_config_options(self, user_input=None): 'action_debug', self._action_debug) self._hide_non_standard_entities_new = user_input.get( 'hide_non_standard_entities', self._hide_non_standard_entities) + self._display_devs_notify = user_input.get( + 'display_devices_changed_notify', self._display_devs_notify) self._update_trans_rules = user_input.get( 'update_trans_rules', self._update_trans_rules) self._update_lan_ctrl_config = user_input.get( @@ -1554,6 +1566,9 @@ async def async_step_config_confirm(self, user_input=None): '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) }, # type: ignore errors={'base': 'not_confirm'} if user_input else {}, last_step=True @@ -1590,6 +1605,11 @@ async def async_step_config_confirm(self, user_input=None): self._entry_data['hide_non_standard_entities'] = ( self._hide_non_standard_entities_new) self._need_reload = True + # Update display_devices_changed_notify + self._entry_data['display_devices_changed_notify'] = ( + self._display_devs_notify) + self._miot_client.display_devices_changed_notify = ( + self._display_devs_notify) if ( self._devices_remove and not await self._miot_storage.update_user_config_async( diff --git a/custom_components/xiaomi_home/miot/miot_client.py b/custom_components/xiaomi_home/miot/miot_client.py index 1346b63..342cec4 100644 --- a/custom_components/xiaomi_home/miot/miot_client.py +++ b/custom_components/xiaomi_home/miot/miot_client.py @@ -164,10 +164,12 @@ class MIoTClient: _refresh_props_retry_count: int # Persistence notify handler, params: notify_id, title, message - _persistence_notify: Callable[[str, str, str], None] + _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 + def __init__( self, entry_id: str, @@ -231,6 +233,9 @@ def __init__( self._persistence_notify = None self._show_devices_changed_notify_timer = None + self._display_devs_notify = entry_data.get( + 'display_devices_changed_notify', True) + async def init_async(self) -> None: # Load user config and check self._user_config = await self._storage.load_user_config_async( @@ -459,6 +464,21 @@ def hide_non_standard_entities(self) -> bool: return self._entry_data.get( 'hide_non_standard_entities', False) + @property + def display_devices_changed_notify(self) -> bool: + 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: + return + self._display_devs_notify = value + if value: + self.__request_show_devices_changed_notify() + else: + self._persistence_notify( + self.__gen_notify_key('dev_list_changed'), None, None) + @property def device_list(self) -> dict: return self._device_list_cache @@ -1801,6 +1821,8 @@ def __show_devices_changed_notify(self) -> None: def __request_show_devices_changed_notify( self, delay_sec: float = 6 ) -> None: + if not self._display_devs_notify: + return if not self._mips_cloud and not self._mips_local and not self._miot_lan: return if self._show_devices_changed_notify_timer: diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index fba9229..a2dbb20 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "Bestätigen Sie die Konfiguration", - "description": "**{nick_name}**, bitte bestätigen Sie die neuesten Konfigurationsinformationen und klicken Sie dann auf \"Senden\". Die Integration wird mit den aktualisierten Konfigurationen erneut geladen.\r\n\r\nIntegrationsprache:\t{lang_new}\r\nBenutzername:\t{nick_name_new}\r\nAction-Debug-Modus:\t{action_debug}\r\nVerstecke Nicht-Standard-Entitäten:\t{hide_non_standard_entities}\r\nGeräteänderungen:\t{devices_add} neue Geräte hinzufügen, {devices_remove} Geräte entfernen\r\nKonvertierungsregeländerungen:\tInsgesamt {trans_rules_count} Regeln, aktualisiert {trans_rules_count_success} Regeln", + "description": "**{nick_name}**, bitte bestätigen Sie die neuesten Konfigurationsinformationen und klicken Sie dann auf \"Senden\". Die Integration wird mit den aktualisierten Konfigurationen erneut geladen.\r\n\r\nIntegrationsprache:\t{lang_new}\r\nBenutzername:\t{nick_name_new}\r\nAction-Debug-Modus:\t{action_debug}\r\nVerstecke Nicht-Standard-Entitäten:\t{hide_non_standard_entities}\r\nGerätestatusänderungen anzeigen:\t{display_devices_changed_notify}\r\nGeräteänderungen:\t{devices_add} neue Geräte hinzufügen, {devices_remove} Geräte entfernen\r\nKonvertierungsregeländerungen:\tInsgesamt {trans_rules_count} Regeln, aktualisiert {trans_rules_count_success} Regeln", "data": { "confirm": "Änderungen bestätigen" } diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index 2e47a24..ee6318d 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -39,7 +39,7 @@ "ctrl_mode": "Control Mode", "action_debug": "Action Debug Mode", "hide_non_standard_entities": "Hide Non-Standard Generated Entities", - "display_devices_changed_notify": "Display Device Status Change Notification" + "display_devices_changed_notify": "Display Device Status Change Notifications" } }, "devices_filter": { @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "Confirm Configuration", - "description": "Hello **{nick_name}**, please confirm the latest configuration information and then Click SUBMIT.\r\nThe integration will reload using the updated configuration.\r\n\r\nIntegration Language: \t{lang_new}\r\nNickname: \t{nick_name_new}\r\nDebug mode for action: \t{action_debug}\r\nHide non-standard created entities: \t{hide_non_standard_entities}\r\nDevice Changes: \tAdd **{devices_add}** devices, Remove **{devices_remove}** devices\r\nTransformation rules change: \tThere are a total of **{trans_rules_count}** rules, and updated **{trans_rules_count_success}** rules", + "description": "Hello **{nick_name}**, please confirm the latest configuration information and then Click SUBMIT.\r\nThe integration will reload using the updated configuration.\r\n\r\nIntegration Language: \t{lang_new}\r\nNickname: \t{nick_name_new}\r\nDebug mode for action: \t{action_debug}\r\nHide non-standard created entities: \t{hide_non_standard_entities}\r\nDisplay device status change notifications:\t{display_devices_changed_notify}\r\nDevice Changes: \tAdd **{devices_add}** devices, Remove **{devices_remove}** devices\r\nTransformation rules change: \tThere are a total of **{trans_rules_count}** rules, and updated **{trans_rules_count_success}** rules", "data": { "confirm": "Confirm the change" } diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index 11d6f2f..e6a4c99 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "Confirmar configuración", - "description": "¡Hola, **{nick_name}**! Por favor, confirme la última información de configuración y haga clic en \"Enviar\" para finalizar la configuración.\r\nLa integración se volverá a cargar con la nueva configuración.\r\n\r\nIdioma de la integración:\t{lang_new}\r\nApodo de usuario:\t{nick_name_new}\r\nModo de depuración de Action:\t{action_debug}\r\nOcultar entidades generadas no estándar:\t{hide_non_standard_entities}\r\nCambios de dispositivos:\t{devices_add} dispositivos agregados, {devices_remove} dispositivos eliminados\r\nCambios en las reglas de conversión:\t{trans_rules_count} reglas en total, {trans_rules_count_success} reglas actualizadas", + "description": "¡Hola, **{nick_name}**! Por favor, confirme la última información de configuración y haga clic en \"Enviar\" para finalizar la configuración.\r\nLa integración se volverá a cargar con la nueva configuración.\r\n\r\nIdioma de la integración:\t{lang_new}\r\nApodo de usuario:\t{nick_name_new}\r\nModo de depuración de Action:\t{action_debug}\r\nOcultar entidades generadas no estándar:\t{hide_non_standard_entities}\r\nMostrar notificaciones de cambio de estado del dispositivo:\t{display_devices_changed_notify}\r\nCambios de dispositivos:\t{devices_add} dispositivos agregados, {devices_remove} dispositivos eliminados\r\nCambios en las reglas de conversión:\t{trans_rules_count} reglas en total, {trans_rules_count_success} reglas actualizadas", "data": { "confirm": "Confirmar modificación" } diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index d035c62..905164f 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "Confirmer la configuration", - "description": "**{nick_name}** Bonjour ! Veuillez confirmer les dernières informations de configuration et cliquer sur \"Soumettre\".\r\nL'intégration rechargera avec la nouvelle configuration.\r\n\r\nLangue d'intégration : {lang_new}\r\nPseudo utilisateur : {nick_name_new}\r\nMode de débogage d'action : {action_debug}\r\nMasquer les entités générées non standard : {hide_non_standard_entities}\r\nModifications des appareils : Ajouter **{devices_add}** appareils, supprimer **{devices_remove}** appareils\r\nModifications des règles de conversion : **{trans_rules_count}** règles au total, mise à jour de **{trans_rules_count_success}** règles", + "description": "**{nick_name}** Bonjour ! Veuillez confirmer les dernières informations de configuration et cliquer sur \"Soumettre\".\r\nL'intégration rechargera avec la nouvelle configuration.\r\n\r\nLangue d'intégration : {lang_new}\r\nPseudo utilisateur : {nick_name_new}\r\nMode de débogage d'action : {action_debug}\r\nMasquer les entités générées non standard : {hide_non_standard_entities}\r\nAfficher les notifications de changement d'état de l'appareil:\t{display_devices_changed_notify}\r\nModifications des appareils : Ajouter **{devices_add}** appareils, supprimer **{devices_remove}** appareils\r\nModifications des règles de conversion : **{trans_rules_count}** règles au total, mise à jour de **{trans_rules_count_success}** règles", "data": { "confirm": "Confirmer la modification" } diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index be0d668..d88ffb4 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "構成を確認する", - "description": "**{nick_name}** さん、こんにちは! 最新の構成情報を確認してください。[送信] をクリックして、更新された構成を使用して再度読み込みます。\r\n\r\n統合言語:\t{lang_new}\r\nユーザー名:\t{nick_name_new}\r\nAction デバッグモード:\t{action_debug}\r\n非標準生成エンティティを非表示にする:\t{hide_non_standard_entities}\r\nデバイス変更:\t追加 **{devices_add}** 個のデバイス、削除 **{devices_remove}** 個のデバイス\r\n変換ルール変更:\t合計 **{trans_rules_count}** 個の規則、更新 **{trans_rules_count_success}** 個の規則", + "description": "**{nick_name}** さん、こんにちは! 最新の構成情報を確認してください。[送信] をクリックして、更新された構成を使用して再度読み込みます。\r\n\r\n統合言語:\t{lang_new}\r\nユーザー名:\t{nick_name_new}\r\nAction デバッグモード:\t{action_debug}\r\n非標準生成エンティティを非表示にする:\t{hide_non_standard_entities}\r\nデバイスの状態変化通知を表示:\t{display_devices_changed_notify}\r\nデバイス変更:\t追加 **{devices_add}** 個のデバイス、削除 **{devices_remove}** 個のデバイス\r\n変換ルール変更:\t合計 **{trans_rules_count}** 個の規則、更新 **{trans_rules_count_success}** 個の規則", "data": { "confirm": "変更を確認する" } diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index 13cf9a0..e0540d6 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "Bevestig Configuratie", - "description": "Hallo **{nick_name}**, bevestig alstublieft de nieuwste configuratie-informatie en klik vervolgens op INDENKEN.\r\nDe integratie zal opnieuw laden met de bijgewerkte configuratie.\r\n\r\nIntegratietaal: \t{lang_new}\r\nBijnaam: \t{nick_name_new}\r\nDebugmodus voor actie: \t{action_debug}\r\nVerberg niet-standaard gemaakte entiteiten: \t{hide_non_standard_entities}\r\nWijzigingen in apparaten: \tVoeg **{devices_add}** apparaten toe, Verwijder **{devices_remove}** apparaten\r\nWijzigingen in transformateregels: \tEr zijn in totaal **{trans_rules_count}** regels, en **{trans_rules_count_success}** regels zijn bijgewerkt", + "description": "Hallo **{nick_name}**, bevestig alstublieft de nieuwste configuratie-informatie en klik vervolgens op INDENKEN.\r\nDe integratie zal opnieuw laden met de bijgewerkte configuratie.\r\n\r\nIntegratietaal: \t{lang_new}\r\nBijnaam: \t{nick_name_new}\r\nDebugmodus voor actie: \t{action_debug}\r\nVerberg niet-standaard gemaakte entiteiten: \t{hide_non_standard_entities}\r\nApparaatstatuswijzigingen weergeven:\t{display_devices_changed_notify}\r\nWijzigingen in apparaten: \tVoeg **{devices_add}** apparaten toe, Verwijder **{devices_remove}** apparaten\r\nWijzigingen in transformateregels: \tEr zijn in totaal **{trans_rules_count}** regels, en **{trans_rules_count_success}** regels zijn bijgewerkt", "data": { "confirm": "Bevestig de wijziging" } diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index 8d58aa6..c7b1d3c 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -39,7 +39,7 @@ "ctrl_mode": "Modo de Controle", "action_debug": "Modo de Depuração de Ações", "hide_non_standard_entities": "Ocultar Entidades Geradas Não Padrão", - "display_devices_changed_notify": "Exibir notificações de mudança de status do dispositivo", + "display_devices_changed_notify": "Exibir notificações de mudança de status do dispositivo" } }, "devices_filter": { @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "Confirmar Configuração", - "description": "Olá **{nick_name}**, confirme as informações da configuração mais recente e depois clique em ENVIAR.\r\nA integração será recarregada com a configuração atualizada.\r\n\r\nIdioma da Integração:\t{lang_new}\r\nApelido:\t{nick_name_new}\r\nModo de depuração para ação:\t{action_debug}\r\nOcultar entidades não padrão criadas:\t{hide_non_standard_entities}\r\nAlterações de Dispositivos:\tAdicionar **{devices_add}** dispositivos, Remover **{devices_remove}** dispositivos\r\nAlteração nas Regras de Transformação:\tUm total de **{trans_rules_count}** regras, e **{trans_rules_count_success}** regras atualizadas", + "description": "Olá **{nick_name}**, confirme as informações da configuração mais recente e depois clique em ENVIAR.\r\nA integração será recarregada com a configuração atualizada.\r\n\r\nIdioma da Integração:\t{lang_new}\r\nApelido:\t{nick_name_new}\r\nModo de depuração para ação:\t{action_debug}\r\nOcultar entidades não padrão criadas:\t{hide_non_standard_entities}\r\nExibir notificações de mudança de status do dispositivo:\t{display_devices_changed_notify}\r\nAlterações de Dispositivos:\tAdicionar **{devices_add}** dispositivos, Remover **{devices_remove}** dispositivos\r\nAlteração nas Regras de Transformação:\tUm total de **{trans_rules_count}** regras, e **{trans_rules_count_success}** regras atualizadas", "data": { "confirm": "Confirmar a mudança" } diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index a8c681f..6e08c5a 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "Confirmar Configuração", - "description": "Olá **{nick_name}**, confirme a informação da configuração mais recente e depois clique em SUBMETER.\r\nA integração será recarregada com a configuração atualizada.\r\n\r\nIdioma da Integração:\t{lang_new}\r\nAlcunha:\t{nick_name_new}\r\nModo de depuração de ação:\t{action_debug}\r\nOcultar entidades não padrão:\t{hide_non_standard_entities}\r\nAlterações aos Dispositivos:\tAdicionar **{devices_add}** dispositivos, Remover **{devices_remove}** dispositivos\r\nAlteração das Regras de Transformação:\tExistem **{trans_rules_count}** regras no total, com **{trans_rules_count_success}** regras atualizadas", + "description": "Olá **{nick_name}**, confirme a informação da configuração mais recente e depois clique em SUBMETER.\r\nA integração será recarregada com a configuração atualizada.\r\n\r\nIdioma da Integração:\t{lang_new}\r\nAlcunha:\t{nick_name_new}\r\nModo de depuração de ação:\t{action_debug}\r\nOcultar entidades não padrão:\t{hide_non_standard_entities}\r\nExibir notificações de mudança de status do dispositivo:\t{display_devices_changed_notify}\r\nAlterações aos Dispositivos:\tAdicionar **{devices_add}** dispositivos, Remover **{devices_remove}** dispositivos\r\nAlteração das Regras de Transformação:\tExistem **{trans_rules_count}** regras no total, com **{trans_rules_count_success}** regras atualizadas", "data": { "confirm": "Confirmar a alteração" } diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index 0eec2e8..e8c6c31 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "Подтверждение настройки", - "description": "**{nick_name}** Здравствуйте! Подтвердите последнюю информацию о настройке и нажмите «Отправить». Интеграция будет перезагружена с использованием обновленных настроек.\r\n\r\nЯзык интеграции:\t{lang_new}\r\nИмя пользователя:\t{nick_name_new}\r\nРежим отладки Action:\t{action_debug}\r\nСкрыть непроизводственные сущности:\t{hide_non_standard_entities}\r\nИзменение устройства:\tДобавлено **{devices_add}** устройство, удалено **{devices_remove}** устройства\r\nИзменение правил преобразования:\tВсего **{trans_rules_count}** правил, обновлено **{trans_rules_count_success}** правил", + "description": "**{nick_name}** Здравствуйте! Подтвердите последнюю информацию о настройке и нажмите «Отправить». Интеграция будет перезагружена с использованием обновленных настроек.\r\n\r\nЯзык интеграции:\t{lang_new}\r\nИмя пользователя:\t{nick_name_new}\r\nРежим отладки Action:\t{action_debug}\r\nСкрыть непроизводственные сущности:\t{hide_non_standard_entities}\r\nОтображать уведомления о изменении состояния устройства:\t{display_devices_changed_notify}\r\nИзменение устройства:\tДобавлено **{devices_add}** устройство, удалено **{devices_remove}** устройства\r\nИзменение правил преобразования:\tВсего **{trans_rules_count}** правил, обновлено **{trans_rules_count_success}** правил", "data": { "confirm": "Подтвердить изменения" } diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index be981fa..0374ad1 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "确认配置", - "description": "**{nick_name}** 您好!请确认最新的配置信息,然后点击“提交”。\r\n集成将会使用更新后的配置重新载入。\r\n\r\n集成语言:\t{lang_new}\r\n用户昵称:\t{nick_name_new}\r\nAction 调试模式:\t{action_debug}\r\n隐藏非标准生成实体:\t{hide_non_standard_entities}\r\n设备变化:\t新增 **{devices_add}** 个设备,移除 **{devices_remove}** 个设备\r\n转换规则变化:\t共条 **{trans_rules_count}** 规则,更新 **{trans_rules_count_success}** 条规则", + "description": "**{nick_name}** 您好!请确认最新的配置信息,然后点击“提交”。\r\n集成将会使用更新后的配置重新载入。\r\n\r\n集成语言:\t{lang_new}\r\n用户昵称:\t{nick_name_new}\r\nAction 调试模式:\t{action_debug}\r\n隐藏非标准生成实体:\t{hide_non_standard_entities}\r\n显示设备状态变化通知:\t{display_devices_changed_notify}\r\n设备变化:\t新增 **{devices_add}** 个设备,移除 **{devices_remove}** 个设备\r\n转换规则变化:\t共条 **{trans_rules_count}** 规则,更新 **{trans_rules_count_success}** 条规则", "data": { "confirm": "确认修改" } diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index d956011..2600b5e 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -153,7 +153,7 @@ }, "config_confirm": { "title": "確認配置", - "description": "**{nick_name}** 您好!請確認最新的配置信息,然後點擊“提交”。\r\n集成將會使用更新後的配置重新載入。\r\n\r\n集成語言:\t{lang_new}\r\n用戶暱稱:\t{nick_name_new}\r\nAction 調試模式:\t{action_debug}\r\n隱藏非標準生成實體:\t{hide_non_standard_entities}\r\n設備變化:\t新增 **{devices_add}** 個設備,移除 **{devices_remove}** 個設備\r\n轉換規則變化:\t共條 **{trans_rules_count}** 規則,更新 **{trans_rules_count_success}** 條規則", + "description": "**{nick_name}** 您好!請確認最新的配置信息,然後點擊“提交”。\r\n集成將會使用更新後的配置重新載入。\r\n\r\n集成語言:\t{lang_new}\r\n用戶暱稱:\t{nick_name_new}\r\nAction 調試模式:\t{action_debug}\r\n隱藏非標準生成實體:\t{hide_non_standard_entities}\r\n顯示設備狀態變化通知:\t{display_devices_changed_notify}\r\n設備變化:\t新增 **{devices_add}** 個設備,移除 **{devices_remove}** 個設備\r\n轉換規則變化:\t共條 **{trans_rules_count}** 規則,更新 **{trans_rules_count_success}** 條規則", "data": { "confirm": "確認修改" } From 97e343e1b5246c16e8b9ad984b6673e39e4b2218 Mon Sep 17 00:00:00 2001 From: topsworld Date: Tue, 24 Dec 2024 15:37:15 +0800 Subject: [PATCH 23/24] feat: device changed notify logical refinement --- custom_components/xiaomi_home/config_flow.py | 26 ++++++++---- .../xiaomi_home/miot/i18n/de.json | 8 +++- .../xiaomi_home/miot/i18n/en.json | 8 +++- .../xiaomi_home/miot/i18n/es.json | 8 +++- .../xiaomi_home/miot/i18n/fr.json | 8 +++- .../xiaomi_home/miot/i18n/ja.json | 8 +++- .../xiaomi_home/miot/i18n/nl.json | 8 +++- .../xiaomi_home/miot/i18n/pt-BR.json | 8 +++- .../xiaomi_home/miot/i18n/pt.json | 8 +++- .../xiaomi_home/miot/i18n/ru.json | 8 +++- .../xiaomi_home/miot/i18n/zh-Hans.json | 8 +++- .../xiaomi_home/miot/i18n/zh-Hant.json | 8 +++- .../xiaomi_home/miot/miot_client.py | 42 ++++++++++--------- 13 files changed, 116 insertions(+), 40 deletions(-) diff --git a/custom_components/xiaomi_home/config_flow.py b/custom_components/xiaomi_home/config_flow.py index 820de47..167e2e5 100644 --- a/custom_components/xiaomi_home/config_flow.py +++ b/custom_components/xiaomi_home/config_flow.py @@ -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 @@ def __init__(self) -> None: 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 @@ async def async_step_advanced_options( 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 @@ def __init__(self, config_entry: config_entries.ConfigEntry): 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 @@ async def async_step_config_options(self, user_input=None): 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 @@ async def async_step_config_confirm(self, user_input=None): 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 @@ async def async_step_config_confirm(self, user_input=None): '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 diff --git a/custom_components/xiaomi_home/miot/i18n/de.json b/custom_components/xiaomi_home/miot/i18n/de.json index 74fe7dc..81fb203 100644 --- a/custom_components/xiaomi_home/miot/i18n/de.json +++ b/custom_components/xiaomi_home/miot/i18n/de.json @@ -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" diff --git a/custom_components/xiaomi_home/miot/i18n/en.json b/custom_components/xiaomi_home/miot/i18n/en.json index e3afb45..219b276 100644 --- a/custom_components/xiaomi_home/miot/i18n/en.json +++ b/custom_components/xiaomi_home/miot/i18n/en.json @@ -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" diff --git a/custom_components/xiaomi_home/miot/i18n/es.json b/custom_components/xiaomi_home/miot/i18n/es.json index 0524e2c..49a6ea6 100644 --- a/custom_components/xiaomi_home/miot/i18n/es.json +++ b/custom_components/xiaomi_home/miot/i18n/es.json @@ -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" diff --git a/custom_components/xiaomi_home/miot/i18n/fr.json b/custom_components/xiaomi_home/miot/i18n/fr.json index 0f0cec0..40feb65 100644 --- a/custom_components/xiaomi_home/miot/i18n/fr.json +++ b/custom_components/xiaomi_home/miot/i18n/fr.json @@ -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" diff --git a/custom_components/xiaomi_home/miot/i18n/ja.json b/custom_components/xiaomi_home/miot/i18n/ja.json index d714539..3ffc22a 100644 --- a/custom_components/xiaomi_home/miot/i18n/ja.json +++ b/custom_components/xiaomi_home/miot/i18n/ja.json @@ -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": "インターフェースが利用できません" diff --git a/custom_components/xiaomi_home/miot/i18n/nl.json b/custom_components/xiaomi_home/miot/i18n/nl.json index 01ada51..101ff3a 100644 --- a/custom_components/xiaomi_home/miot/i18n/nl.json +++ b/custom_components/xiaomi_home/miot/i18n/nl.json @@ -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" diff --git a/custom_components/xiaomi_home/miot/i18n/pt-BR.json b/custom_components/xiaomi_home/miot/i18n/pt-BR.json index 109837e..8e37ecb 100644 --- a/custom_components/xiaomi_home/miot/i18n/pt-BR.json +++ b/custom_components/xiaomi_home/miot/i18n/pt-BR.json @@ -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" diff --git a/custom_components/xiaomi_home/miot/i18n/pt.json b/custom_components/xiaomi_home/miot/i18n/pt.json index 1ff075e..08afe4d 100644 --- a/custom_components/xiaomi_home/miot/i18n/pt.json +++ b/custom_components/xiaomi_home/miot/i18n/pt.json @@ -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" diff --git a/custom_components/xiaomi_home/miot/i18n/ru.json b/custom_components/xiaomi_home/miot/i18n/ru.json index acd66f4..d018603 100644 --- a/custom_components/xiaomi_home/miot/i18n/ru.json +++ b/custom_components/xiaomi_home/miot/i18n/ru.json @@ -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": "Интерфейс недоступен" diff --git a/custom_components/xiaomi_home/miot/i18n/zh-Hans.json b/custom_components/xiaomi_home/miot/i18n/zh-Hans.json index bb5f742..d8f7c8a 100644 --- a/custom_components/xiaomi_home/miot/i18n/zh-Hans.json +++ b/custom_components/xiaomi_home/miot/i18n/zh-Hans.json @@ -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": "接口不可用" diff --git a/custom_components/xiaomi_home/miot/i18n/zh-Hant.json b/custom_components/xiaomi_home/miot/i18n/zh-Hant.json index aec5293..73bfa98 100644 --- a/custom_components/xiaomi_home/miot/i18n/zh-Hant.json +++ b/custom_components/xiaomi_home/miot/i18n/zh-Hant.json @@ -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": "接口不可用" diff --git a/custom_components/xiaomi_home/miot/miot_client.py b/custom_components/xiaomi_home/miot/miot_client.py index 342cec4..9c57c34 100644 --- a/custom_components/xiaomi_home/miot/miot_client.py +++ b/custom_components/xiaomi_home/miot/miot_client.py @@ -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 @@ def __init__( 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 @@ def hide_non_standard_entities(self) -> bool: '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 @@ def __show_devices_changed_notify(self) -> None: 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 @@ def __show_devices_changed_notify(self) -> None: 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 @@ def __show_devices_changed_notify(self) -> None: 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 @@ def __show_devices_changed_notify(self) -> None: 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={ From a526e717f51837e01a60d2730f7907892a0f29f0 Mon Sep 17 00:00:00 2001 From: topsworld Date: Tue, 24 Dec 2024 16:34:27 +0800 Subject: [PATCH 24/24] doc: update translations content --- custom_components/xiaomi_home/translations/de.json | 2 +- custom_components/xiaomi_home/translations/en.json | 2 +- custom_components/xiaomi_home/translations/es.json | 2 +- custom_components/xiaomi_home/translations/fr.json | 2 +- custom_components/xiaomi_home/translations/ja.json | 2 +- custom_components/xiaomi_home/translations/nl.json | 2 +- custom_components/xiaomi_home/translations/pt-BR.json | 2 +- custom_components/xiaomi_home/translations/pt.json | 2 +- custom_components/xiaomi_home/translations/ru.json | 2 +- custom_components/xiaomi_home/translations/zh-Hans.json | 2 +- custom_components/xiaomi_home/translations/zh-Hant.json | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) diff --git a/custom_components/xiaomi_home/translations/de.json b/custom_components/xiaomi_home/translations/de.json index a2dbb20..c027233 100644 --- a/custom_components/xiaomi_home/translations/de.json +++ b/custom_components/xiaomi_home/translations/de.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Erweiterte Einstellungen", - "description": "## Gebrauchsanweisung\r\n### Wenn Sie die Bedeutung der folgenden Optionen nicht genau kennen, belassen Sie sie bitte auf den Standardeinstellungen.\r\n### Geräte filtern\r\nUnterstützt das Filtern von Geräten nach Raumnamen und Gerätetypen sowie das Filtern nach Gerätedimensionen.\r\n\r\n### Steuerungsmodus\r\n- Automatisch: Wenn ein verfügbarer Xiaomi-Hub im lokalen Netzwerk vorhanden ist, priorisiert Home Assistant das Senden von Steuerbefehlen über den Hub, um eine lokale Steuerung zu ermöglichen. Wenn kein Hub vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden. Nur wenn diese Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Befehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden ausschließlich über die Cloud gesendet.\r\n### Action-Debug-Modus\r\nFür Methoden, die von MIoT-Spec-V2-Geräten definiert werden, wird neben der Benachrichtigungsentität auch eine Texteingabe-Entität erstellt, mit der Sie während des Debuggens Steuerbefehle an das Gerät senden können.\r\n### Nicht standardmäßige Entitäten ausblenden\r\nBlendet Entitäten aus, die von nicht-standardmäßigen MIoT-Spec-V2-Instanzen generiert werden und deren Name mit „*“ beginnt.", + "description": "## Gebrauchsanweisung\r\n### Wenn Sie die Bedeutung der folgenden Optionen nicht genau kennen, belassen Sie sie bitte auf den Standardeinstellungen.\r\n### Geräte filtern\r\nUnterstützt das Filtern von Geräten nach Raumnamen und Gerätetypen sowie das Filtern nach Gerätedimensionen.\r\n\r\n### Steuerungsmodus\r\n- Automatisch: Wenn ein verfügbarer Xiaomi-Hub im lokalen Netzwerk vorhanden ist, priorisiert Home Assistant das Senden von Steuerbefehlen über den Hub, um eine lokale Steuerung zu ermöglichen. Wenn kein Hub vorhanden ist, wird versucht, Steuerbefehle über das Xiaomi-OT-Protokoll zu senden. Nur wenn diese Bedingungen für die lokale Steuerung nicht erfüllt sind, werden die Befehle über die Cloud gesendet.\r\n- Cloud: Steuerbefehle werden ausschließlich über die Cloud gesendet.\r\n### Action-Debug-Modus\r\nFür Methoden, die von MIoT-Spec-V2-Geräten definiert werden, wird neben der Benachrichtigungsentität auch eine Texteingabe-Entität erstellt, mit der Sie während des Debuggens Steuerbefehle an das Gerät senden können.\r\n### Nicht standardmäßige Entitäten ausblenden\r\nBlendet Entitäten aus, die von nicht-standardmäßigen MIoT-Spec-V2-Instanzen generiert werden und deren Name mit „*“ beginnt.\r\n### Gerätestatusänderungen anzeigen\r\nDetaillierte Anzeige von Gerätestatusänderungen, es werden nur die ausgewählten Benachrichtigungen angezeigt.", "data": { "devices_filter": "Geräte filtern", "ctrl_mode": "Steuerungsmodus", diff --git a/custom_components/xiaomi_home/translations/en.json b/custom_components/xiaomi_home/translations/en.json index ee6318d..67fe41c 100644 --- a/custom_components/xiaomi_home/translations/en.json +++ b/custom_components/xiaomi_home/translations/en.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Advanced Settings", - "description": "## Introduction\r\n### Unless you are very clear about the meaning of the following options, please keep the default settings.\r\n### Filter Devices\r\nSupports filtering devices by room name and device type, and also supports device dimension filtering.\r\n### Control Mode\r\n- Auto: When there is an available Xiaomi central hub gateway in the local area network, Home Assistant will prioritize sending device control commands through the central hub gateway to achieve local control. If there is no central hub gateway in the local area network, it will attempt to send control commands through Xiaomi OT protocol to achieve local control. Only when the above local control conditions are not met, the device control commands will be sent through the cloud.\r\n- Cloud: All control commands are sent through the cloud.\r\n### Action Debug Mode\r\nFor the methods defined by the device MIoT-Spec-V2, in addition to generating notification entities, a text input box entity will also be generated. You can use it to send control commands to the device during debugging.\r\n### Hide Non-Standard Generated Entities\r\nHide entities generated by non-standard MIoT-Spec-V2 instances with names starting with \"*\".", + "description": "## Introduction\r\n### Unless you are very clear about the meaning of the following options, please keep the default settings.\r\n### Filter Devices\r\nSupports filtering devices by room name and device type, and also supports device dimension filtering.\r\n### Control Mode\r\n- Auto: When there is an available Xiaomi central hub gateway in the local area network, Home Assistant will prioritize sending device control commands through the central hub gateway to achieve local control. If there is no central hub gateway in the local area network, it will attempt to send control commands through Xiaomi OT protocol to achieve local control. Only when the above local control conditions are not met, the device control commands will be sent through the cloud.\r\n- Cloud: All control commands are sent through the cloud.\r\n### Action Debug Mode\r\nFor the methods defined by the device MIoT-Spec-V2, in addition to generating notification entities, a text input box entity will also be generated. You can use it to send control commands to the device during debugging.\r\n### Hide Non-Standard Generated Entities\r\nHide entities generated by non-standard MIoT-Spec-V2 instances with names starting with \"*\".\r\n### Display Device Status Change Notifications\r\nDisplay detailed device status change notifications, only showing the selected notifications.", "data": { "devices_filter": "Filter Devices", "ctrl_mode": "Control Mode", diff --git a/custom_components/xiaomi_home/translations/es.json b/custom_components/xiaomi_home/translations/es.json index e6a4c99..a402eaa 100644 --- a/custom_components/xiaomi_home/translations/es.json +++ b/custom_components/xiaomi_home/translations/es.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Opciones Avanzadas", - "description": "## Introducción\r\n### A menos que entienda claramente el significado de las siguientes opciones, manténgalas en su configuración predeterminada.\r\n### Filtrar dispositivos\r\nAdmite la filtración de dispositivos por nombre de habitación y tipo de dispositivo, y también admite la filtración por familia.\r\n### Modo de Control\r\n- Automático: Cuando hay una puerta de enlace central de Xiaomi disponible en la red local, Home Assistant enviará comandos de control de dispositivos a través de la puerta de enlace central para lograr la función de control local. Cuando no hay una puerta de enlace central en la red local, intentará enviar comandos de control a través del protocolo OT de Xiaomi para lograr la función de control local. Solo cuando no se cumplan las condiciones de control local anteriores, los comandos de control de dispositivos se enviarán a través de la nube.\r\n- Nube: Los comandos de control solo se envían a través de la nube.\r\n### Modo de Depuración de Acciones\r\nPara los métodos definidos por el dispositivo MIoT-Spec-V2, además de generar una entidad de notificación, también se generará una entidad de cuadro de texto que se puede utilizar para enviar comandos de control al dispositivo durante la depuración.\r\n### Ocultar Entidades Generadas No Estándar\r\nOcultar entidades generadas por instancias MIoT-Spec-V2 no estándar que comienzan con \"*\".", + "description": "## Introducción\r\n### A menos que entienda claramente el significado de las siguientes opciones, manténgalas en su configuración predeterminada.\r\n### Filtrar dispositivos\r\nAdmite la filtración de dispositivos por nombre de habitación y tipo de dispositivo, y también admite la filtración por familia.\r\n### Modo de Control\r\n- Automático: Cuando hay una puerta de enlace central de Xiaomi disponible en la red local, Home Assistant enviará comandos de control de dispositivos a través de la puerta de enlace central para lograr la función de control local. Cuando no hay una puerta de enlace central en la red local, intentará enviar comandos de control a través del protocolo OT de Xiaomi para lograr la función de control local. Solo cuando no se cumplan las condiciones de control local anteriores, los comandos de control de dispositivos se enviarán a través de la nube.\r\n- Nube: Los comandos de control solo se envían a través de la nube.\r\n### Modo de Depuración de Acciones\r\nPara los métodos definidos por el dispositivo MIoT-Spec-V2, además de generar una entidad de notificación, también se generará una entidad de cuadro de texto que se puede utilizar para enviar comandos de control al dispositivo durante la depuración.\r\n### Ocultar Entidades Generadas No Estándar\r\nOcultar entidades generadas por instancias MIoT-Spec-V2 no estándar que comienzan con \"*\".\r\n### Mostrar notificaciones de cambio de estado del dispositivo\r\nMostrar notificaciones detalladas de cambio de estado del dispositivo, mostrando solo las notificaciones seleccionadas.", "data": { "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Control", diff --git a/custom_components/xiaomi_home/translations/fr.json b/custom_components/xiaomi_home/translations/fr.json index 905164f..eed4c6a 100644 --- a/custom_components/xiaomi_home/translations/fr.json +++ b/custom_components/xiaomi_home/translations/fr.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Paramètres Avancés", - "description": "## Introduction\r\n### Sauf si vous comprenez très bien la signification des options suivantes, veuillez les laisser par défaut.\r\n### Filtrer les appareils\r\nPrend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n### Mode de Contrôle\r\n- Automatique : Lorsqu'une passerelle Xiaomi est disponible dans le réseau local, Home Assistant enverra les commandes de contrôle des appareils via la passerelle pour permettre le contrôle local. Si aucune passerelle n'est disponible dans le réseau local, Home Assistant essaiera d'envoyer les commandes de contrôle des appareils via le protocole OT Xiaomi pour permettre le contrôle local. Seules si les conditions de contrôle local ci-dessus ne sont pas remplies, les commandes de contrôle des appareils seront envoyées via le cloud.\r\n- Cloud : Les commandes de contrôle des appareils sont envoyées uniquement via le cloud.\r\n### Mode de Débogage d’Actions\r\nPour les méthodes définies par les appareils MIoT-Spec-V2, en plus de générer une entité de notification, une entité de champ de texte sera également générée pour vous permettre d'envoyer des commandes de contrôle aux appareils lors du débogage.\r\n### Masquer les Entités Non Standard\r\nMasquer les entités générées par des instances MIoT-Spec-V2 non standard et commençant par \"*\".", + "description": "## Introduction\r\n### Sauf si vous comprenez très bien la signification des options suivantes, veuillez les laisser par défaut.\r\n### Filtrer les appareils\r\nPrend en charge le filtrage des appareils en fonction du nom de la pièce et du type d'appareil, ainsi que le filtrage basé sur les appareils.\r\n### Mode de Contrôle\r\n- Automatique : Lorsqu'une passerelle Xiaomi est disponible dans le réseau local, Home Assistant enverra les commandes de contrôle des appareils via la passerelle pour permettre le contrôle local. Si aucune passerelle n'est disponible dans le réseau local, Home Assistant essaiera d'envoyer les commandes de contrôle des appareils via le protocole OT Xiaomi pour permettre le contrôle local. Seules si les conditions de contrôle local ci-dessus ne sont pas remplies, les commandes de contrôle des appareils seront envoyées via le cloud.\r\n- Cloud : Les commandes de contrôle des appareils sont envoyées uniquement via le cloud.\r\n### Mode de Débogage d’Actions\r\nPour les méthodes définies par les appareils MIoT-Spec-V2, en plus de générer une entité de notification, une entité de champ de texte sera également générée pour vous permettre d'envoyer des commandes de contrôle aux appareils lors du débogage.\r\n### Masquer les Entités Non Standard\r\nMasquer les entités générées par des instances MIoT-Spec-V2 non standard et commençant par \"*\".\r\n### Afficher les notifications de changement d'état de l'appareil\r\nAfficher les notifications détaillées de changement d'état de l'appareil, en affichant uniquement les notifications sélectionnées.", "data": { "devices_filter": "Filtrer les Appareils", "ctrl_mode": "Mode de Contrôle", diff --git a/custom_components/xiaomi_home/translations/ja.json b/custom_components/xiaomi_home/translations/ja.json index d88ffb4..5efe18a 100644 --- a/custom_components/xiaomi_home/translations/ja.json +++ b/custom_components/xiaomi_home/translations/ja.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "高度な設定オプション", - "description": "## 紹介\r\n### 以下のオプションの意味がよくわからない場合は、デフォルトのままにしてください。\r\n### デバイスのフィルタリング\r\n部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n### コントロールモード\r\n- 自動:ローカルネットワーク内に利用可能なXiaomi中央ゲートウェイがある場合、Home Assistantはデバイス制御命令を送信するために優先的に中央ゲートウェイを使用します。ローカルネットワークに中央ゲートウェイがない場合、Xiaomi OTプロトコルを使用してデバイス制御命令を送信し、ローカル制御機能を実現します。上記のローカル制御条件が満たされない場合のみ、デバイス制御命令はクラウドを介して送信されます。\r\n- クラウド:制御命令はクラウドを介してのみ送信されます。\r\n### Actionデバッグモード\r\nデバイスが定義するMIoT-Spec-V2のメソッドに対して、通知エンティティを生成するだけでなく、デバイスに制御命令を送信するためのテキスト入力ボックスエンティティも生成されます。デバッグ時にデバイスに制御命令を送信するために使用できます。\r\n### 非標準生成エンティティを隠す\r\n「*」で始まる名前の非標準MIoT-Spec-V2インスタンスによって生成されたエンティティを非表示にします。", + "description": "## 紹介\r\n### 以下のオプションの意味がよくわからない場合は、デフォルトのままにしてください。\r\n### デバイスのフィルタリング\r\n部屋名とデバイスタイプでデバイスをフィルタリングすることができます。デバイスの次元でフィルタリングすることもできます。\r\n### コントロールモード\r\n- 自動:ローカルネットワーク内に利用可能なXiaomi中央ゲートウェイがある場合、Home Assistantはデバイス制御命令を送信するために優先的に中央ゲートウェイを使用します。ローカルネットワークに中央ゲートウェイがない場合、Xiaomi OTプロトコルを使用してデバイス制御命令を送信し、ローカル制御機能を実現します。上記のローカル制御条件が満たされない場合のみ、デバイス制御命令はクラウドを介して送信されます。\r\n- クラウド:制御命令はクラウドを介してのみ送信されます。\r\n### Actionデバッグモード\r\nデバイスが定義するMIoT-Spec-V2のメソッドに対して、通知エンティティを生成するだけでなく、デバイスに制御命令を送信するためのテキスト入力ボックスエンティティも生成されます。デバッグ時にデバイスに制御命令を送信するために使用できます。\r\n### 非標準生成エンティティを隠す\r\n「*」で始まる名前の非標準MIoT-Spec-V2インスタンスによって生成されたエンティティを非表示にします。\r\n### デバイスの状態変化通知を表示\r\nデバイスの状態変化通知を詳細に表示し、選択された通知のみを表示します。", "data": { "devices_filter": "デバイスをフィルタリング", "ctrl_mode": "コントロールモード", diff --git a/custom_components/xiaomi_home/translations/nl.json b/custom_components/xiaomi_home/translations/nl.json index e0540d6..a36d30b 100644 --- a/custom_components/xiaomi_home/translations/nl.json +++ b/custom_components/xiaomi_home/translations/nl.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Geavanceerde Instellingen", - "description": "## Inleiding\r\n### Tenzij u zeer goed op de hoogte bent van de betekenis van de volgende opties, houdt u de standaardinstellingen.\r\n### Apparaten filteren\r\nOndersteunt het filteren van apparaten op basis van kamer- en apparaattypen, en ondersteunt ook apparaatdimensiefiltering.\r\n### Besturingsmodus\r\n- Automatisch: Wanneer er een beschikbare Xiaomi centrale hubgateway in het lokale netwerk is, zal Home Assistant eerst apparaatbesturingsinstructies via de centrale hubgateway verzenden om lokale controlefunctionaliteit te bereiken. Als er geen centrale hub in het lokale netwerk is, zal het proberen om besturingsinstructies via het Xiaomi OT-protocol te verzenden om lokale controlefunctionaliteit te bereiken. Alleen als de bovenstaande lokale controlevoorwaarden niet worden vervuld, worden apparaatbesturingsinstructies via de cloud verzonden.\r\n- Cloud: Besturingsinstructies worden alleen via de cloud verzonden.\r\n### Actie-debugmodus\r\nVoor methoden die zijn gedefinieerd in de MIoT-Spec-V2 van het apparaat, wordt naast het genereren van een meldingsentiteit ook een tekstinvoerveldentiteit gegenereerd. U kunt dit gebruiken om besturingsinstructies naar het apparaat te sturen tijdens het debuggen.\r\n### Niet-standaard entiteiten verbergen\r\nVerberg entiteiten die zijn gegenereerd door niet-standaard MIoT-Spec-V2-instanties die beginnen met \"*\".", + "description": "## Inleiding\r\n### Tenzij u zeer goed op de hoogte bent van de betekenis van de volgende opties, houdt u de standaardinstellingen.\r\n### Apparaten filteren\r\nOndersteunt het filteren van apparaten op basis van kamer- en apparaattypen, en ondersteunt ook apparaatdimensiefiltering.\r\n### Besturingsmodus\r\n- Automatisch: Wanneer er een beschikbare Xiaomi centrale hubgateway in het lokale netwerk is, zal Home Assistant eerst apparaatbesturingsinstructies via de centrale hubgateway verzenden om lokale controlefunctionaliteit te bereiken. Als er geen centrale hub in het lokale netwerk is, zal het proberen om besturingsinstructies via het Xiaomi OT-protocol te verzenden om lokale controlefunctionaliteit te bereiken. Alleen als de bovenstaande lokale controlevoorwaarden niet worden vervuld, worden apparaatbesturingsinstructies via de cloud verzonden.\r\n- Cloud: Besturingsinstructies worden alleen via de cloud verzonden.\r\n### Actie-debugmodus\r\nVoor methoden die zijn gedefinieerd in de MIoT-Spec-V2 van het apparaat, wordt naast het genereren van een meldingsentiteit ook een tekstinvoerveldentiteit gegenereerd. U kunt dit gebruiken om besturingsinstructies naar het apparaat te sturen tijdens het debuggen.\r\n### Niet-standaard entiteiten verbergen\r\nVerberg entiteiten die zijn gegenereerd door niet-standaard MIoT-Spec-V2-instanties die beginnen met \"*\".\r\n### Apparaatstatuswijzigingen weergeven\r\nGedetailleerde apparaatstatuswijzigingen weergeven, alleen de geselecteerde meldingen weergeven.", "data": { "devices_filter": "Apparaten filteren", "ctrl_mode": "Besturingsmodus", diff --git a/custom_components/xiaomi_home/translations/pt-BR.json b/custom_components/xiaomi_home/translations/pt-BR.json index c7b1d3c..521c2fa 100644 --- a/custom_components/xiaomi_home/translations/pt-BR.json +++ b/custom_components/xiaomi_home/translations/pt-BR.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Configurações Avançadas", - "description": "## Introdução\r\n### A menos que você entenda claramente o significado das opções a seguir, mantenha as configurações padrão.\r\n### Filtrar Dispositivos\r\nSuporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n### Modo de Controle\r\n- Automático: Quando um gateway central Xiaomi disponível na rede local está disponível, o Home Assistant enviará comandos de controle de dispositivo através do gateway central para realizar a função de controle local. Quando não há gateway central na rede local, ele tentará enviar comandos de controle através do protocolo OT da Xiaomi para realizar a função de controle local. Somente quando as condições de controle local acima não forem atendidas, os comandos de controle do dispositivo serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controle são enviados apenas através da nuvem.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos pelo MIoT-Spec-V2 do dispositivo, além de gerar uma entidade de notificação, também será gerada uma entidade de caixa de texto para você enviar comandos de controle ao dispositivo durante a depuração.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOcultar entidades geradas por instâncias MIoT-Spec-V2 não padrão que começam com \"*\".", + "description": "## Introdução\r\n### A menos que você entenda claramente o significado das opções a seguir, mantenha as configurações padrão.\r\n### Filtrar Dispositivos\r\nSuporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n### Modo de Controle\r\n- Automático: Quando um gateway central Xiaomi disponível na rede local está disponível, o Home Assistant enviará comandos de controle de dispositivo através do gateway central para realizar a função de controle local. Quando não há gateway central na rede local, ele tentará enviar comandos de controle através do protocolo OT da Xiaomi para realizar a função de controle local. Somente quando as condições de controle local acima não forem atendidas, os comandos de controle do dispositivo serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controle são enviados apenas através da nuvem.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos pelo MIoT-Spec-V2 do dispositivo, além de gerar uma entidade de notificação, também será gerada uma entidade de caixa de texto para você enviar comandos de controle ao dispositivo durante a depuração.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOcultar entidades geradas por instâncias MIoT-Spec-V2 não padrão que começam com \"*\".\r\n### Exibir notificações de mudança de status do dispositivo\r\nExibir notificações detalhadas de mudança de status do dispositivo, mostrando apenas as notificações selecionadas.", "data": { "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Controle", diff --git a/custom_components/xiaomi_home/translations/pt.json b/custom_components/xiaomi_home/translations/pt.json index 6e08c5a..3ff0f03 100644 --- a/custom_components/xiaomi_home/translations/pt.json +++ b/custom_components/xiaomi_home/translations/pt.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Opções Avançadas", - "description": "## Introdução\r\n### A menos que você entenda claramente o significado das opções abaixo, mantenha as configurações padrão.\r\n### Filtrar Dispositivos\r\nSuporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n### Modo de Controle\r\n- Automático: Quando um gateway central Xiaomi está disponível na rede local, o Home Assistant enviará comandos de controlo de dispositivos através do gateway central para realizar o controlo local. Quando não há gateway central na rede local, tentará enviar comandos de controlo através do protocolo Xiaomi OT para realizar o controlo local. Apenas quando as condições de controlo local acima não são atendidas, os comandos de controlo de dispositivos serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controlo são enviados apenas através da nuvem.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos pelo MIoT-Spec-V2, além de gerar uma entidade de notificação, também será gerada uma entidade de caixa de texto para depuração de controlo de dispositivos.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOcultar entidades geradas por instâncias MIoT-Spec-V2 não padrão, cujos nomes começam com \"*\".", + "description": "## Introdução\r\n### A menos que você entenda claramente o significado das opções abaixo, mantenha as configurações padrão.\r\n### Filtrar Dispositivos\r\nSuporte para filtrar dispositivos por nome da sala e tipo de dispositivo, bem como filtragem por família.\r\n### Modo de Controle\r\n- Automático: Quando um gateway central Xiaomi está disponível na rede local, o Home Assistant enviará comandos de controlo de dispositivos através do gateway central para realizar o controlo local. Quando não há gateway central na rede local, tentará enviar comandos de controlo através do protocolo Xiaomi OT para realizar o controlo local. Apenas quando as condições de controlo local acima não são atendidas, os comandos de controlo de dispositivos serão enviados através da nuvem.\r\n- Nuvem: Os comandos de controlo são enviados apenas através da nuvem.\r\n### Modo de Depuração de Ações\r\nPara métodos definidos pelo MIoT-Spec-V2, além de gerar uma entidade de notificação, também será gerada uma entidade de caixa de texto para depuração de controlo de dispositivos.\r\n### Ocultar Entidades Geradas Não Padrão\r\nOcultar entidades geradas por instâncias MIoT-Spec-V2 não padrão, cujos nomes começam com \"*\".\r\n### Exibir notificações de mudança de status do dispositivo\r\nExibir notificações detalhadas de mudança de status do dispositivo, mostrando apenas as notificações selecionadas.", "data": { "devices_filter": "Filtrar Dispositivos", "ctrl_mode": "Modo de Controlo", diff --git a/custom_components/xiaomi_home/translations/ru.json b/custom_components/xiaomi_home/translations/ru.json index e8c6c31..6ea2734 100644 --- a/custom_components/xiaomi_home/translations/ru.json +++ b/custom_components/xiaomi_home/translations/ru.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "Расширенные настройки", - "description": "## Введение\r\n### Если вы не очень хорошо понимаете значение следующих параметров, оставьте их по умолчанию.\r\n### Фильтрация устройств\r\nПоддерживает фильтрацию устройств по названию комнаты и типу устройства, а также фильтрацию по уровню устройства.\r\n### Режим управления\r\n- Автоматически: при наличии доступного центрального шлюза Xiaomi в локальной сети Home Assistant Home Assistant будет отправлять команды управления устройствами через центральный шлюз для локального управления. Если центрального шлюза нет в локальной сети, Home Assistant попытается отправить команды управления устройствами через протокол OT Xiaomi для локального управления. Только если вышеуказанные условия локального управления не выполняются, команды управления устройствами будут отправляться через облако.\r\n- Облако: команды управления отправляются только через облако.\r\n### Режим отладки действий\r\nДля методов, определенных устройством MIoT-Spec-V2, помимо создания уведомления, будет создана сущность текстового поля, которую вы можете использовать для отправки команд управления устройством во время отладки.\r\n### Скрыть нестандартные сущности\r\nСкрыть сущности, созданные нестандартными экземплярами MIoT-Spec-V2, имена которых начинаются с «*».", + "description": "## Введение\r\n### Если вы не очень хорошо понимаете значение следующих параметров, оставьте их по умолчанию.\r\n### Фильтрация устройств\r\nПоддерживает фильтрацию устройств по названию комнаты и типу устройства, а также фильтрацию по уровню устройства.\r\n### Режим управления\r\n- Автоматически: при наличии доступного центрального шлюза Xiaomi в локальной сети Home Assistant Home Assistant будет отправлять команды управления устройствами через центральный шлюз для локального управления. Если центрального шлюза нет в локальной сети, Home Assistant попытается отправить команды управления устройствами через протокол OT Xiaomi для локального управления. Только если вышеуказанные условия локального управления не выполняются, команды управления устройствами будут отправляться через облако.\r\n- Облако: команды управления отправляются только через облако.\r\n### Режим отладки действий\r\nДля методов, определенных устройством MIoT-Spec-V2, помимо создания уведомления, будет создана сущность текстового поля, которую вы можете использовать для отправки команд управления устройством во время отладки.\r\n### Скрыть нестандартные сущности\r\nСкрыть сущности, созданные нестандартными экземплярами MIoT-Spec-V2, имена которых начинаются с «*».\r\n### Отображать уведомления о изменении состояния устройства\r\nОтображать подробные уведомления о изменении состояния устройства, показывая только выбранные уведомления.", "data": { "devices_filter": "Фильтрация устройств", "ctrl_mode": "Режим управления", diff --git a/custom_components/xiaomi_home/translations/zh-Hans.json b/custom_components/xiaomi_home/translations/zh-Hans.json index 0374ad1..f2f33d1 100644 --- a/custom_components/xiaomi_home/translations/zh-Hans.json +++ b/custom_components/xiaomi_home/translations/zh-Hans.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "高级设置选项", - "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n### 筛选设备\r\n支持按照家庭房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。", + "description": "## 使用介绍\r\n### 除非您非常清楚下列选项的含义,否则请保持默认。\r\n### 筛选设备\r\n支持按照家庭房间名称、设备接入类型、设备型号筛选设备,同时也支持设备维度筛选。\r\n### 控制模式\r\n- 自动:本地局域网内存在可用的小米中枢网关时, Home Assistant 会优先通过中枢网关发送设备控制指令,以实现本地化控制功能。本地局域网不存在中枢时,会尝试通过小米OT协议发送控制指令,以实现本地化控制功能。只有当上述本地化控制条件不满足时,设备控制指令才会通过云端发送。\r\n- 云端:控制指令仅通过云端发送。\r\n### Action 调试模式\r\n对于设备 MIoT-Spec-V2 定义的方法,在生成通知实体之外,还会生成一个文本输入框实体,您可以在调试时用它向设备发送控制指令。\r\n### 隐藏非标准生成实体\r\n隐藏名称以“*”开头的非标准 MIoT-Spec-V2 实例生成的实体。\r\n### 显示设备状态变化通知\r\n细化显示设备状态变化通知,只显示勾选的通知消息。", "data": { "devices_filter": "筛选设备", "ctrl_mode": "控制模式", diff --git a/custom_components/xiaomi_home/translations/zh-Hant.json b/custom_components/xiaomi_home/translations/zh-Hant.json index 2600b5e..5d9f7ba 100644 --- a/custom_components/xiaomi_home/translations/zh-Hant.json +++ b/custom_components/xiaomi_home/translations/zh-Hant.json @@ -33,7 +33,7 @@ }, "advanced_options": { "title": "高級設置選項", - "description": "## 使用介紹\r\n### 除非您非常清楚下列選項的含義,否則請保持默認。\r\n### 篩選設備\r\n支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n### 控制模式\r\n- 自動:本地局域網內存在可用的小米中樞網關時, Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。本地局域網不存在中樞時,會嘗試通過小米OT協議發送控制指令,以實現本地化控制功能。只有當上述本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令僅通過雲端發送。\r\n### Action 調試模式\r\n對於設備 MIoT-Spec-V2 定義的方法,在生成通知實體之外,還會生成一個文本輸入框實體,您可以在調試時用它向設備發送控制指令。\r\n### 隱藏非標準生成實體\r\n隱藏名稱以“*”開頭的非標準 MIoT-Spec-V2 實例生成的實體。", + "description": "## 使用介紹\r\n### 除非您非常清楚下列選項的含義,否則請保持默認。\r\n### 篩選設備\r\n支持按照房間名稱和設備類型篩選設備,同時也支持設備維度篩選。\r\n### 控制模式\r\n- 自動:本地局域網內存在可用的小米中樞網關時, Home Assistant 會優先通過中樞網關發送設備控制指令,以實現本地化控制功能。本地局域網不存在中樞時,會嘗試通過小米OT協議發送控制指令,以實現本地化控制功能。只有當上述本地化控制條件不滿足時,設備控制指令才會通過雲端發送。\r\n- 雲端:控制指令僅通過雲端發送。\r\n### Action 調試模式\r\n對於設備 MIoT-Spec-V2 定義的方法,在生成通知實體之外,還會生成一個文本輸入框實體,您可以在調試時用它向設備發送控制指令。\r\n### 隱藏非標準生成實體\r\n隱藏名稱以“*”開頭的非標準 MIoT-Spec-V2 實例生成的實體。\r\n### 顯示設備狀態變化通知\r\n細化顯示設備狀態變化通知,只顯示勾選的通知消息。", "data": { "devices_filter": "篩選設備", "ctrl_mode": "控制模式",