Compare commits

...

20 Commits

Author SHA1 Message Date
Feng Wang
2edb1162dc
Merge 0668985969 into d65fe32a98 2025-01-03 23:45:44 +08:00
Paul Shawn
d65fe32a98
docs: update changelog and version to v0.1.5b0 (#563)
Some checks failed
Tests / check-rule-format (push) Has been cancelled
Validate / validate-hassfest (push) Has been cancelled
Validate / validate-hacs (push) Has been cancelled
Validate / validate-lint (push) Has been cancelled
Validate / validate-setup (push) Has been cancelled
* style: code format

* docs: update changelog and version to v0.1.5b0

* docs: update changelog
2025-01-03 21:08:39 +08:00
Feng Wang
50be2c5df9
doc: make git update guide more accurate (#561)
* Improve installation guide

* Improve installation guide (zh)
2025-01-03 20:45:00 +08:00
Paul Shawn
b75cafb184
fix: limit *light.mode count (value-range) (#535)
* feat: spec filter add lemesh.switch.sw3f13 indicator-light.mode

* feat: limit mode count (value-range)

* revert: spec-filter.json

* fix: fix judgment logic

* style: remove unuse code

* style: change light log level
2025-01-03 20:43:15 +08:00
tiger
5438698a6e
feat:add missing parameter state_class (#101)
* feat: add state_class for sensor

* feat: add optional state_class and unit_of_measurement for properties

* feat:add support for state_class and unit process

* style: fix pylint format

* style: fix pylint format

* sytle: change logic to suit conversation

---------

Co-authored-by: LiShuzhen <SusanPhevos@gmail.com>
2025-01-03 20:42:34 +08:00
Paul Shawn
da90e099d1
fix: update miot cloud raise error msg (#551) 2025-01-03 19:00:11 +08:00
ted
2703d68920
docs: fix table header misplacement (#554)
fix table header misplacement
2025-01-03 18:59:24 +08:00
Paul Shawn
b6147de1b8
doc: update changelog and version to v0.1.4 (#522) 2024-12-31 22:45:22 +08:00
Feng Wang
0668985969 fix access violation 2024-12-31 19:36:15 +08:00
Feng Wang
48a931b9f6 remove tev 2024-12-31 18:48:51 +08:00
Feng Wang
ab8a15f40d Merge branch 'main' into remove-tev-from-mips 2024-12-31 18:47:45 +08:00
Paul Shawn
621ca8002b
feat: improve devices filter & optimize the network detection logic (#458)
* fix: fix miot http type error

* style: change some miot cloud log level

* feat: improve devices filter

* feat: update save devices logic

* refator: refactor miot network

* feat: update miot_client.get_miot_instance_async

* feat: option flow support network detect config

* doc: update translations

* feat: update config flow network detect logic

* style: change miot client refresh prop log level

* feat: config flow support network check

* doc: update translations

* refactor: rename func name

* fix: ignore invalid type error

* feat: option flow add check network deps

* --amend

* --amend

* feat: check mqtt broker

* feat: config flow support check network deps

* feat: update manifest requirements, paho-mqtt<2.0.0

* fix: fix mqtt broker check logic

* style: remove unuse params

* feat: show integration instance id

* feat: update data_schema from required to optional

* fix: translation text error
2024-12-31 16:37:46 +08:00
Alone
40a75bef28
feat: use yaml to parse action params (#447)
* feat: use yaml to parse action params

* feat: use yaml to parse action params

* feat: improve notify, action-text trans logic

* perf: reduce the number of judgments

---------

Co-authored-by: topsworld <sworldtop@gmail.com>
2024-12-31 16:36:20 +08:00
Feng Wang
196e19d10a
misc: remove tev dependency for lan control & fixs (#333)
* Remove tev & fix some type issues

* Use call_soon_threadsafe instead of event fd for ipc

* fix lint

* add tev back

* fix lint

* ignore broad exception warning

* revert changes in the license

* do not set asyncio event loop

* fix racing condition

* remove unused data classes

* change internal class scope

* set timers to None after cancel

* Adjust import order

* fix typo

* Fix typo in comments

* guard lan apis with init_done
2024-12-30 20:54:50 +08:00
Feng Wang
55d27409b7 fix the deleted public data class 2024-12-23 17:03:09 +08:00
Feng Wang
d1c49bdf7b fix thread naming 2024-12-23 16:59:45 +08:00
Feng Wang
23bf6817b9 simplify inheritance 2024-12-23 16:43:34 +08:00
Feng Wang
43fd2bf42e make private classes private 2024-12-23 16:26:25 +08:00
Feng Wang
8fcb4d895c lint fix 2024-12-23 16:22:44 +08:00
Feng Wang
8778321b50 remove use of tev & fix type errors 2024-12-22 23:49:25 +08:00
33 changed files with 2390 additions and 1964 deletions

View File

@ -1,5 +1,25 @@
# CHANGELOG
## v0.1.5b0
### Added
- Add missing parameter state_class [#101](https://github.com/XiaoMi/ha_xiaomi_home/pull/101)
### Changed
- Make git update guide more accurate [#561](https://github.com/XiaoMi/ha_xiaomi_home/pull/561)
### Fixed
- Limit *light.mode count (value-range) [#535](https://github.com/XiaoMi/ha_xiaomi_home/pull/535)
- Update miot cloud raise error msg [#551](https://github.com/XiaoMi/ha_xiaomi_home/pull/551)
- Fix table header misplacement [#554](https://github.com/XiaoMi/ha_xiaomi_home/pull/554)
## v0.1.4
### Added
- Refactor miot network, add network detection logic, improve devices filter logic. [458](https://github.com/XiaoMi/ha_xiaomi_home/pull/458) [#191](https://github.com/XiaoMi/ha_xiaomi_home/pull/191)
### Changed
- Remove tev dependency for lan control & fixs. [#333](https://github.com/XiaoMi/ha_xiaomi_home/pull/333)
- Use yaml to parse action params. [#447](https://github.com/XiaoMi/ha_xiaomi_home/pull/447)
- Update issue template. [#445](https://github.com/XiaoMi/ha_xiaomi_home/pull/445)
- Remove duplicate dependency(aiohttp) [#390](https://github.com/XiaoMi/ha_xiaomi_home/pull/390)
### Fixed
## v0.1.4b1
### Added
- Support devices filter, and device changed notify logical refinement. [#332](https://github.com/XiaoMi/ha_xiaomi_home/pull/332)

View File

@ -26,6 +26,7 @@ For example, update to version v1.0.0
```bash
cd config/ha_xiaomi_home
git fetch
git checkout v1.0.0
./install.sh /config
```
@ -140,7 +141,7 @@ In MIoT-Spec-V2 protocol, a product is defined as a device. A device contains se
- Property
| format | access | value-list | value-range | Entity in Home Assistant |
| access | format | value-list | value-range | Entity in Home Assistant |
| ------------ | --------------------- | ------------ | ----------- | ------------------------ |
| writable | string | - | - | Text |
| writable | bool | - | - | Switch |

File diff suppressed because it is too large Load Diff

View File

@ -95,6 +95,7 @@ async def async_setup_entry(
class Light(MIoTServiceEntity, LightEntity):
"""Light entities for Xiaomi Home."""
# pylint: disable=unused-argument
_VALUE_RANGE_MODE_COUNT_MAX = 30
_prop_on: Optional[MIoTSpecProperty]
_prop_brightness: Optional[MIoTSpecProperty]
_prop_color_temp: Optional[MIoTSpecProperty]
@ -147,13 +148,13 @@ class Light(MIoTServiceEntity, LightEntity):
self._attr_supported_features |= LightEntityFeature.EFFECT
self._prop_mode = prop
else:
_LOGGER.error(
_LOGGER.info(
'invalid brightness format, %s', self.entity_id)
continue
# color-temperature
if prop.name == 'color-temperature':
if not isinstance(prop.value_range, dict):
_LOGGER.error(
_LOGGER.info(
'invalid color-temperature value_range format, %s',
self.entity_id)
continue
@ -179,16 +180,29 @@ class Light(MIoTServiceEntity, LightEntity):
for item in prop.value_list}
elif isinstance(prop.value_range, dict):
mode_list = {}
for value in range(
prop.value_range['min'], prop.value_range['max']):
mode_list[value] = f'{value}'
if (
int((
prop.value_range['max']
- prop.value_range['min']
) / prop.value_range['step'])
> self._VALUE_RANGE_MODE_COUNT_MAX
):
_LOGGER.info(
'too many mode values, %s, %s, %s',
self.entity_id, prop.name, prop.value_range)
else:
for value in range(
prop.value_range['min'],
prop.value_range['max'],
prop.value_range['step']):
mode_list[value] = f'mode {value}'
if mode_list:
self._mode_list = mode_list
self._attr_effect_list = list(self._mode_list.values())
self._attr_supported_features |= LightEntityFeature.EFFECT
self._prop_mode = prop
else:
_LOGGER.error('invalid mode format, %s', self.entity_id)
_LOGGER.info('invalid mode format, %s', self.entity_id)
continue
if not self._attr_supported_color_modes:

View File

@ -20,12 +20,12 @@
],
"requirements": [
"construct>=2.10.56",
"paho-mqtt<=2.0.0",
"paho-mqtt<2.0.0",
"numpy",
"cryptography",
"psutil"
],
"version": "v0.1.4b1",
"version": "v0.1.5b0",
"zeroconf": [
"_miot-central._tcp.local."
]

View File

@ -83,6 +83,9 @@ def randomize_int(value: int, ratio: float) -> int:
"""Randomize an integer value."""
return int(value * (1 - ratio + random.random()*2*ratio))
def randomize_float(value: float, ratio: float) -> float:
"""Randomize a float value."""
return value * (1 - ratio + random.random()*2*ratio)
class MIoTMatcher(MQTTMatcher):
"""MIoT Pub/Sub topic matcher."""

View File

@ -1089,7 +1089,7 @@ class MIoTClient:
handler=self.__on_lan_device_state_changed)
for did, info in (
await self._miot_lan.get_dev_list_async()).items():
self.__on_lan_device_state_changed(
await self.__on_lan_device_state_changed(
did=did, state=info, ctx=None)
_LOGGER.info('lan device list, %s', self._device_list_lan)
self._miot_lan.update_devices(devices={
@ -1558,7 +1558,7 @@ class MIoTClient:
None)
self.__on_prop_msg(params=result, ctx=None)
if request_list:
_LOGGER.error(
_LOGGER.info(
'refresh props failed, cloud, %s',
list(request_list.keys()))
request_list = None
@ -1614,7 +1614,7 @@ class MIoTClient:
succeed_once = True
if succeed_once:
return True
_LOGGER.error(
_LOGGER.info(
'refresh props failed, gw, %s', list(request_list.keys()))
# Add failed request back to the list
self._refresh_props_list.update(request_list)
@ -1657,7 +1657,7 @@ class MIoTClient:
succeed_once = True
if succeed_once:
return True
_LOGGER.error(
_LOGGER.info(
'refresh props failed, lan, %s', list(request_list.keys()))
# Add failed request back to the list
self._refresh_props_list.update(request_list)
@ -1689,10 +1689,10 @@ class MIoTClient:
if self._refresh_props_timer:
self._refresh_props_timer.cancel()
self._refresh_props_timer = None
_LOGGER.error('refresh props failed, retry count exceed')
_LOGGER.info('refresh props failed, retry count exceed')
return
self._refresh_props_retry_count += 1
_LOGGER.error(
_LOGGER.info(
'refresh props failed, retry, %s', self._refresh_props_retry_count)
self._refresh_props_timer = self._main_loop.call_later(
3, lambda: self._main_loop.create_task(
@ -1851,15 +1851,6 @@ async def get_miot_instance_async(
loop: asyncio.AbstractEventLoop = asyncio.get_running_loop()
if loop is None:
raise MIoTClientError('loop is None')
# MIoT network
network: Optional[MIoTNetwork] = hass.data[DOMAIN].get(
'miot_network', None)
if not network:
network = MIoTNetwork(loop=loop)
hass.data[DOMAIN]['miot_network'] = network
await network.init_async(
refresh_interval=NETWORK_REFRESH_INTERVAL)
_LOGGER.info('create miot_network instance')
# MIoT storage
storage: Optional[MIoTStorage] = hass.data[DOMAIN].get(
'miot_storage', None)
@ -1868,12 +1859,29 @@ async def get_miot_instance_async(
root_path=entry_data['storage_path'], loop=loop)
hass.data[DOMAIN]['miot_storage'] = storage
_LOGGER.info('create miot_storage instance')
global_config: dict = await storage.load_user_config_async(
uid='global_config', cloud_server='all',
keys=['network_detect_addr', 'net_interfaces', 'enable_subscribe'])
# MIoT network
network_detect_addr: dict = global_config.get(
'network_detect_addr', {})
network: Optional[MIoTNetwork] = hass.data[DOMAIN].get(
'miot_network', None)
if not network:
network = MIoTNetwork(
ip_addr_list=network_detect_addr.get('ip', []),
url_addr_list=network_detect_addr.get('url', []),
refresh_interval=NETWORK_REFRESH_INTERVAL,
loop=loop)
hass.data[DOMAIN]['miot_network'] = network
await network.init_async()
_LOGGER.info('create miot_network instance')
# MIoT service
mips_service: Optional[MipsService] = hass.data[DOMAIN].get(
'mips_service', None)
if not mips_service:
aiozc = await zeroconf.async_get_async_instance(hass)
mips_service: MipsService = MipsService(aiozc=aiozc, loop=loop)
mips_service = MipsService(aiozc=aiozc, loop=loop)
hass.data[DOMAIN]['mips_service'] = mips_service
await mips_service.init_async()
_LOGGER.info('create mips_service instance')
@ -1881,15 +1889,11 @@ async def get_miot_instance_async(
miot_lan: Optional[MIoTLan] = hass.data[DOMAIN].get(
'miot_lan', None)
if not miot_lan:
lan_config = (await storage.load_user_config_async(
uid='global_config',
cloud_server='all',
keys=['net_interfaces', 'enable_subscribe'])) or {}
miot_lan = MIoTLan(
net_ifs=lan_config.get('net_interfaces', []),
net_ifs=global_config.get('net_interfaces', []),
network=network,
mips_service=mips_service,
enable_subscribe=lan_config.get('enable_subscribe', False),
enable_subscribe=global_config.get('enable_subscribe', False),
loop=loop)
hass.data[DOMAIN]['miot_lan'] = miot_lan
_LOGGER.info('create miot_lan instance')

View File

@ -166,7 +166,7 @@ class MIoTOauthClient:
key in res_obj['result']
for key in ['access_token', 'refresh_token', 'expires_in'])
):
raise MIoTOauthError(f'invalid http response, {http_res.text}')
raise MIoTOauthError(f'invalid http response, {res_str}')
return {
**res_obj['result'],
@ -224,20 +224,20 @@ class MIoTHttpClient:
_client_id: str
_access_token: str
_get_prop_timer: asyncio.TimerHandle
_get_prop_list: dict[str, dict[str, asyncio.Future | str | bool]]
_get_prop_timer: Optional[asyncio.TimerHandle]
_get_prop_list: dict[str, dict]
def __init__(
self, cloud_server: str, client_id: str, access_token: str,
loop: Optional[asyncio.AbstractEventLoop] = None
) -> None:
self._main_loop = loop or asyncio.get_running_loop()
self._host = None
self._base_url = None
self._client_id = None
self._access_token = None
self._host = DEFAULT_OAUTH2_API_HOST
self._base_url = ''
self._client_id = ''
self._access_token = ''
self._get_prop_timer: asyncio.TimerHandle = None
self._get_prop_timer = None
self._get_prop_list = {}
if (
@ -258,8 +258,9 @@ class MIoTHttpClient:
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()
fut: Optional[asyncio.Future] = item.get('fut', None)
if fut:
fut.cancel()
self._get_prop_list.clear()
if self._session and not self._session.closed:
await self._session.close()
@ -270,9 +271,7 @@ class MIoTHttpClient:
access_token: Optional[str] = None
) -> None:
if isinstance(cloud_server, str):
if cloud_server == 'cn':
self._host = DEFAULT_OAUTH2_API_HOST
else:
if cloud_server != 'cn':
self._host = f'{cloud_server}.{DEFAULT_OAUTH2_API_HOST}'
self._base_url = f'https://{self._host}'
if isinstance(client_id, str):
@ -350,8 +349,8 @@ class MIoTHttpClient:
async def get_user_info_async(self) -> dict:
http_res = await self._session.get(
url='https://open.account.xiaomi.com/user/profile',
params={'clientId': self._client_id,
'token': self._access_token},
params={
'clientId': self._client_id, 'token': self._access_token},
headers={'content-type': 'application/x-www-form-urlencoded'},
timeout=MIHOME_HTTP_API_TIMEOUT
)
@ -386,7 +385,9 @@ class MIoTHttpClient:
return cert
async def __get_dev_room_page_async(self, max_id: str = None) -> dict:
async def __get_dev_room_page_async(
self, max_id: Optional[str] = None
) -> dict:
res_obj = await self.__mihome_api_post_async(
url_path='/app/v2/homeroom/get_dev_room_page',
data={
@ -442,7 +443,7 @@ class MIoTHttpClient:
if 'result' not in res_obj:
raise MIoTHttpError('invalid response result')
uid: str = None
uid: Optional[str] = None
home_infos: dict = {}
for device_source in ['homelist', 'share_home_list']:
home_infos.setdefault(device_source, {})
@ -507,7 +508,7 @@ class MIoTHttpClient:
return (await self.get_homeinfos_async()).get('uid', None)
async def __get_device_list_page_async(
self, dids: list[str], start_did: str = None
self, dids: list[str], start_did: Optional[str] = None
) -> dict[str, dict]:
req_data: dict = {
'limit': 200,
@ -575,9 +576,9 @@ class MIoTHttpClient:
async def get_devices_with_dids_async(
self, dids: list[str]
) -> dict[str, dict]:
) -> Optional[dict[str, dict]]:
results: list[dict[str, dict]] = await asyncio.gather(
*[self.__get_device_list_page_async(dids[index:index+150])
*[self.__get_device_list_page_async(dids=dids[index:index+150])
for index in range(0, len(dids), 150)])
devices = {}
for result in results:
@ -587,7 +588,7 @@ class MIoTHttpClient:
return devices
async def get_devices_async(
self, home_ids: list[str] = None
self, home_ids: Optional[list[str]] = None
) -> dict[str, dict]:
homeinfos = await self.get_homeinfos_async()
homes: dict[str, dict[str, Any]] = {}
@ -627,8 +628,9 @@ class MIoTHttpClient:
'group_id': group_id
} for did in room_info.get('dids', [])})
dids = sorted(list(devices.keys()))
results: dict[str, dict] = await self.get_devices_with_dids_async(
dids=dids)
results = await self.get_devices_with_dids_async(dids=dids)
if results is None:
raise MIoTHttpError('get devices failed')
for did in dids:
if did not in results:
devices.pop(did, None)
@ -706,7 +708,7 @@ class MIoTHttpClient:
key = f'{result["did"]}.{result["siid"]}.{result["piid"]}'
prop_obj = self._get_prop_list.pop(key, None)
if prop_obj is None:
_LOGGER.error('get prop error, key not exists, %s', result)
_LOGGER.info('get prop error, key not exists, %s', result)
continue
prop_obj['fut'].set_result(result['value'])
props_req.remove(key)
@ -717,7 +719,7 @@ class MIoTHttpClient:
continue
prop_obj['fut'].set_result(None)
if props_req:
_LOGGER.error(
_LOGGER.info(
'get prop from cloud failed, %s, %s', len(key), props_req)
if self._get_prop_list:

View File

@ -515,9 +515,15 @@ class MIoTDevice:
prop.icon = self.icon_convert(prop.unit)
device_class = SPEC_PROP_TRANS_MAP['properties'][prop_name][
'device_class']
prop.platform = device_class
return {'platform': platform, 'device_class': device_class}
result = {'platform': platform, 'device_class': device_class}
# optional:
if 'optional' in SPEC_PROP_TRANS_MAP['properties'][prop_name]:
optional = SPEC_PROP_TRANS_MAP['properties'][prop_name]['optional']
if 'state_class' in optional:
result['state_class'] = optional['state_class']
if not prop.unit and 'unit_of_measurement' in optional:
result['unit_of_measurement'] = optional['unit_of_measurement']
return result
def spec_transform(self) -> None:
"""Parse service, property, event, action from device spec."""
@ -544,6 +550,13 @@ class MIoTDevice:
if prop_entity:
prop.platform = prop_entity['platform']
prop.device_class = prop_entity['device_class']
if 'state_class' in prop_entity:
prop.state_class = prop_entity['state_class']
if 'unit_of_measurement' in prop_entity:
prop.external_unit = self.unit_convert(
prop_entity['unit_of_measurement'])
prop.icon = self.icon_convert(
prop_entity['unit_of_measurement'])
# general conversion
if not prop.platform:
if prop.writable:

View File

@ -74,6 +74,7 @@ class MIoTErrorCode(Enum):
# Config flow error code, -10100
# Options flow error code , -10110
# MIoT lan error code, -10120
CODE_LAN_UNAVAILABLE = -10120
class MIoTError(Exception):
@ -141,3 +142,7 @@ class MIoTConfigError(MIoTError):
class MIoTOptionsError(MIoTError):
...
class MIoTLanError(MIoTError):
...

View File

@ -1,324 +0,0 @@
# -*- coding: utf-8 -*-
"""
Copyright (C) 2024 Xiaomi Corporation.
The ownership and intellectual property rights of Xiaomi Home Assistant
Integration and related Xiaomi cloud service API interface provided under this
license, including source code and object code (collectively, "Licensed Work"),
are owned by Xiaomi. Subject to the terms and conditions of this License, Xiaomi
hereby grants you a personal, limited, non-exclusive, non-transferable,
non-sublicensable, and royalty-free license to reproduce, use, modify, and
distribute the Licensed Work only for your use of Home Assistant for
non-commercial purposes. For the avoidance of doubt, Xiaomi does not authorize
you to use the Licensed Work for any other purpose, including but not limited
to use Licensed Work to develop applications (APP), Web services, and other
forms of software.
You may reproduce and distribute copies of the Licensed Work, with or without
modifications, whether in source or object form, provided that you must give
any other recipients of the Licensed Work a copy of this License and retain all
copyright and disclaimers.
Xiaomi provides the Licensed Work on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied, including, without
limitation, any warranties, undertakes, or conditions of TITLE, NO ERROR OR
OMISSION, CONTINUITY, RELIABILITY, NON-INFRINGEMENT, MERCHANTABILITY, or
FITNESS FOR A PARTICULAR PURPOSE. In any event, you are solely responsible
for any direct, indirect, special, incidental, or consequential damages or
losses arising from the use or inability to use the Licensed Work.
Xiaomi reserves all rights not expressly granted to you in this License.
Except for the rights expressly granted by Xiaomi under this License, Xiaomi
does not authorize you in any form to use the trademarks, copyrights, or other
forms of intellectual property rights of Xiaomi and its affiliates, including,
without limitation, without obtaining other written permission from Xiaomi, you
shall not use "Xiaomi", "Mijia" and other words related to Xiaomi or words that
may make the public associate with Xiaomi in any form to publicize or promote
the software or hardware devices that use the Licensed Work.
Xiaomi has the right to immediately terminate all your authorization under this
License in the event:
1. You assert patent invalidation, litigation, or other claims against patents
or other intellectual property rights of Xiaomi or its affiliates; or,
2. You make, have made, manufacture, sell, or offer to sell products that knock
off Xiaomi or its affiliates' products.
MIoT event loop.
"""
import selectors
import heapq
import time
import traceback
from typing import Any, Callable, TypeVar
import logging
import threading
# pylint: disable=relative-beyond-top-level
from .miot_error import MIoTEvError
_LOGGER = logging.getLogger(__name__)
TimeoutHandle = TypeVar('TimeoutHandle')
class MIoTFdHandler:
"""File descriptor handler."""
fd: int
read_handler: Callable[[Any], None]
read_handler_ctx: Any
write_handler: Callable[[Any], None]
write_handler_ctx: Any
def __init__(
self, fd: int,
read_handler: Callable[[Any], None] = None,
read_handler_ctx: Any = None,
write_handler: Callable[[Any], None] = None,
write_handler_ctx: Any = None
) -> None:
self.fd = fd
self.read_handler = read_handler
self.read_handler_ctx = read_handler_ctx
self.write_handler = write_handler
self.write_handler_ctx = write_handler_ctx
class MIoTTimeout:
"""Timeout handler."""
key: TimeoutHandle
target: int
handler: Callable[[Any], None]
handler_ctx: Any
def __init__(
self, key: str = None, target: int = None,
handler: Callable[[Any], None] = None,
handler_ctx: Any = None
) -> None:
self.key = key
self.target = target
self.handler = handler
self.handler_ctx = handler_ctx
def __lt__(self, other):
return self.target < other.target
class MIoTEventLoop:
"""MIoT event loop."""
_poll_fd: selectors.DefaultSelector
_fd_handlers: dict[str, MIoTFdHandler]
_timer_heap: list[MIoTTimeout]
_timer_handlers: dict[str, MIoTTimeout]
_timer_handle_seed: int
# Label if the current fd handler is freed inside a read handler to
# avoid invalid reading.
_fd_handler_freed_in_read_handler: bool
def __init__(self) -> None:
self._poll_fd = selectors.DefaultSelector()
self._timer_heap = []
self._timer_handlers = {}
self._timer_handle_seed = 1
self._fd_handlers = {}
self._fd_handler_freed_in_read_handler = False
def loop_forever(self) -> None:
"""Run an event loop in current thread."""
next_timeout: int
while True:
next_timeout = 0
# Handle timer
now_ms: int = self.__get_monotonic_ms
while len(self._timer_heap) > 0:
timer: MIoTTimeout = self._timer_heap[0]
if timer is None:
break
if timer.target <= now_ms:
heapq.heappop(self._timer_heap)
del self._timer_handlers[timer.key]
if timer.handler:
timer.handler(timer.handler_ctx)
else:
next_timeout = timer.target-now_ms
break
# Are there any files to listen to
if next_timeout == 0 and self._fd_handlers:
next_timeout = None # None == infinite
# Wait for timers & fds
if next_timeout == 0:
# Neither timer nor fds exist, exit loop
break
# Handle fd event
events = self._poll_fd.select(
timeout=next_timeout/1000.0 if next_timeout else next_timeout)
for key, mask in events:
fd_handler: MIoTFdHandler = key.data
if fd_handler is None:
continue
self._fd_handler_freed_in_read_handler = False
fd_key = str(id(fd_handler.fd))
if fd_key not in self._fd_handlers:
continue
if (
mask & selectors.EVENT_READ > 0
and fd_handler.read_handler
):
fd_handler.read_handler(fd_handler.read_handler_ctx)
if (
mask & selectors.EVENT_WRITE > 0
and self._fd_handler_freed_in_read_handler is False
and fd_handler.write_handler
):
fd_handler.write_handler(fd_handler.write_handler_ctx)
def loop_stop(self) -> None:
"""Stop the event loop."""
if self._poll_fd:
self._poll_fd.close()
self._poll_fd = None
self._fd_handlers = {}
self._timer_heap = []
self._timer_handlers = {}
def set_timeout(
self, timeout_ms: int, handler: Callable[[Any], None],
handler_ctx: Any = None
) -> TimeoutHandle:
"""Set a timer."""
if timeout_ms is None or handler is None:
raise MIoTEvError('invalid params')
new_timeout: MIoTTimeout = MIoTTimeout()
new_timeout.key = self.__get_next_timeout_handle
new_timeout.target = self.__get_monotonic_ms + timeout_ms
new_timeout.handler = handler
new_timeout.handler_ctx = handler_ctx
heapq.heappush(self._timer_heap, new_timeout)
self._timer_handlers[new_timeout.key] = new_timeout
return new_timeout.key
def clear_timeout(self, timer_key: TimeoutHandle) -> None:
"""Stop and remove the timer."""
if timer_key is None:
return
timer: MIoTTimeout = self._timer_handlers.pop(timer_key, None)
if timer:
self._timer_heap = list(self._timer_heap)
self._timer_heap.remove(timer)
heapq.heapify(self._timer_heap)
def set_read_handler(
self, fd: int, handler: Callable[[Any], None], handler_ctx: Any = None
) -> bool:
"""Set a read handler for a file descriptor.
Returns:
bool: True, success. False, failed.
"""
self.__set_handler(
fd, is_read=True, handler=handler, handler_ctx=handler_ctx)
def set_write_handler(
self, fd: int, handler: Callable[[Any], None], handler_ctx: Any = None
) -> bool:
"""Set a write handler for a file descriptor.
Returns:
bool: True, success. False, failed.
"""
self.__set_handler(
fd, is_read=False, handler=handler, handler_ctx=handler_ctx)
def __set_handler(
self, fd, is_read: bool, handler: Callable[[Any], None],
handler_ctx: Any = None
) -> bool:
"""Set a handler."""
if fd is None:
raise MIoTEvError('invalid params')
if not self._poll_fd:
raise MIoTEvError('event loop not started')
fd_key: str = str(id(fd))
fd_handler = self._fd_handlers.get(fd_key, None)
if fd_handler is None:
fd_handler = MIoTFdHandler(fd=fd)
fd_handler.fd = fd
self._fd_handlers[fd_key] = fd_handler
read_handler_existed = fd_handler.read_handler is not None
write_handler_existed = fd_handler.write_handler is not None
if is_read is True:
fd_handler.read_handler = handler
fd_handler.read_handler_ctx = handler_ctx
else:
fd_handler.write_handler = handler
fd_handler.write_handler_ctx = handler_ctx
if fd_handler.read_handler is None and fd_handler.write_handler is None:
# Remove from epoll and map
try:
self._poll_fd.unregister(fd)
except (KeyError, ValueError, OSError) as e:
del e
self._fd_handlers.pop(fd_key, None)
# May be inside a read handler, if not, this has no effect
self._fd_handler_freed_in_read_handler = True
elif read_handler_existed is False and write_handler_existed is False:
# Add to epoll
events = 0x0
if fd_handler.read_handler:
events |= selectors.EVENT_READ
if fd_handler.write_handler:
events |= selectors.EVENT_WRITE
try:
self._poll_fd.register(fd, events=events, data=fd_handler)
except (KeyError, ValueError, OSError) as e:
_LOGGER.error(
'%s, register fd, error, %s, %s, %s, %s, %s',
threading.current_thread().name,
'read' if is_read else 'write',
fd_key, handler, e, traceback.format_exc())
self._fd_handlers.pop(fd_key, None)
return False
elif (
read_handler_existed != (fd_handler.read_handler is not None)
or write_handler_existed != (fd_handler.write_handler is not None)
):
# Modify epoll
events = 0x0
if fd_handler.read_handler:
events |= selectors.EVENT_READ
if fd_handler.write_handler:
events |= selectors.EVENT_WRITE
try:
self._poll_fd.modify(fd, events=events, data=fd_handler)
except (KeyError, ValueError, OSError) as e:
_LOGGER.error(
'%s, modify fd, error, %s, %s, %s, %s, %s',
threading.current_thread().name,
'read' if is_read else 'write',
fd_key, handler, e, traceback.format_exc())
self._fd_handlers.pop(fd_key, None)
return False
return True
@property
def __get_next_timeout_handle(self) -> str:
# Get next timeout handle, that is not larger than the maximum
# value of UINT64 type.
self._timer_handle_seed += 1
# uint64 max
self._timer_handle_seed %= 0xFFFFFFFFFFFFFFFF
return str(self._timer_handle_seed)
@property
def __get_monotonic_ms(self) -> int:
"""Get monotonic ms timestamp."""
return int(time.monotonic()*1000)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -52,7 +52,8 @@ import socket
from dataclasses import dataclass
from enum import Enum, auto
import subprocess
from typing import Callable, Optional
from typing import Callable, Coroutine, Optional
import aiohttp
import psutil
import ipaddress
@ -77,38 +78,54 @@ class NetworkInfo:
class MIoTNetwork:
"""MIoT network utilities."""
PING_ADDRESS_LIST = [
_IP_ADDRESS_LIST: list[str] = [
'1.2.4.8', # CNNIC sDNS
'8.8.8.8', # Google Public DNS
'233.5.5.5', # AliDNS
'1.1.1.1', # Cloudflare DNS
'114.114.114.114', # 114 DNS
'208.67.222.222', # OpenDNS
'9.9.9.9', # Quad9 DNS
'9.9.9.9' # Quad9
]
_URL_ADDRESS_LIST: list[str] = [
'https://www.bing.com',
'https://www.google.com',
'https://www.baidu.com'
]
_REFRESH_INTERVAL = 30
_DETECT_TIMEOUT = 6
_main_loop: asyncio.AbstractEventLoop
_ip_addr_map: dict[str, float]
_url_addr_list: dict[str, float]
_http_session: aiohttp.ClientSession
_refresh_interval: int
_refresh_task: asyncio.Task
_refresh_timer: asyncio.TimerHandle
_refresh_task: Optional[asyncio.Task]
_refresh_timer: Optional[asyncio.TimerHandle]
_network_status: bool
_network_info: dict[str, NetworkInfo]
_sub_list_network_status: dict[str, Callable[[bool], asyncio.Future]]
_sub_list_network_status: dict[str, Callable[[bool], Coroutine]]
_sub_list_network_info: dict[str, Callable[[
InterfaceStatus, NetworkInfo], asyncio.Future]]
_ping_address_priority: int
InterfaceStatus, NetworkInfo], Coroutine]]
_done_event: asyncio.Event
def __init__(
self, loop: Optional[asyncio.AbstractEventLoop] = None
self,
ip_addr_list: Optional[list[str]] = None,
url_addr_list: Optional[list[str]] = None,
refresh_interval: Optional[int] = None,
loop: Optional[asyncio.AbstractEventLoop] = None
) -> None:
self._main_loop = loop or asyncio.get_running_loop()
self._ip_addr_map = {
ip: self._DETECT_TIMEOUT for ip in
ip_addr_list or self._IP_ADDRESS_LIST}
self._http_addr_map = {
url: self._DETECT_TIMEOUT for url in
url_addr_list or self._URL_ADDRESS_LIST}
self._http_session = aiohttp.ClientSession()
self._refresh_interval = refresh_interval or self._REFRESH_INTERVAL
self._refresh_interval = None
self._refresh_task = None
self._refresh_timer = None
@ -118,10 +135,28 @@ class MIoTNetwork:
self._sub_list_network_status = {}
self._sub_list_network_info = {}
self._ping_address_priority = 0
self._done_event = asyncio.Event()
async def init_async(self) -> bool:
self.__refresh_timer_handler()
# MUST get network info before starting
return await self._done_event.wait()
async def deinit_async(self) -> None:
if self._refresh_task:
self._refresh_task.cancel()
self._refresh_task = None
if self._refresh_timer:
self._refresh_timer.cancel()
self._refresh_timer = None
await self._http_session.close()
self._network_status = False
self._network_info.clear()
self._sub_list_network_status.clear()
self._sub_list_network_info.clear()
self._done_event.clear()
@property
def network_status(self) -> bool:
return self._network_status
@ -130,23 +165,28 @@ class MIoTNetwork:
def network_info(self) -> dict[str, NetworkInfo]:
return self._network_info
async def deinit_async(self) -> None:
if self._refresh_task:
self._refresh_task.cancel()
self._refresh_task = None
if self._refresh_timer:
self._refresh_timer.cancel()
self._refresh_timer = None
self._refresh_interval = None
self._network_status = False
self._network_info.clear()
self._sub_list_network_status.clear()
self._sub_list_network_info.clear()
self._done_event.clear()
async def update_addr_list_async(
self,
ip_addr_list: Optional[list[str]] = None,
url_addr_list: Optional[list[str]] = None,
) -> None:
new_ip_map: dict = {}
for ip in ip_addr_list or self._IP_ADDRESS_LIST:
if ip in self._ip_addr_map:
new_ip_map[ip] = self._ip_addr_map[ip]
else:
new_ip_map[ip] = self._DETECT_TIMEOUT
self._ip_addr_map = new_ip_map
new_url_map: dict = {}
for url in url_addr_list or self._URL_ADDRESS_LIST:
if url in self._http_addr_map:
new_url_map[url] = self._http_addr_map[url]
else:
new_url_map[url] = self._DETECT_TIMEOUT
self._http_addr_map = new_url_map
def sub_network_status(
self, key: str, handler: Callable[[bool], asyncio.Future]
self, key: str, handler: Callable[[bool], Coroutine]
) -> None:
self._sub_list_network_status[key] = handler
@ -155,65 +195,114 @@ class MIoTNetwork:
def sub_network_info(
self, key: str,
handler: Callable[[InterfaceStatus, NetworkInfo], asyncio.Future]
handler: Callable[[InterfaceStatus, NetworkInfo], Coroutine]
) -> None:
self._sub_list_network_info[key] = handler
def unsub_network_info(self, key: str) -> None:
self._sub_list_network_info.pop(key, None)
async def init_async(self, refresh_interval: int = 30) -> bool:
self._refresh_interval = refresh_interval
self.__refresh_timer_handler()
# MUST get network info before starting
return await self._done_event.wait()
async def refresh_async(self) -> None:
self.__refresh_timer_handler()
async def get_network_status_async(self, timeout: int = 6) -> bool:
return await self._main_loop.run_in_executor(
None, self.__get_network_status, False, timeout)
async def get_network_status_async(self) -> bool:
try:
ip_addr: str = ''
ip_ts: float = self._DETECT_TIMEOUT
for ip, ts in self._ip_addr_map.items():
if ts < ip_ts:
ip_addr = ip
ip_ts = ts
if (
ip_ts < self._DETECT_TIMEOUT
and await self.ping_multi_async(ip_list=[ip_addr])
):
return True
url_addr: str = ''
url_ts: float = self._DETECT_TIMEOUT
for http, ts in self._http_addr_map.items():
if ts < url_ts:
url_addr = http
url_ts = ts
if (
url_ts < self._DETECT_TIMEOUT
and await self.http_multi_async(url_list=[url_addr])
):
return True
# Detect all addresses
results = await asyncio.gather(
*[self.ping_multi_async(), self.http_multi_async()])
return any(results)
except Exception as err: # pylint: disable=broad-exception-caught
_LOGGER.error('get network status error, %s', err)
return False
async def get_network_info_async(self) -> dict[str, NetworkInfo]:
return await self._main_loop.run_in_executor(
None, self.__get_network_info)
async def ping_multi_async(
self, ip_list: Optional[list[str]] = None
) -> bool:
addr_list = ip_list or list(self._ip_addr_map.keys())
tasks = []
for addr in addr_list:
tasks.append(self.__ping_async(addr))
results = await asyncio.gather(*tasks)
for addr, ts in zip(addr_list, results):
if addr in self._ip_addr_map:
self._ip_addr_map[addr] = ts
return any([ts < self._DETECT_TIMEOUT for ts in results])
async def http_multi_async(
self, url_list: Optional[list[str]] = None
) -> bool:
addr_list = url_list or list(self._http_addr_map.keys())
tasks = []
for addr in addr_list:
tasks.append(self.__http_async(url=addr))
results = await asyncio.gather(*tasks)
for addr, ts in zip(addr_list, results):
if addr in self._http_addr_map:
self._http_addr_map[addr] = ts
return any([ts < self._DETECT_TIMEOUT for ts in results])
def __calc_network_address(self, ip: str, netmask: str) -> str:
return str(ipaddress.IPv4Network(
f'{ip}/{netmask}', strict=False).network_address)
def __ping(
self, address: Optional[str] = None, timeout: int = 6
) -> bool:
param = '-n' if platform.system().lower() == 'windows' else '-c'
command = ['ping', param, '1', address]
async def __ping_async(self, address: Optional[str] = None) -> float:
start_ts: float = self._main_loop.time()
try:
output = subprocess.run(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
check=True, timeout=timeout)
return output.returncode == 0
process = await asyncio.create_subprocess_exec(
*(
[
'ping', '-n', '1', '-w',
str(self._DETECT_TIMEOUT*1000), address]
if platform.system().lower() == 'windows' else
[
'ping', '-c', '1', '-w',
str(self._DETECT_TIMEOUT), address]),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
await process.communicate()
if process.returncode == 0:
return self._main_loop.time() - start_ts
return self._DETECT_TIMEOUT
except Exception as err: # pylint: disable=broad-exception-caught
print(err)
return self._DETECT_TIMEOUT
async def __http_async(self, url: str) -> float:
start_ts: float = self._main_loop.time()
try:
async with self._http_session.get(
url, timeout=self._DETECT_TIMEOUT):
return self._main_loop.time() - start_ts
except Exception: # pylint: disable=broad-exception-caught
return False
def __get_network_status(
self, with_retry: bool = True, timeout: int = 6
) -> bool:
if self._ping_address_priority >= len(self.PING_ADDRESS_LIST):
self._ping_address_priority = 0
if self.__ping(
self.PING_ADDRESS_LIST[self._ping_address_priority], timeout):
return True
if not with_retry:
return False
for index in range(len(self.PING_ADDRESS_LIST)):
if index == self._ping_address_priority:
continue
if self.__ping(self.PING_ADDRESS_LIST[index], timeout):
self._ping_address_priority = index
return True
return False
pass
return self._DETECT_TIMEOUT
def __get_network_info(self) -> dict[str, NetworkInfo]:
interfaces = psutil.net_if_addrs()
@ -246,12 +335,10 @@ class MIoTNetwork:
for handler in self._sub_list_network_info.values():
self._main_loop.create_task(handler(status, info))
async def __update_status_and_info_async(self, timeout: int = 6) -> None:
async def __update_status_and_info_async(self) -> None:
try:
status: bool = await self._main_loop.run_in_executor(
None, self.__get_network_status, timeout)
infos = await self._main_loop.run_in_executor(
None, self.__get_network_info)
status: bool = await self.get_network_status_async()
infos = await self.get_network_info_async()
if self._network_status != status:
for handler in self._sub_list_network_status.values():
@ -273,7 +360,7 @@ class MIoTNetwork:
# Remove
self.__call_network_info_change(
InterfaceStatus.REMOVE,
self._network_info.pop(name, None))
self._network_info.pop(name))
# Add
for name, info in infos.items():
self._network_info[name] = info

View File

@ -79,6 +79,7 @@ class MIoTSpecBase:
# External params
platform: str
device_class: Any
state_class: Any
icon: str
external_unit: Any
@ -96,6 +97,7 @@ class MIoTSpecBase:
self.platform = None
self.device_class = None
self.state_class = None
self.icon = None
self.external_unit = None

View File

@ -46,8 +46,16 @@ off Xiaomi or its affiliates' products.
Conversion rules of MIoT-Spec-V2 instance to Home Assistant entity.
"""
from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.components.sensor import SensorStateClass
from homeassistant.components.event import EventDeviceClass
from homeassistant.const import (
UnitOfEnergy,
UnitOfPower,
UnitOfElectricCurrent,
UnitOfElectricPotential,
)
# pylint: disable=pointless-string-statement
"""SPEC_DEVICE_TRANS_MAP
{
@ -325,7 +333,11 @@ SPEC_SERVICE_TRANS_MAP: dict[str, dict | str] = {
'properties': {
'<property instance name>':{
'device_class': str,
'entity': str
'entity': str,
'optional':{
'state_class': str,
'unit_of_measurement': str
}
}
}
}
@ -381,7 +393,11 @@ SPEC_PROP_TRANS_MAP: dict[str, dict | str] = {
},
'voltage': {
'device_class': SensorDeviceClass.VOLTAGE,
'entity': 'sensor'
'entity': 'sensor',
'optional': {
'state_class': SensorStateClass.MEASUREMENT,
'unit_of_measurement': UnitOfElectricPotential.VOLT
}
},
'illumination': {
'device_class': SensorDeviceClass.ILLUMINANCE,
@ -391,6 +407,38 @@ SPEC_PROP_TRANS_MAP: dict[str, dict | str] = {
'device_class': SensorDeviceClass.DURATION,
'entity': 'sensor'
},
'electric-power': {
'device_class': SensorDeviceClass.POWER,
'entity': 'sensor',
'optional': {
'state_class': SensorStateClass.MEASUREMENT,
'unit_of_measurement': UnitOfPower.WATT
}
},
'electric-current': {
'device_class': SensorDeviceClass.CURRENT,
'entity': 'sensor',
'optional': {
'state_class': SensorStateClass.MEASUREMENT,
'unit_of_measurement': UnitOfElectricCurrent.AMPERE
}
},
'power-consumption': {
'device_class': SensorDeviceClass.ENERGY,
'entity': 'sensor',
'optional': {
'state_class': SensorStateClass.TOTAL_INCREASING,
'unit_of_measurement': UnitOfEnergy.KILO_WATT_HOUR
}
},
'total-battery': {
'device_class': SensorDeviceClass.ENERGY,
'entity': 'sensor',
'optional': {
'state_class': SensorStateClass.TOTAL_INCREASING,
'unit_of_measurement': UnitOfEnergy.KILO_WATT_HOUR
}
},
'has-someone-duration': 'no-one-determine-time',
'no-one-duration': 'no-one-determine-time'
}

View File

@ -46,14 +46,15 @@ off Xiaomi or its affiliates' products.
Notify entities for Xiaomi Home.
"""
from __future__ import annotations
import json
import logging
from typing import Optional
from typing import Any, Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.notify import NotifyEntity
from homeassistant.util import yaml
from homeassistant.exceptions import HomeAssistantError
from .miot.miot_spec import MIoTSpecAction
from .miot.miot_device import MIoTDevice, MIoTActionEntity
@ -82,6 +83,7 @@ async def async_setup_entry(
class Notify(MIoTActionEntity, NotifyEntity):
"""Notify entities for Xiaomi Home."""
# pylint: disable=unused-argument
def __init__(self, miot_device: MIoTDevice, spec: MIoTSpecAction) -> None:
"""Initialize the Notify."""
@ -96,34 +98,58 @@ class Notify(MIoTActionEntity, NotifyEntity):
self, message: str, title: Optional[str] = None
) -> None:
"""Send a message."""
del title
if not message:
_LOGGER.error(
'action exec failed, %s(%s), empty action params',
self.name, self.entity_id)
return
in_list: Any = None
try:
in_list: list = json.loads(message)
except json.JSONDecodeError:
# YAML will convert yes, no, on, off, true, false to the bool type,
# and if it is a string, quotation marks need to be added.
in_list = yaml.parse_yaml(content=message)
except HomeAssistantError:
_LOGGER.error(
'action exec failed, %s(%s), invalid action params format, %s',
self.name, self.entity_id, message)
return
if len(self.spec.in_) == 1 and not isinstance(in_list, list):
in_list = [in_list]
if not isinstance(in_list, list) or len(in_list) != len(self.spec.in_):
_LOGGER.error(
'action exec failed, %s(%s), invalid action params, %s',
self.name, self.entity_id, message)
return
in_value: list[dict] = []
for index, prop in enumerate(self.spec.in_):
if type(in_list[index]).__name__ != prop.format_:
_LOGGER.error(
'action exec failed, %s(%s), invalid params item, '
'which item(%s) in the list must be %s, %s',
self.name, self.entity_id, prop.description_trans,
prop.format_, message)
return
in_value.append({'piid': prop.iid, 'value': in_list[index]})
return await self.action_async(in_list=in_value)
if prop.format_ == 'str':
if isinstance(in_list[index], (bool, int, float, str)):
in_value.append(
{'piid': prop.iid, 'value': str(in_list[index])})
continue
elif prop.format_ == 'bool':
if isinstance(in_list[index], (bool, int)):
# yes, no, on, off, true, false and other bool types
# will also be parsed as 0 and 1 of int.
in_value.append(
{'piid': prop.iid, 'value': bool(in_list[index])})
continue
elif prop.format_ == 'float':
if isinstance(in_list[index], (int, float)):
in_value.append(
{'piid': prop.iid, 'value': in_list[index]})
continue
elif prop.format_ == 'int':
if isinstance(in_list[index], int):
in_value.append(
{'piid': prop.iid, 'value': in_list[index]})
continue
# Invalid params type, raise error.
_LOGGER.error(
'action exec failed, %s(%s), invalid params item, '
'which item(%s) in the list must be %s, %s type was %s, %s',
self.name, self.entity_id, prop.description_trans,
prop.format_, in_list[index], type(
in_list[index]).__name__, message)
return
await self.action_async(in_list=in_value)

View File

@ -106,6 +106,9 @@ class Sensor(MIoTPropertyEntity, SensorEntity):
# Set icon
if spec.icon:
self._attr_icon = spec.icon
# Set state_class
if spec.state_class:
self._attr_state_class = spec.state_class
@property
def native_value(self) -> Any:

View File

@ -46,14 +46,15 @@ off Xiaomi or its affiliates' products.
Text entities for Xiaomi Home.
"""
from __future__ import annotations
import json
import logging
from typing import Optional
from typing import Any, Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.text import TextEntity
from homeassistant.util import yaml
from homeassistant.exceptions import HomeAssistantError
from .miot.const import DOMAIN
from .miot.miot_spec import MIoTSpecAction, MIoTSpecProperty
@ -119,16 +120,18 @@ class ActionText(MIoTActionEntity, TextEntity):
async def async_set_value(self, value: str) -> None:
if not value:
return
in_list: list = None
in_list: Any = None
try:
in_list = json.loads(value)
except json.JSONDecodeError as e:
in_list = yaml.parse_yaml(content=value)
except HomeAssistantError as e:
_LOGGER.error(
'action exec failed, %s(%s), invalid action params format, %s',
self.name, self.entity_id, value)
raise ValueError(
f'action exec failed, {self.name}({self.entity_id}), '
f'invalid action params format, {value}') from e
if len(self.spec.in_) == 1 and not isinstance(in_list, list):
in_list = [in_list]
if not isinstance(in_list, list) or len(in_list) != len(self.spec.in_):
_LOGGER.error(
'action exec failed, %s(%s), invalid action params, %s',
@ -138,16 +141,40 @@ class ActionText(MIoTActionEntity, TextEntity):
f'invalid action params, {value}')
in_value: list[dict] = []
for index, prop in enumerate(self.spec.in_):
if type(in_list[index]).__name__ != prop.format_:
logging.error(
'action exec failed, %s(%s), invalid params item, which '
'item(%s) in the list must be %s, %s', self.name,
self.entity_id, prop.description_trans, prop.format_, value)
raise ValueError(
f'action exec failed, {self.name}({self.entity_id}), '
f'invalid params item, which item({prop.description_trans})'
f' in the list must be {prop.format_}, {value}')
in_value.append({'piid': prop.iid, 'value': in_list[index]})
if prop.format_ == 'str':
if isinstance(in_list[index], (bool, int, float, str)):
in_value.append(
{'piid': prop.iid, 'value': str(in_list[index])})
continue
elif prop.format_ == 'bool':
if isinstance(in_list[index], (bool, int)):
# yes, no, on, off, true, false and other bool types
# will also be parsed as 0 and 1 of int.
in_value.append(
{'piid': prop.iid, 'value': bool(in_list[index])})
continue
elif prop.format_ == 'float':
if isinstance(in_list[index], (int, float)):
in_value.append(
{'piid': prop.iid, 'value': in_list[index]})
continue
elif prop.format_ == 'int':
if isinstance(in_list[index], int):
in_value.append(
{'piid': prop.iid, 'value': in_list[index]})
continue
# Invalid params type, raise error.
_LOGGER.error(
'action exec failed, %s(%s), invalid params item, '
'which item(%s) in the list must be %s, %s type was %s, %s',
self.name, self.entity_id, prop.description_trans,
prop.format_, in_list[index], type(
in_list[index]).__name__, value)
raise ValueError(
f'action exec failed, {self.name}({self.entity_id}), '
f'invalid params item, which item({prop.description_trans}) '
f'in the list must be {prop.format_}, {in_list[index]} type '
f'was {type(in_list[index]).__name__}, {value}')
self._attr_native_value = value
if await self.action_async(in_list=in_value):

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "Grundkonfiguration",
"description": "### Anmeldegebiet\r\nWählen Sie das Gebiet, in dem sich Ihr Xiaomi Home-Konto befindet. Sie können es in der Xiaomi Home App unter `Mein (unten im Menü) > Weitere Einstellungen > Über Xiaomi Home` überprüfen.\r\n### Sprache\r\nWählen Sie die Sprache, in der Geräte und Entitätsnamen angezeigt werden. Teile von Sätzen, die nicht übersetzt sind, werden in Englisch angezeigt.\r\n### OAuth2-Authentifizierungs-Umleitungs-URL\r\nDie Umleitungs-URL für die OAuth2-Authentifizierung lautet **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. Home Assistant muss im selben lokalen Netzwerk wie das aktuelle Betriebsterminal (z. B. ein persönlicher Computer) und das Betriebsterminal muss über diese Adresse auf die Home Assistant-Homepage zugreifen können. Andernfalls kann die Anmeldeauthentifizierung fehlschlagen.\r\n### Hinweis\r\n- Für Benutzer mit Hunderten oder mehr Mi Home-Geräten wird das erste Hinzufügen der Integration einige Zeit in Anspruch nehmen. Bitte haben Sie Geduld.\r\n- Wenn Home Assistant in einer Docker-Umgebung läuft, stellen Sie bitte sicher, dass der Docker-Netzwerkmodus auf host eingestellt ist, da sonst die lokale Steuerungsfunktion möglicherweise nicht richtig funktioniert.\r\n- Die lokale Steuerungsfunktion der Integration hat einige Abhängigkeiten. Bitte lesen Sie das README sorgfältig.",
"description": "### Anmeldegebiet\r\nWählen Sie das Gebiet, in dem sich Ihr Xiaomi Home-Konto befindet. Sie können es in der Xiaomi Home App unter `Mein (unten im Menü) > Weitere Einstellungen > Über Xiaomi Home` überprüfen.\r\n### Sprache\r\nWählen Sie die Sprache, in der Geräte und Entitätsnamen angezeigt werden. Teile von Sätzen, die nicht übersetzt sind, werden in Englisch angezeigt.\r\n### OAuth2-Authentifizierungs-Umleitungs-URL\r\nDie Umleitungs-URL für die OAuth2-Authentifizierung lautet **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. Home Assistant muss im selben lokalen Netzwerk wie das aktuelle Betriebsterminal (z. B. ein persönlicher Computer) und das Betriebsterminal muss über diese Adresse auf die Home Assistant-Homepage zugreifen können. Andernfalls kann die Anmeldeauthentifizierung fehlschlagen.\r\n### Integrierte Netzwerkkonfiguration\r\nÜberprüfen Sie, ob das lokale Netzwerk normal funktioniert und ob die zugehörigen Netzwerkressourcen zugänglich sind. **Es wird empfohlen, dies beim ersten Hinzufügen auszuwählen.**\r\n### Hinweis\r\n- Für Benutzer mit Hunderten oder mehr Mi Home-Geräten wird das erste Hinzufügen der Integration einige Zeit in Anspruch nehmen. Bitte haben Sie Geduld.\r\n- Wenn Home Assistant in einer Docker-Umgebung läuft, stellen Sie bitte sicher, dass der Docker-Netzwerkmodus auf host eingestellt ist, da sonst die lokale Steuerungsfunktion möglicherweise nicht richtig funktioniert.\r\n- Die lokale Steuerungsfunktion der Integration hat einige Abhängigkeiten. Bitte lesen Sie das README sorgfältig.",
"data": {
"cloud_server": "Anmeldegebiet",
"integration_language": "Sprache",
"oauth_redirect_url": "OAuth2-Authentifizierungs-Umleitungs-URL"
"oauth_redirect_url": "OAuth2-Authentifizierungs-Umleitungs-URL",
"network_detect_config": "Integrierte Netzwerkkonfiguration"
}
},
"network_detect_config": {
"title": "Integrierte Netzwerkkonfiguration",
"description": "## Gebrauchsanweisung\r\n### Netzwerk-Erkennungsadresse\r\nWird verwendet, um zu überprüfen, ob das Netzwerk normal funktioniert. Wenn nicht festgelegt, wird die Standardadresse des Systems verwendet. Wenn die Standardadressprüfung fehlschlägt, können Sie versuchen, eine benutzerdefinierte Adresse einzugeben.\r\n- Sie können mehrere Erkennungsadressen eingeben, getrennt durch ein Komma, z. B. `8.8.8.8,https://www.bing.com`\r\n- Wenn es sich um eine IP-Adresse handelt, wird die Erkennung durch Ping durchgeführt. Wenn es sich um eine HTTP(s)-Adresse handelt, wird die Erkennung durch einen HTTP GET-Aufruf durchgeführt.\r\n- Wenn Sie die Standarderkennungsadresse des Systems wiederherstellen möchten, geben Sie ein Komma `,` ein und klicken Sie auf 'Weiter'.\r\n- **Diese Konfiguration ist global und Änderungen wirken sich auf andere Integrationsinstanzen aus. Bitte ändern Sie sie mit Vorsicht.**\r\n### Überprüfung der Netzwerkabhängigkeiten\r\nÜberprüfen Sie nacheinander, ob die folgenden Netzwerkabhängigkeiten zugänglich sind. Wenn die entsprechenden Adressen nicht zugänglich sind, führt dies zu Integrationsfehlern.\r\n- OAuth2-Authentifizierungsadresse: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Xiaomi HTTP API-Adresse: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Xiaomi SPEC API-Adresse: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Xiaomi MQTT Broker-Adresse: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Netzwerkerkennungsadresse",
"check_network_deps": "Überprüfung der Netzwerkabhängigkeiten"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "Lokaler Geräteerkennungsdienst ist nicht verfügbar.",
"get_cert_error": "Fehler beim Abrufen des Gateway-Zertifikats.",
"no_family_selected": "Keine Familie ausgewählt.",
"no_devices": "In der ausgewählten Familie sind keine Geräte enthalten. Bitte wählen Sie eine Familie mit Geräten aus und fahren Sie fort.",
"no_central_device": "Im Modus \"Xiaomi Central Hub Gateway\" muss ein verfügbares Xiaomi Central Hub Gateway im lokalen Netzwerk von Home Assistant vorhanden sein. Stellen Sie sicher, dass die ausgewählte Familie diese Anforderungen erfüllt."
"no_devices": "Im ausgewählten Haushalt sind keine Geräte vorhanden. Bitte wählen Sie einen Haushalt mit Geräten aus und fahren Sie fort.",
"no_filter_devices": "Gefilterte Geräte sind leer. Bitte wählen Sie gültige Filterkriterien aus und fahren Sie fort.",
"no_central_device": "Im Modus \"Xiaomi Central Hub Gateway\" muss ein verfügbares Xiaomi Central Hub Gateway im lokalen Netzwerk von Home Assistant vorhanden sein. Stellen Sie sicher, dass die ausgewählte Familie diese Anforderungen erfüllt.",
"invalid_network_addr": "Ungültige IP-Adresse oder HTTP-Adresse vorhanden, bitte geben Sie eine gültige Adresse ein.",
"invalid_ip_addr": "Unzugängliche IP-Adresse vorhanden, bitte geben Sie eine gültige IP-Adresse ein.",
"invalid_http_addr": "Unzugängliche HTTP-Adresse vorhanden, bitte geben Sie eine gültige HTTP-Adresse ein.",
"invalid_default_addr": "Die Standard-Netzwerkerkennungsadresse ist nicht erreichbar, bitte überprüfen Sie die Netzwerkkonfiguration oder verwenden Sie eine benutzerdefinierte Netzwerkerkennungsadresse.",
"unreachable_oauth2_host": "OAuth2-Authentifizierungsadresse ist nicht erreichbar, bitte überprüfen Sie die Netzwerkkonfiguration.",
"unreachable_http_host": "Xiaomi HTTP API-Adresse ist nicht erreichbar, bitte überprüfen Sie die Netzwerkkonfiguration.",
"unreachable_spec_host": "Xiaomi SPEC API-Adresse ist nicht erreichbar, bitte überprüfen Sie die Netzwerkkonfiguration.",
"unreachable_mqtt_broker": "Xiaomi MQTT Broker-Adresse ist nicht erreichbar, bitte überprüfen Sie die Netzwerkkonfiguration."
},
"abort": {
"network_connect_error": "Konfiguration fehlgeschlagen. Netzwerkverbindung fehlgeschlagen. Überprüfen Sie die Netzwerkkonfiguration des Geräts.",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "Konfigurationsoptionen",
"description": "### Hallo {nick_name}!\r\n\r\nXiaomi Home-Konto-ID: {uid}\r\nAktuelles Anmeldegebiet: {cloud_server}\r\n\r\nWählen Sie die Optionen aus, die Sie erneut konfigurieren möchten, und klicken Sie dann auf \"Weiter\".",
"description": "### Hallo {nick_name}!\r\n\r\nXiaomi Home-Konto-ID: {uid}\r\nAktuelles Anmeldegebiet: {cloud_server}\r\nIntegrationsinstanz-ID: {instance_id}\r\n\r\nWählen Sie die Optionen aus, die Sie erneut konfigurieren möchten, und klicken Sie dann auf \"Weiter\".",
"data": {
"integration_language": "Integrationsprache",
"update_user_info": "Benutzerinformationen aktualisieren",
@ -102,7 +120,8 @@
"hide_non_standard_entities": "Verstecke Nicht-Standard-Entitäten",
"display_devices_changed_notify": "Gerätestatusänderungen anzeigen",
"update_trans_rules": "Entitätskonvertierungsregeln aktualisieren",
"update_lan_ctrl_config": "LAN-Steuerungskonfiguration aktualisieren"
"update_lan_ctrl_config": "LAN-Steuerungskonfiguration aktualisieren",
"network_detect_config": "Integrierte Netzwerkkonfiguration"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "LAN-Abonnement aktivieren"
}
},
"network_detect_config": {
"title": "Integrierte Netzwerkkonfiguration",
"description": "## Gebrauchsanweisung\r\n### Netzwerk-Erkennungsadresse\r\nWird verwendet, um zu überprüfen, ob das Netzwerk normal funktioniert. Wenn nicht festgelegt, wird die Standardadresse des Systems verwendet. Wenn die Standardadressprüfung fehlschlägt, können Sie versuchen, eine benutzerdefinierte Adresse einzugeben.\r\n- Sie können mehrere Erkennungsadressen eingeben, getrennt durch ein Komma, z. B. `8.8.8.8,https://www.bing.com`\r\n- Wenn es sich um eine IP-Adresse handelt, wird die Erkennung durch Ping durchgeführt. Wenn es sich um eine HTTP(s)-Adresse handelt, wird die Erkennung durch einen HTTP GET-Aufruf durchgeführt.\r\n- Wenn Sie die Standarderkennungsadresse des Systems wiederherstellen möchten, geben Sie ein Komma `,` ein und klicken Sie auf 'Weiter'.\r\n- **Diese Konfiguration ist global und Änderungen wirken sich auf andere Integrationsinstanzen aus. Bitte ändern Sie sie mit Vorsicht.**\r\n### Überprüfung der Netzwerkabhängigkeiten\r\nÜberprüfen Sie nacheinander, ob die folgenden Netzwerkabhängigkeiten zugänglich sind. Wenn die entsprechenden Adressen nicht zugänglich sind, führt dies zu Integrationsfehlern.\r\n- OAuth2-Authentifizierungsadresse: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Xiaomi HTTP API-Adresse: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Xiaomi SPEC API-Adresse: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Xiaomi MQTT Broker-Adresse: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Netzwerkerkennungsadresse",
"check_network_deps": "Überprüfung der Netzwerkabhängigkeiten"
}
},
"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ä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",
@ -168,11 +195,20 @@
"get_homeinfo_error": "Fehler beim Abrufen von Home-Informationen.",
"get_cert_error": "Fehler beim Abrufen des Zentralzertifikats.",
"no_family_selected": "Keine Familie ausgewählt.",
"no_devices": "In der ausgewählten Familie sind keine Geräte vorhanden. Bitte wählen Sie eine Familie mit Geräten und fahren Sie dann fort.",
"no_devices": "Im ausgewählten Haushalt sind keine Geräte vorhanden. Bitte wählen Sie einen Haushalt mit Geräten aus und fahren Sie fort.",
"no_filter_devices": "Gefilterte Geräte sind leer. Bitte wählen Sie gültige Filterkriterien aus und fahren Sie fort.",
"no_central_device": "Der Modus \"Zentral Gateway\" erfordert ein verfügbares Xiaomi-Zentral-Gateway im lokalen Netzwerk, in dem Home Assistant installiert ist. Überprüfen Sie, ob die ausgewählte Familie diese Anforderung erfüllt.",
"mdns_discovery_error": "Lokaler Geräteerkennungsdienstfehler.",
"update_config_error": "Fehler beim Aktualisieren der Konfigurationsinformationen.",
"not_confirm": "Änderungen wurden nicht bestätigt. Bitte bestätigen Sie die Auswahl, bevor Sie sie einreichen."
"not_confirm": "Änderungen wurden nicht bestätigt. Bitte bestätigen Sie die Auswahl, bevor Sie sie einreichen.",
"invalid_network_addr": "Ungültige IP-Adresse oder HTTP-Adresse vorhanden, bitte geben Sie eine gültige Adresse ein.",
"invalid_ip_addr": "Unzugängliche IP-Adresse vorhanden, bitte geben Sie eine gültige IP-Adresse ein.",
"invalid_http_addr": "Unzugängliche HTTP-Adresse vorhanden, bitte geben Sie eine gültige HTTP-Adresse ein.",
"invalid_default_addr": "Die Standard-Netzwerkerkennungsadresse ist nicht erreichbar, bitte überprüfen Sie die Netzwerkkonfiguration oder verwenden Sie eine benutzerdefinierte Netzwerkerkennungsadresse.",
"unreachable_oauth2_host": "OAuth2-Authentifizierungsadresse ist nicht erreichbar, bitte überprüfen Sie die Netzwerkkonfiguration.",
"unreachable_http_host": "Xiaomi HTTP API-Adresse ist nicht erreichbar, bitte überprüfen Sie die Netzwerkkonfiguration.",
"unreachable_spec_host": "Xiaomi SPEC API-Adresse ist nicht erreichbar, bitte überprüfen Sie die Netzwerkkonfiguration.",
"unreachable_mqtt_broker": "Xiaomi MQTT Broker-Adresse ist nicht erreichbar, bitte überprüfen Sie die Netzwerkkonfiguration."
},
"abort": {
"network_connect_error": "Konfiguration fehlgeschlagen. Netzwerkverbindungsfehler. Überprüfen Sie die Netzwerkkonfiguration des Geräts.",

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "Basic configuration",
"description": "### Login Region\r\nSelect the region of your Xiaomi account. You can find it in the Xiaomi Home APP > Profile (located in the menu at the bottom) > Additional settings > About Xiaomi Home.\r\n### Language\r\nSelect the language of the device and entity names. Some sentences without translation will be displayed in English.\r\n### OAuth2 Redirect URL\r\nThe OAuth2 authentication redirect address is **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. The Home Assistant needs to be in the same local area network as the current operating terminal (e.g., the personal computer) and the operating terminal can access the Home Assistant home page through this address. Otherwise, the login authentication may fail.\r\n### Note\r\n- For users with hundreds or more Mi Home devices, the initial addition of the integration will take some time. Please be patient.\r\n- If Home Assistant is running in a Docker environment, please ensure that the Docker network mode is set to host, otherwise local control functionality may not work properly.\r\n- The local control functionality of the integration has some dependencies. Please read the README carefully.",
"description": "### Login Region\r\nSelect the region of your Xiaomi account. You can find it in the Xiaomi Home APP > Profile (located in the menu at the bottom) > Additional settings > About Xiaomi Home.\r\n### Language\r\nSelect the language of the device and entity names. Some sentences without translation will be displayed in English.\r\n### OAuth2 Redirect URL\r\nThe OAuth2 authentication redirect address is **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. The Home Assistant needs to be in the same local area network as the current operating terminal (e.g., the personal computer) and the operating terminal can access the Home Assistant home page through this address. Otherwise, the login authentication may fail.\r\n### Integrated Network Configuration\r\nCheck if the local network is functioning properly and if the related network resources are accessible. **It is recommended to select this when adding for the first time.**\r\n### Note\r\n- For users with hundreds or more Mi Home devices, the initial addition of the integration will take some time. Please be patient.\r\n- If Home Assistant is running in a Docker environment, please ensure that the Docker network mode is set to host, otherwise local control functionality may not work properly.\r\n- The local control functionality of the integration has some dependencies. Please read the README carefully.",
"data": {
"cloud_server": "Login Region",
"integration_language": "Language",
"oauth_redirect_url": "OAuth2 Redirect URL"
"oauth_redirect_url": "OAuth2 Redirect URL",
"network_detect_config": "Integrated Network Configuration"
}
},
"network_detect_config": {
"title": "Integrated Network Configuration",
"description": "## Usage Introduction\r\n### Network Detection Address\r\nUsed to check if the network is functioning properly. If not set, the system default address will be used. If the default address check fails, you can try entering a custom address.\r\n- You can enter multiple detection addresses, separated by commas, such as `8.8.8.8,https://www.bing.com`\r\n- If it is an IP address, detection will be done via ping. If it is an HTTP(s) address, detection will be done via HTTP GET request.\r\n- If you want to restore the system default detection address, please enter a comma `,` and click 'Next'.\r\n- **This configuration is global, and changes will affect other integration instances. Please modify with caution.**\r\n### Check Network Dependencies\r\nCheck the following network dependencies one by one to see if they are accessible. If the related addresses are not accessible, it will cause integration issues.\r\n- OAuth2 Authentication Address: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Xiaomi HTTP API Address: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Xiaomi SPEC API Address: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Xiaomi MQTT Broker Address: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Network Detection Address",
"check_network_deps": "Check Network Dependencies"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "Local device discovery service exception.",
"get_cert_error": "Failed to retrieve the central hub gateway certificate.",
"no_family_selected": "No home selected.",
"no_devices": "The selected home does not have any devices. Please choose a home containing devices and continue.",
"no_central_device": "[Central Hub Gateway Mode] requires a Xiaomi central hub gateway available in the local network where Home Assistant exists. Please check if the selected home meets the requirement."
"no_devices": "There are no devices in the selected home. Please select a home with devices and continue.",
"no_filter_devices": "Filtered devices are empty. Please select valid filter criteria and continue.",
"no_central_device": "[Central Hub Gateway Mode] requires a Xiaomi central hub gateway available in the local network where Home Assistant exists. Please check if the selected home meets the requirement.",
"invalid_network_addr": "Invalid IP address or HTTP address detected, please enter a valid address.",
"invalid_ip_addr": "Unreachable IP address detected, please enter a valid IP address.",
"invalid_http_addr": "Unreachable HTTP address detected, please enter a valid HTTP address.",
"invalid_default_addr": "Default network detection address is unreachable, please check network configuration or use a custom network detection address.",
"unreachable_oauth2_host": "Unable to reach OAuth2 authentication address, please check network configuration.",
"unreachable_http_host": "Unable to reach Xiaomi HTTP API address, please check network configuration.",
"unreachable_spec_host": "Unable to reach Xiaomi SPEC API address, please check network configuration.",
"unreachable_mqtt_broker": "Unable to reach Xiaomi MQTT Broker address, please check network configuration."
},
"abort": {
"network_connect_error": "Configuration failed. The network connection is abnormal. Please check the equipment network configuration.",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "Configuration Options",
"description": "### Hello, {nick_name}\r\n\r\nXiaomi ID: {uid}\r\nCurrent Login Region: {cloud_server}\r\n\r\nPlease select the options you need to configure, then click NEXT.",
"description": "### Hello, {nick_name}\r\n\r\nXiaomi ID: {uid}\r\nCurrent Login Region: {cloud_server}\r\nIntegration Instance ID: {instance_id}\r\n\r\nPlease select the options you need to configure, then click NEXT.",
"data": {
"integration_language": "Integration Language",
"update_user_info": "Update user information",
@ -102,7 +120,8 @@
"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"
"update_lan_ctrl_config": "Update LAN control configuration",
"network_detect_config": "Integrated Network Configuration"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "Enable LAN subscription"
}
},
"network_detect_config": {
"title": "Integrated Network Configuration",
"description": "## Usage Introduction\r\n### Network Detection Address\r\nUsed to check if the network is functioning properly. If not set, the system default address will be used. If the default address check fails, you can try entering a custom address.\r\n- You can enter multiple detection addresses, separated by commas, such as `8.8.8.8,https://www.bing.com`\r\n- If it is an IP address, detection will be done via ping. If it is an HTTP(s) address, detection will be done via HTTP GET request.\r\n- If you want to restore the system default detection address, please enter a comma `,` and click 'Next'.\r\n- **This configuration is global, and changes will affect other integration instances. Please modify with caution.**\r\n### Check Network Dependencies\r\nCheck the following network dependencies one by one to see if they are accessible. If the related addresses are not accessible, it will cause integration issues.\r\n- OAuth2 Authentication Address: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Xiaomi HTTP API Address: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Xiaomi SPEC API Address: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Xiaomi MQTT Broker Address: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Network Detection Address",
"check_network_deps": "Check Network Dependencies"
}
},
"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\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",
@ -167,12 +194,21 @@
"get_token_error": "Failed to retrieve login authorization information (OAuth token).",
"get_homeinfo_error": "Failed to retrieve home information.",
"get_cert_error": "Failed to retrieve the central hub gateway certificate.",
"no_devices": "The selected home does not have any devices. Please choose a home containing devices and continue.",
"no_devices": "There are no devices in the selected home. Please select a home with devices and continue.",
"no_filter_devices": "Filtered devices are empty. Please select valid filter criteria and continue.",
"no_family_selected": "No home selected.",
"no_central_device": "[Central Hub Gateway Mode] requires a Xiaomi central hub gateway available in the local network where Home Assistant exists. Please check if the selected home meets the requirement.",
"mdns_discovery_error": "Local device discovery service exception.",
"update_config_error": "Failed to update configuration information.",
"not_confirm": "Changes are not confirmed. Please confirm the change before submitting."
"not_confirm": "Changes are not confirmed. Please confirm the change before submitting.",
"invalid_network_addr": "Invalid IP address or HTTP address detected, please enter a valid address.",
"invalid_ip_addr": "Unreachable IP address detected, please enter a valid IP address.",
"invalid_http_addr": "Unreachable HTTP address detected, please enter a valid HTTP address.",
"invalid_default_addr": "Default network detection address is unreachable, please check network configuration or use a custom network detection address.",
"unreachable_oauth2_host": "Unable to reach OAuth2 authentication address, please check network configuration.",
"unreachable_http_host": "Unable to reach Xiaomi HTTP API address, please check network configuration.",
"unreachable_spec_host": "Unable to reach Xiaomi SPEC API address, please check network configuration.",
"unreachable_mqtt_broker": "Unable to reach Xiaomi MQTT Broker address, please check network configuration."
},
"abort": {
"network_connect_error": "Configuration failed. The network connection is abnormal. Please check the equipment network configuration.",

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "Configuración básica",
"description": "### Región de inicio de sesión\r\nSeleccione la región donde se encuentra su cuenta de Xiaomi. Puede consultar esta información en `Xiaomi Home APP > Yo (ubicado en el menú inferior) > Más ajustes > Acerca de Xiaomi Home`.\r\n### Idioma\r\nSeleccione el idioma utilizado para los nombres de los dispositivos y entidades. Las partes de las frases que no están traducidas se mostrarán en inglés.\r\n### Dirección de redireccionamiento de autenticación de OAuth2\r\nLa dirección de redireccionamiento de autenticación de OAuth2 es **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. Home Assistant debe estar en la misma red local que el terminal de operación actual (por ejemplo, una computadora personal) y el terminal de operación debe poder acceder a la página de inicio de Home Assistant a través de esta dirección, de lo contrario, la autenticación de inicio de sesión podría fallar.\r\n### Nota\r\n- Para los usuarios con cientos o más dispositivos Mi Home, la adición inicial de la integración tomará algún tiempo. Por favor, sea paciente.\r\n- Si Home Assistant se está ejecutando en un entorno Docker, asegúrese de que el modo de red de Docker esté configurado en host, de lo contrario, la funcionalidad de control local puede no funcionar correctamente.\r\n- La funcionalidad de control local de la integración tiene algunas dependencias. Por favor, lea el README cuidadosamente.",
"description": "### Región de inicio de sesión\r\nSeleccione la región donde se encuentra su cuenta de Xiaomi. Puede consultar esta información en `Xiaomi Home APP > Yo (ubicado en el menú inferior) > Más ajustes > Acerca de Xiaomi Home`.\r\n### Idioma\r\nSeleccione el idioma utilizado para los nombres de los dispositivos y entidades. Las partes de las frases que no están traducidas se mostrarán en inglés.\r\n### Dirección de redireccionamiento de autenticación de OAuth2\r\nLa dirección de redireccionamiento de autenticación de OAuth2 es **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. Home Assistant debe estar en la misma red local que el terminal de operación actual (por ejemplo, una computadora personal) y el terminal de operación debe poder acceder a la página de inicio de Home Assistant a través de esta dirección, de lo contrario, la autenticación de inicio de sesión podría fallar.\r\n### Configuración de Red Integrada\r\nVerifique si la red local funciona correctamente y si los recursos de red relacionados son accesibles. **Se recomienda seleccionar esto al agregar por primera vez.**\r\n### Nota\r\n- Para los usuarios con cientos o más dispositivos Mi Home, la adición inicial de la integración tomará algún tiempo. Por favor, sea paciente.\r\n- Si Home Assistant se está ejecutando en un entorno Docker, asegúrese de que el modo de red de Docker esté configurado en host, de lo contrario, la funcionalidad de control local puede no funcionar correctamente.\r\n- La funcionalidad de control local de la integración tiene algunas dependencias. Por favor, lea el README cuidadosamente.",
"data": {
"cloud_server": "Región de inicio de sesión",
"integration_language": "Idioma",
"oauth_redirect_url": "Dirección de redireccionamiento de autenticación de OAuth2"
"oauth_redirect_url": "Dirección de redireccionamiento de autenticación de OAuth2",
"network_detect_config": "Configuración de Red Integrada"
}
},
"network_detect_config": {
"title": "Configuración de Red Integrada",
"description": "## Introducción al Uso\r\n### Dirección de Detección de Red\r\nSe utiliza para verificar si la red funciona correctamente. Si no se establece, se utilizará la dirección predeterminada del sistema. Si la verificación de la dirección predeterminada falla, puede intentar ingresar una dirección personalizada.\r\n- Puede ingresar varias direcciones de detección, separadas por comas, como `8.8.8.8,https://www.bing.com`\r\n- Si es una dirección IP, la detección se realizará mediante ping. Si es una dirección HTTP(s), la detección se realizará mediante una solicitud HTTP GET.\r\n- Si desea restaurar la dirección de detección predeterminada del sistema, ingrese una coma `,` y haga clic en 'Siguiente'.\r\n- **Esta configuración es global y los cambios afectarán a otras instancias de integración. Modifique con precaución.**\r\n### Verificar Dependencias de Red\r\nVerifique una por una las siguientes dependencias de red para ver si son accesibles. Si las direcciones relacionadas no son accesibles, causará problemas de integración.\r\n- Dirección de Autenticación OAuth2: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Dirección de API HTTP de Xiaomi: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Dirección de API SPEC de Xiaomi: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Dirección del Broker MQTT de Xiaomi: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Dirección de Detección de Red",
"check_network_deps": "Verificar Dependencias de Red"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "Error en el servicio de descubrimiento de dispositivos locales.",
"get_cert_error": "Error al obtener el certificado de la puerta de enlace.",
"no_family_selected": "No se ha seleccionado ningún hogar.",
"no_devices": "No hay dispositivos en el hogar seleccionado. Seleccione un hogar con dispositivos y continúe.",
"no_central_device": "【Modo de puerta de enlace central】Se requiere una puerta de enlace Xiaomi disponible en la red local donde se encuentra Home Assistant. Verifique si el hogar seleccionado cumple con este requisito."
"no_devices": "No hay dispositivos en el hogar seleccionado. Por favor, seleccione un hogar con dispositivos y continúe.",
"no_filter_devices": "Los dispositivos filtrados están vacíos. Por favor, seleccione criterios de filtro válidos y continúe.",
"no_central_device": "【Modo de puerta de enlace central】Se requiere una puerta de enlace Xiaomi disponible en la red local donde se encuentra Home Assistant. Verifique si el hogar seleccionado cumple con este requisito.",
"invalid_network_addr": "Se detectó una dirección IP o HTTP no válida, por favor ingrese una dirección válida.",
"invalid_ip_addr": "Se detectó una dirección IP inaccesible, por favor ingrese una dirección IP válida.",
"invalid_http_addr": "Se detectó una dirección HTTP inaccesible, por favor ingrese una dirección HTTP válida.",
"invalid_default_addr": "La dirección de detección de red predeterminada no es accesible, por favor verifique la configuración de la red o use una dirección de detección de red personalizada.",
"unreachable_oauth2_host": "No se puede acceder a la dirección de autenticación OAuth2, por favor verifique la configuración de la red.",
"unreachable_http_host": "No se puede acceder a la dirección de la API HTTP de Xiaomi, por favor verifique la configuración de la red.",
"unreachable_spec_host": "No se puede acceder a la dirección de la API SPEC de Xiaomi, por favor verifique la configuración de la red.",
"unreachable_mqtt_broker": "No se puede acceder a la dirección del Broker MQTT de Xiaomi, por favor verifique la configuración de la red."
},
"abort": {
"network_connect_error": "La configuración ha fallado. Existe un problema con la conexión de red, verifique la configuración de red del dispositivo.",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "Opciones de configuración",
"description": "### ¡Hola, {nick_name}!\r\n\r\nID de cuenta de Xiaomi: {uid}\r\nRegión de inicio de sesión actual: {cloud_server}\r\n\r\nSeleccione las opciones que desea reconfigurar y haga clic en \"Siguiente\".",
"description": "### ¡Hola, {nick_name}!\r\n\r\nID de cuenta de Xiaomi: {uid}\r\nRegión de inicio de sesión actual: {cloud_server}\r\nID de Instancia de Integración: {instance_id}\r\n\r\nSeleccione las opciones que desea reconfigurar y haga clic en \"Siguiente\".",
"data": {
"integration_language": "Idioma de la integración",
"update_user_info": "Actualizar información de usuario",
@ -102,7 +120,8 @@
"hide_non_standard_entities": "Ocultar entidades generadas no estándar",
"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_lan_ctrl_config": "Actualizar configuración de control LAN",
"network_detect_config": "Configuración de Red Integrada"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "Habilitar suscripción LAN"
}
},
"network_detect_config": {
"title": "Configuración de Red Integrada",
"description": "## Introducción al Uso\r\n### Dirección de Detección de Red\r\nSe utiliza para verificar si la red funciona correctamente. Si no se establece, se utilizará la dirección predeterminada del sistema. Si la verificación de la dirección predeterminada falla, puede intentar ingresar una dirección personalizada.\r\n- Puede ingresar varias direcciones de detección, separadas por comas, como `8.8.8.8,https://www.bing.com`\r\n- Si es una dirección IP, la detección se realizará mediante ping. Si es una dirección HTTP(s), la detección se realizará mediante una solicitud HTTP GET.\r\n- Si desea restaurar la dirección de detección predeterminada del sistema, ingrese una coma `,` y haga clic en 'Siguiente'.\r\n- **Esta configuración es global y los cambios afectarán a otras instancias de integración. Modifique con precaución.**\r\n### Verificar Dependencias de Red\r\nVerifique una por una las siguientes dependencias de red para ver si son accesibles. Si las direcciones relacionadas no son accesibles, causará problemas de integración.\r\n- Dirección de Autenticación OAuth2: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Dirección de API HTTP de Xiaomi: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Dirección de API SPEC de Xiaomi: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Dirección del Broker MQTT de Xiaomi: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Dirección de Detección de Red",
"check_network_deps": "Verificar Dependencias de Red"
}
},
"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\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",
@ -168,11 +195,20 @@
"get_homeinfo_error": "Error al obtener la información del hogar.",
"get_cert_error": "Error al obtener el certificado de la puerta de enlace.",
"no_family_selected": "No se ha seleccionado ningún hogar.",
"no_devices": "No hay dispositivos en el hogar seleccionado. Seleccione un hogar con dispositivos y continúe.",
"no_devices": "No hay dispositivos en el hogar seleccionado. Por favor, seleccione un hogar con dispositivos y continúe.",
"no_filter_devices": "Los dispositivos filtrados están vacíos. Por favor, seleccione criterios de filtro válidos y continúe.",
"no_central_device": "【Modo de puerta de enlace central】Se requiere una puerta de enlace Xiaomi disponible en la red local donde se encuentra Home Assistant. Verifique si el hogar seleccionado cumple con este requisito.",
"mdns_discovery_error": "Error en el servicio de descubrimiento de dispositivos locales.",
"update_config_error": "Error al actualizar la información de configuración.",
"not_confirm": "No se ha confirmado la opción de modificación. Seleccione y confirme la opción antes de enviar."
"not_confirm": "No se ha confirmado la opción de modificación. Seleccione y confirme la opción antes de enviar.",
"invalid_network_addr": "Se detectó una dirección IP o HTTP no válida, por favor ingrese una dirección válida.",
"invalid_ip_addr": "Se detectó una dirección IP inaccesible, por favor ingrese una dirección IP válida.",
"invalid_http_addr": "Se detectó una dirección HTTP inaccesible, por favor ingrese una dirección HTTP válida.",
"invalid_default_addr": "La dirección de detección de red predeterminada no es accesible, por favor verifique la configuración de la red o use una dirección de detección de red personalizada.",
"unreachable_oauth2_host": "No se puede acceder a la dirección de autenticación OAuth2, por favor verifique la configuración de la red.",
"unreachable_http_host": "No se puede acceder a la dirección de la API HTTP de Xiaomi, por favor verifique la configuración de la red.",
"unreachable_spec_host": "No se puede acceder a la dirección de la API SPEC de Xiaomi, por favor verifique la configuración de la red.",
"unreachable_mqtt_broker": "No se puede acceder a la dirección del Broker MQTT de Xiaomi, por favor verifique la configuración de la red."
},
"abort": {
"network_connect_error": "La configuración ha fallado. Existe un problema con la conexión de red, verifique la configuración de red del dispositivo.",

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "Configuration de base",
"description": "### Région de connexion\r\nSélectionnez la région où se trouve votre compte Xiaomi. Vous pouvez le trouver dans `Xiaomi Home APP > Mon (situé dans le menu inférieur) > Plus de paramètres > À propos de Xiaomi Home`.\r\n### Langue\r\nChoisissez la langue utilisée pour les noms de périphériques et d'entités. Les parties de phrases sans traduction seront affichées en anglais.\r\n### Adresse de redirection de l'authentification OAuth2\r\nL'adresse de redirection de l'authentification OAuth2 est **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. Home Assistant doit être dans le même réseau local que le terminal de l'opération actuelle (par exemple, un ordinateur personnel) et le terminal de l'opération doit pouvoir accéder à la page d'accueil de Home Assistant via cette adresse. Sinon, l'authentification de connexion peut échouer.\r\n### Remarque\r\n- Pour les utilisateurs ayant des centaines ou plus d'appareils Mi Home, l'ajout initial de l'intégration prendra un certain temps. Veuillez être patient.\r\n- Si Home Assistant fonctionne dans un environnement Docker, veuillez vous assurer que le mode réseau Docker est réglé sur host, sinon la fonctionnalité de contrôle local peut ne pas fonctionner correctement.\r\n- La fonctionnalité de contrôle local de l'intégration a quelques dépendances. Veuillez lire attentivement le README.",
"description": "### Région de connexion\r\nSélectionnez la région où se trouve votre compte Xiaomi. Vous pouvez le trouver dans `Xiaomi Home APP > Mon (situé dans le menu inférieur) > Plus de paramètres > À propos de Xiaomi Home`.\r\n### Langue\r\nChoisissez la langue utilisée pour les noms de périphériques et d'entités. Les parties de phrases sans traduction seront affichées en anglais.\r\n### Adresse de redirection de l'authentification OAuth2\r\nL'adresse de redirection de l'authentification OAuth2 est **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. Home Assistant doit être dans le même réseau local que le terminal de l'opération actuelle (par exemple, un ordinateur personnel) et le terminal de l'opération doit pouvoir accéder à la page d'accueil de Home Assistant via cette adresse. Sinon, l'authentification de connexion peut échouer.\r\n### Configuration Réseau Intégrée\r\nVérifiez si le réseau local fonctionne correctement et si les ressources réseau associées sont accessibles. **Il est recommandé de sélectionner cela lors du premier ajout.**\r\n### Remarque\r\n- Pour les utilisateurs ayant des centaines ou plus d'appareils Mi Home, l'ajout initial de l'intégration prendra un certain temps. Veuillez être patient.\r\n- Si Home Assistant fonctionne dans un environnement Docker, veuillez vous assurer que le mode réseau Docker est réglé sur host, sinon la fonctionnalité de contrôle local peut ne pas fonctionner correctement.\r\n- La fonctionnalité de contrôle local de l'intégration a quelques dépendances. Veuillez lire attentivement le README.",
"data": {
"cloud_server": "Région de connexion",
"integration_language": "Langue",
"oauth_redirect_url": "Adresse de redirection de l'authentification"
"oauth_redirect_url": "Adresse de redirection de l'authentification",
"network_detect_config": "Configuration Réseau Intégrée"
}
},
"network_detect_config": {
"title": "Configuration Réseau Intégrée",
"description": "## Introduction à l'Utilisation\r\n### Adresse de Détection Réseau\r\nUtilisé pour vérifier si le réseau fonctionne correctement. Si non défini, l'adresse par défaut du système sera utilisée. Si la vérification de l'adresse par défaut échoue, vous pouvez essayer de saisir une adresse personnalisée.\r\n- Vous pouvez entrer plusieurs adresses de détection, séparées par des virgules, telles que `8.8.8.8,https://www.bing.com`\r\n- S'il s'agit d'une adresse IP, la détection se fera par ping. S'il s'agit d'une adresse HTTP(s), la détection se fera par une requête HTTP GET.\r\n- Si vous souhaitez rétablir l'adresse de détection par défaut du système, veuillez entrer une virgule `,` et cliquer sur 'Suivant'.\r\n- **Cette configuration est globale et les modifications affecteront les autres instances d'intégration. Veuillez modifier avec prudence.**\r\n### Vérification des Dépendances Réseau\r\nVérifiez une par une les dépendances réseau suivantes pour voir si elles sont accessibles. Si les adresses associées ne sont pas accessibles, cela entraînera des problèmes d'intégration.\r\n- Adresse d'Authentification OAuth2: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Adresse de l'API HTTP de Xiaomi: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Adresse de l'API SPEC de Xiaomi: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Adresse du Broker MQTT de Xiaomi: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Adresse de Détection Réseau",
"check_network_deps": "Vérification des Dépendances Réseau"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "Le service de découverte de périphériques locaux est anormal.",
"get_cert_error": "Échec de l'obtention du certificat de la passerelle.",
"no_family_selected": "Aucune maison sélectionnée.",
"no_devices": "Il n'y a pas d'appareil dans la maison sélectionnée. Veuillez sélectionner une maison avec des appareils avant de continuer.",
"no_central_device": "Le mode gateway central a besoin d'un Xiaomi Gateway disponible dans le réseau local où se trouve Home Assistant. Veuillez vérifier si la maison sélectionnée répond à cette exigence."
"no_devices": "Il n'y a pas d'appareils dans la maison sélectionnée. Veuillez sélectionner une maison avec des appareils et continuer.",
"no_filter_devices": "Les appareils filtrés sont vides. Veuillez sélectionner des critères de filtre valides et continuer.",
"no_central_device": "Le mode gateway central a besoin d'un Xiaomi Gateway disponible dans le réseau local où se trouve Home Assistant. Veuillez vérifier si la maison sélectionnée répond à cette exigence.",
"invalid_network_addr": "Adresse IP ou HTTP invalide détectée, veuillez entrer une adresse valide.",
"invalid_ip_addr": "Adresse IP inaccessible détectée, veuillez entrer une adresse IP valide.",
"invalid_http_addr": "Adresse HTTP inaccessible détectée, veuillez entrer une adresse HTTP valide.",
"invalid_default_addr": "L'adresse de détection réseau par défaut est inaccessible, veuillez vérifier la configuration réseau ou utiliser une adresse de détection réseau personnalisée.",
"unreachable_oauth2_host": "Impossible d'atteindre l'adresse d'authentification OAuth2, veuillez vérifier la configuration réseau.",
"unreachable_http_host": "Impossible d'atteindre l'adresse de l'API HTTP de Xiaomi, veuillez vérifier la configuration réseau.",
"unreachable_spec_host": "Impossible d'atteindre l'adresse de l'API SPEC de Xiaomi, veuillez vérifier la configuration réseau.",
"unreachable_mqtt_broker": "Impossible d'atteindre l'adresse du Broker MQTT de Xiaomi, veuillez vérifier la configuration réseau."
},
"abort": {
"network_connect_error": "La configuration a échoué. Erreur de connexion réseau. Veuillez vérifier la configuration du réseau de l'appareil.",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "Options de configuration",
"description": "### {nick_name} Bonjour !\r\n\r\nID de compte Xiaomi : {uid}\r\nRégion de connexion actuelle : {cloud_server}\r\n\r\nVeuillez sélectionner les options que vous devez reconfigurer et cliquer sur \"Suivant\".",
"description": "### {nick_name} Bonjour !\r\n\r\nID de compte Xiaomi : {uid}\r\nRégion de connexion actuelle : {cloud_server}\r\nID d'Instance d'Intégration: {instance_id}\r\n\r\nVeuillez sélectionner les options que vous devez reconfigurer et cliquer sur \"Suivant\".",
"data": {
"integration_language": "Langue d'intégration",
"update_user_info": "Mettre à jour les informations utilisateur",
@ -102,7 +120,8 @@
"hide_non_standard_entities": "Masquer les entités générées non standard",
"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_lan_ctrl_config": "Mettre à jour la configuration de contrôle LAN",
"network_detect_config": "Configuration Réseau Intégrée"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "Activer la souscription"
}
},
"network_detect_config": {
"title": "Configuration Réseau Intégrée",
"description": "## Introduction à l'Utilisation\r\n### Adresse de Détection Réseau\r\nUtilisé pour vérifier si le réseau fonctionne correctement. Si non défini, l'adresse par défaut du système sera utilisée. Si la vérification de l'adresse par défaut échoue, vous pouvez essayer de saisir une adresse personnalisée.\r\n- Vous pouvez entrer plusieurs adresses de détection, séparées par des virgules, telles que `8.8.8.8,https://www.bing.com`\r\n- S'il s'agit d'une adresse IP, la détection se fera par ping. S'il s'agit d'une adresse HTTP(s), la détection se fera par une requête HTTP GET.\r\n- Si vous souhaitez rétablir l'adresse de détection par défaut du système, veuillez entrer une virgule `,` et cliquer sur 'Suivant'.\r\n- **Cette configuration est globale et les modifications affecteront les autres instances d'intégration. Veuillez modifier avec prudence.**\r\n### Vérification des Dépendances Réseau\r\nVérifiez une par une les dépendances réseau suivantes pour voir si elles sont accessibles. Si les adresses associées ne sont pas accessibles, cela entraînera des problèmes d'intégration.\r\n- Adresse d'Authentification OAuth2: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Adresse de l'API HTTP de Xiaomi: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Adresse de l'API SPEC de Xiaomi: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Adresse du Broker MQTT de Xiaomi: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Adresse de Détection Réseau",
"check_network_deps": "Vérification des Dépendances Réseau"
}
},
"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\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",
@ -168,11 +195,20 @@
"get_homeinfo_error": "Impossible d'obtenir les informations de la maison.",
"get_cert_error": "Impossible d'obtenir le certificat central.",
"no_family_selected": "Aucune maison sélectionnée.",
"no_devices": "Aucun périphérique dans la maison sélectionnée. Veuillez sélectionner une maison avec des périphériques et continuer.",
"no_devices": "Il n'y a pas d'appareils dans la maison sélectionnée. Veuillez sélectionner une maison avec des appareils et continuer.",
"no_filter_devices": "Les appareils filtrés sont vides. Veuillez sélectionner des critères de filtre valides et continuer.",
"no_central_device": "Le mode passerelle centrale nécessite une passerelle Xiaomi disponible dans le réseau local où est installé Home Assistant. Veuillez vérifier que la maison sélectionnée répond à cette exigence.",
"mdns_discovery_error": "Service de découverte de périphérique local en panne.",
"update_config_error": "Échec de la mise à jour des informations de configuration.",
"not_confirm": "La modification n'a pas été confirmée. Veuillez cocher la case de confirmation avant de soumettre."
"not_confirm": "La modification n'a pas été confirmée. Veuillez cocher la case de confirmation avant de soumettre.",
"invalid_network_addr": "Adresse IP ou HTTP invalide détectée, veuillez entrer une adresse valide.",
"invalid_ip_addr": "Adresse IP inaccessible détectée, veuillez entrer une adresse IP valide.",
"invalid_http_addr": "Adresse HTTP inaccessible détectée, veuillez entrer une adresse HTTP valide.",
"invalid_default_addr": "L'adresse de détection réseau par défaut est inaccessible, veuillez vérifier la configuration réseau ou utiliser une adresse de détection réseau personnalisée.",
"unreachable_oauth2_host": "Impossible d'atteindre l'adresse d'authentification OAuth2, veuillez vérifier la configuration réseau.",
"unreachable_http_host": "Impossible d'atteindre l'adresse de l'API HTTP de Xiaomi, veuillez vérifier la configuration réseau.",
"unreachable_spec_host": "Impossible d'atteindre l'adresse de l'API SPEC de Xiaomi, veuillez vérifier la configuration réseau.",
"unreachable_mqtt_broker": "Impossible d'atteindre l'adresse du Broker MQTT de Xiaomi, veuillez vérifier la configuration réseau."
},
"abort": {
"network_connect_error": "Échec de la configuration. Problème de connexion réseau, veuillez vérifier la configuration du périphérique.",

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "基本設定",
"description": "### ログインエリア\r\nXiaomi アカウントが属する地域を選択します。 `Xiaomi Home アプリ> マイ(ボトムメニューにあります)> その他の設定> Xiaomi Home について` で確認できます。\r\n### 言語\r\nデバイスおよびエンティティ名に使用される言語を選択します。一部の翻訳が欠落している場合、英語が表示されます。\r\n### OAuth2 認証リダイレクトアドレス\r\nOAuth2 認証リダイレクトアドレスは **[http://homeassistant.local:8123](http://homeassistant.local:8123)** です。Home Assistant は、現在の操作端末(たとえば、パーソナルコンピュータ)と同じ LAN 内にあり、操作端末がこのアドレスで Home Assistant ホームページにアクセスできる場合にのみログイン認証が成功する場合があります。\r\n### 注意事項\r\n- 数百台以上のMi Homeデバイスをお持ちのユーザーの場合、統合の初回追加には時間がかかります。しばらくお待ちください。\r\n- Home AssistantがDocker環境で実行されている場合は、Dockerのネットワークモードがhostに設定されていることを確認してください。そうしないと、ローカル制御機能が正しく動作しない可能性があります。\r\n- 統合のローカル制御機能にはいくつかの依存関係があります。READMEを注意深く読んでください。",
"description": "### ログインエリア\r\nXiaomi アカウントが属する地域を選択します。 `Xiaomi Home アプリ> マイ(ボトムメニューにあります)> その他の設定> Xiaomi Home について` で確認できます。\r\n### 言語\r\nデバイスおよびエンティティ名に使用される言語を選択します。一部の翻訳が欠落している場合、英語が表示されます。\r\n### OAuth2 認証リダイレクトアドレス\r\nOAuth2 認証リダイレクトアドレスは **[http://homeassistant.local:8123](http://homeassistant.local:8123)** です。Home Assistant は、現在の操作端末(たとえば、パーソナルコンピュータ)と同じ LAN 内にあり、操作端末がこのアドレスで Home Assistant ホームページにアクセスできる場合にのみログイン認証が成功する場合があります。\r\n### 統合ネットワーク構成\r\nローカルネットワークが正常に機能しているかどうか、および関連するネットワークリソースにアクセスできるかどうかを確認します。**初めて追加する場合は、これを選択することをお勧めします。**\r\n### 注意事項\r\n- 数百台以上のMi Homeデバイスをお持ちのユーザーの場合、統合の初回追加には時間がかかります。しばらくお待ちください。\r\n- Home AssistantがDocker環境で実行されている場合は、Dockerのネットワークモードがhostに設定されていることを確認してください。そうしないと、ローカル制御機能が正しく動作しない可能性があります。\r\n- 統合のローカル制御機能にはいくつかの依存関係があります。READMEを注意深く読んでください。",
"data": {
"cloud_server": "ログインエリア",
"integration_language": "言語",
"oauth_redirect_url": "認証リダイレクトアドレス"
"oauth_redirect_url": "認証リダイレクトアドレス",
"network_detect_config": "統合ネットワーク構成"
}
},
"network_detect_config": {
"title": "統合ネットワーク構成",
"description": "## 使用方法の紹介\r\n### ネットワーク検出アドレス\r\nネットワークが正常に機能しているかどうかを確認するために使用されます。設定されていない場合、システムのデフォルトアドレスが使用されます。デフォルトアドレスのチェックが失敗した場合は、カスタムアドレスを入力してみてください。\r\n- 複数の検出アドレスを入力できます。アドレスはコンマで区切ります。例:`8.8.8.8,https://www.bing.com`\r\n- IPアドレスの場合、pingによる検出が行われます。HTTP(s)アドレスの場合、HTTP GETリクエストによる検出が行われます。\r\n- システムのデフォルト検出アドレスを復元する場合は、カンマ `,` を入力して「次へ」をクリックしてください。\r\n- **この設定はグローバルであり、変更は他の統合インスタンスに影響を与えます。慎重に変更してください。**\r\n### ネットワーク依存関係のチェック\r\n次のネットワーク依存関係がアクセス可能かどうかを順番に確認します。関連するアドレスにアクセスできない場合、統合に問題が発生します。\r\n- OAuth2 認証アドレス: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Xiaomi HTTP API アドレス: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Xiaomi SPEC API アドレス: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Xiaomi MQTT ブローカーアドレス: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "ネットワーク検出アドレス",
"check_network_deps": "ネットワーク依存関係のチェック"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "ローカルデバイス検出サービスに異常があります。",
"get_cert_error": "ゲートウェイ証明書を取得できませんでした。",
"no_family_selected": "家庭が選択されていません。",
"no_devices": "選択された家庭にデバイスがありません。デバイスがある家庭を選択して続行してください。",
"no_central_device": "【中央ゲートウェイモード】Home Assistant が存在する LAN 内に使用可能な Xiaomi 中央ゲートウェイがある必要があります。選択された家庭がこの要件を満たしているかどうかを確認してください。"
"no_devices": "選択した家庭にはデバイスがありません。デバイスがある家庭を選択して続行してください。",
"no_filter_devices": "フィルタリングされたデバイスが空です。有効なフィルター条件を選択して続行してください。",
"no_central_device": "【中央ゲートウェイモード】Home Assistant が存在する LAN 内に使用可能な Xiaomi 中央ゲートウェイがある必要があります。選択された家庭がこの要件を満たしているかどうかを確認してください。",
"invalid_network_addr": "無効なIPアドレスまたはHTTPアドレスが検出されました。有効なアドレスを入力してください。",
"invalid_ip_addr": "アクセスできないIPアドレスが検出されました。有効なIPアドレスを入力してください。",
"invalid_http_addr": "アクセスできないHTTPアドレスが検出されました。有効なHTTPアドレスを入力してください。",
"invalid_default_addr": "デフォルトのネットワーク検出アドレスにアクセスできません。ネットワーク設定を確認するか、カスタムネットワーク検出アドレスを使用してください。",
"unreachable_oauth2_host": "OAuth2 認証アドレスにアクセスできません。ネットワーク設定を確認してください。",
"unreachable_http_host": "Xiaomi HTTP API アドレスにアクセスできません。ネットワーク設定を確認してください。",
"unreachable_spec_host": "Xiaomi SPEC API アドレスにアクセスできません。ネットワーク設定を確認してください。",
"unreachable_mqtt_broker": "Xiaomi MQTT ブローカーアドレスにアクセスできません。ネットワーク設定を確認してください。"
},
"abort": {
"network_connect_error": "設定に失敗しました。ネットワーク接続に異常があります。デバイスのネットワーク設定を確認してください。",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "設定オプション",
"description": "### {nick_name} さん、こんにちは!\r\n\r\nXiaomi アカウントID{uid}\r\n現在のログインエリア{cloud_server}\r\n\r\n必要な構成オプションを選択して、[次へ] をクリックしてください。",
"description": "### {nick_name} さん、こんにちは!\r\n\r\nXiaomi アカウントID{uid}\r\n現在のログインエリア{cloud_server}\r\n統合インスタンスID: {instance_id}\r\n\r\n必要な構成オプションを選択して、[次へ] をクリックしてください。",
"data": {
"integration_language": "統合言語",
"update_user_info": "ユーザー情報を更新する",
@ -102,7 +120,8 @@
"hide_non_standard_entities": "非標準生成エンティティを非表示にする",
"display_devices_changed_notify": "デバイスの状態変化通知を表示",
"update_trans_rules": "エンティティ変換ルールを更新する",
"update_lan_ctrl_config": "LAN制御構成を更新する"
"update_lan_ctrl_config": "LAN制御構成を更新する",
"network_detect_config": "統合ネットワーク構成"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "LANサブスクリプションを有効にする"
}
},
"network_detect_config": {
"title": "統合ネットワーク構成",
"description": "## 使用方法の紹介\r\n### ネットワーク検出アドレス\r\nネットワークが正常に機能しているかどうかを確認するために使用されます。設定されていない場合、システムのデフォルトアドレスが使用されます。デフォルトアドレスのチェックが失敗した場合は、カスタムアドレスを入力してみてください。\r\n- 複数の検出アドレスを入力できます。アドレスはコンマで区切ります。例:`8.8.8.8,https://www.bing.com`\r\n- IPアドレスの場合、pingによる検出が行われます。HTTP(s)アドレスの場合、HTTP GETリクエストによる検出が行われます。\r\n- システムのデフォルト検出アドレスを復元する場合は、カンマ `,` を入力して「次へ」をクリックしてください。\r\n- **この設定はグローバルであり、変更は他の統合インスタンスに影響を与えます。慎重に変更してください。**\r\n### ネットワーク依存関係のチェック\r\n次のネットワーク依存関係がアクセス可能かどうかを順番に確認します。関連するアドレスにアクセスできない場合、統合に問題が発生します。\r\n- OAuth2 認証アドレス: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Xiaomi HTTP API アドレス: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Xiaomi SPEC API アドレス: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Xiaomi MQTT ブローカーアドレス: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "ネットワーク検出アドレス",
"check_network_deps": "ネットワーク依存関係のチェック"
}
},
"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{display_devices_changed_notify}\r\nデバイス変更\t追加 **{devices_add}** 個のデバイス、削除 **{devices_remove}** 個のデバイス\r\n変換ルール変更\t合計 **{trans_rules_count}** 個の規則、更新 **{trans_rules_count_success}** 個の規則",
@ -168,11 +195,20 @@
"get_homeinfo_error": "家庭情報の取得に失敗しました。",
"get_cert_error": "中枢証明書の取得に失敗しました。",
"no_family_selected": "家族が選択されていません。",
"no_devices": "選択された家庭にはデバイスがありません。デバイスがある家庭を選択してから続行してください。",
"no_devices": "選択した家庭にはデバイスがありません。デバイスがある家庭を選択して続行してください。",
"no_filter_devices": "フィルタリングされたデバイスが空です。有効なフィルター条件を選択して続行してください。",
"no_central_device": "【中枢ゲートウェイモード】には、Home Assistantが存在するローカルネットワークに使用可能なXiaomi Central Hub Gatewayが存在する必要があります。選択された家庭がこの要件を満たしているかどうかを確認してください。",
"mdns_discovery_error": "ローカルデバイス発見サービスが異常です。",
"update_config_error": "構成情報の更新に失敗しました。",
"not_confirm": "変更を確認していません。確認をチェックしてから送信してください。"
"not_confirm": "変更を確認していません。確認をチェックしてから送信してください。",
"invalid_network_addr": "無効なIPアドレスまたはHTTPアドレスが検出されました。有効なアドレスを入力してください。",
"invalid_ip_addr": "アクセスできないIPアドレスが検出されました。有効なIPアドレスを入力してください。",
"invalid_http_addr": "アクセスできないHTTPアドレスが検出されました。有効なHTTPアドレスを入力してください。",
"invalid_default_addr": "デフォルトのネットワーク検出アドレスにアクセスできません。ネットワーク設定を確認するか、カスタムネットワーク検出アドレスを使用してください。",
"unreachable_oauth2_host": "OAuth2 認証アドレスにアクセスできません。ネットワーク設定を確認してください。",
"unreachable_http_host": "Xiaomi HTTP API アドレスにアクセスできません。ネットワーク設定を確認してください。",
"unreachable_spec_host": "Xiaomi SPEC API アドレスにアクセスできません。ネットワーク設定を確認してください。",
"unreachable_mqtt_broker": "Xiaomi MQTT ブローカーアドレスにアクセスできません。ネットワーク設定を確認してください。"
},
"abort": {
"network_connect_error": "構成に失敗しました。ネットワーク接続に異常があります。デバイスのネットワーク構成を確認してください。",

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "Basisconfiguratie",
"description": "### Inlogregio\r\nSelecteer de regio van uw Xiaomi-account. U kunt deze vinden in de Xiaomi Home APP > Profiel (onderin het menu) > Extra instellingen > Over Xiaomi Home.\r\n### Taal\r\nKies de taal voor de apparaats- en entiteitsnamen. Sommige zinnen zonder vertaling worden in het Engels weergegeven.\r\n### OAuth2 Omleidings-URL\r\nHet OAuth2 authenticatie omleidingsadres is **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. Home Assistant moet zich in hetzelfde lokale netwerk bevinden als de huidige werkterminal (bijv. de persoonlijke computer) en de werkterminal moet toegang hebben tot de startpagina van Home Assistant via dit adres. Anders kan de inlogauthenticatie mislukken.\r\n### Opmerking\r\n- Voor gebruikers met honderden of meer Mi Home-apparaten kan het aanvankelijke toevoegen van de integratie enige tijd duren. Wees geduldig.\r\n- Als Home Assistant draait in een Docker-omgeving, zorg er dan voor dat de Docker-netwerkmodus is ingesteld op host, anders werkt de lokale controlefunctionaliteit mogelijk niet correct.\r\n- De lokale controlefunctionaliteit van de integratie heeft enkele afhankelijkheden. Lees het README zorgvuldig.",
"description": "### Inlogregio\r\nSelecteer de regio van uw Xiaomi-account. U kunt deze vinden in de Xiaomi Home APP > Profiel (onderin het menu) > Extra instellingen > Over Xiaomi Home.\r\n### Taal\r\nKies de taal voor de apparaats- en entiteitsnamen. Sommige zinnen zonder vertaling worden in het Engels weergegeven.\r\n### OAuth2 Omleidings-URL\r\nHet OAuth2 authenticatie omleidingsadres is **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. Home Assistant moet zich in hetzelfde lokale netwerk bevinden als de huidige werkterminal (bijv. de persoonlijke computer) en de werkterminal moet toegang hebben tot de startpagina van Home Assistant via dit adres. Anders kan de inlogauthenticatie mislukken.\r\n### Geïntegreerde Netwerkconfiguratie\r\nControleer of het lokale netwerk correct functioneert en of de gerelateerde netwerkbronnen toegankelijk zijn. **Het wordt aanbevolen om dit te selecteren bij het eerste toevoegen.**\r\n### Opmerking\r\n- Voor gebruikers met honderden of meer Mi Home-apparaten kan het aanvankelijke toevoegen van de integratie enige tijd duren. Wees geduldig.\r\n- Als Home Assistant draait in een Docker-omgeving, zorg er dan voor dat de Docker-netwerkmodus is ingesteld op host, anders werkt de lokale controlefunctionaliteit mogelijk niet correct.\r\n- De lokale controlefunctionaliteit van de integratie heeft enkele afhankelijkheden. Lees het README zorgvuldig.",
"data": {
"cloud_server": "Inlogregio",
"integration_language": "Taal",
"oauth_redirect_url": "OAuth2 Omleidings-URL"
"oauth_redirect_url": "OAuth2 Omleidings-URL",
"network_detect_config": "Geïntegreerde Netwerkconfiguratie"
}
},
"network_detect_config": {
"title": "Geïntegreerde Netwerkconfiguratie",
"description": "## Gebruiksinstructie\r\n### Netwerkdetectieadres\r\nWordt gebruikt om te controleren of het netwerk correct functioneert. Als dit niet is ingesteld, wordt het standaardadres van het systeem gebruikt. Als de standaardadrescontrole mislukt, kunt u proberen een aangepast adres in te voeren.\r\n- U kunt meerdere detectieadressen invoeren, gescheiden door komma's, zoals `8.8.8.8,https://www.bing.com`\r\n- Als het een IP-adres is, wordt de detectie uitgevoerd via ping. Als het een HTTP(s)-adres is, wordt de detectie uitgevoerd via een HTTP GET-verzoek.\r\n- Als u het standaarddetectieadres van het systeem wilt herstellen, voert u een komma `,` in en klikt u op 'Volgende'.\r\n- **Deze configuratie is globaal en wijzigingen zullen andere integratie-instanties beïnvloeden. Wijzig met voorzichtigheid.**\r\n### Controleer Netwerkafhankelijkheden\r\nControleer een voor een de volgende netwerkafhankelijkheden om te zien of ze toegankelijk zijn. Als de gerelateerde adressen niet toegankelijk zijn, zal dit integratieproblemen veroorzaken.\r\n- OAuth2-authenticatieadres: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Xiaomi HTTP API-adres: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Xiaomi SPEC API-adres: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Xiaomi MQTT Broker-adres: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Netwerkdetectieadres",
"check_network_deps": "Controleer Netwerkafhankelijkheden"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "Lokaal apparaatsontdekkingsservice-exceptie.",
"get_cert_error": "Mislukt bij het ophalen van het certificaat van de centrale hubgateway.",
"no_family_selected": "Geen huis geselecteerd.",
"no_devices": "Het geselecteerde huis heeft geen apparaten. Kies a.u.b. een huis met apparaten en ga verder.",
"no_central_device": "[Centrale Hub Gateway Modus] vereist een beschikbare Xiaomi centrale hubgateway in het lokale netwerk waar Home Assistant zich bevindt. Controleer of het geselecteerde huis aan deze vereiste voldoet."
"no_devices": "Er zijn geen apparaten in het geselecteerde huis. Selecteer een huis met apparaten en ga verder.",
"no_filter_devices": "Gefilterde apparaten zijn leeg. Selecteer geldige filtercriteria en ga verder.",
"no_central_device": "[Centrale Hub Gateway Modus] vereist een beschikbare Xiaomi centrale hubgateway in het lokale netwerk waar Home Assistant zich bevindt. Controleer of het geselecteerde huis aan deze vereiste voldoet.",
"invalid_network_addr": "Ongeldig IP-adres of HTTP-adres gedetecteerd, voer een geldig adres in.",
"invalid_ip_addr": "Onbereikbaar IP-adres gedetecteerd, voer een geldig IP-adres in.",
"invalid_http_addr": "Onbereikbaar HTTP-adres gedetecteerd, voer een geldig HTTP-adres in.",
"invalid_default_addr": "Standaard netwerkdetectieadres is onbereikbaar, controleer de netwerkconfiguratie of gebruik een aangepast netwerkdetectieadres.",
"unreachable_oauth2_host": "Kan OAuth2-authenticatieadres niet bereiken, controleer de netwerkconfiguratie.",
"unreachable_http_host": "Kan Xiaomi HTTP API-adres niet bereiken, controleer de netwerkconfiguratie.",
"unreachable_spec_host": "Kan Xiaomi SPEC API-adres niet bereiken, controleer de netwerkconfiguratie.",
"unreachable_mqtt_broker": "Kan Xiaomi MQTT Broker-adres niet bereiken, controleer de netwerkconfiguratie."
},
"abort": {
"network_connect_error": "Configuratie mislukt. De netwerkverbinding is abnormaal. Controleer de netwerkinstellingen van de apparatuur.",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "Configuratie-opties",
"description": "### Hallo, {nick_name}\r\n\r\nXiaomi ID: {uid}\r\nHuidige inlogregio: {cloud_server}\r\n\r\nKies de opties die u wilt configureren en klik vervolgens op VOLGENDE.",
"description": "### Hallo, {nick_name}\r\n\r\nXiaomi ID: {uid}\r\nHuidige inlogregio: {cloud_server}\r\nIntegratie-instantie-ID: {instance_id}\r\n\r\nKies de opties die u wilt configureren en klik vervolgens op VOLGENDE.",
"data": {
"integration_language": "Integratietaal",
"update_user_info": "Werk gebruikersinformatie bij",
@ -102,7 +120,8 @@
"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"
"update_lan_ctrl_config": "Werk LAN controleconfiguratie bij",
"network_detect_config": "Geïntegreerde Netwerkconfiguratie"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "Zet LAN-abonnement aan"
}
},
"network_detect_config": {
"title": "Geïntegreerde Netwerkconfiguratie",
"description": "## Gebruiksinstructie\r\n### Netwerkdetectieadres\r\nWordt gebruikt om te controleren of het netwerk correct functioneert. Als dit niet is ingesteld, wordt het standaardadres van het systeem gebruikt. Als de standaardadrescontrole mislukt, kunt u proberen een aangepast adres in te voeren.\r\n- U kunt meerdere detectieadressen invoeren, gescheiden door komma's, zoals `8.8.8.8,https://www.bing.com`\r\n- Als het een IP-adres is, wordt de detectie uitgevoerd via ping. Als het een HTTP(s)-adres is, wordt de detectie uitgevoerd via een HTTP GET-verzoek.\r\n- Als u het standaarddetectieadres van het systeem wilt herstellen, voert u een komma `,` in en klikt u op 'Volgende'.\r\n- **Deze configuratie is globaal en wijzigingen zullen andere integratie-instanties beïnvloeden. Wijzig met voorzichtigheid.**\r\n### Controleer Netwerkafhankelijkheden\r\nControleer een voor een de volgende netwerkafhankelijkheden om te zien of ze toegankelijk zijn. Als de gerelateerde adressen niet toegankelijk zijn, zal dit integratieproblemen veroorzaken.\r\n- OAuth2-authenticatieadres: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Xiaomi HTTP API-adres: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Xiaomi SPEC API-adres: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Xiaomi MQTT Broker-adres: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Netwerkdetectieadres",
"check_network_deps": "Controleer Netwerkafhankelijkheden"
}
},
"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\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",
@ -167,12 +194,21 @@
"get_token_error": "Mislukt bij het ophalen van inlogautorisatie-informatie (OAuth-token).",
"get_homeinfo_error": "Mislukt bij het ophalen van huisinformatie.",
"get_cert_error": "Mislukt bij het ophalen van het certificaat van de centrale hubgateway.",
"no_devices": "Het geselecteerde huis heeft geen apparaten. Kies a.u.b. een huis met apparaten en ga verder.",
"no_devices": "Er zijn geen apparaten in het geselecteerde huis. Selecteer een huis met apparaten en ga verder.",
"no_filter_devices": "Gefilterde apparaten zijn leeg. Selecteer geldige filtercriteria en ga verder.",
"no_family_selected": "Geen huis geselecteerd.",
"no_central_device": "[Centrale Hub Gateway Modus] vereist een beschikbare Xiaomi centrale hubgateway in het lokale netwerk waar Home Assistant zich bevindt. Controleer of het geselecteerde huis aan deze vereiste voldoet.",
"mdns_discovery_error": "Lokaal apparaatsontdekkingsservice-exceptie.",
"update_config_error": "Mislukt bij het bijwerken van configuratie-informatie.",
"not_confirm": "Wijzigingen zijn niet bevestigd. Bevestig de wijziging voordat u deze indient."
"not_confirm": "Wijzigingen zijn niet bevestigd. Bevestig de wijziging voordat u deze indient.",
"invalid_network_addr": "Ongeldig IP-adres of HTTP-adres gedetecteerd, voer een geldig adres in.",
"invalid_ip_addr": "Onbereikbaar IP-adres gedetecteerd, voer een geldig IP-adres in.",
"invalid_http_addr": "Onbereikbaar HTTP-adres gedetecteerd, voer een geldig HTTP-adres in.",
"invalid_default_addr": "Standaard netwerkdetectieadres is onbereikbaar, controleer de netwerkconfiguratie of gebruik een aangepast netwerkdetectieadres.",
"unreachable_oauth2_host": "Kan OAuth2-authenticatieadres niet bereiken, controleer de netwerkconfiguratie.",
"unreachable_http_host": "Kan Xiaomi HTTP API-adres niet bereiken, controleer de netwerkconfiguratie.",
"unreachable_spec_host": "Kan Xiaomi SPEC API-adres niet bereiken, controleer de netwerkconfiguratie.",
"unreachable_mqtt_broker": "Kan Xiaomi MQTT Broker-adres niet bereiken, controleer de netwerkconfiguratie."
},
"abort": {
"network_connect_error": "Configuratie mislukt. De netwerkverbinding is abnormaal. Controleer de netwerkinstellingen van de apparatuur.",

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "Configuração básica",
"description": "### Região de Login\r\nSelecione a região da sua conta Xiaomi. Você pode encontrá-la no aplicativo Xiaomi Home > Perfil (localizado no menu inferior) > Configurações adicionais > Sobre o Xiaomi Home.\r\n### Idioma\r\nSelecione o idioma dos nomes dos dispositivos e entidades. Algumas frases sem tradução serão exibidas em inglês.\r\n### URL de Redirecionamento OAuth2\r\nO endereço de redirecionamento da autenticação OAuth2 é **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. O Home Assistant precisa estar na mesma rede local que o terminal atual (por exemplo, o computador pessoal) e o terminal precisa acessar a página inicial do Home Assistant através desse endereço. Caso contrário, a autenticação de login pode falhar.\r\n### Observações\r\n- Para usuários com centenas ou mais dispositivos Mi Home, a adição inicial da integração levará algum tempo. Seja paciente.\r\n- Se o Home Assistant estiver sendo executado em um ambiente Docker, certifique-se de que o modo de rede do Docker esteja definido como host, caso contrário a funcionalidade de controle local pode não funcionar corretamente.\r\n- A funcionalidade de controle local da integração tem algumas dependências. Por favor, leia o README atentamente.",
"description": "### Região de Login\r\nSelecione a região da sua conta Xiaomi. Você pode encontrá-la no aplicativo Xiaomi Home > Perfil (localizado no menu inferior) > Configurações adicionais > Sobre o Xiaomi Home.\r\n### Idioma\r\nSelecione o idioma dos nomes dos dispositivos e entidades. Algumas frases sem tradução serão exibidas em inglês.\r\n### URL de Redirecionamento OAuth2\r\nO endereço de redirecionamento da autenticação OAuth2 é **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. O Home Assistant precisa estar na mesma rede local que o terminal atual (por exemplo, o computador pessoal) e o terminal precisa acessar a página inicial do Home Assistant através desse endereço. Caso contrário, a autenticação de login pode falhar.\r\n### Configuração de Rede Integrada\r\nVerifique se a rede local está funcionando corretamente e se os recursos de rede relacionados estão acessíveis. **Recomenda-se selecionar isso ao adicionar pela primeira vez.**\r\n### Observações\r\n- Para usuários com centenas ou mais dispositivos Mi Home, a adição inicial da integração levará algum tempo. Seja paciente.\r\n- Se o Home Assistant estiver sendo executado em um ambiente Docker, certifique-se de que o modo de rede do Docker esteja definido como host, caso contrário a funcionalidade de controle local pode não funcionar corretamente.\r\n- A funcionalidade de controle local da integração tem algumas dependências. Por favor, leia o README atentamente.",
"data": {
"cloud_server": "Região de Login",
"integration_language": "Idioma",
"oauth_redirect_url": "URL de Redirecionamento OAuth2"
"oauth_redirect_url": "URL de Redirecionamento OAuth2",
"network_detect_config": "Configuração de Rede Integrada"
}
},
"network_detect_config": {
"title": "Configuração de Detecção de Rede",
"description": "## Introdução ao Uso\r\n### Endereço de Detecção de Rede\r\nUsado para verificar se a rede está funcionando corretamente. Se não for definido, o endereço padrão do sistema será usado. Se a verificação do endereço padrão falhar, você pode tentar inserir um endereço personalizado.\r\n- Você pode inserir vários endereços de detecção, separados por vírgulas, como `8.8.8.8,https://www.bing.com`\r\n- Se for um endereço IP, a detecção será feita via ping. Se for um endereço HTTP(s), a detecção será feita via solicitação HTTP GET.\r\n- Se você deseja restaurar o endereço de detecção padrão do sistema, insira uma vírgula `,` e clique em 'Próximo'.\r\n- **Esta configuração é global e as alterações afetarão outras instâncias de integração. Modifique com cautela.**\r\n### Verificar Dependências de Rede\r\nVerifique uma por uma as seguintes dependências de rede para ver se são acessíveis. Se os endereços relacionados não forem acessíveis, isso causará problemas de integração.\r\n- Endereço de Autenticação OAuth2: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Endereço da API HTTP da Xiaomi: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Endereço da API SPEC da Xiaomi: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Endereço do Broker MQTT da Xiaomi: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Endereço de Detecção de Rede",
"check_network_deps": "Verificar Dependências de Rede"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "Exceção no serviço de descoberta de dispositivos locais.",
"get_cert_error": "Falha ao obter o certificado do gateway central.",
"no_family_selected": "Nenhuma casa selecionada.",
"no_devices": "A casa selecionada não possui nenhum dispositivo. Por favor, escolha uma casa que contenha dispositivos e continue.",
"no_central_device": "[Modo Gateway Central] requer um gateway central Xiaomi disponível na rede local onde o Home Assistant está. Verifique se a casa selecionada atende a esse requisito."
"no_devices": "Não há dispositivos na casa selecionada. Por favor, selecione uma casa com dispositivos e continue.",
"no_filter_devices": "Os dispositivos filtrados estão vazios. Por favor, selecione critérios de filtro válidos e continue.",
"no_central_device": "[Modo Gateway Central] requer um gateway central Xiaomi disponível na rede local onde o Home Assistant está. Verifique se a casa selecionada atende a esse requisito.",
"invalid_network_addr": "Endereço IP ou HTTP inválido detectado, por favor insira um endereço válido.",
"invalid_ip_addr": "Endereço IP inacessível detectado, por favor insira um endereço IP válido.",
"invalid_http_addr": "Endereço HTTP inacessível detectado, por favor insira um endereço HTTP válido.",
"invalid_default_addr": "O endereço de detecção de rede padrão está inacessível, por favor verifique a configuração da rede ou use um endereço de detecção de rede personalizado.",
"unreachable_oauth2_host": "Não é possível acessar o endereço de autenticação OAuth2, verifique a configuração da rede.",
"unreachable_http_host": "Não é possível acessar o endereço da API HTTP da Xiaomi, verifique a configuração da rede.",
"unreachable_spec_host": "Não é possível acessar o endereço da API SPEC da Xiaomi, verifique a configuração da rede.",
"unreachable_mqtt_broker": "Não é possível acessar o endereço do Broker MQTT da Xiaomi, verifique a configuração da rede."
},
"abort": {
"network_connect_error": "Configuração falhou. A conexão de rede está anormal. Verifique a configuração de rede do equipamento.",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "Opções de Configuração",
"description": "### Olá, {nick_name}\r\n\r\nID Xiaomi: {uid}\r\nRegião de Login Atual: {cloud_server}\r\n\r\nSelecione as opções que você deseja configurar e clique em AVANÇAR.",
"description": "### Olá, {nick_name}\r\n\r\nID Xiaomi: {uid}\r\nRegião de Login Atual: {cloud_server}\r\nID da Instância de Integração: {instance_id}\r\n\r\nSelecione as opções que você deseja configurar e clique em AVANÇAR.",
"data": {
"integration_language": "Idioma da Integração",
"update_user_info": "Atualizar informações do usuário",
@ -102,7 +120,8 @@
"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"
"update_lan_ctrl_config": "Atualizar configuração de controle LAN",
"network_detect_config": "Configuração de Rede Integrada"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "Habilitar assinatura LAN"
}
},
"network_detect_config": {
"title": "Configuração de Detecção de Rede",
"description": "## Introdução ao Uso\r\n### Endereço de Detecção de Rede\r\nUsado para verificar se a rede está funcionando corretamente. Se não for definido, o endereço padrão do sistema será usado. Se a verificação do endereço padrão falhar, você pode tentar inserir um endereço personalizado.\r\n- Você pode inserir vários endereços de detecção, separados por vírgulas, como `8.8.8.8,https://www.bing.com`\r\n- Se for um endereço IP, a detecção será feita via ping. Se for um endereço HTTP(s), a detecção será feita via solicitação HTTP GET.\r\n- Se você deseja restaurar o endereço de detecção padrão do sistema, insira uma vírgula `,` e clique em 'Próximo'.\r\n- **Esta configuração é global e as alterações afetarão outras instâncias de integração. Modifique com cautela.**\r\n### Verificar Dependências de Rede\r\nVerifique uma por uma as seguintes dependências de rede para ver se são acessíveis. Se os endereços relacionados não forem acessíveis, isso causará problemas de integração.\r\n- Endereço de Autenticação OAuth2: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Endereço da API HTTP da Xiaomi: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Endereço da API SPEC da Xiaomi: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Endereço do Broker MQTT da Xiaomi: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Endereço de Detecção de Rede",
"check_network_deps": "Verificar Dependências de Rede"
}
},
"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\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",
@ -167,12 +194,21 @@
"get_token_error": "Falha ao obter as informações de autorização de login (token OAuth).",
"get_homeinfo_error": "Falha ao obter as informações da casa.",
"get_cert_error": "Falha ao obter o certificado do gateway central.",
"no_devices": "A casa selecionada não possui nenhum dispositivo. Por favor, escolha uma casa com dispositivos e continue.",
"no_devices": "Não há dispositivos na casa selecionada. Por favor, selecione uma casa com dispositivos e continue.",
"no_filter_devices": "Os dispositivos filtrados estão vazios. Por favor, selecione critérios de filtro válidos e continue.",
"no_family_selected": "Nenhuma casa selecionada.",
"no_central_device": "[Modo Gateway Central] requer um gateway central Xiaomi disponível na rede local onde o Home Assistant está. Verifique se a casa selecionada atende a esse requisito.",
"mdns_discovery_error": "Exceção no serviço de descoberta de dispositivos locais.",
"update_config_error": "Falha ao atualizar as informações de configuração.",
"not_confirm": "As alterações não foram confirmadas. Por favor, confirme a mudança antes de enviar."
"not_confirm": "As alterações não foram confirmadas. Por favor, confirme a mudança antes de enviar.",
"invalid_network_addr": "Endereço IP ou HTTP inválido detectado, por favor insira um endereço válido.",
"invalid_ip_addr": "Endereço IP inacessível detectado, por favor insira um endereço IP válido.",
"invalid_http_addr": "Endereço HTTP inacessível detectado, por favor insira um endereço HTTP válido.",
"invalid_default_addr": "O endereço de detecção de rede padrão está inacessível, por favor verifique a configuração da rede ou use um endereço de detecção de rede personalizado.",
"unreachable_oauth2_host": "Não é possível acessar o endereço de autenticação OAuth2, verifique a configuração da rede.",
"unreachable_http_host": "Não é possível acessar o endereço da API HTTP da Xiaomi, verifique a configuração da rede.",
"unreachable_spec_host": "Não é possível acessar o endereço da API SPEC da Xiaomi, verifique a configuração da rede.",
"unreachable_mqtt_broker": "Não é possível acessar o endereço do Broker MQTT da Xiaomi, verifique a configuração da rede."
},
"abort": {
"network_connect_error": "Configuração falhou. A conexão de rede está anormal. Verifique a configuração da rede do equipamento.",

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "Configuração Básica",
"description": "### Região de Login\r\nSelecione a região da sua conta Xiaomi. Pode encontrá-la na aplicação Xiaomi Home > Perfil (menu inferior) > Configurações adicionais > Sobre o Xiaomi Home.\r\n### Idioma\r\nSelecione o idioma para os nomes de dispositivos e entidades. Algumas frases sem tradução serão apresentadas em inglês.\r\n### URL de Redirecionamento OAuth2\r\nO endereço de redirecionamento para a autenticação OAuth2 é **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. O Home Assistant deve estar na mesma rede local que o terminal atual (por exemplo, o computador pessoal) e esse terminal deve conseguir aceder à página inicial do Home Assistant através deste endereço. Caso contrário, a autenticação de login pode falhar.\r\n### Notas\r\n- Para utilizadores com centenas (ou mais) de dispositivos Mi Home, a adição inicial da integração demorará algum tempo. Seja paciente.\r\n- Se o Home Assistant estiver a ser executado num ambiente Docker, assegure-se de que o modo de rede do Docker está configurado como host; caso contrário, a funcionalidade de controlo local pode não funcionar corretamente.\r\n- A funcionalidade de controlo local da integração tem algumas dependências. Leia cuidadosamente o README.",
"description": "### Região de Login\r\nSelecione a região da sua conta Xiaomi. Pode encontrá-la na aplicação Xiaomi Home > Perfil (menu inferior) > Configurações adicionais > Sobre o Xiaomi Home.\r\n### Idioma\r\nSelecione o idioma para os nomes de dispositivos e entidades. Algumas frases sem tradução serão apresentadas em inglês.\r\n### URL de Redirecionamento OAuth2\r\nO endereço de redirecionamento para a autenticação OAuth2 é **[http://homeassistant.local:8123](http://homeassistant.local:8123)**. O Home Assistant deve estar na mesma rede local que o terminal atual (por exemplo, o computador pessoal) e esse terminal deve conseguir aceder à página inicial do Home Assistant através deste endereço. Caso contrário, a autenticação de login pode falhar.\r\n### Configuração de Rede Integrada\r\nVerifique se a rede local está funcionando corretamente e se os recursos de rede relacionados estão acessíveis. **Recomenda-se selecionar isso ao adicionar pela primeira vez.**\r\n### Notas\r\n- Para utilizadores com centenas (ou mais) de dispositivos Mi Home, a adição inicial da integração demorará algum tempo. Seja paciente.\r\n- Se o Home Assistant estiver a ser executado num ambiente Docker, assegure-se de que o modo de rede do Docker está configurado como host; caso contrário, a funcionalidade de controlo local pode não funcionar corretamente.\r\n- A funcionalidade de controlo local da integração tem algumas dependências. Leia cuidadosamente o README.",
"data": {
"cloud_server": "Região de Login",
"integration_language": "Idioma",
"oauth_redirect_url": "URL de Redirecionamento OAuth2"
"oauth_redirect_url": "URL de Redirecionamento OAuth2",
"network_detect_config": "Configuração de Rede Integrada"
}
},
"network_detect_config": {
"title": "Configuração de Rede Integrada",
"description": "## Introdução ao Uso\r\n### Endereço de Detecção de Rede\r\nUsado para verificar se a rede está funcionando corretamente. Se não for definido, o endereço padrão do sistema será usado. Se a verificação do endereço padrão falhar, você pode tentar inserir um endereço personalizado.\r\n- Você pode inserir vários endereços de detecção, separados por vírgulas, como `8.8.8.8,https://www.bing.com`\r\n- Se for um endereço IP, a detecção será feita via ping. Se for um endereço HTTP(s), a detecção será feita via solicitação HTTP GET.\r\n- Se você deseja restaurar o endereço de detecção padrão do sistema, insira uma vírgula `,` e clique em 'Próximo'.\r\n- **Esta configuração é global e as alterações afetarão outras instâncias de integração. Modifique com cautela.**\r\n### Verificar Dependências de Rede\r\nVerifique uma por uma as seguintes dependências de rede para ver se são acessíveis. Se os endereços relacionados não forem acessíveis, isso causará problemas de integração.\r\n- Endereço de Autenticação OAuth2: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Endereço da API HTTP da Xiaomi: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Endereço da API SPEC da Xiaomi: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Endereço do Broker MQTT da Xiaomi: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Endereço de Detecção de Rede",
"check_network_deps": "Verificar Dependências de Rede"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "Exceção no serviço de descoberta de dispositivos locais.",
"get_cert_error": "Não foi possível obter o certificado do gateway central.",
"no_family_selected": "Nenhuma casa selecionada.",
"no_devices": "A casa selecionada não possui quaisquer dispositivos. Por favor, selecione uma casa que contenha dispositivos e continue.",
"no_central_device": "O [Modo Gateway Central] requer um gateway central Xiaomi disponível na rede local onde o Home Assistant está. Verifique se a casa selecionada cumpre este requisito."
"no_devices": "Não há dispositivos na casa selecionada. Por favor, selecione uma casa com dispositivos e continue.",
"no_filter_devices": "Os dispositivos filtrados estão vazios. Por favor, selecione critérios de filtro válidos e continue.",
"no_central_device": "O [Modo Gateway Central] requer um gateway central Xiaomi disponível na rede local onde o Home Assistant está. Verifique se a casa selecionada cumpre este requisito.",
"invalid_network_addr": "Endereço IP ou HTTP inválido detectado, por favor insira um endereço válido.",
"invalid_ip_addr": "Endereço IP inacessível detectado, por favor insira um endereço IP válido.",
"invalid_http_addr": "Endereço HTTP inacessível detectado, por favor insira um endereço HTTP válido.",
"invalid_default_addr": "O endereço de detecção de rede padrão está inacessível, por favor verifique a configuração da rede ou use um endereço de detecção de rede personalizado.",
"unreachable_oauth2_host": "Não é possível acessar o endereço de autenticação OAuth2, verifique a configuração da rede.",
"unreachable_http_host": "Não é possível acessar o endereço da API HTTP da Xiaomi, verifique a configuração da rede.",
"unreachable_spec_host": "Não é possível acessar o endereço da API SPEC da Xiaomi, verifique a configuração da rede.",
"unreachable_mqtt_broker": "Não é possível acessar o endereço do Broker MQTT da Xiaomi, verifique a configuração da rede."
},
"abort": {
"network_connect_error": "A configuração falhou. A ligação de rede é anormal. Verifique a configuração de rede do equipamento.",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "Opções de Configuração",
"description": "### Olá, {nick_name}\r\n\r\nID Xiaomi: {uid}\r\nRegião de Login Atual: {cloud_server}\r\n\r\nSelecione as opções que pretende configurar e depois clique em SEGUINTE.",
"description": "### Olá, {nick_name}\r\n\r\nID Xiaomi: {uid}\r\nRegião de Login Atual: {cloud_server}\r\nID da Instância de Integração: {instance_id}\r\n\r\nSelecione as opções que pretende configurar e depois clique em SEGUINTE.",
"data": {
"integration_language": "Idioma da Integração",
"update_user_info": "Atualizar informação do utilizador",
@ -102,7 +120,8 @@
"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"
"update_lan_ctrl_config": "Atualizar configuração de controlo LAN",
"network_detect_config": "Configuração de Rede Integrada"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "Ativar subscrição LAN"
}
},
"network_detect_config": {
"title": "Configuração de Rede Integrada",
"description": "## Introdução ao Uso\r\n### Endereço de Detecção de Rede\r\nUsado para verificar se a rede está funcionando corretamente. Se não for definido, o endereço padrão do sistema será usado. Se a verificação do endereço padrão falhar, você pode tentar inserir um endereço personalizado.\r\n- Você pode inserir vários endereços de detecção, separados por vírgulas, como `8.8.8.8,https://www.bing.com`\r\n- Se for um endereço IP, a detecção será feita via ping. Se for um endereço HTTP(s), a detecção será feita via solicitação HTTP GET.\r\n- Se você deseja restaurar o endereço de detecção padrão do sistema, insira uma vírgula `,` e clique em 'Próximo'.\r\n- **Esta configuração é global e as alterações afetarão outras instâncias de integração. Modifique com cautela.**\r\n### Verificar Dependências de Rede\r\nVerifique uma por uma as seguintes dependências de rede para ver se são acessíveis. Se os endereços relacionados não forem acessíveis, isso causará problemas de integração.\r\n- Endereço de Autenticação OAuth2: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Endereço da API HTTP da Xiaomi: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Endereço da API SPEC da Xiaomi: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Endereço do Broker MQTT da Xiaomi: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Endereço de Detecção de Rede",
"check_network_deps": "Verificar Dependências de Rede"
}
},
"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\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",
@ -167,12 +194,21 @@
"get_token_error": "Não foi possível obter a informação de autorização de login (token OAuth).",
"get_homeinfo_error": "Não foi possível obter a informação da casa.",
"get_cert_error": "Não foi possível obter o certificado do gateway central.",
"no_devices": "A casa selecionada não possui quaisquer dispositivos. Por favor, selecione uma casa com dispositivos e continue.",
"no_devices": "Não há dispositivos na casa selecionada. Por favor, selecione uma casa com dispositivos e continue.",
"no_filter_devices": "Os dispositivos filtrados estão vazios. Por favor, selecione critérios de filtro válidos e continue.",
"no_family_selected": "Nenhuma casa selecionada.",
"no_central_device": "O [Modo Gateway Central] requer um gateway central Xiaomi disponível na rede local onde o Home Assistant está. Verifique se a casa selecionada cumpre este requisito.",
"mdns_discovery_error": "Exceção no serviço de descoberta de dispositivos locais.",
"update_config_error": "Não foi possível atualizar a informação de configuração.",
"not_confirm": "As alterações não foram confirmadas. Por favor, confirme a alteração antes de submeter."
"not_confirm": "As alterações não foram confirmadas. Por favor, confirme a alteração antes de submeter.",
"invalid_network_addr": "Endereço IP ou HTTP inválido detectado, por favor insira um endereço válido.",
"invalid_ip_addr": "Endereço IP inacessível detectado, por favor insira um endereço IP válido.",
"invalid_http_addr": "Endereço HTTP inacessível detectado, por favor insira um endereço HTTP válido.",
"invalid_default_addr": "O endereço de detecção de rede padrão está inacessível, por favor verifique a configuração da rede ou use um endereço de detecção de rede personalizado.",
"unreachable_oauth2_host": "Não é possível acessar o endereço de autenticação OAuth2, verifique a configuração da rede.",
"unreachable_http_host": "Não é possível acessar o endereço da API HTTP da Xiaomi, verifique a configuração da rede.",
"unreachable_spec_host": "Não é possível acessar o endereço da API SPEC da Xiaomi, verifique a configuração da rede.",
"unreachable_mqtt_broker": "Não é possível acessar o endereço do Broker MQTT da Xiaomi, verifique a configuração da rede."
},
"abort": {
"network_connect_error": "A configuração falhou. A ligação de rede é anormal. Verifique a configuração da rede do equipamento.",

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "Основные настройки",
"description": "### Регион входа в систему\r\nВыберите регион, в котором находится ваша учетная запись Xiaomi. Вы можете узнать об этом в `Xiaomi Home> Мой (в нижнем меню)> Дополнительные настройки> О Xiaomi Home`.\r\n### Язык\r\nВыберите язык, используемый для имен устройств и сущностей. Части предложений, которые не имеют перевода, будут отображаться на английском языке.\r\n### Адрес перенаправления для аутентификации OAuth2\r\nАдрес перенаправления для аутентификации OAuth2 - ** [http: //homeassistant.local: 8123] (http: //homeassistant.local: 8123) **, Home Assistant должен находиться в одной локальной сети с текущим терминалом (например, персональный компьютер), и терминал должен иметь доступ к домашней странице Home Assistant по этому адресу, в противном случае аутентификация входа может завершиться неудачно.\r\n### Примечание\r\n- Для пользователей с сотнями или более устройств Mi Home первоначальное добавление интеграции займет некоторое время. Пожалуйста, будьте терпеливы.\r\n- Если Home Assistant работает в среде Docker, убедитесь, что сетевой режим Docker установлен на host, иначе функция локального управления может работать неправильно.\r\n- Функция локального управления интеграции имеет некоторые зависимости. Пожалуйста, внимательно прочитайте README.",
"description": "### Регион входа в систему\r\nВыберите регион, в котором находится ваша учетная запись Xiaomi. Вы можете узнать об этом в `Xiaomi Home> Мой (в нижнем меню)> Дополнительные настройки> О Xiaomi Home`.\r\n### Язык\r\nВыберите язык, используемый для имен устройств и сущностей. Части предложений, которые не имеют перевода, будут отображаться на английском языке.\r\n### Адрес перенаправления для аутентификации OAuth2\r\nАдрес перенаправления для аутентификации OAuth2 - ** [http: //homeassistant.local: 8123] (http: //homeassistant.local: 8123) **, Home Assistant должен находиться в одной локальной сети с текущим терминалом (например, персональный компьютер), и терминал должен иметь доступ к домашней странице Home Assistant по этому адресу, в противном случае аутентификация входа может завершиться неудачно.\r\n### Интегрированная Сетевая Конфигурация\r\nПроверьте, нормально ли функционирует локальная сеть и доступны ли связанные сетевые ресурсы. **Рекомендуется выбрать это при первом добавлении.**\r\n### Примечание\r\n- Для пользователей с сотнями или более устройств Mi Home первоначальное добавление интеграции займет некоторое время. Пожалуйста, будьте терпеливы.\r\n- Если Home Assistant работает в среде Docker, убедитесь, что сетевой режим Docker установлен на host, иначе функция локального управления может работать неправильно.\r\n- Функция локального управления интеграции имеет некоторые зависимости. Пожалуйста, внимательно прочитайте README.",
"data": {
"cloud_server": "Регион входа в систему",
"integration_language": "Язык",
"oauth_redirect_url": "Адрес перенаправления для аутентификации OAuth2"
"oauth_redirect_url": "Адрес перенаправления для аутентификации OAuth2",
"network_detect_config": "Интегрированная Сетевая Конфигурация"
}
},
"network_detect_config": {
"title": "Интегрированная Сетевая Конфигурация",
"description": "## Введение в Использование\r\n### Адрес Обнаружения Сети\r\nИспользуется для проверки работоспособности сети. Если не задано, будет использоваться адрес по умолчанию. Если проверка адреса по умолчанию не удалась, вы можете попробовать ввести пользовательский адрес.\r\n- Вы можете ввести несколько адресов для проверки, разделенных запятыми, например `8.8.8.8,https://www.bing.com`\r\n- Если это IP-адрес, проверка будет выполняться с помощью ping. Если это HTTP(s)-адрес, проверка будет выполняться с помощью HTTP GET запроса.\r\n- Если вы хотите восстановить адрес обнаружения по умолчанию, введите запятую `,` и нажмите 'Далее'.\r\n- **Эта конфигурация является глобальной, и изменения повлияют на другие экземпляры интеграции. Пожалуйста, изменяйте с осторожностью.**\r\n### Проверка Сетевых Зависимостей\r\nПроверьте поочередно следующие сетевые зависимости, чтобы убедиться, что они доступны. Если соответствующие адреса недоступны, это приведет к проблемам с интеграцией.\r\n- Адрес аутентификации OAuth2: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Адрес HTTP API Xiaomi: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Адрес SPEC API Xiaomi: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Адрес MQTT брокера Xiaomi: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Адрес Обнаружения Сети",
"check_network_deps": "Проверка Сетевых Зависимостей"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "Сервис обнаружения локальных устройств недоступен.",
"get_cert_error": "Не удалось получить сертификат центрального шлюза.",
"no_family_selected": "Не выбрана домашняя сеть.",
"no_devices": "В выбранной домашней сети нет устройств. Пожалуйста, выберите домашнюю сеть с устройствами и продолжайте.",
"no_central_device": "Для режима центрального шлюза Xiaomi необходимо наличие доступного центрального шлюза Xiaomi в локальной сети Home Assistant. Проверьте, соответствует ли выбранная домашняя сеть этому требованию."
"no_devices": "В выбранном доме нет устройств. Пожалуйста, выберите дом с устройствами и продолжите.",
"no_filter_devices": "Список устройств после фильтрации пуст. Пожалуйста, выберите действительные условия фильтрации и продолжите.",
"no_central_device": "Для режима центрального шлюза Xiaomi необходимо наличие доступного центрального шлюза Xiaomi в локальной сети Home Assistant. Проверьте, соответствует ли выбранная домашняя сеть этому требованию.",
"invalid_network_addr": "Обнаружен недействительный IP-адрес или HTTP-адрес, пожалуйста, введите действительный адрес.",
"invalid_ip_addr": "Обнаружен недоступный IP-адрес, пожалуйста, введите действительный IP-адрес.",
"invalid_http_addr": "Обнаружен недоступный HTTP-адрес, пожалуйста, введите действительный HTTP-адрес.",
"invalid_default_addr": "Адрес обнаружения сети по умолчанию недоступен, пожалуйста, проверьте конфигурацию сети или используйте пользовательский адрес обнаружения сети.",
"unreachable_oauth2_host": "Не удается подключиться к адресу аутентификации OAuth2, проверьте настройки сети.",
"unreachable_http_host": "Не удается подключиться к адресу HTTP API Xiaomi, проверьте настройки сети.",
"unreachable_spec_host": "Не удается подключиться к адресу SPEC API Xiaomi, проверьте настройки сети.",
"unreachable_mqtt_broker": "Не удается подключиться к адресу MQTT брокера Xiaomi, проверьте настройки сети."
},
"abort": {
"network_connect_error": "Ошибка настройки. Сетевое подключение недоступно. Проверьте настройки сети устройства.",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "Параметры настройки",
"description": "### {nick_name} Здравствуйте!\r\n\r\nID учетной записи Xiaomi: {uid}\r\nТекущий регион входа в систему: {cloud_server}\r\n\r\nВыберите параметры, которые нужно настроить заново, а затем нажмите «Далее».",
"description": "### {nick_name} Здравствуйте!\r\n\r\nID учетной записи Xiaomi: {uid}\r\nТекущий регион входа в систему: {cloud_server}\r\nID экземпляра интеграции: {instance_id}\r\n\r\nВыберите параметры, которые нужно настроить заново, а затем нажмите «Далее».",
"data": {
"integration_language": "Язык интеграции",
"update_user_info": "Обновить информацию о пользователе",
@ -102,7 +120,8 @@
"hide_non_standard_entities": "Скрыть нестандартные сущности",
"display_devices_changed_notify": "Отображать уведомления о изменении состояния устройства",
"update_trans_rules": "Обновить правила преобразования сущностей",
"update_lan_ctrl_config": "Обновить конфигурацию управления LAN"
"update_lan_ctrl_config": "Обновить конфигурацию управления LAN",
"network_detect_config": "Интегрированная Сетевая Конфигурация"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "Включить подписку LAN"
}
},
"network_detect_config": {
"title": "Интегрированная Сетевая Конфигурация",
"description": "## Введение в Использование\r\n### Адрес Обнаружения Сети\r\nИспользуется для проверки работоспособности сети. Если не задано, будет использоваться адрес по умолчанию. Если проверка адреса по умолчанию не удалась, вы можете попробовать ввести пользовательский адрес.\r\n- Вы можете ввести несколько адресов для проверки, разделенных запятыми, например `8.8.8.8,https://www.bing.com`\r\n- Если это IP-адрес, проверка будет выполняться с помощью ping. Если это HTTP(s)-адрес, проверка будет выполняться с помощью HTTP GET запроса.\r\n- Если вы хотите восстановить адрес обнаружения по умолчанию, введите запятую `,` и нажмите 'Далее'.\r\n- **Эта конфигурация является глобальной, и изменения повлияют на другие экземпляры интеграции. Пожалуйста, изменяйте с осторожностью.**\r\n### Проверка Сетевых Зависимостей\r\nПроверьте поочередно следующие сетевые зависимости, чтобы убедиться, что они доступны. Если соответствующие адреса недоступны, это приведет к проблемам с интеграцией.\r\n- Адрес аутентификации OAuth2: `https://account.xiaomi.com/oauth2/authorize`.\r\n- Адрес HTTP API Xiaomi: `https://{http_host}/app/v2/ha/oauth/get_token`.\r\n- Адрес SPEC API Xiaomi: `https://miot-spec.org/miot-spec-v2/template/list/device`.\r\n- Адрес MQTT брокера Xiaomi: `mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`.",
"data": {
"network_detect_addr": "Адрес Обнаружения Сети",
"check_network_deps": "Проверка Сетевых Зависимостей"
}
},
"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{display_devices_changed_notify}\r\nИзменение устройства:\tДобавлено **{devices_add}** устройство, удалено **{devices_remove}** устройства\r\nИзменение правил преобразования:\tВсего **{trans_rules_count}** правил, обновлено **{trans_rules_count_success}** правил",
@ -168,11 +195,20 @@
"get_homeinfo_error": "Не удалось получить информацию о домашней сети.",
"get_cert_error": "Не удалось получить центральный сертификат.",
"no_family_selected": "Не выбрана семья.",
"no_devices": "В выбранной семье нет устройств. Пожалуйста, выберите семью с устройствами и продолжайте.",
"no_devices": "В выбранном доме нет устройств. Пожалуйста, выберите дом с устройствами и продолжите.",
"no_filter_devices": "Список устройств после фильтрации пуст. Пожалуйста, выберите действительные условия фильтрации и продолжите.",
"no_central_device": "Для режима центрального шлюза необходим существующий в локальной сети Home Assistant с доступным Xiaomi-шлюзом. Пожалуйста, проверьте, соответствует ли выбранная семья этому требованию.",
"mdns_discovery_error": "Ошибка сервиса поиска локальных устройств.",
"update_config_error": "Не удалось обновить информацию о конфигурации.",
"not_confirm": "Изменение не подтверждено. Пожалуйста, отметьте для подтверждения и отправки."
"not_confirm": "Изменение не подтверждено. Пожалуйста, отметьте для подтверждения и отправки.",
"invalid_network_addr": "Обнаружен недействительный IP-адрес или HTTP-адрес, пожалуйста, введите действительный адрес.",
"invalid_ip_addr": "Обнаружен недоступный IP-адрес, пожалуйста, введите действительный IP-адрес.",
"invalid_http_addr": "Обнаружен недоступный HTTP-адрес, пожалуйста, введите действительный HTTP-адрес.",
"invalid_default_addr": "Адрес обнаружения сети по умолчанию недоступен, пожалуйста, проверьте конфигурацию сети или используйте пользовательский адрес обнаружения сети.",
"unreachable_oauth2_host": "Не удается подключиться к адресу аутентификации OAuth2, проверьте настройки сети.",
"unreachable_http_host": "Не удается подключиться к адресу HTTP API Xiaomi, проверьте настройки сети.",
"unreachable_spec_host": "Не удается подключиться к адресу SPEC API Xiaomi, проверьте настройки сети.",
"unreachable_mqtt_broker": "Не удается подключиться к адресу MQTT брокера Xiaomi, проверьте настройки сети."
},
"abort": {
"network_connect_error": "Ошибка конфигурации. Сбой сетевого подключения. Проверьте настройки сети устройства.",

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "基础配置",
"description": "### 登录地区\r\n选择小米账号所在的地区。您可以在 `米家APP > 我的(位于底部菜单) > 更多设置 > 关于米家` 中查看。\r\n### 语言\r\n选择设备及实体名称所用的语言。缺少翻译的部分语句将使用英文显示。\r\n### OAuth2 认证跳转地址\r\nOAuth2 认证跳转地址为 **[http://homeassistant.local:8123](http://homeassistant.local:8123)**Home Assistant 需要与当前操作终端(例如,个人电脑)在同一局域网内,且操作终端能通过该地址访问 Home Assistant 首页,否则登录认证可能会失败。\r\n### 注意事项\r\n- 对于数百个及以上米家设备的用户,首次添加集成会耗费一些时间,请耐心等待。\r\n- 如果 Home Assistant 运行在docker环境下请确保docker网络模式为host否则会导致本地控制功能异常。\r\n- 集成本地控制功能存在一些依赖项请仔细阅读README。",
"description": "### 登录地区\r\n选择小米账号所在的地区。您可以在 `米家APP > 我的(位于底部菜单) > 更多设置 > 关于米家` 中查看。\r\n### 语言\r\n选择设备及实体名称所用的语言。缺少翻译的部分语句将使用英文显示。\r\n### OAuth2 认证跳转地址\r\nOAuth2 认证跳转地址为 **[http://homeassistant.local:8123](http://homeassistant.local:8123)**Home Assistant 需要与当前操作终端(例如,个人电脑)在同一局域网内,且操作终端能通过该地址访问 Home Assistant 首页,否则登录认证可能会失败。\r\n### 集成网络配置\r\n检测本地网络是否正常相关网络资源是否可访问。**首次添加时建议勾选。**\r\n### 注意事项\r\n- 对于数百个及以上米家设备的用户,首次添加集成会耗费一些时间,请耐心等待。\r\n- 如果 Home Assistant 运行在docker环境下请确保docker网络模式为host否则会导致本地控制功能异常。\r\n- 集成本地控制功能存在一些依赖项请仔细阅读README。",
"data": {
"cloud_server": "登录地区",
"integration_language": "语言",
"oauth_redirect_url": "认证跳转地址"
"oauth_redirect_url": "认证跳转地址",
"network_detect_config": "集成网络配置"
}
},
"network_detect_config": {
"title": "网络检测配置",
"description": "## 使用介绍\r\n### 网络检测地址\r\n用于检测网络是否正常未设置时将使用系统默认地址检测。如果默认地址检测异常时可尝试输入可用的自定义地址检测。\r\n- 可输入多个检测地址,地址之间使用`,`号间隔,如`8.8.8.8,https://www.bing.com`\r\n- 如果为IP地址将采用ping方式检测如果为http(s)地址,将采用 HTTP GET 访问该地址检测。\r\n- 如果想恢复系统默认检测地址,请输入`,`号,然后点击'下一步'。\r\n- **该配置为全局配置,修改会影响其它集成实例的网络检测,请谨慎修改。**\r\n### 检测网络依赖项\r\n依次检查下述网络依赖项是否可访问。如果相关地址无法访问将会导致集成异常。\r\n- OAuth2 认证地址:`https://account.xiaomi.com/oauth2/authorize`。\r\n- 小米 HTTP API 地址:`https://{http_host}/app/v2/ha/oauth/get_token`。\r\n- 小米 SPEC API 地址:`https://miot-spec.org/miot-spec-v2/template/list/device`。\r\n- 小米 MQTT Broker 地址:`mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`。",
"data": {
"network_detect_addr": "网络检测地址",
"check_network_deps": "检测网络依赖项"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "本地设备发现服务异常。",
"get_cert_error": "获取中枢证书失败。",
"no_family_selected": "未选择家庭。",
"no_devices": "选择的家庭中没有设备。请选择有设备的家庭,而后继续。",
"no_central_device": "【中枢网关模式】需要 Home Assistant 所在的局域网中存在可用的小米中枢网关。请检查选择的家庭是否符合该要求。"
"no_devices": "选择的家庭中没有设备。请选择有设备的家庭,然后继续。",
"no_filter_devices": "筛选设备为空。请选择有效的筛选条件,然后继续。",
"no_central_device": "【中枢网关模式】需要 Home Assistant 所在的局域网中存在可用的小米中枢网关。请检查选择的家庭是否符合该要求。",
"invalid_network_addr": "存在无效的IP地址或者HTTP地址请输入有效的地址。",
"invalid_ip_addr": "存在无法访问的IP地址请输入有效的IP地址。",
"invalid_http_addr": "存在无法访问的HTTP地址请输入有效的HTTP地址。",
"invalid_default_addr": "默认网络检测地址无法访问,请检查网络配置或者使用自定义网络检测地址。",
"unreachable_oauth2_host": "无法访问 OAuth2 认证地址,请检查网络配置。",
"unreachable_http_host": "无法访问小米 HTTP API 地址,请检查网络配置。",
"unreachable_spec_host": "无法访问小米 SPEC API 地址,请检查网络配置。",
"unreachable_mqtt_broker": "无法访问小米 MQTT Broker 地址,请检查网络配置。"
},
"abort": {
"network_connect_error": "配置失败。网络连接异常,请检查设备网络配置。",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "配置选项",
"description": "### {nick_name} 您好!\r\n\r\n小米账号ID{uid}\r\n当前登录区域{cloud_server}\r\n\r\n请勾选需要重新配置的选项然后点击“下一步”。",
"description": "### {nick_name} 您好!\r\n\r\n小米账号ID{uid}\r\n当前登录区域{cloud_server}\r\n集成实例ID{instance_id}\r\n\r\n请勾选需要重新配置的选项然后点击“下一步”。",
"data": {
"integration_language": "集成语言",
"update_user_info": "更新用户信息",
@ -102,7 +120,8 @@
"hide_non_standard_entities": "隐藏非标准生成实体",
"display_devices_changed_notify": "显示设备状态变化通知",
"update_trans_rules": "更新实体转换规则",
"update_lan_ctrl_config": "更新局域网控制配置"
"update_lan_ctrl_config": "更新局域网控制配置",
"network_detect_config": "集成网络配置"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "启用局域网订阅"
}
},
"network_detect_config": {
"title": "网络检测配置",
"description": "## 使用介绍\r\n### 网络检测地址\r\n用于检测网络是否正常未设置时将使用系统默认地址检测。如果默认地址检测异常时可尝试输入可用的自定义地址检测。\r\n- 可输入多个检测地址,地址之间使用`,`号间隔,如`8.8.8.8,https://www.bing.com`\r\n- 如果为IP地址将采用ping方式检测如果为http(s)地址,将采用 HTTP GET 访问该地址检测。\r\n- 如果想恢复系统默认检测地址,请输入`,`号,然后点击'下一步'。\r\n- **该配置为全局配置,修改会影响其它集成实例的网络检测,请谨慎修改。**\r\n### 检测网络依赖项\r\n依次检查下述网络依赖项是否可访问。如果相关地址无法访问将会导致集成异常。\r\n- OAuth2 认证地址:`https://account.xiaomi.com/oauth2/authorize`。\r\n- 小米 HTTP API 地址:`https://{http_host}/app/v2/ha/oauth/get_token`。\r\n- 小米 SPEC API 地址:`https://miot-spec.org/miot-spec-v2/template/list/device`。\r\n- 小米 MQTT Broker 地址:`mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`。",
"data": {
"network_detect_addr": "网络检测地址",
"check_network_deps": "检测网络依赖项"
}
},
"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{display_devices_changed_notify}\r\n设备变化\t新增 **{devices_add}** 个设备,移除 **{devices_remove}** 个设备\r\n转换规则变化\t共条 **{trans_rules_count}** 规则,更新 **{trans_rules_count_success}** 条规则",
@ -168,11 +195,20 @@
"get_homeinfo_error": "获取家庭信息失败。",
"get_cert_error": "获取中枢证书失败。",
"no_family_selected": "未选择家庭。",
"no_devices": "选择的家庭中没有设备,请选择有设备的家庭,而后继续。",
"no_devices": "选择的家庭中没有设备,请选择有设备的家庭,然后继续。",
"no_filter_devices": "筛选设备为空。请选择有效的筛选条件,然后继续。",
"no_central_device": "【中枢网关模式】需要 Home Assistant 所在的局域网中存在可用的小米中枢网关。请检查选择的家庭是否符合该要求。",
"mdns_discovery_error": "本地设备发现服务异常。",
"update_config_error": "配置信息更新失败。",
"not_confirm": "未确认修改项。请勾选确认后再提交。"
"not_confirm": "未确认修改项。请勾选确认后再提交。",
"invalid_network_addr": "存在无效的IP地址或者HTTP地址请输入有效的地址。",
"invalid_ip_addr": "存在无法访问的IP地址请输入有效的IP地址。",
"invalid_http_addr": "存在无法访问的HTTP地址请输入有效的HTTP地址。",
"invalid_default_addr": "默认网络检测地址无法访问,请检查网络配置或者使用自定义网络检测地址。",
"unreachable_oauth2_host": "无法访问 OAuth2 认证地址,请检查网络配置。",
"unreachable_http_host": "无法访问小米 HTTP API 地址,请检查网络配置。",
"unreachable_spec_host": "无法访问小米 SPEC API 地址,请检查网络配置。",
"unreachable_mqtt_broker": "无法访问小米 MQTT Broker 地址,请检查网络配置。"
},
"abort": {
"network_connect_error": "配置失败。网络连接异常,请检查设备网络配置。",

View File

@ -11,11 +11,20 @@
},
"auth_config": {
"title": "基礎配置",
"description": "### 登錄地區\r\n選擇小米帳號所在的地區。您可以在 `米家APP > 我的(位於底部菜單) > 更多設置 > 關於米家` 中查看。\r\n### 語言\r\n選擇設備及實體名稱所用的語言。缺少翻譯的部分語句將使用英文顯示。\r\n### OAuth2 認證跳轉地址\r\nOAuth2 認證跳轉地址為 **[http://homeassistant.local:8123](http://homeassistant.local:8123)**Home Assistant 需要與當前操作終端(例如,個人電腦)在同一局域網內,且操作終端能通過該地址訪問 Home Assistant 首頁,否則登錄認證可能會失敗。\r\n### 注意事項\r\n- 對於數百個及以上米家設備的用戶,首次添加集成會耗費一些時間,請耐心等待。\r\n- 如果 Home Assistant 運行在docker環境下請確保docker網絡模式為host否則會導致本地控制功能異常。\r\n- 集成本地控制功能存在一些依賴項請仔細閱讀README。",
"description": "### 登錄地區\r\n選擇小米帳號所在的地區。您可以在 `米家APP > 我的(位於底部菜單) > 更多設置 > 關於米家` 中查看。\r\n### 語言\r\n選擇設備及實體名稱所用的語言。缺少翻譯的部分語句將使用英文顯示。\r\n### OAuth2 認證跳轉地址\r\nOAuth2 認證跳轉地址為 **[http://homeassistant.local:8123](http://homeassistant.local:8123)**Home Assistant 需要與當前操作終端(例如,個人電腦)在同一局域網內,且操作終端能通過該地址訪問 Home Assistant 首頁,否則登錄認證可能會失敗。\r\n### 集成網絡配置\r\n檢測本地網絡是否正常相關網絡資源是否可訪問。**首次添加時建議勾選。**\r\n### 注意事項\r\n- 對於數百個及以上米家設備的用戶,首次添加集成會耗費一些時間,請耐心等待。\r\n- 如果 Home Assistant 運行在docker環境下請確保docker網絡模式為host否則會導致本地控制功能異常。\r\n- 集成本地控制功能存在一些依賴項請仔細閱讀README。",
"data": {
"cloud_server": "登錄地區",
"integration_language": "語言",
"oauth_redirect_url": "認證跳轉地址"
"oauth_redirect_url": "認證跳轉地址",
"network_detect_config": "集成網絡配置"
}
},
"network_detect_config": {
"title": "集成網絡配置",
"description": "## 使用介紹\r\n### 網絡檢測地址\r\n用於檢測網絡是否正常未設置時將使用系統默認地址檢測。如果默認地址檢測異常時可嘗試輸入可用的自定義地址檢測。\r\n- 可輸入多個檢測地址,地址之間使用`,`號間隔,如`8.8.8.8,https://www.bing.com`\r\n- 如果為IP地址將採用ping方式檢測如果為http(s)地址,將採用 HTTP GET 訪問該地址檢測。\r\n- 如果想恢復系統默認檢測地址,請輸入`,`號,然後點擊'下一步'。\r\n- **該配置為全局配置,修改會影響其它集成實例的網絡檢測,請謹慎修改。**\r\n### 檢測網絡依賴項\r\n依次檢查下述網絡依賴項是否可訪問。如果相關地址無法訪問將會導致集成異常。\r\n- OAuth2 認證地址:`https://account.xiaomi.com/oauth2/authorize`。\r\n- 小米 HTTP API 地址:`https://{http_host}/app/v2/ha/oauth/get_token`。\r\n- 小米 SPEC API 地址:`https://miot-spec.org/miot-spec-v2/template/list/device`。\r\n- 小米 MQTT Broker 地址:`mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`。",
"data": {
"network_detect_addr": "網絡檢測地址",
"check_network_deps": "檢測網絡依賴項"
}
},
"oauth_error": {
@ -68,8 +77,17 @@
"mdns_discovery_error": "本地設備發現服務異常。",
"get_cert_error": "獲取中樞證書失敗。",
"no_family_selected": "未選擇家庭。",
"no_devices": "選擇的家庭中沒有設備。請選擇有設備的家庭,而後繼續。",
"no_central_device": "【中樞網關模式】需要 Home Assistant 所在的局域網中存在可用的小米中樞網關。請檢查選擇的家庭是否符合該要求。"
"no_devices": "選擇的家庭中沒有設備。請選擇有設備的家庭,然後繼續。",
"no_filter_devices": "篩選設備為空。請選擇有效的篩選條件,然後繼續。",
"no_central_device": "【中樞網關模式】需要 Home Assistant 所在的局域網中存在可用的小米中樞網關。請檢查選擇的家庭是否符合該要求。",
"invalid_network_addr": "存在無效的IP地址或者HTTP地址請輸入有效的地址。",
"invalid_ip_addr": "存在無法訪問的IP地址請輸入有效的IP地址。",
"invalid_http_addr": "存在無法訪問的HTTP地址請輸入有效的HTTP地址。",
"invalid_default_addr": "默認網絡檢測地址無法訪問,請檢查網絡配置或者使用自定義網絡檢測地址。",
"unreachable_oauth2_host": "無法訪問 OAuth2 認證地址,請檢查網絡配置。",
"unreachable_http_host": "無法訪問小米 HTTP API 地址,請檢查網絡配置。",
"unreachable_spec_host": "無法訪問小米 SPEC API 地址,請檢查網絡配置。",
"unreachable_mqtt_broker": "無法訪問小米 MQTT Broker 地址,請檢查網絡配置。"
},
"abort": {
"network_connect_error": "配置失敗。網絡連接異常,請檢查設備網絡配置。",
@ -93,7 +111,7 @@
},
"config_options": {
"title": "配置選項",
"description": "### {nick_name} 您好!\r\n\r\n小米帳號ID{uid}\r\n當前登錄區域{cloud_server}\r\n\r\n請勾選需要重新配置的選項然後點擊“下一步”。",
"description": "### {nick_name} 您好!\r\n\r\n小米帳號ID{uid}\r\n當前登錄區域{cloud_server}\r\n集成實例ID{instance_id}\r\n\r\n請勾選需要重新配置的選項然後點擊“下一步”。",
"data": {
"integration_language": "集成語言",
"update_user_info": "更新用戶信息",
@ -102,7 +120,8 @@
"hide_non_standard_entities": "隱藏非標準生成實體",
"display_devices_changed_notify": "顯示設備狀態變化通知",
"update_trans_rules": "更新實體轉換規則",
"update_lan_ctrl_config": "更新局域網控制配置"
"update_lan_ctrl_config": "更新局域網控制配置",
"network_detect_config": "集成網絡配置"
}
},
"update_user_info": {
@ -151,6 +170,14 @@
"enable_subscribe": "啟用局域網訂閱"
}
},
"network_detect_config": {
"title": "集成網絡配置",
"description": "## 使用介紹\r\n### 網絡檢測地址\r\n用於檢測網絡是否正常未設置時將使用系統默認地址檢測。如果默認地址檢測異常時可嘗試輸入可用的自定義地址檢測。\r\n- 可輸入多個檢測地址,地址之間使用`,`號間隔,如`8.8.8.8,https://www.bing.com`\r\n- 如果為IP地址將採用ping方式檢測如果為http(s)地址,將採用 HTTP GET 訪問該地址檢測。\r\n- 如果想恢復系統默認檢測地址,請輸入`,`號,然後點擊'下一步'。\r\n- **該配置為全局配置,修改會影響其它集成實例的網絡檢測,請謹慎修改。**\r\n### 檢測網絡依賴項\r\n依次檢查下述網絡依賴項是否可訪問。如果相關地址無法訪問將會導致集成異常。\r\n- OAuth2 認證地址:`https://account.xiaomi.com/oauth2/authorize`。\r\n- 小米 HTTP API 地址:`https://{http_host}/app/v2/ha/oauth/get_token`。\r\n- 小米 SPEC API 地址:`https://miot-spec.org/miot-spec-v2/template/list/device`。\r\n- 小米 MQTT Broker 地址:`mqtts://{cloud_server}-ha.mqtt.io.mi.com:8883`。",
"data": {
"network_detect_addr": "網絡檢測地址",
"check_network_deps": "檢測網絡依賴項"
}
},
"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{display_devices_changed_notify}\r\n設備變化\t新增 **{devices_add}** 個設備,移除 **{devices_remove}** 個設備\r\n轉換規則變化\t共條 **{trans_rules_count}** 規則,更新 **{trans_rules_count_success}** 條規則",
@ -168,11 +195,20 @@
"get_homeinfo_error": "獲取家庭信息失敗。",
"get_cert_error": "獲取中樞證書失敗。",
"no_family_selected": "未選擇家庭。",
"no_devices": "選擇的家庭中沒有設備,請選擇有設備的家庭,而後繼續。",
"no_devices": "選擇的家庭中沒有設備。請選擇有設備的家庭,然後繼續。",
"no_filter_devices": "篩選設備為空。請選擇有效的篩選條件,然後繼續。",
"no_central_device": "【中樞網關模式】需要 Home Assistant 所在的局域網中存在可用的小米中樞網關。請檢查選擇的家庭是否符合該要求。",
"mdns_discovery_error": "本地設備發現服務異常。",
"update_config_error": "配置信息更新失敗。",
"not_confirm": "未確認修改項。請勾選確認後再提交。"
"not_confirm": "未確認修改項。請勾選確認後再提交。",
"invalid_network_addr": "存在無效的IP地址或者HTTP地址請輸入有效的地址。",
"invalid_ip_addr": "存在無法訪問的IP地址請輸入有效的IP地址。",
"invalid_http_addr": "存在無法訪問的HTTP地址請輸入有效的HTTP地址。",
"invalid_default_addr": "默認網絡檢測地址無法訪問,請檢查網絡配置或者使用自定義網絡檢測地址。",
"unreachable_oauth2_host": "無法訪問 OAuth2 認證地址,請檢查網絡配置。",
"unreachable_http_host": "無法訪問小米 HTTP API 地址,請檢查網絡配置。",
"unreachable_spec_host": "無法訪問小米 SPEC API 地址,請檢查網絡配置。",
"unreachable_mqtt_broker": "無法訪問小米 MQTT Broker 地址,請檢查網絡配置。"
},
"abort": {
"network_connect_error": "配置失敗。網絡連接異常,請檢查設備網絡配置。",

View File

@ -26,6 +26,7 @@ cd ha_xiaomi_home
```bash
cd config/ha_xiaomi_home
git fetch
git checkout v1.0.0
./install.sh /config
```

View File

@ -20,7 +20,6 @@ def load_py_file():
'const.py',
'miot_cloud.py',
'miot_error.py',
'miot_ev.py',
'miot_i18n.py',
'miot_lan.py',
'miot_mdns.py',

View File

@ -1,55 +0,0 @@
# -*- coding: utf-8 -*-
"""Unit test for miot_ev.py."""
import os
import pytest
# pylint: disable=import-outside-toplevel, disable=unused-argument
@pytest.mark.github
def test_mev_timer_and_fd():
from miot.miot_ev import MIoTEventLoop, TimeoutHandle
mev = MIoTEventLoop()
assert mev
event_fd: os.eventfd = os.eventfd(0, os.O_NONBLOCK)
assert event_fd
timer4: TimeoutHandle = None
def event_handler(event_fd):
value: int = os.eventfd_read(event_fd)
if value == 1:
mev.clear_timeout(timer4)
print('cancel timer4')
elif value == 2:
print('event write twice in a row')
elif value == 3:
mev.set_read_handler(event_fd, None, None)
os.close(event_fd)
event_fd = None
print('close event fd')
def timer1_handler(event_fd):
os.eventfd_write(event_fd, 1)
def timer2_handler(event_fd):
os.eventfd_write(event_fd, 1)
os.eventfd_write(event_fd, 1)
def timer3_handler(event_fd):
os.eventfd_write(event_fd, 3)
def timer4_handler(event_fd):
raise ValueError('unreachable code')
mev.set_read_handler(
event_fd, event_handler, event_fd)
mev.set_timeout(500, timer1_handler, event_fd)
mev.set_timeout(1000, timer2_handler, event_fd)
mev.set_timeout(1500, timer3_handler, event_fd)
timer4 = mev.set_timeout(2000, timer4_handler, event_fd)
mev.loop_forever()
# Loop will exit when there are no timers or fd handlers.
mev.loop_stop()