mirror of
https://github.com/XiaoMi/ha_xiaomi_home.git
synced 2026-01-12 11:50:43 +08:00
review
This commit is contained in:
parent
5dc6f400c2
commit
b95a2c18ee
@ -80,11 +80,7 @@ async def async_setup_entry(
|
|||||||
async_add_entities: AddEntitiesCallback,
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up a config entry."""
|
"""Set up a config entry."""
|
||||||
<<<<<<< HEAD
|
|
||||||
device_list: list[MIoTDevice] = hass.data[DOMAIN]['devices'][
|
device_list: list[MIoTDevice] = hass.data[DOMAIN]['devices'][
|
||||||
=======
|
|
||||||
device_list: list[MIoTDevice] = hass.data[DOMAIN]["devices"][
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
config_entry.entry_id]
|
config_entry.entry_id]
|
||||||
|
|
||||||
new_entities = []
|
new_entities = []
|
||||||
@ -110,14 +106,9 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
_brightness_scale: Optional[tuple[int, int]]
|
_brightness_scale: Optional[tuple[int, int]]
|
||||||
_mode_map: Optional[dict[Any, Any]]
|
_mode_map: Optional[dict[Any, Any]]
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self, miot_device: MIoTDevice, entity_data: MIoTEntityData,hass: HomeAssistant
|
self, miot_device: MIoTDevice, entity_data: MIoTEntityData,hass: HomeAssistant
|
||||||
) -> None:
|
) -> None:
|
||||||
=======
|
|
||||||
def __init__(self, miot_device: MIoTDevice, entity_data: MIoTEntityData,
|
|
||||||
hass: HomeAssistant) -> None:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
"""Initialize the Light."""
|
"""Initialize the Light."""
|
||||||
super().__init__(miot_device=miot_device, entity_data=entity_data)
|
super().__init__(miot_device=miot_device, entity_data=entity_data)
|
||||||
self.hass = hass
|
self.hass = hass
|
||||||
@ -158,13 +149,8 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
self._attr_supported_features |= LightEntityFeature.EFFECT
|
self._attr_supported_features |= LightEntityFeature.EFFECT
|
||||||
self._prop_mode = prop
|
self._prop_mode = prop
|
||||||
else:
|
else:
|
||||||
<<<<<<< HEAD
|
|
||||||
_LOGGER.info(
|
_LOGGER.info(
|
||||||
'invalid brightness format, %s', self.entity_id)
|
'invalid brightness format, %s', self.entity_id)
|
||||||
=======
|
|
||||||
_LOGGER.info("invalid brightness format, %s",
|
|
||||||
self.entity_id)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
continue
|
continue
|
||||||
# color-temperature
|
# color-temperature
|
||||||
if prop.name == 'color-temperature':
|
if prop.name == 'color-temperature':
|
||||||
@ -190,7 +176,6 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
mode_list = prop.value_list.to_map()
|
mode_list = prop.value_list.to_map()
|
||||||
elif prop.value_range:
|
elif prop.value_range:
|
||||||
mode_list = {}
|
mode_list = {}
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
int((
|
int((
|
||||||
prop.value_range.max_
|
prop.value_range.max_
|
||||||
@ -198,11 +183,6 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
) / prop.value_range.step)
|
) / prop.value_range.step)
|
||||||
> self._VALUE_RANGE_MODE_COUNT_MAX
|
> self._VALUE_RANGE_MODE_COUNT_MAX
|
||||||
):
|
):
|
||||||
=======
|
|
||||||
if (int((prop.value_range.max_ - prop.value_range.min_) /
|
|
||||||
prop.value_range.step)
|
|
||||||
> self._VALUE_RANGE_MODE_COUNT_MAX):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
'too many mode values, %s, %s, %s',
|
'too many mode values, %s, %s, %s',
|
||||||
self.entity_id, prop.name, prop.value_range)
|
self.entity_id, prop.name, prop.value_range)
|
||||||
@ -210,14 +190,8 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
for value in range(
|
for value in range(
|
||||||
prop.value_range.min_,
|
prop.value_range.min_,
|
||||||
prop.value_range.max_,
|
prop.value_range.max_,
|
||||||
<<<<<<< HEAD
|
|
||||||
prop.value_range.step):
|
prop.value_range.step):
|
||||||
mode_list[value] = f'mode {value}'
|
mode_list[value] = f'mode {value}'
|
||||||
=======
|
|
||||||
prop.value_range.step,
|
|
||||||
):
|
|
||||||
mode_list[value] = f"mode {value}"
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if mode_list:
|
if mode_list:
|
||||||
self._mode_map = mode_list
|
self._mode_map = mode_list
|
||||||
self._attr_effect_list = list(self._mode_map.values())
|
self._attr_effect_list = list(self._mode_map.values())
|
||||||
@ -271,14 +245,9 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
@property
|
@property
|
||||||
def effect(self) -> Optional[str]:
|
def effect(self) -> Optional[str]:
|
||||||
"""Return the current mode."""
|
"""Return the current mode."""
|
||||||
<<<<<<< HEAD
|
|
||||||
return self.get_map_value(
|
return self.get_map_value(
|
||||||
map_=self._mode_map,
|
map_=self._mode_map,
|
||||||
key=self.get_prop_value(prop=self._prop_mode))
|
key=self.get_prop_value(prop=self._prop_mode))
|
||||||
=======
|
|
||||||
return self.get_map_value(map_=self._mode_map,
|
|
||||||
key=self.get_prop_value(prop=self._prop_mode))
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
async def async_turn_on(self, **kwargs) -> None:
|
async def async_turn_on(self, **kwargs) -> None:
|
||||||
"""Turn the light on.
|
"""Turn the light on.
|
||||||
@ -316,7 +285,6 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
# 开始发送开灯命令
|
# 开始发送开灯命令
|
||||||
if command_send_mode and command_send_mode.state == "Send Together":
|
if command_send_mode and command_send_mode.state == "Send Together":
|
||||||
set_properties_list: List[Dict[str, Any]] = []
|
set_properties_list: List[Dict[str, Any]] = []
|
||||||
<<<<<<< HEAD
|
|
||||||
# mode
|
# mode
|
||||||
if ATTR_EFFECT in kwargs:
|
if ATTR_EFFECT in kwargs:
|
||||||
set_properties_list.append({
|
set_properties_list.append({
|
||||||
@ -328,18 +296,6 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
if send_brightness_first and ATTR_BRIGHTNESS in kwargs:
|
if send_brightness_first and ATTR_BRIGHTNESS in kwargs:
|
||||||
brightness = brightness_to_value(
|
brightness = brightness_to_value(
|
||||||
self._brightness_scale,kwargs[ATTR_BRIGHTNESS])
|
self._brightness_scale,kwargs[ATTR_BRIGHTNESS])
|
||||||
=======
|
|
||||||
if self._prop_on:
|
|
||||||
value_on = True if self._prop_on.format_ == bool else 1 # noqa: E721
|
|
||||||
set_properties_list.append({
|
|
||||||
"prop": self._prop_on,
|
|
||||||
"value": value_on
|
|
||||||
})
|
|
||||||
# brightness
|
|
||||||
if ATTR_BRIGHTNESS in kwargs:
|
|
||||||
brightness = brightness_to_value(self._brightness_scale,
|
|
||||||
kwargs[ATTR_BRIGHTNESS])
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
set_properties_list.append({
|
set_properties_list.append({
|
||||||
"prop": self._prop_brightness,
|
"prop": self._prop_brightness,
|
||||||
"value": brightness
|
"value": brightness
|
||||||
@ -362,7 +318,6 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
"value": rgb
|
"value": rgb
|
||||||
})
|
})
|
||||||
self._attr_color_mode = ColorMode.RGB
|
self._attr_color_mode = ColorMode.RGB
|
||||||
<<<<<<< HEAD
|
|
||||||
# brightness
|
# brightness
|
||||||
if not send_brightness_first and ATTR_BRIGHTNESS in kwargs:
|
if not send_brightness_first and ATTR_BRIGHTNESS in kwargs:
|
||||||
brightness = brightness_to_value(
|
brightness = brightness_to_value(
|
||||||
@ -379,33 +334,16 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
"value": value_on
|
"value": value_on
|
||||||
})
|
})
|
||||||
await self.set_properties_async(set_properties_list,write_ha_state=False)
|
await self.set_properties_async(set_properties_list,write_ha_state=False)
|
||||||
=======
|
|
||||||
# mode
|
|
||||||
if ATTR_EFFECT in kwargs:
|
|
||||||
set_properties_list.append({
|
|
||||||
"prop":
|
|
||||||
self._prop_mode,
|
|
||||||
"value":
|
|
||||||
self.get_map_key(map_=self._mode_map,
|
|
||||||
value=kwargs[ATTR_EFFECT]),
|
|
||||||
})
|
|
||||||
await self.set_properties_async(set_properties_list)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
|
|
||||||
elif command_send_mode and command_send_mode.state == "Send Turn On First":
|
elif command_send_mode and command_send_mode.state == "Send Turn On First":
|
||||||
set_properties_list: List[Dict[str, Any]] = []
|
set_properties_list: List[Dict[str, Any]] = []
|
||||||
if self._prop_on:
|
if self._prop_on:
|
||||||
<<<<<<< HEAD
|
|
||||||
value_on = True if self._prop_on.format_ == bool else 1
|
value_on = True if self._prop_on.format_ == bool else 1
|
||||||
=======
|
|
||||||
value_on = True if self._prop_on.format_ == bool else 1 # noqa: E721
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
set_properties_list.append({
|
set_properties_list.append({
|
||||||
"prop": self._prop_on,
|
"prop": self._prop_on,
|
||||||
"value": value_on
|
"value": value_on
|
||||||
})
|
})
|
||||||
<<<<<<< HEAD
|
|
||||||
# mode
|
# mode
|
||||||
if ATTR_EFFECT in kwargs:
|
if ATTR_EFFECT in kwargs:
|
||||||
set_properties_list.append({
|
set_properties_list.append({
|
||||||
@ -419,14 +357,6 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
if send_brightness_first and ATTR_BRIGHTNESS in kwargs:
|
if send_brightness_first and ATTR_BRIGHTNESS in kwargs:
|
||||||
brightness = brightness_to_value(
|
brightness = brightness_to_value(
|
||||||
self._brightness_scale,kwargs[ATTR_BRIGHTNESS])
|
self._brightness_scale,kwargs[ATTR_BRIGHTNESS])
|
||||||
=======
|
|
||||||
await self.set_property_async(prop=self._prop_on,
|
|
||||||
value=value_on)
|
|
||||||
# brightness
|
|
||||||
if ATTR_BRIGHTNESS in kwargs:
|
|
||||||
brightness = brightness_to_value(self._brightness_scale,
|
|
||||||
kwargs[ATTR_BRIGHTNESS])
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
set_properties_list.append({
|
set_properties_list.append({
|
||||||
"prop": self._prop_brightness,
|
"prop": self._prop_brightness,
|
||||||
"value": brightness
|
"value": brightness
|
||||||
@ -449,7 +379,6 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
"value": rgb
|
"value": rgb
|
||||||
})
|
})
|
||||||
self._attr_color_mode = ColorMode.RGB
|
self._attr_color_mode = ColorMode.RGB
|
||||||
<<<<<<< HEAD
|
|
||||||
# brightness
|
# brightness
|
||||||
if not send_brightness_first and ATTR_BRIGHTNESS in kwargs:
|
if not send_brightness_first and ATTR_BRIGHTNESS in kwargs:
|
||||||
brightness = brightness_to_value(
|
brightness = brightness_to_value(
|
||||||
@ -460,23 +389,10 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
})
|
})
|
||||||
|
|
||||||
await self.set_properties_async(set_properties_list,write_ha_state=False)
|
await self.set_properties_async(set_properties_list,write_ha_state=False)
|
||||||
=======
|
|
||||||
# mode
|
|
||||||
if ATTR_EFFECT in kwargs:
|
|
||||||
set_properties_list.append({
|
|
||||||
"prop":
|
|
||||||
self._prop_mode,
|
|
||||||
"value":
|
|
||||||
self.get_map_key(map_=self._mode_map,
|
|
||||||
value=kwargs[ATTR_EFFECT]),
|
|
||||||
})
|
|
||||||
await self.set_properties_async(set_properties_list)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
|
|
||||||
else:
|
else:
|
||||||
if self._prop_on:
|
if self._prop_on:
|
||||||
<<<<<<< HEAD
|
|
||||||
value_on = True if self._prop_on.format_ == bool else 1
|
value_on = True if self._prop_on.format_ == bool else 1
|
||||||
await self.set_property_async(
|
await self.set_property_async(
|
||||||
prop=self._prop_on, value=value_on)
|
prop=self._prop_on, value=value_on)
|
||||||
@ -487,18 +403,6 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
await self.set_property_async(
|
await self.set_property_async(
|
||||||
prop=self._prop_brightness, value=brightness,
|
prop=self._prop_brightness, value=brightness,
|
||||||
write_ha_state=False)
|
write_ha_state=False)
|
||||||
=======
|
|
||||||
value_on = True if self._prop_on.format_ == bool else 1 # noqa: E721
|
|
||||||
await self.set_property_async(prop=self._prop_on,
|
|
||||||
value=value_on)
|
|
||||||
# brightness
|
|
||||||
if ATTR_BRIGHTNESS in kwargs:
|
|
||||||
brightness = brightness_to_value(self._brightness_scale,
|
|
||||||
kwargs[ATTR_BRIGHTNESS])
|
|
||||||
await self.set_property_async(prop=self._prop_brightness,
|
|
||||||
value=brightness,
|
|
||||||
write_ha_state=False)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
# color-temperature
|
# color-temperature
|
||||||
if ATTR_COLOR_TEMP_KELVIN in kwargs:
|
if ATTR_COLOR_TEMP_KELVIN in kwargs:
|
||||||
await self.set_property_async(
|
await self.set_property_async(
|
||||||
@ -512,30 +416,17 @@ class Light(MIoTServiceEntity, LightEntity):
|
|||||||
g = kwargs[ATTR_RGB_COLOR][1]
|
g = kwargs[ATTR_RGB_COLOR][1]
|
||||||
b = kwargs[ATTR_RGB_COLOR][2]
|
b = kwargs[ATTR_RGB_COLOR][2]
|
||||||
rgb = (r << 16) | (g << 8) | b
|
rgb = (r << 16) | (g << 8) | b
|
||||||
<<<<<<< HEAD
|
|
||||||
await self.set_property_async(
|
await self.set_property_async(
|
||||||
prop=self._prop_color, value=rgb,
|
prop=self._prop_color, value=rgb,
|
||||||
write_ha_state=False)
|
write_ha_state=False)
|
||||||
=======
|
|
||||||
await self.set_property_async(prop=self._prop_color,
|
|
||||||
value=rgb,
|
|
||||||
write_ha_state=False)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._attr_color_mode = ColorMode.RGB
|
self._attr_color_mode = ColorMode.RGB
|
||||||
# mode
|
# mode
|
||||||
if ATTR_EFFECT in kwargs:
|
if ATTR_EFFECT in kwargs:
|
||||||
await self.set_property_async(
|
await self.set_property_async(
|
||||||
prop=self._prop_mode,
|
prop=self._prop_mode,
|
||||||
<<<<<<< HEAD
|
|
||||||
value=self.get_map_key(
|
value=self.get_map_key(
|
||||||
map_=self._mode_map, value=kwargs[ATTR_EFFECT]),
|
map_=self._mode_map, value=kwargs[ATTR_EFFECT]),
|
||||||
write_ha_state=False)
|
write_ha_state=False)
|
||||||
=======
|
|
||||||
value=self.get_map_key(map_=self._mode_map,
|
|
||||||
value=kwargs[ATTR_EFFECT]),
|
|
||||||
write_ha_state=False,
|
|
||||||
)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
|
|
||||||
async def async_turn_off(self, **kwargs) -> None:
|
async def async_turn_off(self, **kwargs) -> None:
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -99,17 +99,10 @@ class MIoTOauthClient:
|
|||||||
if cloud_server == 'cn':
|
if cloud_server == 'cn':
|
||||||
self._oauth_host = DEFAULT_OAUTH2_API_HOST
|
self._oauth_host = DEFAULT_OAUTH2_API_HOST
|
||||||
else:
|
else:
|
||||||
<<<<<<< HEAD
|
|
||||||
self._oauth_host = f'{cloud_server}.{DEFAULT_OAUTH2_API_HOST}'
|
self._oauth_host = f'{cloud_server}.{DEFAULT_OAUTH2_API_HOST}'
|
||||||
self._device_id = f'ha.{uuid}'
|
self._device_id = f'ha.{uuid}'
|
||||||
self._state = hashlib.sha1(
|
self._state = hashlib.sha1(
|
||||||
f'd={self._device_id}'.encode('utf-8')).hexdigest()
|
f'd={self._device_id}'.encode('utf-8')).hexdigest()
|
||||||
=======
|
|
||||||
self._oauth_host = f"{cloud_server}.{DEFAULT_OAUTH2_API_HOST}"
|
|
||||||
self._device_id = f"ha.{uuid}"
|
|
||||||
self._state = hashlib.sha1(
|
|
||||||
f"d={self._device_id}".encode("utf-8")).hexdigest()
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._session = aiohttp.ClientSession(loop=self._main_loop)
|
self._session = aiohttp.ClientSession(loop=self._main_loop)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -172,20 +165,14 @@ class MIoTOauthClient:
|
|||||||
timeout=MIHOME_HTTP_API_TIMEOUT
|
timeout=MIHOME_HTTP_API_TIMEOUT
|
||||||
)
|
)
|
||||||
if http_res.status == 401:
|
if http_res.status == 401:
|
||||||
<<<<<<< HEAD
|
|
||||||
raise MIoTOauthError(
|
raise MIoTOauthError(
|
||||||
'unauthorized(401)', MIoTErrorCode.CODE_OAUTH_UNAUTHORIZED)
|
'unauthorized(401)', MIoTErrorCode.CODE_OAUTH_UNAUTHORIZED)
|
||||||
=======
|
|
||||||
raise MIoTOauthError("unauthorized(401)",
|
|
||||||
MIoTErrorCode.CODE_OAUTH_UNAUTHORIZED)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if http_res.status != 200:
|
if http_res.status != 200:
|
||||||
raise MIoTOauthError(
|
raise MIoTOauthError(
|
||||||
f'invalid http status code, {http_res.status}')
|
f'invalid http status code, {http_res.status}')
|
||||||
|
|
||||||
res_str = await http_res.text()
|
res_str = await http_res.text()
|
||||||
res_obj = json.loads(res_str)
|
res_obj = json.loads(res_str)
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
not res_obj
|
not res_obj
|
||||||
or res_obj.get('code', None) != 0
|
or res_obj.get('code', None) != 0
|
||||||
@ -201,19 +188,6 @@ class MIoTOauthClient:
|
|||||||
'expires_ts': int(
|
'expires_ts': int(
|
||||||
time.time() +
|
time.time() +
|
||||||
(res_obj['result'].get('expires_in', 0)*TOKEN_EXPIRES_TS_RATIO))
|
(res_obj['result'].get('expires_in', 0)*TOKEN_EXPIRES_TS_RATIO))
|
||||||
=======
|
|
||||||
if (not res_obj or res_obj.get("code", None) != 0 or
|
|
||||||
"result" not in res_obj or
|
|
||||||
not all(key in res_obj["result"] for key in
|
|
||||||
["access_token", "refresh_token", "expires_in"])):
|
|
||||||
raise MIoTOauthError(f"invalid http response, {res_str}")
|
|
||||||
|
|
||||||
return {
|
|
||||||
**res_obj["result"],
|
|
||||||
"expires_ts":
|
|
||||||
int(time.time() + (res_obj["result"].get("expires_in", 0) *
|
|
||||||
TOKEN_EXPIRES_TS_RATIO)),
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async def get_access_token_async(self, code: str) -> dict:
|
async def get_access_token_async(self, code: str) -> dict:
|
||||||
@ -228,22 +202,12 @@ class MIoTOauthClient:
|
|||||||
if not isinstance(code, str):
|
if not isinstance(code, str):
|
||||||
raise MIoTOauthError('invalid code')
|
raise MIoTOauthError('invalid code')
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
return await self.__get_token_async(data={
|
return await self.__get_token_async(data={
|
||||||
'client_id': self._client_id,
|
'client_id': self._client_id,
|
||||||
'redirect_uri': self._redirect_url,
|
'redirect_uri': self._redirect_url,
|
||||||
'code': code,
|
'code': code,
|
||||||
'device_id': self._device_id
|
'device_id': self._device_id
|
||||||
})
|
})
|
||||||
=======
|
|
||||||
return await self.__get_token_async(
|
|
||||||
data={
|
|
||||||
"client_id": self._client_id,
|
|
||||||
"redirect_uri": self._redirect_url,
|
|
||||||
"code": code,
|
|
||||||
"device_id": self._device_id,
|
|
||||||
})
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
async def refresh_access_token_async(self, refresh_token: str) -> dict:
|
async def refresh_access_token_async(self, refresh_token: str) -> dict:
|
||||||
"""get access token by refresh token.
|
"""get access token by refresh token.
|
||||||
@ -257,20 +221,11 @@ class MIoTOauthClient:
|
|||||||
if not isinstance(refresh_token, str):
|
if not isinstance(refresh_token, str):
|
||||||
raise MIoTOauthError('invalid refresh_token')
|
raise MIoTOauthError('invalid refresh_token')
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
return await self.__get_token_async(data={
|
return await self.__get_token_async(data={
|
||||||
'client_id': self._client_id,
|
'client_id': self._client_id,
|
||||||
'redirect_uri': self._redirect_url,
|
'redirect_uri': self._redirect_url,
|
||||||
'refresh_token': refresh_token,
|
'refresh_token': refresh_token,
|
||||||
})
|
})
|
||||||
=======
|
|
||||||
return await self.__get_token_async(
|
|
||||||
data={
|
|
||||||
"client_id": self._client_id,
|
|
||||||
"redirect_uri": self._redirect_url,
|
|
||||||
"refresh_token": refresh_token,
|
|
||||||
})
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
|
|
||||||
class MIoTHttpClient:
|
class MIoTHttpClient:
|
||||||
@ -301,7 +256,6 @@ class MIoTHttpClient:
|
|||||||
self._get_prop_timer = None
|
self._get_prop_timer = None
|
||||||
self._get_prop_list = {}
|
self._get_prop_list = {}
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
not isinstance(cloud_server, str)
|
not isinstance(cloud_server, str)
|
||||||
or not isinstance(client_id, str)
|
or not isinstance(client_id, str)
|
||||||
@ -312,16 +266,6 @@ class MIoTHttpClient:
|
|||||||
self.update_http_header(
|
self.update_http_header(
|
||||||
cloud_server=cloud_server, client_id=client_id,
|
cloud_server=cloud_server, client_id=client_id,
|
||||||
access_token=access_token)
|
access_token=access_token)
|
||||||
=======
|
|
||||||
if (not isinstance(cloud_server, str) or
|
|
||||||
not isinstance(client_id, str) or
|
|
||||||
not isinstance(access_token, str)):
|
|
||||||
raise MIoTHttpError("invalid params")
|
|
||||||
|
|
||||||
self.update_http_header(cloud_server=cloud_server,
|
|
||||||
client_id=client_id,
|
|
||||||
access_token=access_token)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
self._session = aiohttp.ClientSession(loop=self._main_loop)
|
self._session = aiohttp.ClientSession(loop=self._main_loop)
|
||||||
|
|
||||||
@ -363,16 +307,9 @@ class MIoTHttpClient:
|
|||||||
|
|
||||||
# pylint: disable=unused-private-member
|
# pylint: disable=unused-private-member
|
||||||
async def __mihome_api_get_async(
|
async def __mihome_api_get_async(
|
||||||
<<<<<<< HEAD
|
|
||||||
self, url_path: str, params: dict,
|
self, url_path: str, params: dict,
|
||||||
timeout: int = MIHOME_HTTP_API_TIMEOUT
|
timeout: int = MIHOME_HTTP_API_TIMEOUT
|
||||||
) -> dict:
|
) -> dict:
|
||||||
=======
|
|
||||||
self,
|
|
||||||
url_path: str,
|
|
||||||
params: dict,
|
|
||||||
timeout: int = MIHOME_HTTP_API_TIMEOUT) -> dict:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
http_res = await self._session.get(
|
http_res = await self._session.get(
|
||||||
url=f'{self._base_url}{url_path}',
|
url=f'{self._base_url}{url_path}',
|
||||||
params=params,
|
params=params,
|
||||||
@ -390,7 +327,6 @@ class MIoTHttpClient:
|
|||||||
res_obj: dict = json.loads(res_str)
|
res_obj: dict = json.loads(res_str)
|
||||||
if res_obj.get('code', None) != 0:
|
if res_obj.get('code', None) != 0:
|
||||||
raise MIoTHttpError(
|
raise MIoTHttpError(
|
||||||
<<<<<<< HEAD
|
|
||||||
f'invalid response code, {res_obj.get("code",None)}, '
|
f'invalid response code, {res_obj.get("code",None)}, '
|
||||||
f'{res_obj.get("message","")}')
|
f'{res_obj.get("message","")}')
|
||||||
_LOGGER.debug(
|
_LOGGER.debug(
|
||||||
@ -402,19 +338,6 @@ class MIoTHttpClient:
|
|||||||
self, url_path: str, data: dict,
|
self, url_path: str, data: dict,
|
||||||
timeout: int = MIHOME_HTTP_API_TIMEOUT
|
timeout: int = MIHOME_HTTP_API_TIMEOUT
|
||||||
) -> dict:
|
) -> dict:
|
||||||
=======
|
|
||||||
f"invalid response code, {res_obj.get('code', None)}, "
|
|
||||||
f"{res_obj.get('message', '')}")
|
|
||||||
_LOGGER.debug("mihome api get, %s%s, %s -> %s", self._base_url,
|
|
||||||
url_path, params, res_obj)
|
|
||||||
return res_obj
|
|
||||||
|
|
||||||
async def __mihome_api_post_async(
|
|
||||||
self,
|
|
||||||
url_path: str,
|
|
||||||
data: dict,
|
|
||||||
timeout: int = MIHOME_HTTP_API_TIMEOUT) -> dict:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
http_res = await self._session.post(
|
http_res = await self._session.post(
|
||||||
url=f'{self._base_url}{url_path}',
|
url=f'{self._base_url}{url_path}',
|
||||||
json=data,
|
json=data,
|
||||||
@ -432,42 +355,24 @@ class MIoTHttpClient:
|
|||||||
res_obj: dict = json.loads(res_str)
|
res_obj: dict = json.loads(res_str)
|
||||||
if res_obj.get('code', None) != 0:
|
if res_obj.get('code', None) != 0:
|
||||||
raise MIoTHttpError(
|
raise MIoTHttpError(
|
||||||
<<<<<<< HEAD
|
|
||||||
f'invalid response code, {res_obj.get("code",None)}, '
|
f'invalid response code, {res_obj.get("code",None)}, '
|
||||||
f'{res_obj.get("message","")}')
|
f'{res_obj.get("message","")}')
|
||||||
_LOGGER.debug(
|
_LOGGER.debug(
|
||||||
'mihome api post, %s%s, %s -> %s',
|
'mihome api post, %s%s, %s -> %s',
|
||||||
self._base_url, url_path, data, res_obj)
|
self._base_url, url_path, data, res_obj)
|
||||||
=======
|
|
||||||
f"invalid response code, {res_obj.get('code', None)}, "
|
|
||||||
f"{res_obj.get('message', '')}")
|
|
||||||
_LOGGER.debug("mihome api post, %s%s, %s -> %s", self._base_url,
|
|
||||||
url_path, data, res_obj)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return res_obj
|
return res_obj
|
||||||
|
|
||||||
async def get_user_info_async(self) -> dict:
|
async def get_user_info_async(self) -> dict:
|
||||||
http_res = await self._session.get(
|
http_res = await self._session.get(
|
||||||
<<<<<<< HEAD
|
|
||||||
url='https://open.account.xiaomi.com/user/profile',
|
url='https://open.account.xiaomi.com/user/profile',
|
||||||
params={
|
params={
|
||||||
'clientId': self._client_id, 'token': self._access_token},
|
'clientId': self._client_id, 'token': self._access_token},
|
||||||
headers={'content-type': 'application/x-www-form-urlencoded'},
|
headers={'content-type': 'application/x-www-form-urlencoded'},
|
||||||
timeout=MIHOME_HTTP_API_TIMEOUT
|
timeout=MIHOME_HTTP_API_TIMEOUT
|
||||||
=======
|
|
||||||
url="https://open.account.xiaomi.com/user/profile",
|
|
||||||
params={
|
|
||||||
"clientId": self._client_id,
|
|
||||||
"token": self._access_token
|
|
||||||
},
|
|
||||||
headers={"content-type": "application/x-www-form-urlencoded"},
|
|
||||||
timeout=MIHOME_HTTP_API_TIMEOUT,
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
res_str = await http_res.text()
|
res_str = await http_res.text()
|
||||||
res_obj = json.loads(res_str)
|
res_obj = json.loads(res_str)
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
not res_obj
|
not res_obj
|
||||||
or res_obj.get('code', None) != 0
|
or res_obj.get('code', None) != 0
|
||||||
@ -475,11 +380,6 @@ class MIoTHttpClient:
|
|||||||
or 'miliaoNick' not in res_obj['data']
|
or 'miliaoNick' not in res_obj['data']
|
||||||
):
|
):
|
||||||
raise MIoTOauthError(f'invalid http response, {http_res.text}')
|
raise MIoTOauthError(f'invalid http response, {http_res.text}')
|
||||||
=======
|
|
||||||
if (not res_obj or res_obj.get("code", None) != 0 or
|
|
||||||
"data" not in res_obj or "miliaoNick" not in res_obj["data"]):
|
|
||||||
raise MIoTOauthError(f"invalid http response, {http_res.text}")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
return res_obj['data']
|
return res_obj['data']
|
||||||
|
|
||||||
@ -501,14 +401,9 @@ class MIoTHttpClient:
|
|||||||
|
|
||||||
return cert
|
return cert
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
async def __get_dev_room_page_async(
|
async def __get_dev_room_page_async(
|
||||||
self, max_id: Optional[str] = None
|
self, max_id: Optional[str] = None
|
||||||
) -> dict:
|
) -> dict:
|
||||||
=======
|
|
||||||
async def __get_dev_room_page_async(self,
|
|
||||||
max_id: Optional[str] = None) -> dict:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
res_obj = await self.__mihome_api_post_async(
|
res_obj = await self.__mihome_api_post_async(
|
||||||
url_path='/app/v2/homeroom/get_dev_room_page',
|
url_path='/app/v2/homeroom/get_dev_room_page',
|
||||||
data={
|
data={
|
||||||
@ -524,7 +419,6 @@ class MIoTHttpClient:
|
|||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
'get dev room page error, invalid home, %s', home)
|
'get dev room page error, invalid home, %s', home)
|
||||||
continue
|
continue
|
||||||
<<<<<<< HEAD
|
|
||||||
home_list[str(home['id'])] = {'dids': home.get(
|
home_list[str(home['id'])] = {'dids': home.get(
|
||||||
'dids', None) or [], 'room_info': {}}
|
'dids', None) or [], 'room_info': {}}
|
||||||
for room in home.get('roomlist', []):
|
for room in home.get('roomlist', []):
|
||||||
@ -548,32 +442,6 @@ class MIoTHttpClient:
|
|||||||
room_id, {'dids': []})
|
room_id, {'dids': []})
|
||||||
home_list[home_id]['room_info'][room_id]['dids'].extend(
|
home_list[home_id]['room_info'][room_id]['dids'].extend(
|
||||||
info['dids'])
|
info['dids'])
|
||||||
=======
|
|
||||||
home_list[str(home["id"])] = {
|
|
||||||
"dids": home.get("dids", None) or [],
|
|
||||||
"room_info": {},
|
|
||||||
}
|
|
||||||
for room in home.get("roomlist", []):
|
|
||||||
if "id" not in room:
|
|
||||||
_LOGGER.error("get dev room page error, invalid room, %s",
|
|
||||||
room)
|
|
||||||
continue
|
|
||||||
home_list[str(home["id"])]["room_info"][str(room["id"])] = {
|
|
||||||
"dids": room.get("dids", None) or []
|
|
||||||
}
|
|
||||||
if res_obj["result"].get("has_more", False) and isinstance(
|
|
||||||
res_obj["result"].get("max_id", None), str):
|
|
||||||
next_list = await self.__get_dev_room_page_async(
|
|
||||||
max_id=res_obj["result"]["max_id"])
|
|
||||||
for home_id, info in next_list.items():
|
|
||||||
home_list.setdefault(home_id, {"dids": [], "room_info": {}})
|
|
||||||
home_list[home_id]["dids"].extend(info["dids"])
|
|
||||||
for room_id, info in info["room_info"].items():
|
|
||||||
home_list[home_id]["room_info"].setdefault(
|
|
||||||
room_id, {"dids": []})
|
|
||||||
home_list[home_id]["room_info"][room_id]["dids"].extend(
|
|
||||||
info["dids"])
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
return home_list
|
return home_list
|
||||||
|
|
||||||
@ -582,16 +450,10 @@ class MIoTHttpClient:
|
|||||||
device_list: dict[str, dict] = await self.__get_device_list_page_async(
|
device_list: dict[str, dict] = await self.__get_device_list_page_async(
|
||||||
dids=[], start_did=None)
|
dids=[], start_did=None)
|
||||||
for did, value in device_list.items():
|
for did, value in device_list.items():
|
||||||
<<<<<<< HEAD
|
|
||||||
if value['owner'] is not None and ('userid' in value['owner']) and (
|
if value['owner'] is not None and ('userid' in value['owner']) and (
|
||||||
'nickname' in value['owner']
|
'nickname' in value['owner']
|
||||||
):
|
):
|
||||||
separated_shared_devices.setdefault(did, value['owner'])
|
separated_shared_devices.setdefault(did, value['owner'])
|
||||||
=======
|
|
||||||
if (value["owner"] is not None and ("userid" in value["owner"]) and
|
|
||||||
("nickname" in value["owner"])):
|
|
||||||
separated_shared_devices.setdefault(did, value["owner"])
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return separated_shared_devices
|
return separated_shared_devices
|
||||||
|
|
||||||
async def get_homeinfos_async(self) -> dict:
|
async def get_homeinfos_async(self) -> dict:
|
||||||
@ -619,7 +481,6 @@ class MIoTHttpClient:
|
|||||||
or 'roomlist' not in home
|
or 'roomlist' not in home
|
||||||
):
|
):
|
||||||
continue
|
continue
|
||||||
<<<<<<< HEAD
|
|
||||||
if uid is None and device_source == 'homelist':
|
if uid is None and device_source == 'homelist':
|
||||||
uid = str(home['uid'])
|
uid = str(home['uid'])
|
||||||
home_infos[device_source][home['id']] = {
|
home_infos[device_source][home['id']] = {
|
||||||
@ -651,48 +512,10 @@ class MIoTHttpClient:
|
|||||||
more_list = await self.__get_dev_room_page_async(
|
more_list = await self.__get_dev_room_page_async(
|
||||||
max_id=res_obj['result']['max_id'])
|
max_id=res_obj['result']['max_id'])
|
||||||
for device_source in ['homelist', 'share_home_list']:
|
for device_source in ['homelist', 'share_home_list']:
|
||||||
=======
|
|
||||||
if uid is None and device_source == "homelist":
|
|
||||||
uid = str(home["uid"])
|
|
||||||
home_infos[device_source][home["id"]] = {
|
|
||||||
"home_id":
|
|
||||||
home["id"],
|
|
||||||
"home_name":
|
|
||||||
home["name"],
|
|
||||||
"city_id":
|
|
||||||
home.get("city_id", None),
|
|
||||||
"longitude":
|
|
||||||
home.get("longitude", None),
|
|
||||||
"latitude":
|
|
||||||
home.get("latitude", None),
|
|
||||||
"address":
|
|
||||||
home.get("address", None),
|
|
||||||
"dids":
|
|
||||||
home.get("dids", []),
|
|
||||||
"room_info": {
|
|
||||||
room["id"]: {
|
|
||||||
"room_id": room["id"],
|
|
||||||
"room_name": room["name"],
|
|
||||||
"dids": room.get("dids", []),
|
|
||||||
} for room in home.get("roomlist", []) if "id" in room
|
|
||||||
},
|
|
||||||
"group_id":
|
|
||||||
calc_group_id(uid=home["uid"], home_id=home["id"]),
|
|
||||||
"uid":
|
|
||||||
str(home["uid"]),
|
|
||||||
}
|
|
||||||
home_infos["uid"] = uid
|
|
||||||
if res_obj["result"].get("has_more", False) and isinstance(
|
|
||||||
res_obj["result"].get("max_id", None), str):
|
|
||||||
more_list = await self.__get_dev_room_page_async(
|
|
||||||
max_id=res_obj["result"]["max_id"])
|
|
||||||
for device_source in ["homelist", "share_home_list"]:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
for home_id, info in more_list.items():
|
for home_id, info in more_list.items():
|
||||||
if home_id not in home_infos[device_source]:
|
if home_id not in home_infos[device_source]:
|
||||||
_LOGGER.info('unknown home, %s, %s', home_id, info)
|
_LOGGER.info('unknown home, %s, %s', home_id, info)
|
||||||
continue
|
continue
|
||||||
<<<<<<< HEAD
|
|
||||||
home_infos[device_source][home_id]['dids'].extend(
|
home_infos[device_source][home_id]['dids'].extend(
|
||||||
info['dids'])
|
info['dids'])
|
||||||
for room_id, info in info['room_info'].items():
|
for room_id, info in info['room_info'].items():
|
||||||
@ -704,19 +527,6 @@ class MIoTHttpClient:
|
|||||||
'dids': []})
|
'dids': []})
|
||||||
home_infos[device_source][home_id]['room_info'][
|
home_infos[device_source][home_id]['room_info'][
|
||||||
room_id]['dids'].extend(info['dids'])
|
room_id]['dids'].extend(info['dids'])
|
||||||
=======
|
|
||||||
home_infos[device_source][home_id]["dids"].extend(
|
|
||||||
info["dids"])
|
|
||||||
for room_id, info in info["room_info"].items():
|
|
||||||
home_infos[device_source][home_id][
|
|
||||||
"room_info"].setdefault(room_id, {
|
|
||||||
"room_id": room_id,
|
|
||||||
"room_name": "",
|
|
||||||
"dids": []
|
|
||||||
})
|
|
||||||
home_infos[device_source][home_id]["room_info"][
|
|
||||||
room_id]["dids"].extend(info["dids"])
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'uid': uid,
|
'uid': uid,
|
||||||
@ -728,7 +538,6 @@ class MIoTHttpClient:
|
|||||||
return (await self.get_homeinfos_async()).get('uid', None)
|
return (await self.get_homeinfos_async()).get('uid', None)
|
||||||
|
|
||||||
async def __get_device_list_page_async(
|
async def __get_device_list_page_async(
|
||||||
<<<<<<< HEAD
|
|
||||||
self, dids: list[str], start_did: Optional[str] = None
|
self, dids: list[str], start_did: Optional[str] = None
|
||||||
) -> dict[str, dict]:
|
) -> dict[str, dict]:
|
||||||
req_data: dict = {
|
req_data: dict = {
|
||||||
@ -737,29 +546,16 @@ class MIoTHttpClient:
|
|||||||
'get_third_device': True,
|
'get_third_device': True,
|
||||||
'dids': dids
|
'dids': dids
|
||||||
}
|
}
|
||||||
=======
|
|
||||||
self,
|
|
||||||
dids: list[str],
|
|
||||||
start_did: Optional[str] = None) -> dict[str, dict]:
|
|
||||||
req_data: dict = {"limit": 200, "get_split_device": True, "dids": dids}
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if start_did:
|
if start_did:
|
||||||
req_data['start_did'] = start_did
|
req_data['start_did'] = start_did
|
||||||
device_infos: dict = {}
|
device_infos: dict = {}
|
||||||
res_obj = await self.__mihome_api_post_async(
|
res_obj = await self.__mihome_api_post_async(
|
||||||
<<<<<<< HEAD
|
|
||||||
url_path='/app/v2/home/device_list_page',
|
url_path='/app/v2/home/device_list_page',
|
||||||
data=req_data
|
data=req_data
|
||||||
)
|
)
|
||||||
if 'result' not in res_obj:
|
if 'result' not in res_obj:
|
||||||
raise MIoTHttpError('invalid response result')
|
raise MIoTHttpError('invalid response result')
|
||||||
res_obj = res_obj['result']
|
res_obj = res_obj['result']
|
||||||
=======
|
|
||||||
url_path="/app/v2/home/device_list_page", data=req_data)
|
|
||||||
if "result" not in res_obj:
|
|
||||||
raise MIoTHttpError("invalid response result")
|
|
||||||
res_obj = res_obj["result"]
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
for device in res_obj.get('list', []) or []:
|
for device in res_obj.get('list', []) or []:
|
||||||
did = device.get('did', None)
|
did = device.get('did', None)
|
||||||
@ -784,7 +580,6 @@ class MIoTHttpClient:
|
|||||||
model, did)
|
model, did)
|
||||||
continue
|
continue
|
||||||
device_infos[did] = {
|
device_infos[did] = {
|
||||||
<<<<<<< HEAD
|
|
||||||
'did': did,
|
'did': did,
|
||||||
'uid': device.get('uid', None),
|
'uid': device.get('uid', None),
|
||||||
'name': name,
|
'name': name,
|
||||||
@ -811,79 +606,17 @@ class MIoTHttpClient:
|
|||||||
|
|
||||||
next_start_did = res_obj.get('next_start_did', None)
|
next_start_did = res_obj.get('next_start_did', None)
|
||||||
if res_obj.get('has_more', False) and next_start_did:
|
if res_obj.get('has_more', False) and next_start_did:
|
||||||
=======
|
|
||||||
"did":
|
|
||||||
did,
|
|
||||||
"uid":
|
|
||||||
device.get("uid", None),
|
|
||||||
"name":
|
|
||||||
name,
|
|
||||||
"urn":
|
|
||||||
urn,
|
|
||||||
"model":
|
|
||||||
model,
|
|
||||||
"connect_type":
|
|
||||||
device.get("pid", -1),
|
|
||||||
"token":
|
|
||||||
device.get("token", None),
|
|
||||||
"online":
|
|
||||||
device.get("isOnline", False),
|
|
||||||
"icon":
|
|
||||||
device.get("icon", None),
|
|
||||||
"parent_id":
|
|
||||||
device.get("parent_id", None),
|
|
||||||
"manufacturer":
|
|
||||||
model.split(".")[0],
|
|
||||||
# 2: xiao-ai, 1: general speaker
|
|
||||||
"voice_ctrl":
|
|
||||||
device.get("voice_ctrl", 0),
|
|
||||||
"rssi":
|
|
||||||
device.get("rssi", None),
|
|
||||||
"owner":
|
|
||||||
device.get("owner", None),
|
|
||||||
"pid":
|
|
||||||
device.get("pid", None),
|
|
||||||
"local_ip":
|
|
||||||
device.get("local_ip", None),
|
|
||||||
"ssid":
|
|
||||||
device.get("ssid", None),
|
|
||||||
"bssid":
|
|
||||||
device.get("bssid", None),
|
|
||||||
"order_time":
|
|
||||||
device.get("orderTime", 0),
|
|
||||||
"fw_version":
|
|
||||||
device.get("extra", {}).get("fw_version", "unknown"),
|
|
||||||
}
|
|
||||||
if isinstance(device.get("extra", None), dict) and device["extra"]:
|
|
||||||
device_infos[did]["fw_version"] = device["extra"].get(
|
|
||||||
"fw_version", None)
|
|
||||||
device_infos[did]["mcu_version"] = device["extra"].get(
|
|
||||||
"mcu_version", None)
|
|
||||||
device_infos[did]["platform"] = device["extra"].get(
|
|
||||||
"platform", None)
|
|
||||||
|
|
||||||
next_start_did = res_obj.get("next_start_did", None)
|
|
||||||
if res_obj.get("has_more", False) and next_start_did:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
device_infos.update(await self.__get_device_list_page_async(
|
device_infos.update(await self.__get_device_list_page_async(
|
||||||
dids=dids, start_did=next_start_did))
|
dids=dids, start_did=next_start_did))
|
||||||
|
|
||||||
return device_infos
|
return device_infos
|
||||||
|
|
||||||
async def get_devices_with_dids_async(
|
async def get_devices_with_dids_async(
|
||||||
<<<<<<< HEAD
|
|
||||||
self, dids: list[str]
|
self, dids: list[str]
|
||||||
) -> Optional[dict[str, dict]]:
|
) -> Optional[dict[str, dict]]:
|
||||||
results: list[dict[str, dict]] = await asyncio.gather(
|
results: list[dict[str, dict]] = await asyncio.gather(
|
||||||
*[self.__get_device_list_page_async(dids=dids[index:index+150])
|
*[self.__get_device_list_page_async(dids=dids[index:index+150])
|
||||||
for index in range(0, len(dids), 150)])
|
for index in range(0, len(dids), 150)])
|
||||||
=======
|
|
||||||
self, dids: list[str]) -> Optional[dict[str, dict]]:
|
|
||||||
results: list[dict[str, dict]] = await asyncio.gather(*[
|
|
||||||
self.__get_device_list_page_async(dids=dids[index:index + 150])
|
|
||||||
for index in range(0, len(dids), 150)
|
|
||||||
])
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
devices = {}
|
devices = {}
|
||||||
for result in results:
|
for result in results:
|
||||||
if result is None:
|
if result is None:
|
||||||
@ -899,19 +632,13 @@ class MIoTHttpClient:
|
|||||||
devices: dict[str, dict] = {}
|
devices: dict[str, dict] = {}
|
||||||
for device_type in ['home_list', 'share_home_list']:
|
for device_type in ['home_list', 'share_home_list']:
|
||||||
homes.setdefault(device_type, {})
|
homes.setdefault(device_type, {})
|
||||||
<<<<<<< HEAD
|
|
||||||
for home_id, home_info in (homeinfos.get(
|
for home_id, home_info in (homeinfos.get(
|
||||||
device_type, None) or {}).items():
|
device_type, None) or {}).items():
|
||||||
=======
|
|
||||||
for home_id, home_info in (homeinfos.get(device_type, None) or
|
|
||||||
{}).items():
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if isinstance(home_ids, list) and home_id not in home_ids:
|
if isinstance(home_ids, list) and home_id not in home_ids:
|
||||||
continue
|
continue
|
||||||
home_name: str = home_info['home_name']
|
home_name: str = home_info['home_name']
|
||||||
group_id: str = home_info['group_id']
|
group_id: str = home_info['group_id']
|
||||||
homes[device_type].setdefault(
|
homes[device_type].setdefault(
|
||||||
<<<<<<< HEAD
|
|
||||||
home_id, {
|
home_id, {
|
||||||
'home_name': home_name,
|
'home_name': home_name,
|
||||||
'uid': home_info['uid'],
|
'uid': home_info['uid'],
|
||||||
@ -939,44 +666,9 @@ class MIoTHttpClient:
|
|||||||
} for did in room_info.get('dids', [])})
|
} for did in room_info.get('dids', [])})
|
||||||
separated_shared_devices: dict = (
|
separated_shared_devices: dict = (
|
||||||
await self.get_separated_shared_devices_async())
|
await self.get_separated_shared_devices_async())
|
||||||
=======
|
|
||||||
home_id,
|
|
||||||
{
|
|
||||||
"home_name": home_name,
|
|
||||||
"uid": home_info["uid"],
|
|
||||||
"group_id": group_id,
|
|
||||||
"room_info": {},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
devices.update({
|
|
||||||
did: {
|
|
||||||
"home_id": home_id,
|
|
||||||
"home_name": home_name,
|
|
||||||
"room_id": home_id,
|
|
||||||
"room_name": home_name,
|
|
||||||
"group_id": group_id,
|
|
||||||
} for did in home_info.get("dids", [])
|
|
||||||
})
|
|
||||||
for room_id, room_info in home_info.get("room_info").items():
|
|
||||||
room_name: str = room_info.get("room_name", "")
|
|
||||||
homes[device_type][home_id]["room_info"][
|
|
||||||
room_id] = room_name
|
|
||||||
devices.update({
|
|
||||||
did: {
|
|
||||||
"home_id": home_id,
|
|
||||||
"home_name": home_name,
|
|
||||||
"room_id": room_id,
|
|
||||||
"room_name": room_name,
|
|
||||||
"group_id": group_id,
|
|
||||||
} for did in room_info.get("dids", [])
|
|
||||||
})
|
|
||||||
separated_shared_devices: dict = await self.get_separated_shared_devices_async(
|
|
||||||
)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if separated_shared_devices:
|
if separated_shared_devices:
|
||||||
homes.setdefault('separated_shared_list', {})
|
homes.setdefault('separated_shared_list', {})
|
||||||
for did, owner in separated_shared_devices.items():
|
for did, owner in separated_shared_devices.items():
|
||||||
<<<<<<< HEAD
|
|
||||||
owner_id = str(owner['userid'])
|
owner_id = str(owner['userid'])
|
||||||
homes['separated_shared_list'].setdefault(owner_id,{
|
homes['separated_shared_list'].setdefault(owner_id,{
|
||||||
'home_name': owner['nickname'],
|
'home_name': owner['nickname'],
|
||||||
@ -991,29 +683,6 @@ class MIoTHttpClient:
|
|||||||
'room_name': 'shared_device',
|
'room_name': 'shared_device',
|
||||||
'group_id': 'NotSupport'
|
'group_id': 'NotSupport'
|
||||||
}})
|
}})
|
||||||
=======
|
|
||||||
owner_id = str(owner["userid"])
|
|
||||||
homes["separated_shared_list"].setdefault(
|
|
||||||
owner_id,
|
|
||||||
{
|
|
||||||
"home_name": owner["nickname"],
|
|
||||||
"uid": owner_id,
|
|
||||||
"group_id": "NotSupport",
|
|
||||||
"room_info": {
|
|
||||||
"shared_device": "shared_device"
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
devices.update({
|
|
||||||
did: {
|
|
||||||
"home_id": owner_id,
|
|
||||||
"home_name": owner["nickname"],
|
|
||||||
"room_id": "shared_device",
|
|
||||||
"room_name": "shared_device",
|
|
||||||
"group_id": "NotSupport",
|
|
||||||
}
|
|
||||||
})
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
dids = sorted(list(devices.keys()))
|
dids = sorted(list(devices.keys()))
|
||||||
results = await self.get_devices_with_dids_async(dids=dids)
|
results = await self.get_devices_with_dids_async(dids=dids)
|
||||||
if results is None:
|
if results is None:
|
||||||
@ -1031,15 +700,9 @@ class MIoTHttpClient:
|
|||||||
device = devices.pop(did, None)
|
device = devices.pop(did, None)
|
||||||
parent_did = did.replace(match_str.group(), '')
|
parent_did = did.replace(match_str.group(), '')
|
||||||
if parent_did in devices:
|
if parent_did in devices:
|
||||||
<<<<<<< HEAD
|
|
||||||
devices[parent_did].setdefault('sub_devices', {})
|
devices[parent_did].setdefault('sub_devices', {})
|
||||||
devices[parent_did]['sub_devices'][match_str.group()[
|
devices[parent_did]['sub_devices'][match_str.group()[
|
||||||
1:]] = device
|
1:]] = device
|
||||||
=======
|
|
||||||
devices[parent_did].setdefault("sub_devices", {})
|
|
||||||
devices[parent_did]["sub_devices"][match_str.group()
|
|
||||||
[1:]] = device
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
else:
|
else:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
'unknown sub devices, %s, %s', did, parent_did)
|
'unknown sub devices, %s, %s', did, parent_did)
|
||||||
@ -1055,17 +718,10 @@ class MIoTHttpClient:
|
|||||||
{"did": "xxxxxx", "siid": 2, "piid": 2}]
|
{"did": "xxxxxx", "siid": 2, "piid": 2}]
|
||||||
"""
|
"""
|
||||||
res_obj = await self.__mihome_api_post_async(
|
res_obj = await self.__mihome_api_post_async(
|
||||||
<<<<<<< HEAD
|
|
||||||
url_path='/app/v2/miotspec/prop/get',
|
url_path='/app/v2/miotspec/prop/get',
|
||||||
data={
|
data={
|
||||||
'datasource': 1,
|
'datasource': 1,
|
||||||
'params': params
|
'params': params
|
||||||
=======
|
|
||||||
url_path="/app/v2/miotspec/prop/get",
|
|
||||||
data={
|
|
||||||
"datasource": 1,
|
|
||||||
"params": params
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
if 'result' not in res_obj:
|
if 'result' not in res_obj:
|
||||||
@ -1073,16 +729,8 @@ class MIoTHttpClient:
|
|||||||
return res_obj['result']
|
return res_obj['result']
|
||||||
|
|
||||||
async def __get_prop_async(self, did: str, siid: int, piid: int) -> Any:
|
async def __get_prop_async(self, did: str, siid: int, piid: int) -> Any:
|
||||||
<<<<<<< HEAD
|
|
||||||
results = await self.get_props_async(
|
results = await self.get_props_async(
|
||||||
params=[{'did': did, 'siid': siid, 'piid': piid}])
|
params=[{'did': did, 'siid': siid, 'piid': piid}])
|
||||||
=======
|
|
||||||
results = await self.get_props_async(params=[{
|
|
||||||
"did": did,
|
|
||||||
"siid": siid,
|
|
||||||
"piid": piid
|
|
||||||
}])
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if not results:
|
if not results:
|
||||||
return None
|
return None
|
||||||
result = results[0]
|
result = results[0]
|
||||||
@ -1111,11 +759,7 @@ class MIoTHttpClient:
|
|||||||
|
|
||||||
for result in results:
|
for result in results:
|
||||||
if not all(
|
if not all(
|
||||||
<<<<<<< HEAD
|
|
||||||
key in result for key in ['did', 'siid', 'piid', 'value']):
|
key in result for key in ['did', 'siid', 'piid', 'value']):
|
||||||
=======
|
|
||||||
key in result for key in ["did", "siid", "piid", "value"]):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
continue
|
continue
|
||||||
key = f'{result["did"]}.{result["siid"]}.{result["piid"]}'
|
key = f'{result["did"]}.{result["siid"]}.{result["piid"]}'
|
||||||
prop_obj = self._get_prop_list.pop(key, None)
|
prop_obj = self._get_prop_list.pop(key, None)
|
||||||
@ -1156,17 +800,8 @@ class MIoTHttpClient:
|
|||||||
return await prop_obj['fut']
|
return await prop_obj['fut']
|
||||||
fut = self._main_loop.create_future()
|
fut = self._main_loop.create_future()
|
||||||
self._get_prop_list[key] = {
|
self._get_prop_list[key] = {
|
||||||
<<<<<<< HEAD
|
|
||||||
'param': {'did': did, 'siid': siid, 'piid': piid},
|
'param': {'did': did, 'siid': siid, 'piid': piid},
|
||||||
'fut': fut
|
'fut': fut
|
||||||
=======
|
|
||||||
"param": {
|
|
||||||
"did": did,
|
|
||||||
"siid": siid,
|
|
||||||
"piid": piid
|
|
||||||
},
|
|
||||||
"fut": fut,
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
}
|
}
|
||||||
if self._get_prop_timer is None:
|
if self._get_prop_timer is None:
|
||||||
self._get_prop_timer = self._main_loop.call_later(
|
self._get_prop_timer = self._main_loop.call_later(
|
||||||
@ -1181,7 +816,6 @@ class MIoTHttpClient:
|
|||||||
params = [{"did": "xxxx", "siid": 2, "piid": 1, "value": False}]
|
params = [{"did": "xxxx", "siid": 2, "piid": 1, "value": False}]
|
||||||
"""
|
"""
|
||||||
res_obj = await self.__mihome_api_post_async(
|
res_obj = await self.__mihome_api_post_async(
|
||||||
<<<<<<< HEAD
|
|
||||||
url_path='/app/v2/miotspec/prop/set',
|
url_path='/app/v2/miotspec/prop/set',
|
||||||
data={
|
data={
|
||||||
'params': params
|
'params': params
|
||||||
@ -1190,13 +824,6 @@ class MIoTHttpClient:
|
|||||||
)
|
)
|
||||||
if 'result' not in res_obj:
|
if 'result' not in res_obj:
|
||||||
raise MIoTHttpError('invalid response result')
|
raise MIoTHttpError('invalid response result')
|
||||||
=======
|
|
||||||
url_path="/app/v2/miotspec/prop/set",
|
|
||||||
data={"params": params},
|
|
||||||
timeout=15)
|
|
||||||
if "result" not in res_obj:
|
|
||||||
raise MIoTHttpError("invalid response result")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
return res_obj['result']
|
return res_obj['result']
|
||||||
|
|
||||||
@ -1205,7 +832,6 @@ class MIoTHttpClient:
|
|||||||
params = [{"did": "xxxx", "siid": 2, "piid": 1, "value": False}]
|
params = [{"did": "xxxx", "siid": 2, "piid": 1, "value": False}]
|
||||||
"""
|
"""
|
||||||
res_obj = await self.__mihome_api_post_async(
|
res_obj = await self.__mihome_api_post_async(
|
||||||
<<<<<<< HEAD
|
|
||||||
url_path='/app/v2/miotspec/prop/set',
|
url_path='/app/v2/miotspec/prop/set',
|
||||||
data={
|
data={
|
||||||
'params': params
|
'params': params
|
||||||
@ -1214,13 +840,6 @@ class MIoTHttpClient:
|
|||||||
)
|
)
|
||||||
if 'result' not in res_obj:
|
if 'result' not in res_obj:
|
||||||
raise MIoTHttpError('invalid response result')
|
raise MIoTHttpError('invalid response result')
|
||||||
=======
|
|
||||||
url_path="/app/v2/miotspec/prop/set",
|
|
||||||
data={"params": params},
|
|
||||||
timeout=15)
|
|
||||||
if "result" not in res_obj:
|
|
||||||
raise MIoTHttpError("invalid response result")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
return res_obj['result']
|
return res_obj['result']
|
||||||
|
|
||||||
|
|||||||
@ -114,14 +114,9 @@ class MIoTEntityData:
|
|||||||
events: set[MIoTSpecEvent]
|
events: set[MIoTSpecEvent]
|
||||||
actions: set[MIoTSpecAction]
|
actions: set[MIoTSpecAction]
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self, platform: str, spec: MIoTSpecInstance | MIoTSpecService
|
self, platform: str, spec: MIoTSpecInstance | MIoTSpecService
|
||||||
) -> None:
|
) -> None:
|
||||||
=======
|
|
||||||
def __init__(self, platform: str,
|
|
||||||
spec: MIoTSpecInstance | MIoTSpecService) -> None:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self.platform = platform
|
self.platform = platform
|
||||||
self.spec = spec
|
self.spec = spec
|
||||||
self.device_class = None
|
self.device_class = None
|
||||||
@ -154,13 +149,8 @@ class MIoTDevice:
|
|||||||
_suggested_area: Optional[str]
|
_suggested_area: Optional[str]
|
||||||
|
|
||||||
_sub_id: int
|
_sub_id: int
|
||||||
<<<<<<< HEAD
|
|
||||||
_device_state_sub_list: dict[str, dict[
|
_device_state_sub_list: dict[str, dict[
|
||||||
str, Callable[[str, MIoTDeviceState], None]]]
|
str, Callable[[str, MIoTDeviceState], None]]]
|
||||||
=======
|
|
||||||
_device_state_sub_list: dict[str, dict[str, Callable[[str, MIoTDeviceState],
|
|
||||||
None]]]
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
_value_sub_list: dict[str, dict[str, Callable[[dict, Any], None]]]
|
_value_sub_list: dict[str, dict[str, Callable[[dict, Any], None]]]
|
||||||
|
|
||||||
_entity_list: dict[str, list[MIoTEntityData]]
|
_entity_list: dict[str, list[MIoTEntityData]]
|
||||||
@ -190,17 +180,10 @@ class MIoTDevice:
|
|||||||
self._room_id = device_info.get('room_id', None)
|
self._room_id = device_info.get('room_id', None)
|
||||||
self._room_name = device_info.get('room_name', None)
|
self._room_name = device_info.get('room_name', None)
|
||||||
match self.miot_client.area_name_rule:
|
match self.miot_client.area_name_rule:
|
||||||
<<<<<<< HEAD
|
|
||||||
case 'home_room':
|
case 'home_room':
|
||||||
self._suggested_area = (
|
self._suggested_area = (
|
||||||
f'{self._home_name} {self._room_name}'.strip())
|
f'{self._home_name} {self._room_name}'.strip())
|
||||||
case 'home':
|
case 'home':
|
||||||
=======
|
|
||||||
case "home_room":
|
|
||||||
self._suggested_area = f"{self._home_name} {self._room_name}".strip(
|
|
||||||
)
|
|
||||||
case "home":
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._suggested_area = self._home_name.strip()
|
self._suggested_area = self._home_name.strip()
|
||||||
case 'room':
|
case 'room':
|
||||||
self._suggested_area = self._room_name.strip()
|
self._suggested_area = self._room_name.strip()
|
||||||
@ -222,7 +205,6 @@ class MIoTDevice:
|
|||||||
sub_info = sub_devices.get(f's{service.iid}', None)
|
sub_info = sub_devices.get(f's{service.iid}', None)
|
||||||
if sub_info is None:
|
if sub_info is None:
|
||||||
continue
|
continue
|
||||||
<<<<<<< HEAD
|
|
||||||
_LOGGER.debug(
|
_LOGGER.debug(
|
||||||
'miot device, update service sub info, %s, %s',
|
'miot device, update service sub info, %s, %s',
|
||||||
self.did, sub_info)
|
self.did, sub_info)
|
||||||
@ -232,16 +214,6 @@ class MIoTDevice:
|
|||||||
# Sub device state
|
# Sub device state
|
||||||
self.miot_client.sub_device_state(
|
self.miot_client.sub_device_state(
|
||||||
self._did, self.__on_device_state_changed)
|
self._did, self.__on_device_state_changed)
|
||||||
=======
|
|
||||||
_LOGGER.debug("miot device, update service sub info, %s, %s",
|
|
||||||
self.did, sub_info)
|
|
||||||
service.description_trans = sub_info.get(
|
|
||||||
"name", service.description_trans)
|
|
||||||
|
|
||||||
# Sub device state
|
|
||||||
self.miot_client.sub_device_state(self._did,
|
|
||||||
self.__on_device_state_changed)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
_LOGGER.debug('miot device init %s', device_info)
|
_LOGGER.debug('miot device init %s', device_info)
|
||||||
|
|
||||||
@ -266,15 +238,8 @@ class MIoTDevice:
|
|||||||
return self._action_list
|
return self._action_list
|
||||||
|
|
||||||
async def action_async(self, siid: int, aiid: int, in_list: list) -> list:
|
async def action_async(self, siid: int, aiid: int, in_list: list) -> list:
|
||||||
<<<<<<< HEAD
|
|
||||||
return await self.miot_client.action_async(
|
return await self.miot_client.action_async(
|
||||||
did=self._did, siid=siid, aiid=aiid, in_list=in_list)
|
did=self._did, siid=siid, aiid=aiid, in_list=in_list)
|
||||||
=======
|
|
||||||
return await self.miot_client.action_async(did=self._did,
|
|
||||||
siid=siid,
|
|
||||||
aiid=aiid,
|
|
||||||
in_list=in_list)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def sub_device_state(
|
def sub_device_state(
|
||||||
self, key: str, handler: Callable[[str, MIoTDeviceState],
|
self, key: str, handler: Callable[[str, MIoTDeviceState],
|
||||||
@ -293,16 +258,10 @@ class MIoTDevice:
|
|||||||
if not sub_list:
|
if not sub_list:
|
||||||
self._device_state_sub_list.pop(key, None)
|
self._device_state_sub_list.pop(key, None)
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def sub_property(
|
def sub_property(
|
||||||
self, handler: Callable[[dict, Any], None], siid: int, piid: int
|
self, handler: Callable[[dict, Any], None], siid: int, piid: int
|
||||||
) -> int:
|
) -> int:
|
||||||
key: str = f'p.{siid}.{piid}'
|
key: str = f'p.{siid}.{piid}'
|
||||||
=======
|
|
||||||
def sub_property(self, handler: Callable[[dict, Any], None], siid: int,
|
|
||||||
piid: int) -> int:
|
|
||||||
key: str = f"p.{siid}.{piid}"
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def _on_prop_changed(params: dict, ctx: Any) -> None:
|
def _on_prop_changed(params: dict, ctx: Any) -> None:
|
||||||
for handler in self._value_sub_list[key].values():
|
for handler in self._value_sub_list[key].values():
|
||||||
@ -313,15 +272,8 @@ class MIoTDevice:
|
|||||||
self._value_sub_list[key][str(sub_id)] = handler
|
self._value_sub_list[key][str(sub_id)] = handler
|
||||||
else:
|
else:
|
||||||
self._value_sub_list[key] = {str(sub_id): handler}
|
self._value_sub_list[key] = {str(sub_id): handler}
|
||||||
<<<<<<< HEAD
|
|
||||||
self.miot_client.sub_prop(
|
self.miot_client.sub_prop(
|
||||||
did=self._did, handler=_on_prop_changed, siid=siid, piid=piid)
|
did=self._did, handler=_on_prop_changed, siid=siid, piid=piid)
|
||||||
=======
|
|
||||||
self.miot_client.sub_prop(did=self._did,
|
|
||||||
handler=_on_prop_changed,
|
|
||||||
siid=siid,
|
|
||||||
piid=piid)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return sub_id
|
return sub_id
|
||||||
|
|
||||||
def unsub_property(self, siid: int, piid: int, sub_id: int) -> None:
|
def unsub_property(self, siid: int, piid: int, sub_id: int) -> None:
|
||||||
@ -334,16 +286,10 @@ class MIoTDevice:
|
|||||||
self.miot_client.unsub_prop(did=self._did, siid=siid, piid=piid)
|
self.miot_client.unsub_prop(did=self._did, siid=siid, piid=piid)
|
||||||
self._value_sub_list.pop(key, None)
|
self._value_sub_list.pop(key, None)
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def sub_event(
|
def sub_event(
|
||||||
self, handler: Callable[[dict, Any], None], siid: int, eiid: int
|
self, handler: Callable[[dict, Any], None], siid: int, eiid: int
|
||||||
) -> int:
|
) -> int:
|
||||||
key: str = f'e.{siid}.{eiid}'
|
key: str = f'e.{siid}.{eiid}'
|
||||||
=======
|
|
||||||
def sub_event(self, handler: Callable[[dict, Any], None], siid: int,
|
|
||||||
eiid: int) -> int:
|
|
||||||
key: str = f"e.{siid}.{eiid}"
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def _on_event_occurred(params: dict, ctx: Any) -> None:
|
def _on_event_occurred(params: dict, ctx: Any) -> None:
|
||||||
for handler in self._value_sub_list[key].values():
|
for handler in self._value_sub_list[key].values():
|
||||||
@ -354,15 +300,8 @@ class MIoTDevice:
|
|||||||
self._value_sub_list[key][str(sub_id)] = handler
|
self._value_sub_list[key][str(sub_id)] = handler
|
||||||
else:
|
else:
|
||||||
self._value_sub_list[key] = {str(sub_id): handler}
|
self._value_sub_list[key] = {str(sub_id): handler}
|
||||||
<<<<<<< HEAD
|
|
||||||
self.miot_client.sub_event(
|
self.miot_client.sub_event(
|
||||||
did=self._did, handler=_on_event_occurred, siid=siid, eiid=eiid)
|
did=self._did, handler=_on_event_occurred, siid=siid, eiid=eiid)
|
||||||
=======
|
|
||||||
self.miot_client.sub_event(did=self._did,
|
|
||||||
handler=_on_event_occurred,
|
|
||||||
siid=siid,
|
|
||||||
eiid=eiid)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return sub_id
|
return sub_id
|
||||||
|
|
||||||
def unsub_event(self, siid: int, eiid: int, sub_id: int) -> None:
|
def unsub_event(self, siid: int, eiid: int, sub_id: int) -> None:
|
||||||
@ -386,13 +325,8 @@ class MIoTDevice:
|
|||||||
manufacturer=self._manufacturer,
|
manufacturer=self._manufacturer,
|
||||||
suggested_area=self._suggested_area,
|
suggested_area=self._suggested_area,
|
||||||
configuration_url=(
|
configuration_url=(
|
||||||
<<<<<<< HEAD
|
|
||||||
f'https://home.mi.com/webapp/content/baike/product/index.html?'
|
f'https://home.mi.com/webapp/content/baike/product/index.html?'
|
||||||
f'model={self._model}')
|
f'model={self._model}')
|
||||||
=======
|
|
||||||
f"https://home.mi.com/webapp/content/baike/product/index.html?"
|
|
||||||
f"model={self._model}"),
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -402,7 +336,6 @@ class MIoTDevice:
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def did_tag(self) -> str:
|
def did_tag(self) -> str:
|
||||||
<<<<<<< HEAD
|
|
||||||
return slugify_did(
|
return slugify_did(
|
||||||
cloud_server=self.miot_client.cloud_server, did=self._did)
|
cloud_server=self.miot_client.cloud_server, did=self._did)
|
||||||
|
|
||||||
@ -440,37 +373,6 @@ class MIoTDevice:
|
|||||||
f'{ha_domain}.{self._model_strs[0][:9]}_{self.did_tag}_'
|
f'{ha_domain}.{self._model_strs[0][:9]}_{self.did_tag}_'
|
||||||
f'{self._model_strs[-1][:20]}_{slugify_name(spec_name)}'
|
f'{self._model_strs[-1][:20]}_{slugify_name(spec_name)}'
|
||||||
f'_a_{siid}_{aiid}')
|
f'_a_{siid}_{aiid}')
|
||||||
=======
|
|
||||||
return slugify_did(cloud_server=self.miot_client.cloud_server,
|
|
||||||
did=self._did)
|
|
||||||
|
|
||||||
def gen_device_entity_id(self, ha_domain: str) -> str:
|
|
||||||
return (f"{ha_domain}.{self._model_strs[0][:9]}_{self.did_tag}_"
|
|
||||||
f"{self._model_strs[-1][:20]}")
|
|
||||||
|
|
||||||
def gen_service_entity_id(self, ha_domain: str, siid: int,
|
|
||||||
description: str) -> str:
|
|
||||||
return (f"{ha_domain}.{self._model_strs[0][:9]}_{self.did_tag}_"
|
|
||||||
f"{self._model_strs[-1][:20]}_s_{siid}_{description}")
|
|
||||||
|
|
||||||
def gen_prop_entity_id(self, ha_domain: str, spec_name: str, siid: int,
|
|
||||||
piid: int) -> str:
|
|
||||||
return (f"{ha_domain}.{self._model_strs[0][:9]}_{self.did_tag}_"
|
|
||||||
f"{self._model_strs[-1][:20]}_{slugify_name(spec_name)}"
|
|
||||||
f"_p_{siid}_{piid}")
|
|
||||||
|
|
||||||
def gen_event_entity_id(self, ha_domain: str, spec_name: str, siid: int,
|
|
||||||
eiid: int) -> str:
|
|
||||||
return (f"{ha_domain}.{self._model_strs[0][:9]}_{self.did_tag}_"
|
|
||||||
f"{self._model_strs[-1][:20]}_{slugify_name(spec_name)}"
|
|
||||||
f"_e_{siid}_{eiid}")
|
|
||||||
|
|
||||||
def gen_action_entity_id(self, ha_domain: str, spec_name: str, siid: int,
|
|
||||||
aiid: int) -> str:
|
|
||||||
return (f"{ha_domain}.{self._model_strs[0][:9]}_{self.did_tag}_"
|
|
||||||
f"{self._model_strs[-1][:20]}_{slugify_name(spec_name)}"
|
|
||||||
f"_a_{siid}_{aiid}")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self) -> str:
|
def name(self) -> str:
|
||||||
@ -516,16 +418,10 @@ class MIoTDevice:
|
|||||||
if 'required' not in SPEC_DEVICE_TRANS_MAP[spec_name]:
|
if 'required' not in SPEC_DEVICE_TRANS_MAP[spec_name]:
|
||||||
return None
|
return None
|
||||||
# 1. The device shall have all required services.
|
# 1. The device shall have all required services.
|
||||||
<<<<<<< HEAD
|
|
||||||
required_services = SPEC_DEVICE_TRANS_MAP[spec_name]['required'].keys()
|
required_services = SPEC_DEVICE_TRANS_MAP[spec_name]['required'].keys()
|
||||||
if not {
|
if not {
|
||||||
service.name for service in spec_instance.services
|
service.name for service in spec_instance.services
|
||||||
}.issuperset(required_services):
|
}.issuperset(required_services):
|
||||||
=======
|
|
||||||
required_services = SPEC_DEVICE_TRANS_MAP[spec_name]["required"].keys()
|
|
||||||
if not {service.name for service in spec_instance.services
|
|
||||||
}.issuperset(required_services):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return None
|
return None
|
||||||
optional_services = SPEC_DEVICE_TRANS_MAP[spec_name]['optional'].keys()
|
optional_services = SPEC_DEVICE_TRANS_MAP[spec_name]['optional'].keys()
|
||||||
|
|
||||||
@ -541,7 +437,6 @@ class MIoTDevice:
|
|||||||
# 2. The required service shall have all required properties
|
# 2. The required service shall have all required properties
|
||||||
# and actions.
|
# and actions.
|
||||||
if service.name in required_services:
|
if service.name in required_services:
|
||||||
<<<<<<< HEAD
|
|
||||||
required_properties = SPEC_DEVICE_TRANS_MAP[spec_name][
|
required_properties = SPEC_DEVICE_TRANS_MAP[spec_name][
|
||||||
'required'].get(
|
'required'].get(
|
||||||
service.name, {}
|
service.name, {}
|
||||||
@ -613,59 +508,6 @@ class MIoTDevice:
|
|||||||
for prop in service.properties:
|
for prop in service.properties:
|
||||||
if prop.name in set.union(
|
if prop.name in set.union(
|
||||||
set(required_properties.keys()), optional_properties):
|
set(required_properties.keys()), optional_properties):
|
||||||
=======
|
|
||||||
required_properties = (
|
|
||||||
SPEC_DEVICE_TRANS_MAP[spec_name]["required"].get(
|
|
||||||
service.name, {}).get("required",
|
|
||||||
{}).get("properties", {}))
|
|
||||||
optional_properties = (
|
|
||||||
SPEC_DEVICE_TRANS_MAP[spec_name]["required"].get(
|
|
||||||
service.name, {}).get("optional",
|
|
||||||
{}).get("properties", set({})))
|
|
||||||
required_actions = (
|
|
||||||
SPEC_DEVICE_TRANS_MAP[spec_name]["required"].get(
|
|
||||||
service.name, {}).get("required",
|
|
||||||
{}).get("actions", set({})))
|
|
||||||
optional_actions = (
|
|
||||||
SPEC_DEVICE_TRANS_MAP[spec_name]["required"].get(
|
|
||||||
service.name, {}).get("optional",
|
|
||||||
{}).get("actions", set({})))
|
|
||||||
elif service.name in optional_services:
|
|
||||||
required_properties = (
|
|
||||||
SPEC_DEVICE_TRANS_MAP[spec_name]["optional"].get(
|
|
||||||
service.name, {}).get("required",
|
|
||||||
{}).get("properties", {}))
|
|
||||||
optional_properties = (
|
|
||||||
SPEC_DEVICE_TRANS_MAP[spec_name]["optional"].get(
|
|
||||||
service.name, {}).get("optional",
|
|
||||||
{}).get("properties", set({})))
|
|
||||||
required_actions = (
|
|
||||||
SPEC_DEVICE_TRANS_MAP[spec_name]["optional"].get(
|
|
||||||
service.name, {}).get("required",
|
|
||||||
{}).get("actions", set({})))
|
|
||||||
optional_actions = (
|
|
||||||
SPEC_DEVICE_TRANS_MAP[spec_name]["optional"].get(
|
|
||||||
service.name, {}).get("optional",
|
|
||||||
{}).get("actions", set({})))
|
|
||||||
else:
|
|
||||||
continue
|
|
||||||
if not {prop.name for prop in service.properties if prop.access
|
|
||||||
}.issuperset(set(required_properties.keys())):
|
|
||||||
return None
|
|
||||||
if not {action.name for action in service.actions
|
|
||||||
}.issuperset(required_actions):
|
|
||||||
return None
|
|
||||||
# 3. The required property shall have all required access mode.
|
|
||||||
for prop in service.properties:
|
|
||||||
if prop.name in required_properties:
|
|
||||||
if not set(prop.access).issuperset(
|
|
||||||
required_properties[prop.name]):
|
|
||||||
return None
|
|
||||||
# property
|
|
||||||
for prop in service.properties:
|
|
||||||
if prop.name in set.union(set(required_properties.keys()),
|
|
||||||
optional_properties):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if prop.unit:
|
if prop.unit:
|
||||||
prop.external_unit = self.unit_convert(prop.unit)
|
prop.external_unit = self.unit_convert(prop.unit)
|
||||||
# prop.icon = self.icon_convert(prop.unit)
|
# prop.icon = self.icon_convert(prop.unit)
|
||||||
@ -683,17 +525,12 @@ class MIoTDevice:
|
|||||||
return entity_data
|
return entity_data
|
||||||
|
|
||||||
def parse_miot_service_entity(
|
def parse_miot_service_entity(
|
||||||
<<<<<<< HEAD
|
|
||||||
self, miot_service: MIoTSpecService
|
self, miot_service: MIoTSpecService
|
||||||
) -> Optional[MIoTEntityData]:
|
) -> Optional[MIoTEntityData]:
|
||||||
if (
|
if (
|
||||||
miot_service.platform
|
miot_service.platform
|
||||||
or miot_service.name not in SPEC_SERVICE_TRANS_MAP
|
or miot_service.name not in SPEC_SERVICE_TRANS_MAP
|
||||||
):
|
):
|
||||||
=======
|
|
||||||
self, miot_service: MIoTSpecService) -> Optional[MIoTEntityData]:
|
|
||||||
if miot_service.platform or miot_service.name not in SPEC_SERVICE_TRANS_MAP:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return None
|
return None
|
||||||
service_name = miot_service.name
|
service_name = miot_service.name
|
||||||
if isinstance(SPEC_SERVICE_TRANS_MAP[service_name], str):
|
if isinstance(SPEC_SERVICE_TRANS_MAP[service_name], str):
|
||||||
@ -702,16 +539,10 @@ class MIoTDevice:
|
|||||||
return None
|
return None
|
||||||
# Required properties, required access mode
|
# Required properties, required access mode
|
||||||
required_properties: dict = SPEC_SERVICE_TRANS_MAP[service_name][
|
required_properties: dict = SPEC_SERVICE_TRANS_MAP[service_name][
|
||||||
<<<<<<< HEAD
|
|
||||||
'required'].get('properties', {})
|
'required'].get('properties', {})
|
||||||
if not {
|
if not {
|
||||||
prop.name for prop in miot_service.properties if prop.access
|
prop.name for prop in miot_service.properties if prop.access
|
||||||
}.issuperset(set(required_properties.keys())):
|
}.issuperset(set(required_properties.keys())):
|
||||||
=======
|
|
||||||
"required"].get("properties", {})
|
|
||||||
if not {prop.name for prop in miot_service.properties if prop.access
|
|
||||||
}.issuperset(set(required_properties.keys())):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return None
|
return None
|
||||||
for prop in miot_service.properties:
|
for prop in miot_service.properties:
|
||||||
if prop.name in required_properties:
|
if prop.name in required_properties:
|
||||||
@ -724,17 +555,10 @@ class MIoTDevice:
|
|||||||
entity_data = MIoTEntityData(platform=platform, spec=miot_service)
|
entity_data = MIoTEntityData(platform=platform, spec=miot_service)
|
||||||
# Optional properties
|
# Optional properties
|
||||||
optional_properties = SPEC_SERVICE_TRANS_MAP[service_name][
|
optional_properties = SPEC_SERVICE_TRANS_MAP[service_name][
|
||||||
<<<<<<< HEAD
|
|
||||||
'optional'].get('properties', set({}))
|
'optional'].get('properties', set({}))
|
||||||
for prop in miot_service.properties:
|
for prop in miot_service.properties:
|
||||||
if prop.name in set.union(
|
if prop.name in set.union(
|
||||||
set(required_properties.keys()), optional_properties):
|
set(required_properties.keys()), optional_properties):
|
||||||
=======
|
|
||||||
"optional"].get("properties", set({}))
|
|
||||||
for prop in miot_service.properties:
|
|
||||||
if prop.name in set.union(set(required_properties.keys()),
|
|
||||||
optional_properties):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if prop.unit:
|
if prop.unit:
|
||||||
prop.external_unit = self.unit_convert(prop.unit)
|
prop.external_unit = self.unit_convert(prop.unit)
|
||||||
# prop.icon = self.icon_convert(prop.unit)
|
# prop.icon = self.icon_convert(prop.unit)
|
||||||
@ -745,24 +569,15 @@ class MIoTDevice:
|
|||||||
miot_service.platform = platform
|
miot_service.platform = platform
|
||||||
# entity_category
|
# entity_category
|
||||||
if entity_category := SPEC_SERVICE_TRANS_MAP[service_name].get(
|
if entity_category := SPEC_SERVICE_TRANS_MAP[service_name].get(
|
||||||
<<<<<<< HEAD
|
|
||||||
'entity_category', None):
|
'entity_category', None):
|
||||||
=======
|
|
||||||
"entity_category", None):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
miot_service.entity_category = entity_category
|
miot_service.entity_category = entity_category
|
||||||
return entity_data
|
return entity_data
|
||||||
|
|
||||||
def parse_miot_property_entity(self, miot_prop: MIoTSpecProperty) -> bool:
|
def parse_miot_property_entity(self, miot_prop: MIoTSpecProperty) -> bool:
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
miot_prop.platform
|
miot_prop.platform
|
||||||
or miot_prop.name not in SPEC_PROP_TRANS_MAP['properties']
|
or miot_prop.name not in SPEC_PROP_TRANS_MAP['properties']
|
||||||
):
|
):
|
||||||
=======
|
|
||||||
if (miot_prop.platform or
|
|
||||||
miot_prop.name not in SPEC_PROP_TRANS_MAP["properties"]):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return False
|
return False
|
||||||
prop_name = miot_prop.name
|
prop_name = miot_prop.name
|
||||||
if isinstance(SPEC_PROP_TRANS_MAP['properties'][prop_name], str):
|
if isinstance(SPEC_PROP_TRANS_MAP['properties'][prop_name], str):
|
||||||
@ -777,7 +592,6 @@ class MIoTDevice:
|
|||||||
if prop_access != (SPEC_PROP_TRANS_MAP[
|
if prop_access != (SPEC_PROP_TRANS_MAP[
|
||||||
'entities'][platform]['access']):
|
'entities'][platform]['access']):
|
||||||
return False
|
return False
|
||||||
<<<<<<< HEAD
|
|
||||||
if miot_prop.format_.__name__ not in SPEC_PROP_TRANS_MAP[
|
if miot_prop.format_.__name__ not in SPEC_PROP_TRANS_MAP[
|
||||||
'entities'][platform]['format']:
|
'entities'][platform]['format']:
|
||||||
return False
|
return False
|
||||||
@ -795,22 +609,6 @@ class MIoTDevice:
|
|||||||
# Priority: spec_modify.unit > unit_convert > specv2entity.unit
|
# Priority: spec_modify.unit > unit_convert > specv2entity.unit
|
||||||
miot_prop.external_unit = SPEC_PROP_TRANS_MAP['properties'][
|
miot_prop.external_unit = SPEC_PROP_TRANS_MAP['properties'][
|
||||||
prop_name]['unit_of_measurement']
|
prop_name]['unit_of_measurement']
|
||||||
=======
|
|
||||||
if (miot_prop.format_.__name__
|
|
||||||
not in SPEC_PROP_TRANS_MAP["entities"][platform]["format"]):
|
|
||||||
return False
|
|
||||||
miot_prop.device_class = SPEC_PROP_TRANS_MAP["properties"][prop_name][
|
|
||||||
"device_class"]
|
|
||||||
# Optional params
|
|
||||||
if "state_class" in SPEC_PROP_TRANS_MAP["properties"][prop_name]:
|
|
||||||
miot_prop.state_class = SPEC_PROP_TRANS_MAP["properties"][
|
|
||||||
prop_name]["state_class"]
|
|
||||||
if (not miot_prop.external_unit and "unit_of_measurement"
|
|
||||||
in SPEC_PROP_TRANS_MAP["properties"][prop_name]):
|
|
||||||
# Priority: spec_modify.unit > unit_convert > specv2entity.unit
|
|
||||||
miot_prop.external_unit = SPEC_PROP_TRANS_MAP["properties"][
|
|
||||||
prop_name]["unit_of_measurement"]
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
# Priority: default.icon when device_class is set > spec_modify.icon
|
# Priority: default.icon when device_class is set > spec_modify.icon
|
||||||
# > icon_convert
|
# > icon_convert
|
||||||
miot_prop.platform = platform
|
miot_prop.platform = platform
|
||||||
@ -1011,18 +809,7 @@ class MIoTDevice:
|
|||||||
if spec_unit in {'percentage'}:
|
if spec_unit in {'percentage'}:
|
||||||
return 'mdi:percent'
|
return 'mdi:percent'
|
||||||
if spec_unit in {
|
if spec_unit in {
|
||||||
<<<<<<< HEAD
|
|
||||||
'weeks', 'days', 'hour', 'hours', 'minutes', 'seconds', 'ms', 'μs'
|
'weeks', 'days', 'hour', 'hours', 'minutes', 'seconds', 'ms', 'μs'
|
||||||
=======
|
|
||||||
"weeks",
|
|
||||||
"days",
|
|
||||||
"hour",
|
|
||||||
"hours",
|
|
||||||
"minutes",
|
|
||||||
"seconds",
|
|
||||||
"ms",
|
|
||||||
"μs",
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
}:
|
}:
|
||||||
return 'mdi:clock'
|
return 'mdi:clock'
|
||||||
if spec_unit in {'celsius'}:
|
if spec_unit in {'celsius'}:
|
||||||
@ -1100,7 +887,6 @@ class MIoTServiceEntity(Entity):
|
|||||||
_state_sub_id: int
|
_state_sub_id: int
|
||||||
_value_sub_ids: dict[str, int]
|
_value_sub_ids: dict[str, int]
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
_event_occurred_handler: Optional[
|
_event_occurred_handler: Optional[
|
||||||
Callable[[MIoTSpecEvent, dict], None]]
|
Callable[[MIoTSpecEvent, dict], None]]
|
||||||
_prop_changed_subs: dict[
|
_prop_changed_subs: dict[
|
||||||
@ -1117,18 +903,6 @@ class MIoTServiceEntity(Entity):
|
|||||||
or entity_data.spec is None
|
or entity_data.spec is None
|
||||||
):
|
):
|
||||||
raise MIoTDeviceError('init error, invalid params')
|
raise MIoTDeviceError('init error, invalid params')
|
||||||
=======
|
|
||||||
_event_occurred_handler: Optional[Callable[[MIoTSpecEvent, dict], None]]
|
|
||||||
_prop_changed_subs: dict[MIoTSpecProperty, Callable[[MIoTSpecProperty, Any],
|
|
||||||
None]]
|
|
||||||
|
|
||||||
_pending_write_ha_state_timer: Optional[asyncio.TimerHandle]
|
|
||||||
|
|
||||||
def __init__(self, miot_device: MIoTDevice,
|
|
||||||
entity_data: MIoTEntityData) -> None:
|
|
||||||
if miot_device is None or entity_data is None or entity_data.spec is None:
|
|
||||||
raise MIoTDeviceError("init error, invalid params")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self.miot_device = miot_device
|
self.miot_device = miot_device
|
||||||
self.entity_data = entity_data
|
self.entity_data = entity_data
|
||||||
self._main_loop = miot_device.miot_client.main_loop
|
self._main_loop = miot_device.miot_client.main_loop
|
||||||
@ -1144,13 +918,8 @@ class MIoTServiceEntity(Entity):
|
|||||||
DOMAIN, siid=self.entity_data.spec.iid,
|
DOMAIN, siid=self.entity_data.spec.iid,
|
||||||
description=self.entity_data.spec.description)
|
description=self.entity_data.spec.description)
|
||||||
self._attr_name = (
|
self._attr_name = (
|
||||||
<<<<<<< HEAD
|
|
||||||
f'{"* "if self.entity_data.spec.proprietary else " "}'
|
f'{"* "if self.entity_data.spec.proprietary else " "}'
|
||||||
f'{self.entity_data.spec.description_trans}')
|
f'{self.entity_data.spec.description_trans}')
|
||||||
=======
|
|
||||||
f"{'* ' if self.entity_data.spec.proprietary else ' '}"
|
|
||||||
f"{self.entity_data.spec.description_trans}")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._attr_entity_category = entity_data.spec.entity_category
|
self._attr_entity_category = entity_data.spec.entity_category
|
||||||
# Set entity attr
|
# Set entity attr
|
||||||
self._attr_unique_id = self.entity_id
|
self._attr_unique_id = self.entity_id
|
||||||
@ -1168,12 +937,8 @@ class MIoTServiceEntity(Entity):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def event_occurred_handler(
|
def event_occurred_handler(
|
||||||
<<<<<<< HEAD
|
|
||||||
self
|
self
|
||||||
) -> Optional[Callable[[MIoTSpecEvent, dict], None]]:
|
) -> Optional[Callable[[MIoTSpecEvent, dict], None]]:
|
||||||
=======
|
|
||||||
self) -> Optional[Callable[[MIoTSpecEvent, dict], None]]:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return self._event_occurred_handler
|
return self._event_occurred_handler
|
||||||
|
|
||||||
@event_occurred_handler.setter
|
@event_occurred_handler.setter
|
||||||
@ -1181,14 +946,9 @@ class MIoTServiceEntity(Entity):
|
|||||||
self._event_occurred_handler = func
|
self._event_occurred_handler = func
|
||||||
|
|
||||||
def sub_prop_changed(
|
def sub_prop_changed(
|
||||||
<<<<<<< HEAD
|
|
||||||
self, prop: MIoTSpecProperty,
|
self, prop: MIoTSpecProperty,
|
||||||
handler: Callable[[MIoTSpecProperty, Any], None]
|
handler: Callable[[MIoTSpecProperty, Any], None]
|
||||||
) -> None:
|
) -> None:
|
||||||
=======
|
|
||||||
self, prop: MIoTSpecProperty,
|
|
||||||
handler: Callable[[MIoTSpecProperty, Any], None]) -> None:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if not prop or not handler:
|
if not prop or not handler:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
'sub_prop_changed error, invalid prop/handler')
|
'sub_prop_changed error, invalid prop/handler')
|
||||||
@ -1221,12 +981,7 @@ class MIoTServiceEntity(Entity):
|
|||||||
key = f'e.{event.service.iid}.{event.iid}'
|
key = f'e.{event.service.iid}.{event.iid}'
|
||||||
self._value_sub_ids[key] = self.miot_device.sub_event(
|
self._value_sub_ids[key] = self.miot_device.sub_event(
|
||||||
handler=self.__on_event_occurred,
|
handler=self.__on_event_occurred,
|
||||||
<<<<<<< HEAD
|
|
||||||
siid=event.service.iid, eiid=event.iid)
|
siid=event.service.iid, eiid=event.iid)
|
||||||
=======
|
|
||||||
siid=event.service.iid,
|
|
||||||
eiid=event.iid)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
# Refresh value
|
# Refresh value
|
||||||
if self._attr_available:
|
if self._attr_available:
|
||||||
@ -1238,20 +993,13 @@ class MIoTServiceEntity(Entity):
|
|||||||
self._pending_write_ha_state_timer = None
|
self._pending_write_ha_state_timer = None
|
||||||
state_id = 's.0'
|
state_id = 's.0'
|
||||||
if isinstance(self.entity_data.spec, MIoTSpecService):
|
if isinstance(self.entity_data.spec, MIoTSpecService):
|
||||||
<<<<<<< HEAD
|
|
||||||
state_id = f's.{self.entity_data.spec.iid}'
|
state_id = f's.{self.entity_data.spec.iid}'
|
||||||
self.miot_device.unsub_device_state(
|
self.miot_device.unsub_device_state(
|
||||||
key=state_id, sub_id=self._state_sub_id)
|
key=state_id, sub_id=self._state_sub_id)
|
||||||
=======
|
|
||||||
state_id = f"s.{self.entity_data.spec.iid}"
|
|
||||||
self.miot_device.unsub_device_state(key=state_id,
|
|
||||||
sub_id=self._state_sub_id)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
# Unsub prop
|
# Unsub prop
|
||||||
for prop in self.entity_data.props:
|
for prop in self.entity_data.props:
|
||||||
if not prop.notifiable and not prop.readable:
|
if not prop.notifiable and not prop.readable:
|
||||||
continue
|
continue
|
||||||
<<<<<<< HEAD
|
|
||||||
sub_id = self._value_sub_ids.pop(
|
sub_id = self._value_sub_ids.pop(
|
||||||
f'p.{prop.service.iid}.{prop.iid}', None)
|
f'p.{prop.service.iid}.{prop.iid}', None)
|
||||||
if sub_id:
|
if sub_id:
|
||||||
@ -1264,22 +1012,6 @@ class MIoTServiceEntity(Entity):
|
|||||||
if sub_id:
|
if sub_id:
|
||||||
self.miot_device.unsub_event(
|
self.miot_device.unsub_event(
|
||||||
siid=event.service.iid, eiid=event.iid, sub_id=sub_id)
|
siid=event.service.iid, eiid=event.iid, sub_id=sub_id)
|
||||||
=======
|
|
||||||
sub_id = self._value_sub_ids.pop(f"p.{prop.service.iid}.{prop.iid}",
|
|
||||||
None)
|
|
||||||
if sub_id:
|
|
||||||
self.miot_device.unsub_property(siid=prop.service.iid,
|
|
||||||
piid=prop.iid,
|
|
||||||
sub_id=sub_id)
|
|
||||||
# Unsub event
|
|
||||||
for event in self.entity_data.events:
|
|
||||||
sub_id = self._value_sub_ids.pop(
|
|
||||||
f"e.{event.service.iid}.{event.iid}", None)
|
|
||||||
if sub_id:
|
|
||||||
self.miot_device.unsub_event(siid=event.service.iid,
|
|
||||||
eiid=event.iid,
|
|
||||||
sub_id=sub_id)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def get_map_value(
|
def get_map_value(
|
||||||
self, map_: Optional[dict[int, Any]], key: int
|
self, map_: Optional[dict[int, Any]], key: int
|
||||||
@ -1288,14 +1020,9 @@ class MIoTServiceEntity(Entity):
|
|||||||
return None
|
return None
|
||||||
return map_.get(key, None)
|
return map_.get(key, None)
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def get_map_key(
|
def get_map_key(
|
||||||
self, map_: Optional[dict[int, Any]], value: Any
|
self, map_: Optional[dict[int, Any]], value: Any
|
||||||
) -> Optional[int]:
|
) -> Optional[int]:
|
||||||
=======
|
|
||||||
def get_map_key(self, map_: Optional[dict[int, Any]],
|
|
||||||
value: Any) -> Optional[int]:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if map_ is None:
|
if map_ is None:
|
||||||
return None
|
return None
|
||||||
for key, value_ in map_.items():
|
for key, value_ in map_.items():
|
||||||
@ -1311,14 +1038,9 @@ class MIoTServiceEntity(Entity):
|
|||||||
return None
|
return None
|
||||||
return self._prop_value_map.get(prop, None)
|
return self._prop_value_map.get(prop, None)
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def set_prop_value(
|
def set_prop_value(
|
||||||
self, prop: Optional[MIoTSpecProperty], value: Any
|
self, prop: Optional[MIoTSpecProperty], value: Any
|
||||||
) -> None:
|
) -> None:
|
||||||
=======
|
|
||||||
def set_prop_value(self, prop: Optional[MIoTSpecProperty],
|
|
||||||
value: Any) -> None:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if not prop:
|
if not prop:
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
'set_prop_value error, property is None, %s, %s',
|
'set_prop_value error, property is None, %s, %s',
|
||||||
@ -1337,7 +1059,6 @@ class MIoTServiceEntity(Entity):
|
|||||||
value = prop.value_format(value)
|
value = prop.value_format(value)
|
||||||
value = prop.value_precision(value)
|
value = prop.value_precision(value)
|
||||||
if prop not in self.entity_data.props:
|
if prop not in self.entity_data.props:
|
||||||
<<<<<<< HEAD
|
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f'set property failed, unknown property, '
|
f'set property failed, unknown property, '
|
||||||
f'{self.entity_id}, {self.name}, {prop.name}')
|
f'{self.entity_id}, {self.name}, {prop.name}')
|
||||||
@ -1345,24 +1066,13 @@ class MIoTServiceEntity(Entity):
|
|||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f'set property failed, not writable, '
|
f'set property failed, not writable, '
|
||||||
f'{self.entity_id}, {self.name}, {prop.name}')
|
f'{self.entity_id}, {self.name}, {prop.name}')
|
||||||
=======
|
|
||||||
raise RuntimeError(f"set property failed, unknown property, "
|
|
||||||
f"{self.entity_id}, {self.name}, {prop.name}")
|
|
||||||
if not prop.writable:
|
|
||||||
raise RuntimeError(f"set property failed, not writable, "
|
|
||||||
f"{self.entity_id}, {self.name}, {prop.name}")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
try:
|
try:
|
||||||
await self.miot_device.miot_client.set_prop_async(
|
await self.miot_device.miot_client.set_prop_async(
|
||||||
did=self.miot_device.did, siid=prop.service.iid,
|
did=self.miot_device.did, siid=prop.service.iid,
|
||||||
piid=prop.iid, value=value)
|
piid=prop.iid, value=value)
|
||||||
except MIoTClientError as e:
|
except MIoTClientError as e:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
<<<<<<< HEAD
|
|
||||||
f'{e}, {self.entity_id}, {self.name}, {prop.name}') from e
|
f'{e}, {self.entity_id}, {self.name}, {prop.name}') from e
|
||||||
=======
|
|
||||||
f"{e}, {self.entity_id}, {self.name}, {prop.name}") from e
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if update_value:
|
if update_value:
|
||||||
self._prop_value_map[prop] = value
|
self._prop_value_map[prop] = value
|
||||||
if write_ha_state:
|
if write_ha_state:
|
||||||
@ -1379,7 +1089,6 @@ class MIoTServiceEntity(Entity):
|
|||||||
prop = set_property.get("prop")
|
prop = set_property.get("prop")
|
||||||
value = set_property.get("value")
|
value = set_property.get("value")
|
||||||
if not prop:
|
if not prop:
|
||||||
<<<<<<< HEAD
|
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f'set property failed, property is None, '
|
f'set property failed, property is None, '
|
||||||
f'{self.entity_id}, {self.name}')
|
f'{self.entity_id}, {self.name}')
|
||||||
@ -1395,19 +1104,6 @@ class MIoTServiceEntity(Entity):
|
|||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f'set property failed, not writable, '
|
f'set property failed, not writable, '
|
||||||
f'{self.entity_id}, {self.name}, {prop.name}')
|
f'{self.entity_id}, {self.name}, {prop.name}')
|
||||||
=======
|
|
||||||
raise RuntimeError(f"set property failed, property is None, "
|
|
||||||
f"{self.entity_id}, {self.name}")
|
|
||||||
set_property["value"] = prop.value_format(value)
|
|
||||||
if prop not in self.entity_data.props:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"set property failed, unknown property, "
|
|
||||||
f"{self.entity_id}, {self.name}, {prop.name}")
|
|
||||||
if not prop.writable:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"set property failed, not writable, "
|
|
||||||
f"{self.entity_id}, {self.name}, {prop.name}")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
try:
|
try:
|
||||||
await self.miot_device.miot_client.set_props_async([{
|
await self.miot_device.miot_client.set_props_async([{
|
||||||
"did": self.miot_device.did,
|
"did": self.miot_device.did,
|
||||||
@ -1442,19 +1138,11 @@ class MIoTServiceEntity(Entity):
|
|||||||
'get property failed, not readable, %s, %s, %s',
|
'get property failed, not readable, %s, %s, %s',
|
||||||
self.entity_id, self.name, prop.name)
|
self.entity_id, self.name, prop.name)
|
||||||
return None
|
return None
|
||||||
<<<<<<< HEAD
|
|
||||||
value: Any = prop.value_format(
|
value: Any = prop.value_format(
|
||||||
await self.miot_device.miot_client.get_prop_async(
|
await self.miot_device.miot_client.get_prop_async(
|
||||||
did=self.miot_device.did, siid=prop.service.iid, piid=prop.iid))
|
did=self.miot_device.did, siid=prop.service.iid, piid=prop.iid))
|
||||||
value = prop.eval_expr(value)
|
value = prop.eval_expr(value)
|
||||||
result = prop.value_precision(value)
|
result = prop.value_precision(value)
|
||||||
=======
|
|
||||||
result = prop.value_format(await
|
|
||||||
self.miot_device.miot_client.get_prop_async(
|
|
||||||
did=self.miot_device.did,
|
|
||||||
siid=prop.service.iid,
|
|
||||||
piid=prop.iid))
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if result != self._prop_value_map[prop]:
|
if result != self._prop_value_map[prop]:
|
||||||
self._prop_value_map[prop] = result
|
self._prop_value_map[prop] = result
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
@ -1465,22 +1153,14 @@ class MIoTServiceEntity(Entity):
|
|||||||
in_list: Optional[list] = None) -> bool:
|
in_list: Optional[list] = None) -> bool:
|
||||||
if not action:
|
if not action:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
<<<<<<< HEAD
|
|
||||||
f'action failed, action is None, {self.entity_id}, {self.name}')
|
f'action failed, action is None, {self.entity_id}, {self.name}')
|
||||||
=======
|
|
||||||
f"action failed, action is None, {self.entity_id}, {self.name}")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
try:
|
try:
|
||||||
await self.miot_device.miot_client.action_async(
|
await self.miot_device.miot_client.action_async(
|
||||||
did=self.miot_device.did, siid=action.service.iid,
|
did=self.miot_device.did, siid=action.service.iid,
|
||||||
aiid=action.iid, in_list=in_list or [])
|
aiid=action.iid, in_list=in_list or [])
|
||||||
except MIoTClientError as e:
|
except MIoTClientError as e:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
<<<<<<< HEAD
|
|
||||||
f'{e}, {self.entity_id}, {self.name}, {action.name}') from e
|
f'{e}, {self.entity_id}, {self.name}, {action.name}') from e
|
||||||
=======
|
|
||||||
f"{e}, {self.entity_id}, {self.name}, {action.name}") from e
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def __on_properties_changed(self, params: dict, ctx: Any) -> None:
|
def __on_properties_changed(self, params: dict, ctx: Any) -> None:
|
||||||
@ -1506,15 +1186,10 @@ class MIoTServiceEntity(Entity):
|
|||||||
if self._event_occurred_handler is None:
|
if self._event_occurred_handler is None:
|
||||||
return
|
return
|
||||||
for event in self.entity_data.events:
|
for event in self.entity_data.events:
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
event.iid != params['eiid']
|
event.iid != params['eiid']
|
||||||
or event.service.iid != params['siid']
|
or event.service.iid != params['siid']
|
||||||
):
|
):
|
||||||
=======
|
|
||||||
if event.iid != params["eiid"] or event.service.iid != params[
|
|
||||||
"siid"]:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
continue
|
continue
|
||||||
trans_arg = {}
|
trans_arg = {}
|
||||||
for item in params['arguments']:
|
for item in params['arguments']:
|
||||||
@ -1525,14 +1200,9 @@ class MIoTServiceEntity(Entity):
|
|||||||
self._event_occurred_handler(event, trans_arg)
|
self._event_occurred_handler(event, trans_arg)
|
||||||
break
|
break
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def __on_device_state_changed(
|
def __on_device_state_changed(
|
||||||
self, key: str, state: MIoTDeviceState
|
self, key: str, state: MIoTDeviceState
|
||||||
) -> None:
|
) -> None:
|
||||||
=======
|
|
||||||
def __on_device_state_changed(self, key: str,
|
|
||||||
state: MIoTDeviceState) -> None:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
state_new = state == MIoTDeviceState.ONLINE
|
state_new = state == MIoTDeviceState.ONLINE
|
||||||
if state_new == self._attr_available:
|
if state_new == self._attr_available:
|
||||||
return
|
return
|
||||||
@ -1591,27 +1261,15 @@ class MIoTPropertyEntity(Entity):
|
|||||||
self._pending_write_ha_state_timer = None
|
self._pending_write_ha_state_timer = None
|
||||||
# Gen entity_id
|
# Gen entity_id
|
||||||
self.entity_id = self.miot_device.gen_prop_entity_id(
|
self.entity_id = self.miot_device.gen_prop_entity_id(
|
||||||
<<<<<<< HEAD
|
|
||||||
ha_domain=DOMAIN, spec_name=spec.name,
|
ha_domain=DOMAIN, spec_name=spec.name,
|
||||||
siid=spec.service.iid, piid=spec.iid)
|
siid=spec.service.iid, piid=spec.iid)
|
||||||
=======
|
|
||||||
ha_domain=DOMAIN,
|
|
||||||
spec_name=spec.name,
|
|
||||||
siid=spec.service.iid,
|
|
||||||
piid=spec.iid)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
# Set entity attr
|
# Set entity attr
|
||||||
self._attr_unique_id = self.entity_id
|
self._attr_unique_id = self.entity_id
|
||||||
self._attr_should_poll = False
|
self._attr_should_poll = False
|
||||||
self._attr_has_entity_name = True
|
self._attr_has_entity_name = True
|
||||||
self._attr_name = (
|
self._attr_name = (
|
||||||
<<<<<<< HEAD
|
|
||||||
f'{"* "if self.spec.proprietary else " "}'
|
f'{"* "if self.spec.proprietary else " "}'
|
||||||
f'{self.service.description_trans} {spec.description_trans}')
|
f'{self.service.description_trans} {spec.description_trans}')
|
||||||
=======
|
|
||||||
f"{'* ' if self.spec.proprietary else ' '}"
|
|
||||||
f"{self.service.description_trans} {spec.description_trans}")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._attr_available = miot_device.online
|
self._attr_available = miot_device.online
|
||||||
|
|
||||||
_LOGGER.info(
|
_LOGGER.info(
|
||||||
@ -1631,12 +1289,7 @@ class MIoTPropertyEntity(Entity):
|
|||||||
# Sub value changed
|
# Sub value changed
|
||||||
self._value_sub_id = self.miot_device.sub_property(
|
self._value_sub_id = self.miot_device.sub_property(
|
||||||
handler=self.__on_value_changed,
|
handler=self.__on_value_changed,
|
||||||
<<<<<<< HEAD
|
|
||||||
siid=self.service.iid, piid=self.spec.iid)
|
siid=self.service.iid, piid=self.spec.iid)
|
||||||
=======
|
|
||||||
siid=self.service.iid,
|
|
||||||
piid=self.spec.iid)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
# Refresh value
|
# Refresh value
|
||||||
if self._attr_available:
|
if self._attr_available:
|
||||||
self.__request_refresh_prop()
|
self.__request_refresh_prop()
|
||||||
@ -1646,19 +1299,11 @@ class MIoTPropertyEntity(Entity):
|
|||||||
self._pending_write_ha_state_timer.cancel()
|
self._pending_write_ha_state_timer.cancel()
|
||||||
self._pending_write_ha_state_timer = None
|
self._pending_write_ha_state_timer = None
|
||||||
self.miot_device.unsub_device_state(
|
self.miot_device.unsub_device_state(
|
||||||
<<<<<<< HEAD
|
|
||||||
key=f'{ self.service.iid}.{self.spec.iid}',
|
key=f'{ self.service.iid}.{self.spec.iid}',
|
||||||
sub_id=self._state_sub_id)
|
sub_id=self._state_sub_id)
|
||||||
self.miot_device.unsub_property(
|
self.miot_device.unsub_property(
|
||||||
siid=self.service.iid, piid=self.spec.iid,
|
siid=self.service.iid, piid=self.spec.iid,
|
||||||
sub_id=self._value_sub_id)
|
sub_id=self._value_sub_id)
|
||||||
=======
|
|
||||||
key=f"{self.service.iid}.{self.spec.iid}",
|
|
||||||
sub_id=self._state_sub_id)
|
|
||||||
self.miot_device.unsub_property(siid=self.service.iid,
|
|
||||||
piid=self.spec.iid,
|
|
||||||
sub_id=self._value_sub_id)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def get_vlist_description(self, value: Any) -> Optional[str]:
|
def get_vlist_description(self, value: Any) -> Optional[str]:
|
||||||
if not self._value_list:
|
if not self._value_list:
|
||||||
@ -1690,28 +1335,17 @@ class MIoTPropertyEntity(Entity):
|
|||||||
|
|
||||||
async def get_property_async(self) -> Any:
|
async def get_property_async(self) -> Any:
|
||||||
if not self.spec.readable:
|
if not self.spec.readable:
|
||||||
<<<<<<< HEAD
|
|
||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
'get property failed, not readable, %s, %s',
|
'get property failed, not readable, %s, %s',
|
||||||
self.entity_id, self.name)
|
self.entity_id, self.name)
|
||||||
=======
|
|
||||||
_LOGGER.error("get property failed, not readable, %s, %s",
|
|
||||||
self.entity_id, self.name)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return None
|
return None
|
||||||
value: Any = self.spec.value_format(
|
value: Any = self.spec.value_format(
|
||||||
await self.miot_device.miot_client.get_prop_async(
|
await self.miot_device.miot_client.get_prop_async(
|
||||||
<<<<<<< HEAD
|
|
||||||
did=self.miot_device.did, siid=self.spec.service.iid,
|
did=self.miot_device.did, siid=self.spec.service.iid,
|
||||||
piid=self.spec.iid))
|
piid=self.spec.iid))
|
||||||
value = self.spec.eval_expr(value)
|
value = self.spec.eval_expr(value)
|
||||||
result = self.spec.value_precision(value)
|
result = self.spec.value_precision(value)
|
||||||
return result
|
return result
|
||||||
=======
|
|
||||||
did=self.miot_device.did,
|
|
||||||
siid=self.spec.service.iid,
|
|
||||||
piid=self.spec.iid))
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def __on_value_changed(self, params: dict, ctx: Any) -> None:
|
def __on_value_changed(self, params: dict, ctx: Any) -> None:
|
||||||
_LOGGER.debug('property changed, %s', params)
|
_LOGGER.debug('property changed, %s', params)
|
||||||
@ -1721,14 +1355,9 @@ class MIoTPropertyEntity(Entity):
|
|||||||
if not self._pending_write_ha_state_timer:
|
if not self._pending_write_ha_state_timer:
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def __on_device_state_changed(
|
def __on_device_state_changed(
|
||||||
self, key: str, state: MIoTDeviceState
|
self, key: str, state: MIoTDeviceState
|
||||||
) -> None:
|
) -> None:
|
||||||
=======
|
|
||||||
def __on_device_state_changed(self, key: str,
|
|
||||||
state: MIoTDeviceState) -> None:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._attr_available = state == MIoTDeviceState.ONLINE
|
self._attr_available = state == MIoTDeviceState.ONLINE
|
||||||
if not self._attr_available:
|
if not self._attr_available:
|
||||||
self.async_write_ha_state()
|
self.async_write_ha_state()
|
||||||
@ -1739,12 +1368,7 @@ class MIoTPropertyEntity(Entity):
|
|||||||
def __request_refresh_prop(self) -> None:
|
def __request_refresh_prop(self) -> None:
|
||||||
if self.spec.readable:
|
if self.spec.readable:
|
||||||
self.miot_device.miot_client.request_refresh_prop(
|
self.miot_device.miot_client.request_refresh_prop(
|
||||||
<<<<<<< HEAD
|
|
||||||
did=self.miot_device.did, siid=self.service.iid,
|
did=self.miot_device.did, siid=self.service.iid,
|
||||||
=======
|
|
||||||
did=self.miot_device.did,
|
|
||||||
siid=self.service.iid,
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
piid=self.spec.iid)
|
piid=self.spec.iid)
|
||||||
if self._pending_write_ha_state_timer:
|
if self._pending_write_ha_state_timer:
|
||||||
self._pending_write_ha_state_timer.cancel()
|
self._pending_write_ha_state_timer.cancel()
|
||||||
@ -1779,27 +1403,15 @@ class MIoTEventEntity(Entity):
|
|||||||
self._main_loop = miot_device.miot_client.main_loop
|
self._main_loop = miot_device.miot_client.main_loop
|
||||||
# Gen entity_id
|
# Gen entity_id
|
||||||
self.entity_id = self.miot_device.gen_event_entity_id(
|
self.entity_id = self.miot_device.gen_event_entity_id(
|
||||||
<<<<<<< HEAD
|
|
||||||
ha_domain=DOMAIN, spec_name=spec.name,
|
ha_domain=DOMAIN, spec_name=spec.name,
|
||||||
siid=spec.service.iid, eiid=spec.iid)
|
siid=spec.service.iid, eiid=spec.iid)
|
||||||
=======
|
|
||||||
ha_domain=DOMAIN,
|
|
||||||
spec_name=spec.name,
|
|
||||||
siid=spec.service.iid,
|
|
||||||
eiid=spec.iid)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
# Set entity attr
|
# Set entity attr
|
||||||
self._attr_unique_id = self.entity_id
|
self._attr_unique_id = self.entity_id
|
||||||
self._attr_should_poll = False
|
self._attr_should_poll = False
|
||||||
self._attr_has_entity_name = True
|
self._attr_has_entity_name = True
|
||||||
self._attr_name = (
|
self._attr_name = (
|
||||||
<<<<<<< HEAD
|
|
||||||
f'{"* "if self.spec.proprietary else " "}'
|
f'{"* "if self.spec.proprietary else " "}'
|
||||||
f'{self.service.description_trans} {spec.description_trans}')
|
f'{self.service.description_trans} {spec.description_trans}')
|
||||||
=======
|
|
||||||
f"{'* ' if self.spec.proprietary else ' '}"
|
|
||||||
f"{self.service.description_trans} {spec.description_trans}")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._attr_available = miot_device.online
|
self._attr_available = miot_device.online
|
||||||
self._attr_event_types = [spec.description_trans]
|
self._attr_event_types = [spec.description_trans]
|
||||||
|
|
||||||
@ -1826,7 +1438,6 @@ class MIoTEventEntity(Entity):
|
|||||||
# Sub value changed
|
# Sub value changed
|
||||||
self._value_sub_id = self.miot_device.sub_event(
|
self._value_sub_id = self.miot_device.sub_event(
|
||||||
handler=self.__on_event_occurred,
|
handler=self.__on_event_occurred,
|
||||||
<<<<<<< HEAD
|
|
||||||
siid=self.service.iid, eiid=self.spec.iid)
|
siid=self.service.iid, eiid=self.spec.iid)
|
||||||
|
|
||||||
async def async_will_remove_from_hass(self) -> None:
|
async def async_will_remove_from_hass(self) -> None:
|
||||||
@ -1836,18 +1447,6 @@ class MIoTEventEntity(Entity):
|
|||||||
self.miot_device.unsub_event(
|
self.miot_device.unsub_event(
|
||||||
siid=self.service.iid, eiid=self.spec.iid,
|
siid=self.service.iid, eiid=self.spec.iid,
|
||||||
sub_id=self._value_sub_id)
|
sub_id=self._value_sub_id)
|
||||||
=======
|
|
||||||
siid=self.service.iid,
|
|
||||||
eiid=self.spec.iid)
|
|
||||||
|
|
||||||
async def async_will_remove_from_hass(self) -> None:
|
|
||||||
self.miot_device.unsub_device_state(
|
|
||||||
key=f"event.{self.service.iid}.{self.spec.iid}",
|
|
||||||
sub_id=self._state_sub_id)
|
|
||||||
self.miot_device.unsub_event(siid=self.service.iid,
|
|
||||||
eiid=self.spec.iid,
|
|
||||||
sub_id=self._value_sub_id)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def on_event_occurred(self,
|
def on_event_occurred(self,
|
||||||
@ -1862,7 +1461,6 @@ class MIoTEventEntity(Entity):
|
|||||||
try:
|
try:
|
||||||
if 'value' not in item:
|
if 'value' not in item:
|
||||||
continue
|
continue
|
||||||
<<<<<<< HEAD
|
|
||||||
if 'piid' in item:
|
if 'piid' in item:
|
||||||
trans_arg[self._arguments_map[item['piid']]] = item[
|
trans_arg[self._arguments_map[item['piid']]] = item[
|
||||||
'value']
|
'value']
|
||||||
@ -1870,12 +1468,6 @@ class MIoTEventEntity(Entity):
|
|||||||
isinstance(item['value'], list)
|
isinstance(item['value'], list)
|
||||||
and len(item['value']) == len(self.spec.argument)
|
and len(item['value']) == len(self.spec.argument)
|
||||||
):
|
):
|
||||||
=======
|
|
||||||
if "piid" in item:
|
|
||||||
trans_arg[self._arguments_map[item["piid"]]] = item["value"]
|
|
||||||
elif isinstance(item["value"], list) and len(
|
|
||||||
item["value"]) == len(self.spec.argument):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
# Dirty fix for cloud multi-arguments
|
# Dirty fix for cloud multi-arguments
|
||||||
trans_arg = {
|
trans_arg = {
|
||||||
prop.description_trans: item['value'][index]
|
prop.description_trans: item['value'][index]
|
||||||
@ -1884,7 +1476,6 @@ class MIoTEventEntity(Entity):
|
|||||||
break
|
break
|
||||||
except KeyError as error:
|
except KeyError as error:
|
||||||
_LOGGER.debug(
|
_LOGGER.debug(
|
||||||
<<<<<<< HEAD
|
|
||||||
'on event msg, invalid args, %s, %s, %s',
|
'on event msg, invalid args, %s, %s, %s',
|
||||||
self.entity_id, params, error)
|
self.entity_id, params, error)
|
||||||
self.on_event_occurred(
|
self.on_event_occurred(
|
||||||
@ -1894,19 +1485,6 @@ class MIoTEventEntity(Entity):
|
|||||||
def __on_device_state_changed(
|
def __on_device_state_changed(
|
||||||
self, key: str, state: MIoTDeviceState
|
self, key: str, state: MIoTDeviceState
|
||||||
) -> None:
|
) -> None:
|
||||||
=======
|
|
||||||
"on event msg, invalid args, %s, %s, %s",
|
|
||||||
self.entity_id,
|
|
||||||
params,
|
|
||||||
error,
|
|
||||||
)
|
|
||||||
self.on_event_occurred(name=self.spec.description_trans,
|
|
||||||
arguments=trans_arg)
|
|
||||||
self.async_write_ha_state()
|
|
||||||
|
|
||||||
def __on_device_state_changed(self, key: str,
|
|
||||||
state: MIoTDeviceState) -> None:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
state_new = state == MIoTDeviceState.ONLINE
|
state_new = state == MIoTDeviceState.ONLINE
|
||||||
if state_new == self._attr_available:
|
if state_new == self._attr_available:
|
||||||
return
|
return
|
||||||
@ -1937,27 +1515,15 @@ class MIoTActionEntity(Entity):
|
|||||||
self._state_sub_id = 0
|
self._state_sub_id = 0
|
||||||
# Gen entity_id
|
# Gen entity_id
|
||||||
self.entity_id = self.miot_device.gen_action_entity_id(
|
self.entity_id = self.miot_device.gen_action_entity_id(
|
||||||
<<<<<<< HEAD
|
|
||||||
ha_domain=DOMAIN, spec_name=spec.name,
|
ha_domain=DOMAIN, spec_name=spec.name,
|
||||||
siid=spec.service.iid, aiid=spec.iid)
|
siid=spec.service.iid, aiid=spec.iid)
|
||||||
=======
|
|
||||||
ha_domain=DOMAIN,
|
|
||||||
spec_name=spec.name,
|
|
||||||
siid=spec.service.iid,
|
|
||||||
aiid=spec.iid)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
# Set entity attr
|
# Set entity attr
|
||||||
self._attr_unique_id = self.entity_id
|
self._attr_unique_id = self.entity_id
|
||||||
self._attr_should_poll = False
|
self._attr_should_poll = False
|
||||||
self._attr_has_entity_name = True
|
self._attr_has_entity_name = True
|
||||||
self._attr_name = (
|
self._attr_name = (
|
||||||
<<<<<<< HEAD
|
|
||||||
f'{"* "if self.spec.proprietary else " "}'
|
f'{"* "if self.spec.proprietary else " "}'
|
||||||
f'{self.service.description_trans} {spec.description_trans}')
|
f'{self.service.description_trans} {spec.description_trans}')
|
||||||
=======
|
|
||||||
f"{'* ' if self.spec.proprietary else ' '}"
|
|
||||||
f"{self.service.description_trans} {spec.description_trans}")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._attr_available = miot_device.online
|
self._attr_available = miot_device.online
|
||||||
|
|
||||||
_LOGGER.debug(
|
_LOGGER.debug(
|
||||||
@ -1976,20 +1542,12 @@ class MIoTActionEntity(Entity):
|
|||||||
|
|
||||||
async def async_will_remove_from_hass(self) -> None:
|
async def async_will_remove_from_hass(self) -> None:
|
||||||
self.miot_device.unsub_device_state(
|
self.miot_device.unsub_device_state(
|
||||||
<<<<<<< HEAD
|
|
||||||
key=f'a.{ self.service.iid}.{self.spec.iid}',
|
key=f'a.{ self.service.iid}.{self.spec.iid}',
|
||||||
sub_id=self._state_sub_id)
|
sub_id=self._state_sub_id)
|
||||||
|
|
||||||
async def action_async(
|
async def action_async(
|
||||||
self, in_list: Optional[list] = None
|
self, in_list: Optional[list] = None
|
||||||
) -> Optional[list]:
|
) -> Optional[list]:
|
||||||
=======
|
|
||||||
key=f"a.{self.service.iid}.{self.spec.iid}",
|
|
||||||
sub_id=self._state_sub_id)
|
|
||||||
|
|
||||||
async def action_async(self,
|
|
||||||
in_list: Optional[list] = None) -> Optional[list]:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
try:
|
try:
|
||||||
return await self.miot_device.miot_client.action_async(
|
return await self.miot_device.miot_client.action_async(
|
||||||
did=self.miot_device.did,
|
did=self.miot_device.did,
|
||||||
@ -1999,14 +1557,9 @@ class MIoTActionEntity(Entity):
|
|||||||
except MIoTClientError as e:
|
except MIoTClientError as e:
|
||||||
raise RuntimeError(f'{e}, {self.entity_id}, {self.name}') from e
|
raise RuntimeError(f'{e}, {self.entity_id}, {self.name}') from e
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def __on_device_state_changed(
|
def __on_device_state_changed(
|
||||||
self, key: str, state: MIoTDeviceState
|
self, key: str, state: MIoTDeviceState
|
||||||
) -> None:
|
) -> None:
|
||||||
=======
|
|
||||||
def __on_device_state_changed(self, key: str,
|
|
||||||
state: MIoTDeviceState) -> None:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
state_new = state == MIoTDeviceState.ONLINE
|
state_new = state == MIoTDeviceState.ONLINE
|
||||||
if state_new == self._attr_available:
|
if state_new == self._attr_available:
|
||||||
return
|
return
|
||||||
|
|||||||
@ -163,7 +163,6 @@ class _MIoTLanDevice:
|
|||||||
|
|
||||||
# All functions SHOULD be called from the internal loop
|
# All functions SHOULD be called from the internal loop
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
manager: 'MIoTLan',
|
manager: 'MIoTLan',
|
||||||
@ -171,25 +170,13 @@ class _MIoTLanDevice:
|
|||||||
token: str,
|
token: str,
|
||||||
ip: Optional[str] = None
|
ip: Optional[str] = None
|
||||||
) -> None:
|
) -> None:
|
||||||
=======
|
|
||||||
def __init__(self,
|
|
||||||
manager: "MIoTLan",
|
|
||||||
did: str,
|
|
||||||
token: str,
|
|
||||||
ip: Optional[str] = None) -> None:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._manager: MIoTLan = manager
|
self._manager: MIoTLan = manager
|
||||||
self.did = did
|
self.did = did
|
||||||
self.token = bytes.fromhex(token)
|
self.token = bytes.fromhex(token)
|
||||||
aes_key: bytes = self.__md5(self.token)
|
aes_key: bytes = self.__md5(self.token)
|
||||||
aex_iv: bytes = self.__md5(aes_key + self.token)
|
aex_iv: bytes = self.__md5(aes_key + self.token)
|
||||||
<<<<<<< HEAD
|
|
||||||
self.cipher = Cipher(
|
self.cipher = Cipher(
|
||||||
algorithms.AES128(aes_key), modes.CBC(aex_iv), default_backend())
|
algorithms.AES128(aes_key), modes.CBC(aex_iv), default_backend())
|
||||||
=======
|
|
||||||
self.cipher = Cipher(algorithms.AES128(aes_key), modes.CBC(aex_iv),
|
|
||||||
default_backend())
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self.ip = ip
|
self.ip = ip
|
||||||
self.offset = 0
|
self.offset = 0
|
||||||
self.subscribed = False
|
self.subscribed = False
|
||||||
@ -214,13 +201,8 @@ class _MIoTLanDevice:
|
|||||||
self.ip = ip
|
self.ip = ip
|
||||||
if self._if_name != if_name:
|
if self._if_name != if_name:
|
||||||
self._if_name = if_name
|
self._if_name = if_name
|
||||||
<<<<<<< HEAD
|
|
||||||
_LOGGER.info(
|
_LOGGER.info(
|
||||||
'device if_name change, %s, %s', self._if_name, self.did)
|
'device if_name change, %s, %s', self._if_name, self.did)
|
||||||
=======
|
|
||||||
_LOGGER.info("device if_name change, %s, %s", self._if_name,
|
|
||||||
self.did)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self.__update_keep_alive(state=_MIoTLanDeviceState.FRESH)
|
self.__update_keep_alive(state=_MIoTLanDeviceState.FRESH)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -233,48 +215,27 @@ class _MIoTLanDevice:
|
|||||||
return
|
return
|
||||||
self._online = online
|
self._online = online
|
||||||
self._manager.broadcast_device_state(
|
self._manager.broadcast_device_state(
|
||||||
<<<<<<< HEAD
|
|
||||||
did=self.did, state={
|
did=self.did, state={
|
||||||
'online': self._online, 'push_available': self.subscribed})
|
'online': self._online, 'push_available': self.subscribed})
|
||||||
=======
|
|
||||||
did=self.did,
|
|
||||||
state={
|
|
||||||
"online": self._online,
|
|
||||||
"push_available": self.subscribed
|
|
||||||
},
|
|
||||||
)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def if_name(self) -> Optional[str]:
|
def if_name(self) -> Optional[str]:
|
||||||
return self._if_name
|
return self._if_name
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def gen_packet(
|
def gen_packet(
|
||||||
self, out_buffer: bytearray, clear_data: dict, did: str, offset: int
|
self, out_buffer: bytearray, clear_data: dict, did: str, offset: int
|
||||||
) -> int:
|
) -> int:
|
||||||
clear_bytes = json.dumps(clear_data, ensure_ascii=False).encode('utf-8')
|
clear_bytes = json.dumps(clear_data, ensure_ascii=False).encode('utf-8')
|
||||||
=======
|
|
||||||
def gen_packet(self, out_buffer: bytearray, clear_data: dict, did: str,
|
|
||||||
offset: int) -> int:
|
|
||||||
clear_bytes = json.dumps(clear_data, ensure_ascii=False).encode("utf-8")
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
padder = padding.PKCS7(algorithms.AES128.block_size).padder()
|
padder = padding.PKCS7(algorithms.AES128.block_size).padder()
|
||||||
padded_data = padder.update(clear_bytes) + padder.finalize()
|
padded_data = padder.update(clear_bytes) + padder.finalize()
|
||||||
if len(padded_data) + self.OT_HEADER_LEN > len(out_buffer):
|
if len(padded_data) + self.OT_HEADER_LEN > len(out_buffer):
|
||||||
raise ValueError('rpc too long')
|
raise ValueError('rpc too long')
|
||||||
encryptor = self.cipher.encryptor()
|
encryptor = self.cipher.encryptor()
|
||||||
encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
|
encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
|
||||||
<<<<<<< HEAD
|
|
||||||
data_len: int = len(encrypted_data)+self.OT_HEADER_LEN
|
data_len: int = len(encrypted_data)+self.OT_HEADER_LEN
|
||||||
out_buffer[:32] = struct.pack(
|
out_buffer[:32] = struct.pack(
|
||||||
'>HHQI16s', self.OT_HEADER, data_len, int(did), offset,
|
'>HHQI16s', self.OT_HEADER, data_len, int(did), offset,
|
||||||
self.token)
|
self.token)
|
||||||
=======
|
|
||||||
data_len: int = len(encrypted_data) + self.OT_HEADER_LEN
|
|
||||||
out_buffer[:32] = struct.pack(">HHQI16s", self.OT_HEADER, data_len,
|
|
||||||
int(did), offset, self.token)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
out_buffer[32:data_len] = encrypted_data
|
out_buffer[32:data_len] = encrypted_data
|
||||||
msg_md5: bytes = self.__md5(out_buffer[0:data_len])
|
msg_md5: bytes = self.__md5(out_buffer[0:data_len])
|
||||||
out_buffer[16:32] = msg_md5
|
out_buffer[16:32] = msg_md5
|
||||||
@ -288,13 +249,8 @@ class _MIoTLanDevice:
|
|||||||
if md5_orig != md5_calc:
|
if md5_orig != md5_calc:
|
||||||
raise ValueError(f'invalid md5, {md5_orig}, {md5_calc}')
|
raise ValueError(f'invalid md5, {md5_orig}, {md5_calc}')
|
||||||
decryptor = self.cipher.decryptor()
|
decryptor = self.cipher.decryptor()
|
||||||
<<<<<<< HEAD
|
|
||||||
decrypted_padded_data = decryptor.update(
|
decrypted_padded_data = decryptor.update(
|
||||||
encrypted_data[32:data_len]) + decryptor.finalize()
|
encrypted_data[32:data_len]) + decryptor.finalize()
|
||||||
=======
|
|
||||||
decrypted_padded_data = (decryptor.update(encrypted_data[32:data_len]) +
|
|
||||||
decryptor.finalize())
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
unpadder = padding.PKCS7(algorithms.AES128.block_size).unpadder()
|
unpadder = padding.PKCS7(algorithms.AES128.block_size).unpadder()
|
||||||
decrypted_data = unpadder.update(
|
decrypted_data = unpadder.update(
|
||||||
decrypted_padded_data) + unpadder.finalize()
|
decrypted_padded_data) + unpadder.finalize()
|
||||||
@ -345,17 +301,8 @@ class _MIoTLanDevice:
|
|||||||
timeout_ms=5000)
|
timeout_ms=5000)
|
||||||
self.subscribed = False
|
self.subscribed = False
|
||||||
self._manager.broadcast_device_state(
|
self._manager.broadcast_device_state(
|
||||||
<<<<<<< HEAD
|
|
||||||
did=self.did, state={
|
did=self.did, state={
|
||||||
'online': self._online, 'push_available': self.subscribed})
|
'online': self._online, 'push_available': self.subscribed})
|
||||||
=======
|
|
||||||
did=self.did,
|
|
||||||
state={
|
|
||||||
"online": self._online,
|
|
||||||
"push_available": self.subscribed
|
|
||||||
},
|
|
||||||
)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def on_delete(self) -> None:
|
def on_delete(self) -> None:
|
||||||
if self._ka_timer:
|
if self._ka_timer:
|
||||||
@ -367,21 +314,15 @@ class _MIoTLanDevice:
|
|||||||
_LOGGER.debug('miot lan device delete, %s', self.did)
|
_LOGGER.debug('miot lan device delete, %s', self.did)
|
||||||
|
|
||||||
def update_info(self, info: dict) -> None:
|
def update_info(self, info: dict) -> None:
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
'token' in info
|
'token' in info
|
||||||
and len(info['token']) == 32
|
and len(info['token']) == 32
|
||||||
and info['token'].upper() != self.token.hex().upper()
|
and info['token'].upper() != self.token.hex().upper()
|
||||||
):
|
):
|
||||||
=======
|
|
||||||
if ("token" in info and len(info["token"]) == 32 and
|
|
||||||
info["token"].upper() != self.token.hex().upper()):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
# Update token
|
# Update token
|
||||||
self.token = bytes.fromhex(info['token'])
|
self.token = bytes.fromhex(info['token'])
|
||||||
aes_key: bytes = self.__md5(self.token)
|
aes_key: bytes = self.__md5(self.token)
|
||||||
aex_iv: bytes = self.__md5(aes_key + self.token)
|
aex_iv: bytes = self.__md5(aes_key + self.token)
|
||||||
<<<<<<< HEAD
|
|
||||||
self.cipher = Cipher(
|
self.cipher = Cipher(
|
||||||
algorithms.AES128(aes_key),
|
algorithms.AES128(aes_key),
|
||||||
modes.CBC(aex_iv), default_backend())
|
modes.CBC(aex_iv), default_backend())
|
||||||
@ -394,21 +335,10 @@ class _MIoTLanDevice:
|
|||||||
or msg['result']['code'] != 0
|
or msg['result']['code'] != 0
|
||||||
):
|
):
|
||||||
_LOGGER.error('subscribe device error, %s, %s', self.did, msg)
|
_LOGGER.error('subscribe device error, %s, %s', self.did, msg)
|
||||||
=======
|
|
||||||
self.cipher = Cipher(algorithms.AES128(aes_key), modes.CBC(aex_iv),
|
|
||||||
default_backend())
|
|
||||||
_LOGGER.debug("update token, %s", self.did)
|
|
||||||
|
|
||||||
def __subscribe_handler(self, msg: dict, sub_ts: int) -> None:
|
|
||||||
if ("result" not in msg or "code" not in msg["result"] or
|
|
||||||
msg["result"]["code"] != 0):
|
|
||||||
_LOGGER.error("subscribe device error, %s, %s", self.did, msg)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return
|
return
|
||||||
self.subscribed = True
|
self.subscribed = True
|
||||||
self.sub_ts = sub_ts
|
self.sub_ts = sub_ts
|
||||||
self._manager.broadcast_device_state(
|
self._manager.broadcast_device_state(
|
||||||
<<<<<<< HEAD
|
|
||||||
did=self.did, state={
|
did=self.did, state={
|
||||||
'online': self._online, 'push_available': self.subscribed})
|
'online': self._online, 'push_available': self.subscribed})
|
||||||
_LOGGER.info('subscribe success, %s, %s', self._if_name, self.did)
|
_LOGGER.info('subscribe success, %s, %s', self._if_name, self.did)
|
||||||
@ -420,20 +350,6 @@ class _MIoTLanDevice:
|
|||||||
or msg['result']['code'] != 0
|
or msg['result']['code'] != 0
|
||||||
):
|
):
|
||||||
_LOGGER.error('unsubscribe device error, %s, %s', self.did, msg)
|
_LOGGER.error('unsubscribe device error, %s, %s', self.did, msg)
|
||||||
=======
|
|
||||||
did=self.did,
|
|
||||||
state={
|
|
||||||
"online": self._online,
|
|
||||||
"push_available": self.subscribed
|
|
||||||
},
|
|
||||||
)
|
|
||||||
_LOGGER.info("subscribe success, %s, %s", self._if_name, self.did)
|
|
||||||
|
|
||||||
def __unsubscribe_handler(self, msg: dict, ctx: Any) -> None:
|
|
||||||
if ("result" not in msg or "code" not in msg["result"] or
|
|
||||||
msg["result"]["code"] != 0):
|
|
||||||
_LOGGER.error("unsubscribe device error, %s, %s", self.did, msg)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return
|
return
|
||||||
_LOGGER.info('unsubscribe success, %s, %s', self._if_name, self.did)
|
_LOGGER.info('unsubscribe success, %s, %s', self._if_name, self.did)
|
||||||
|
|
||||||
@ -451,7 +367,6 @@ class _MIoTLanDevice:
|
|||||||
self._ka_internal = self.KA_INTERVAL_MIN
|
self._ka_internal = self.KA_INTERVAL_MIN
|
||||||
self.__change_online(True)
|
self.__change_online(True)
|
||||||
self._ka_timer = self._manager.internal_loop.call_later(
|
self._ka_timer = self._manager.internal_loop.call_later(
|
||||||
<<<<<<< HEAD
|
|
||||||
self.__get_next_ka_timeout(), self.__update_keep_alive,
|
self.__get_next_ka_timeout(), self.__update_keep_alive,
|
||||||
_MIoTLanDeviceState.PING1)
|
_MIoTLanDeviceState.PING1)
|
||||||
case (
|
case (
|
||||||
@ -459,14 +374,6 @@ class _MIoTLanDevice:
|
|||||||
| _MIoTLanDeviceState.PING2
|
| _MIoTLanDeviceState.PING2
|
||||||
| _MIoTLanDeviceState.PING3
|
| _MIoTLanDeviceState.PING3
|
||||||
):
|
):
|
||||||
=======
|
|
||||||
self.__get_next_ka_timeout(),
|
|
||||||
self.__update_keep_alive,
|
|
||||||
_MIoTLanDeviceState.PING1,
|
|
||||||
)
|
|
||||||
case (_MIoTLanDeviceState.PING1 | _MIoTLanDeviceState.PING2 |
|
|
||||||
_MIoTLanDeviceState.PING3):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
# Set the timer first to avoid Any early returns
|
# Set the timer first to avoid Any early returns
|
||||||
self._ka_timer = self._manager.internal_loop.call_later(
|
self._ka_timer = self._manager.internal_loop.call_later(
|
||||||
self.FAST_PING_INTERVAL, self.__update_keep_alive,
|
self.FAST_PING_INTERVAL, self.__update_keep_alive,
|
||||||
@ -503,7 +410,6 @@ class _MIoTLanDevice:
|
|||||||
if not online:
|
if not online:
|
||||||
self.online = False
|
self.online = False
|
||||||
else:
|
else:
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
len(self._online_offline_history) < self.NETWORK_UNSTABLE_CNT_TH
|
len(self._online_offline_history) < self.NETWORK_UNSTABLE_CNT_TH
|
||||||
or (
|
or (
|
||||||
@ -517,18 +423,6 @@ class _MIoTLanDevice:
|
|||||||
self._manager.internal_loop.call_later(
|
self._manager.internal_loop.call_later(
|
||||||
self.NETWORK_UNSTABLE_RESUME_TH,
|
self.NETWORK_UNSTABLE_RESUME_TH,
|
||||||
self.__online_resume_handler))
|
self.__online_resume_handler))
|
||||||
=======
|
|
||||||
if len(self._online_offline_history
|
|
||||||
) < self.NETWORK_UNSTABLE_CNT_TH or (
|
|
||||||
ts_now - self._online_offline_history[0]["ts"]
|
|
||||||
> self.NETWORK_UNSTABLE_TIME_TH):
|
|
||||||
self.online = True
|
|
||||||
else:
|
|
||||||
_LOGGER.info("unstable device detected, %s", self.did)
|
|
||||||
self._online_offline_timer = self._manager.internal_loop.call_later(
|
|
||||||
self.NETWORK_UNSTABLE_RESUME_TH,
|
|
||||||
self.__online_resume_handler)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def __online_resume_handler(self) -> None:
|
def __online_resume_handler(self) -> None:
|
||||||
_LOGGER.info('unstable resume threshold past, %s', self.did)
|
_LOGGER.info('unstable resume threshold past, %s', self.did)
|
||||||
@ -607,7 +501,6 @@ class MIoTLan:
|
|||||||
self._net_ifs = set(net_ifs)
|
self._net_ifs = set(net_ifs)
|
||||||
self._network = network
|
self._network = network
|
||||||
self._network.sub_network_info(
|
self._network.sub_network_info(
|
||||||
<<<<<<< HEAD
|
|
||||||
key='miot_lan',
|
key='miot_lan',
|
||||||
handler=self.__on_network_info_change_external_async)
|
handler=self.__on_network_info_change_external_async)
|
||||||
self._mips_service = mips_service
|
self._mips_service = mips_service
|
||||||
@ -624,23 +517,6 @@ class MIoTLan:
|
|||||||
b'!1\x00\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFFMDID')
|
b'!1\x00\x20\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFFMDID')
|
||||||
probe_bytes[20:28] = struct.pack('>Q', int(self._virtual_did))
|
probe_bytes[20:28] = struct.pack('>Q', int(self._virtual_did))
|
||||||
probe_bytes[28:32] = b'\x00\x00\x00\x00'
|
probe_bytes[28:32] = b'\x00\x00\x00\x00'
|
||||||
=======
|
|
||||||
key="miot_lan",
|
|
||||||
handler=self.__on_network_info_change_external_async)
|
|
||||||
self._mips_service = mips_service
|
|
||||||
self._mips_service.sub_service_change(
|
|
||||||
key="miot_lan", group_id="*", handler=self.__on_mips_service_change)
|
|
||||||
self._enable_subscribe = enable_subscribe
|
|
||||||
self._virtual_did = (str(virtual_did) if
|
|
||||||
(virtual_did is not None) else str(
|
|
||||||
secrets.randbits(64)))
|
|
||||||
# Init socket probe message
|
|
||||||
probe_bytes = bytearray(self.OT_PROBE_LEN)
|
|
||||||
probe_bytes[:20] = (
|
|
||||||
b"!1\x00\x20\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xffMDID")
|
|
||||||
probe_bytes[20:28] = struct.pack(">Q", int(self._virtual_did))
|
|
||||||
probe_bytes[28:32] = b"\x00\x00\x00\x00"
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._probe_msg = bytes(probe_bytes)
|
self._probe_msg = bytes(probe_bytes)
|
||||||
self._read_buffer = bytearray(self.OT_MSG_LEN)
|
self._read_buffer = bytearray(self.OT_MSG_LEN)
|
||||||
self._write_buffer = bytearray(self.OT_MSG_LEN)
|
self._write_buffer = bytearray(self.OT_MSG_LEN)
|
||||||
@ -663,7 +539,6 @@ class MIoTLan:
|
|||||||
self._init_lock = asyncio.Lock()
|
self._init_lock = asyncio.Lock()
|
||||||
self._init_done = False
|
self._init_done = False
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
len(self._mips_service.get_services()) == 0
|
len(self._mips_service.get_services()) == 0
|
||||||
and len(self._net_ifs) > 0
|
and len(self._net_ifs) > 0
|
||||||
@ -678,18 +553,6 @@ class MIoTLan:
|
|||||||
raise MIoTLanError(
|
raise MIoTLanError(
|
||||||
'MIoT lan is not ready',
|
'MIoT lan is not ready',
|
||||||
MIoTErrorCode.CODE_LAN_UNAVAILABLE)
|
MIoTErrorCode.CODE_LAN_UNAVAILABLE)
|
||||||
=======
|
|
||||||
if len(self._mips_service.get_services()) == 0 and len(
|
|
||||||
self._net_ifs) > 0:
|
|
||||||
_LOGGER.info("no central hub gateway service, init miot lan")
|
|
||||||
self._main_loop.call_later(
|
|
||||||
0, lambda: self._main_loop.create_task(self.init_async()))
|
|
||||||
|
|
||||||
def __assert_service_ready(self) -> None:
|
|
||||||
if not self._init_done:
|
|
||||||
raise MIoTLanError("MIoT lan is not ready",
|
|
||||||
MIoTErrorCode.CODE_LAN_UNAVAILABLE)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def virtual_did(self) -> str:
|
def virtual_did(self) -> str:
|
||||||
@ -742,23 +605,14 @@ class MIoTLan:
|
|||||||
self._init_done = True
|
self._init_done = True
|
||||||
for handler in list(self._lan_state_sub_map.values()):
|
for handler in list(self._lan_state_sub_map.values()):
|
||||||
self._main_loop.create_task(handler(True))
|
self._main_loop.create_task(handler(True))
|
||||||
<<<<<<< HEAD
|
|
||||||
_LOGGER.info(
|
_LOGGER.info(
|
||||||
'miot lan init, %s ,%s', self._net_ifs, self._available_net_ifs)
|
'miot lan init, %s ,%s', self._net_ifs, self._available_net_ifs)
|
||||||
=======
|
|
||||||
_LOGGER.info("miot lan init, %s ,%s", self._net_ifs,
|
|
||||||
self._available_net_ifs)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def __internal_loop_thread(self) -> None:
|
def __internal_loop_thread(self) -> None:
|
||||||
_LOGGER.info('miot lan thread start')
|
_LOGGER.info('miot lan thread start')
|
||||||
self.__init_socket()
|
self.__init_socket()
|
||||||
self._scan_timer = self._internal_loop.call_later(
|
self._scan_timer = self._internal_loop.call_later(
|
||||||
<<<<<<< HEAD
|
|
||||||
int(3*random.random()), self.__scan_devices)
|
int(3*random.random()), self.__scan_devices)
|
||||||
=======
|
|
||||||
int(3 * random.random()), self.__scan_devices)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._internal_loop.run_forever()
|
self._internal_loop.run_forever()
|
||||||
_LOGGER.info('miot lan thread exit')
|
_LOGGER.info('miot lan thread exit')
|
||||||
|
|
||||||
@ -828,11 +682,7 @@ class MIoTLan:
|
|||||||
return
|
return
|
||||||
self._internal_loop.call_soon_threadsafe(
|
self._internal_loop.call_soon_threadsafe(
|
||||||
self.__update_subscribe_option,
|
self.__update_subscribe_option,
|
||||||
<<<<<<< HEAD
|
|
||||||
{'enable_subscribe': enable_subscribe})
|
{'enable_subscribe': enable_subscribe})
|
||||||
=======
|
|
||||||
{"enable_subscribe": enable_subscribe})
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def update_devices(self, devices: dict[str, dict]) -> bool:
|
def update_devices(self, devices: dict[str, dict]) -> bool:
|
||||||
_LOGGER.info('update devices, %s', devices)
|
_LOGGER.info('update devices, %s', devices)
|
||||||
@ -850,14 +700,9 @@ class MIoTLan:
|
|||||||
self.__delete_devices, devices)
|
self.__delete_devices, devices)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def sub_lan_state(
|
def sub_lan_state(
|
||||||
self, key: str, handler: Callable[[bool], Coroutine]
|
self, key: str, handler: Callable[[bool], Coroutine]
|
||||||
) -> None:
|
) -> None:
|
||||||
=======
|
|
||||||
def sub_lan_state(self, key: str, handler: Callable[[bool],
|
|
||||||
Coroutine]) -> None:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._lan_state_sub_map[key] = handler
|
self._lan_state_sub_map[key] = handler
|
||||||
|
|
||||||
def unsub_lan_state(self, key: str) -> None:
|
def unsub_lan_state(self, key: str) -> None:
|
||||||
@ -872,15 +717,8 @@ class MIoTLan:
|
|||||||
return False
|
return False
|
||||||
self._internal_loop.call_soon_threadsafe(
|
self._internal_loop.call_soon_threadsafe(
|
||||||
self.__sub_device_state,
|
self.__sub_device_state,
|
||||||
<<<<<<< HEAD
|
|
||||||
_MIoTLanSubDeviceData(
|
_MIoTLanSubDeviceData(
|
||||||
key=key, handler=handler, handler_ctx=handler_ctx))
|
key=key, handler=handler, handler_ctx=handler_ctx))
|
||||||
=======
|
|
||||||
_MIoTLanSubDeviceData(key=key,
|
|
||||||
handler=handler,
|
|
||||||
handler_ctx=handler_ctx),
|
|
||||||
)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@final
|
@final
|
||||||
@ -909,7 +747,6 @@ class MIoTLan:
|
|||||||
f'{"#" if siid is None or piid is None else f"{siid}/{piid}"}')
|
f'{"#" if siid is None or piid is None else f"{siid}/{piid}"}')
|
||||||
self._internal_loop.call_soon_threadsafe(
|
self._internal_loop.call_soon_threadsafe(
|
||||||
self.__sub_broadcast,
|
self.__sub_broadcast,
|
||||||
<<<<<<< HEAD
|
|
||||||
_MIoTLanRegisterBroadcastData(
|
_MIoTLanRegisterBroadcastData(
|
||||||
key=key, handler=handler, handler_ctx=handler_ctx))
|
key=key, handler=handler, handler_ctx=handler_ctx))
|
||||||
return True
|
return True
|
||||||
@ -921,19 +758,6 @@ class MIoTLan:
|
|||||||
siid: Optional[int] = None,
|
siid: Optional[int] = None,
|
||||||
piid: Optional[int] = None
|
piid: Optional[int] = None
|
||||||
) -> bool:
|
) -> bool:
|
||||||
=======
|
|
||||||
_MIoTLanRegisterBroadcastData(key=key,
|
|
||||||
handler=handler,
|
|
||||||
handler_ctx=handler_ctx),
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
|
|
||||||
@final
|
|
||||||
def unsub_prop(self,
|
|
||||||
did: str,
|
|
||||||
siid: Optional[int] = None,
|
|
||||||
piid: Optional[int] = None) -> bool:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if not self._init_done:
|
if not self._init_done:
|
||||||
return False
|
return False
|
||||||
if not self._enable_subscribe:
|
if not self._enable_subscribe:
|
||||||
@ -942,12 +766,8 @@ class MIoTLan:
|
|||||||
f'{did}/p/'
|
f'{did}/p/'
|
||||||
f'{"#" if siid is None or piid is None else f"{siid}/{piid}"}')
|
f'{"#" if siid is None or piid is None else f"{siid}/{piid}"}')
|
||||||
self._internal_loop.call_soon_threadsafe(
|
self._internal_loop.call_soon_threadsafe(
|
||||||
<<<<<<< HEAD
|
|
||||||
self.__unsub_broadcast,
|
self.__unsub_broadcast,
|
||||||
_MIoTLanUnregisterBroadcastData(key=key))
|
_MIoTLanUnregisterBroadcastData(key=key))
|
||||||
=======
|
|
||||||
self.__unsub_broadcast, _MIoTLanUnregisterBroadcastData(key=key))
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@final
|
@final
|
||||||
@ -968,7 +788,6 @@ class MIoTLan:
|
|||||||
f'{"#" if siid is None or eiid is None else f"{siid}/{eiid}"}')
|
f'{"#" if siid is None or eiid is None else f"{siid}/{eiid}"}')
|
||||||
self._internal_loop.call_soon_threadsafe(
|
self._internal_loop.call_soon_threadsafe(
|
||||||
self.__sub_broadcast,
|
self.__sub_broadcast,
|
||||||
<<<<<<< HEAD
|
|
||||||
_MIoTLanRegisterBroadcastData(
|
_MIoTLanRegisterBroadcastData(
|
||||||
key=key, handler=handler, handler_ctx=handler_ctx))
|
key=key, handler=handler, handler_ctx=handler_ctx))
|
||||||
return True
|
return True
|
||||||
@ -980,19 +799,6 @@ class MIoTLan:
|
|||||||
siid: Optional[int] = None,
|
siid: Optional[int] = None,
|
||||||
eiid: Optional[int] = None
|
eiid: Optional[int] = None
|
||||||
) -> bool:
|
) -> bool:
|
||||||
=======
|
|
||||||
_MIoTLanRegisterBroadcastData(key=key,
|
|
||||||
handler=handler,
|
|
||||||
handler_ctx=handler_ctx),
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
|
|
||||||
@final
|
|
||||||
def unsub_event(self,
|
|
||||||
did: str,
|
|
||||||
siid: Optional[int] = None,
|
|
||||||
eiid: Optional[int] = None) -> bool:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if not self._init_done:
|
if not self._init_done:
|
||||||
return False
|
return False
|
||||||
if not self._enable_subscribe:
|
if not self._enable_subscribe:
|
||||||
@ -1001,12 +807,8 @@ class MIoTLan:
|
|||||||
f'{did}/e/'
|
f'{did}/e/'
|
||||||
f'{"#" if siid is None or eiid is None else f"{siid}/{eiid}"}')
|
f'{"#" if siid is None or eiid is None else f"{siid}/{eiid}"}')
|
||||||
self._internal_loop.call_soon_threadsafe(
|
self._internal_loop.call_soon_threadsafe(
|
||||||
<<<<<<< HEAD
|
|
||||||
self.__unsub_broadcast,
|
self.__unsub_broadcast,
|
||||||
_MIoTLanUnregisterBroadcastData(key=key))
|
_MIoTLanUnregisterBroadcastData(key=key))
|
||||||
=======
|
|
||||||
self.__unsub_broadcast, _MIoTLanUnregisterBroadcastData(key=key))
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@final
|
@final
|
||||||
@ -1017,7 +819,6 @@ class MIoTLan:
|
|||||||
timeout_ms: int = 10000) -> Any:
|
timeout_ms: int = 10000) -> Any:
|
||||||
self.__assert_service_ready()
|
self.__assert_service_ready()
|
||||||
result_obj = await self.__call_api_async(
|
result_obj = await self.__call_api_async(
|
||||||
<<<<<<< HEAD
|
|
||||||
did=did, msg={
|
did=did, msg={
|
||||||
'method': 'get_properties',
|
'method': 'get_properties',
|
||||||
'params': [{'did': did, 'siid': siid, 'piid': piid}]
|
'params': [{'did': did, 'siid': siid, 'piid': piid}]
|
||||||
@ -1054,71 +855,14 @@ class MIoTLan:
|
|||||||
):
|
):
|
||||||
return result_obj['result'][0]
|
return result_obj['result'][0]
|
||||||
if 'code' in result_obj:
|
if 'code' in result_obj:
|
||||||
=======
|
|
||||||
did=did,
|
|
||||||
msg={
|
|
||||||
"method": "get_properties",
|
|
||||||
"params": [{
|
|
||||||
"did": did,
|
|
||||||
"siid": siid,
|
|
||||||
"piid": piid
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
timeout_ms=timeout_ms,
|
|
||||||
)
|
|
||||||
|
|
||||||
if (result_obj and "result" in result_obj and
|
|
||||||
len(result_obj["result"]) == 1 and
|
|
||||||
"did" in result_obj["result"][0] and
|
|
||||||
result_obj["result"][0]["did"] == did):
|
|
||||||
return result_obj["result"][0].get("value", None)
|
|
||||||
return None
|
|
||||||
|
|
||||||
@final
|
|
||||||
async def set_prop_async(self,
|
|
||||||
did: str,
|
|
||||||
siid: int,
|
|
||||||
piid: int,
|
|
||||||
value: Any,
|
|
||||||
timeout_ms: int = 10000) -> dict:
|
|
||||||
self.__assert_service_ready()
|
|
||||||
result_obj = await self.__call_api_async(
|
|
||||||
did=did,
|
|
||||||
msg={
|
|
||||||
"method":
|
|
||||||
"set_properties",
|
|
||||||
"params": [{
|
|
||||||
"did": did,
|
|
||||||
"siid": siid,
|
|
||||||
"piid": piid,
|
|
||||||
"value": value
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
timeout_ms=timeout_ms,
|
|
||||||
)
|
|
||||||
if result_obj:
|
|
||||||
if ("result" in result_obj and len(result_obj["result"]) == 1 and
|
|
||||||
"did" in result_obj["result"][0] and
|
|
||||||
result_obj["result"][0]["did"] == did and
|
|
||||||
"code" in result_obj["result"][0]):
|
|
||||||
return result_obj["result"][0]
|
|
||||||
if "code" in result_obj:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return result_obj
|
return result_obj
|
||||||
raise MIoTError('Invalid result', MIoTErrorCode.CODE_INTERNAL_ERROR)
|
raise MIoTError('Invalid result', MIoTErrorCode.CODE_INTERNAL_ERROR)
|
||||||
|
|
||||||
@final
|
@final
|
||||||
<<<<<<< HEAD
|
|
||||||
async def set_props_async(
|
async def set_props_async(
|
||||||
self,did: str,props_list: List[Dict[str, Any]],
|
self,did: str,props_list: List[Dict[str, Any]],
|
||||||
timeout_ms: int = 10000) -> dict:
|
timeout_ms: int = 10000) -> dict:
|
||||||
# props_list = [{'did': did, 'siid': siid, 'piid': piid, 'value': value}......]
|
# props_list = [{'did': did, 'siid': siid, 'piid': piid, 'value': value}......]
|
||||||
=======
|
|
||||||
async def set_props_async(self,
|
|
||||||
did: str,
|
|
||||||
props_list: List[Dict[str, Any]],
|
|
||||||
timeout_ms: int = 10000) -> dict:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self.__assert_service_ready()
|
self.__assert_service_ready()
|
||||||
result_obj = await self.__call_api_async(
|
result_obj = await self.__call_api_async(
|
||||||
did=did, msg={
|
did=did, msg={
|
||||||
@ -1126,7 +870,6 @@ class MIoTLan:
|
|||||||
'params': props_list,
|
'params': props_list,
|
||||||
}, timeout_ms=timeout_ms)
|
}, timeout_ms=timeout_ms)
|
||||||
if result_obj:
|
if result_obj:
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
'result' in result_obj and
|
'result' in result_obj and
|
||||||
len(result_obj['result']) == len(props_list)
|
len(result_obj['result']) == len(props_list)
|
||||||
@ -1150,41 +893,6 @@ class MIoTLan:
|
|||||||
'params': {
|
'params': {
|
||||||
'did': did, 'siid': siid, 'aiid': aiid, 'in': in_list}
|
'did': did, 'siid': siid, 'aiid': aiid, 'in': in_list}
|
||||||
}, timeout_ms=timeout_ms)
|
}, timeout_ms=timeout_ms)
|
||||||
=======
|
|
||||||
if ("result" in result_obj and
|
|
||||||
len(result_obj["result"]) == len(props_list) and
|
|
||||||
result_obj["result"][0].get("did") == did and
|
|
||||||
all("code" in item for item in result_obj["result"])):
|
|
||||||
return result_obj["result"]
|
|
||||||
if "error" in result_obj:
|
|
||||||
return result_obj["error"]
|
|
||||||
return {
|
|
||||||
"code": MIoTErrorCode.CODE_INTERNAL_ERROR.value,
|
|
||||||
"message": "Invalid result",
|
|
||||||
}
|
|
||||||
|
|
||||||
@final
|
|
||||||
async def action_async(self,
|
|
||||||
did: str,
|
|
||||||
siid: int,
|
|
||||||
aiid: int,
|
|
||||||
in_list: list,
|
|
||||||
timeout_ms: int = 10000) -> dict:
|
|
||||||
self.__assert_service_ready()
|
|
||||||
result_obj = await self.__call_api_async(
|
|
||||||
did=did,
|
|
||||||
msg={
|
|
||||||
"method": "action",
|
|
||||||
"params": {
|
|
||||||
"did": did,
|
|
||||||
"siid": siid,
|
|
||||||
"aiid": aiid,
|
|
||||||
"in": in_list
|
|
||||||
},
|
|
||||||
},
|
|
||||||
timeout_ms=timeout_ms,
|
|
||||||
)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if result_obj:
|
if result_obj:
|
||||||
if 'result' in result_obj and 'code' in result_obj['result']:
|
if 'result' in result_obj and 'code' in result_obj['result']:
|
||||||
return result_obj['result']
|
return result_obj['result']
|
||||||
@ -1193,14 +901,9 @@ class MIoTLan:
|
|||||||
raise MIoTError('Invalid result', MIoTErrorCode.CODE_INTERNAL_ERROR)
|
raise MIoTError('Invalid result', MIoTErrorCode.CODE_INTERNAL_ERROR)
|
||||||
|
|
||||||
@final
|
@final
|
||||||
<<<<<<< HEAD
|
|
||||||
async def get_dev_list_async(
|
async def get_dev_list_async(
|
||||||
self, timeout_ms: int = 10000
|
self, timeout_ms: int = 10000
|
||||||
) -> dict[str, dict]:
|
) -> dict[str, dict]:
|
||||||
=======
|
|
||||||
async def get_dev_list_async(self,
|
|
||||||
timeout_ms: int = 10000) -> dict[str, dict]:
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if not self._init_done:
|
if not self._init_done:
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
@ -1211,17 +914,10 @@ class MIoTLan:
|
|||||||
fut: asyncio.Future = self._main_loop.create_future()
|
fut: asyncio.Future = self._main_loop.create_future()
|
||||||
self._internal_loop.call_soon_threadsafe(
|
self._internal_loop.call_soon_threadsafe(
|
||||||
self.__get_dev_list,
|
self.__get_dev_list,
|
||||||
<<<<<<< HEAD
|
|
||||||
_MIoTLanGetDevListData(
|
_MIoTLanGetDevListData(
|
||||||
handler=get_device_list_handler,
|
handler=get_device_list_handler,
|
||||||
handler_ctx=fut,
|
handler_ctx=fut,
|
||||||
timeout_ms=timeout_ms))
|
timeout_ms=timeout_ms))
|
||||||
=======
|
|
||||||
_MIoTLanGetDevListData(handler=get_device_list_handler,
|
|
||||||
handler_ctx=fut,
|
|
||||||
timeout_ms=timeout_ms),
|
|
||||||
)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return await fut
|
return await fut
|
||||||
|
|
||||||
async def __call_api_async(self,
|
async def __call_api_async(self,
|
||||||
@ -1234,7 +930,6 @@ class MIoTLan:
|
|||||||
fut.set_result, msg)
|
fut.set_result, msg)
|
||||||
|
|
||||||
fut: asyncio.Future = self._main_loop.create_future()
|
fut: asyncio.Future = self._main_loop.create_future()
|
||||||
<<<<<<< HEAD
|
|
||||||
self._internal_loop.call_soon_threadsafe(
|
self._internal_loop.call_soon_threadsafe(
|
||||||
self.__call_api, did, msg, call_api_handler, fut, timeout_ms)
|
self.__call_api, did, msg, call_api_handler, fut, timeout_ms)
|
||||||
return await fut
|
return await fut
|
||||||
@ -1246,17 +941,6 @@ class MIoTLan:
|
|||||||
) -> None:
|
) -> None:
|
||||||
_LOGGER.info(
|
_LOGGER.info(
|
||||||
'on network info change, status: %s, info: %s', status, info)
|
'on network info change, status: %s, info: %s', status, info)
|
||||||
=======
|
|
||||||
self._internal_loop.call_soon_threadsafe(self.__call_api, did, msg,
|
|
||||||
call_api_handler, fut,
|
|
||||||
timeout_ms)
|
|
||||||
return await fut
|
|
||||||
|
|
||||||
async def __on_network_info_change_external_async(
|
|
||||||
self, status: InterfaceStatus, info: NetworkInfo) -> None:
|
|
||||||
_LOGGER.info("on network info change, status: %s, info: %s", status,
|
|
||||||
info)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
available_net_ifs = set()
|
available_net_ifs = set()
|
||||||
for if_name in list(self._network.network_info.keys()):
|
for if_name in list(self._network.network_info.keys()):
|
||||||
available_net_ifs.add(if_name)
|
available_net_ifs.add(if_name)
|
||||||
@ -1277,19 +961,11 @@ class MIoTLan:
|
|||||||
self.__on_network_info_change,
|
self.__on_network_info_change,
|
||||||
_MIoTLanNetworkUpdateData(status=status, if_name=info.name))
|
_MIoTLanNetworkUpdateData(status=status, if_name=info.name))
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
async def __on_mips_service_change(
|
async def __on_mips_service_change(
|
||||||
self, group_id: str, state: MipsServiceState, data: dict
|
self, group_id: str, state: MipsServiceState, data: dict
|
||||||
) -> None:
|
) -> None:
|
||||||
_LOGGER.info(
|
_LOGGER.info(
|
||||||
'on mips service change, %s, %s, %s', group_id, state, data)
|
'on mips service change, %s, %s, %s', group_id, state, data)
|
||||||
=======
|
|
||||||
async def __on_mips_service_change(self, group_id: str,
|
|
||||||
state: MipsServiceState,
|
|
||||||
data: dict) -> None:
|
|
||||||
_LOGGER.info("on mips service change, %s, %s, %s", group_id, state,
|
|
||||||
data)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if len(self._mips_service.get_services()) > 0:
|
if len(self._mips_service.get_services()) > 0:
|
||||||
_LOGGER.info('find central service, deinit miot lan')
|
_LOGGER.info('find central service, deinit miot lan')
|
||||||
await self.deinit_async()
|
await self.deinit_async()
|
||||||
@ -1302,16 +978,9 @@ class MIoTLan:
|
|||||||
def ping(self, if_name: Optional[str], target_ip: str) -> None:
|
def ping(self, if_name: Optional[str], target_ip: str) -> None:
|
||||||
if not target_ip:
|
if not target_ip:
|
||||||
return
|
return
|
||||||
<<<<<<< HEAD
|
|
||||||
self.__sendto(
|
self.__sendto(
|
||||||
if_name=if_name, data=self._probe_msg, address=target_ip,
|
if_name=if_name, data=self._probe_msg, address=target_ip,
|
||||||
port=self.OT_PORT)
|
port=self.OT_PORT)
|
||||||
=======
|
|
||||||
self.__sendto(if_name=if_name,
|
|
||||||
data=self._probe_msg,
|
|
||||||
address=target_ip,
|
|
||||||
port=self.OT_PORT)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def send2device(
|
def send2device(
|
||||||
self, did: str,
|
self, did: str,
|
||||||
@ -1361,7 +1030,6 @@ class MIoTLan:
|
|||||||
def request_timeout_handler(req_data: _MIoTLanRequestData):
|
def request_timeout_handler(req_data: _MIoTLanRequestData):
|
||||||
self._pending_requests.pop(req_data.msg_id, None)
|
self._pending_requests.pop(req_data.msg_id, None)
|
||||||
if req_data and req_data.handler:
|
if req_data and req_data.handler:
|
||||||
<<<<<<< HEAD
|
|
||||||
req_data.handler({
|
req_data.handler({
|
||||||
'code': MIoTErrorCode.CODE_TIMEOUT.value,
|
'code': MIoTErrorCode.CODE_TIMEOUT.value,
|
||||||
'error': 'timeout'},
|
'error': 'timeout'},
|
||||||
@ -1376,25 +1044,6 @@ class MIoTLan:
|
|||||||
if timeout_ms:
|
if timeout_ms:
|
||||||
timer = self._internal_loop.call_later(
|
timer = self._internal_loop.call_later(
|
||||||
timeout_ms/1000, request_timeout_handler, request_data)
|
timeout_ms/1000, request_timeout_handler, request_data)
|
||||||
=======
|
|
||||||
req_data.handler(
|
|
||||||
{
|
|
||||||
"code": MIoTErrorCode.CODE_TIMEOUT.value,
|
|
||||||
"error": "timeout"
|
|
||||||
},
|
|
||||||
req_data.handler_ctx,
|
|
||||||
)
|
|
||||||
|
|
||||||
timer: Optional[asyncio.TimerHandle] = None
|
|
||||||
request_data = _MIoTLanRequestData(msg_id=msg_id,
|
|
||||||
handler=handler,
|
|
||||||
handler_ctx=handler_ctx,
|
|
||||||
timeout=timer)
|
|
||||||
if timeout_ms:
|
|
||||||
timer = self._internal_loop.call_later(timeout_ms / 1000,
|
|
||||||
request_timeout_handler,
|
|
||||||
request_data)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
request_data.timeout = timer
|
request_data.timeout = timer
|
||||||
self._pending_requests[msg_id] = request_data
|
self._pending_requests[msg_id] = request_data
|
||||||
self.__sendto(if_name=if_name, data=msg, address=ip, port=self.OT_PORT)
|
self.__sendto(if_name=if_name, data=msg, address=ip, port=self.OT_PORT)
|
||||||
@ -1424,34 +1073,16 @@ class MIoTLan:
|
|||||||
try:
|
try:
|
||||||
self.send2device(
|
self.send2device(
|
||||||
did=did,
|
did=did,
|
||||||
<<<<<<< HEAD
|
|
||||||
msg={'from': 'ha.xiaomi_home', **msg},
|
msg={'from': 'ha.xiaomi_home', **msg},
|
||||||
=======
|
|
||||||
msg={
|
|
||||||
"from": "ha.xiaomi_home",
|
|
||||||
**msg
|
|
||||||
},
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
handler=handler,
|
handler=handler,
|
||||||
handler_ctx=handler_ctx,
|
handler_ctx=handler_ctx,
|
||||||
timeout_ms=timeout_ms)
|
timeout_ms=timeout_ms)
|
||||||
except Exception as err: # pylint: disable=broad-exception-caught
|
except Exception as err: # pylint: disable=broad-exception-caught
|
||||||
<<<<<<< HEAD
|
|
||||||
_LOGGER.error('send2device error, %s', err)
|
_LOGGER.error('send2device error, %s', err)
|
||||||
handler({
|
handler({
|
||||||
'code': MIoTErrorCode.CODE_INTERNAL_ERROR.value,
|
'code': MIoTErrorCode.CODE_INTERNAL_ERROR.value,
|
||||||
'error': str(err)},
|
'error': str(err)},
|
||||||
handler_ctx)
|
handler_ctx)
|
||||||
=======
|
|
||||||
_LOGGER.error("send2device error, %s", err)
|
|
||||||
handler(
|
|
||||||
{
|
|
||||||
"code": MIoTErrorCode.CODE_INTERNAL_ERROR.value,
|
|
||||||
"error": str(err)
|
|
||||||
},
|
|
||||||
handler_ctx,
|
|
||||||
)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def __sub_device_state(self, data: _MIoTLanSubDeviceData) -> None:
|
def __sub_device_state(self, data: _MIoTLanSubDeviceData) -> None:
|
||||||
self._device_state_sub_map[data.key] = data
|
self._device_state_sub_map[data.key] = data
|
||||||
@ -1471,7 +1102,6 @@ class MIoTLan:
|
|||||||
def __get_dev_list(self, data: _MIoTLanGetDevListData) -> None:
|
def __get_dev_list(self, data: _MIoTLanGetDevListData) -> None:
|
||||||
dev_list = {
|
dev_list = {
|
||||||
device.did: {
|
device.did: {
|
||||||
<<<<<<< HEAD
|
|
||||||
'online': device.online,
|
'online': device.online,
|
||||||
'push_available': device.subscribed
|
'push_available': device.subscribed
|
||||||
}
|
}
|
||||||
@ -1479,13 +1109,6 @@ class MIoTLan:
|
|||||||
if device.online}
|
if device.online}
|
||||||
data.handler(
|
data.handler(
|
||||||
dev_list, data.handler_ctx)
|
dev_list, data.handler_ctx)
|
||||||
=======
|
|
||||||
"online": device.online,
|
|
||||||
"push_available": device.subscribed
|
|
||||||
} for device in self._lan_devices.values() if device.online
|
|
||||||
}
|
|
||||||
data.handler(dev_list, data.handler_ctx)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def __update_devices(self, devices: dict[str, dict]) -> None:
|
def __update_devices(self, devices: dict[str, dict]) -> None:
|
||||||
for did, info in devices.items():
|
for did, info in devices.items():
|
||||||
@ -1498,14 +1121,9 @@ class MIoTLan:
|
|||||||
or info['model'] in self._profile_models):
|
or info['model'] in self._profile_models):
|
||||||
# Do not support the local control of
|
# Do not support the local control of
|
||||||
# Profile device for the time being
|
# Profile device for the time being
|
||||||
<<<<<<< HEAD
|
|
||||||
_LOGGER.info(
|
_LOGGER.info(
|
||||||
'model not support local ctrl, %s, %s',
|
'model not support local ctrl, %s, %s',
|
||||||
did, info.get('model'))
|
did, info.get('model'))
|
||||||
=======
|
|
||||||
_LOGGER.info("model not support local ctrl, %s, %s", did,
|
|
||||||
info.get("model"))
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
continue
|
continue
|
||||||
if did not in self._lan_devices:
|
if did not in self._lan_devices:
|
||||||
if 'token' not in info:
|
if 'token' not in info:
|
||||||
@ -1516,16 +1134,9 @@ class MIoTLan:
|
|||||||
_LOGGER.error(
|
_LOGGER.error(
|
||||||
'invalid device token, %s, %s', did, info)
|
'invalid device token, %s, %s', did, info)
|
||||||
continue
|
continue
|
||||||
<<<<<<< HEAD
|
|
||||||
self._lan_devices[did] = _MIoTLanDevice(
|
self._lan_devices[did] = _MIoTLanDevice(
|
||||||
manager=self, did=did, token=info['token'],
|
manager=self, did=did, token=info['token'],
|
||||||
ip=info.get('ip', None))
|
ip=info.get('ip', None))
|
||||||
=======
|
|
||||||
self._lan_devices[did] = _MIoTLanDevice(manager=self,
|
|
||||||
did=did,
|
|
||||||
token=info["token"],
|
|
||||||
ip=info.get("ip", None))
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
else:
|
else:
|
||||||
self._lan_devices[did].update_info(info)
|
self._lan_devices[did].update_info(info)
|
||||||
|
|
||||||
@ -1596,7 +1207,6 @@ class MIoTLan:
|
|||||||
return
|
return
|
||||||
# Create socket
|
# Create socket
|
||||||
try:
|
try:
|
||||||
<<<<<<< HEAD
|
|
||||||
sock = socket.socket(
|
sock = socket.socket(
|
||||||
socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||||
@ -1607,19 +1217,6 @@ class MIoTLan:
|
|||||||
sock.bind(('', self._local_port or 0))
|
sock.bind(('', self._local_port or 0))
|
||||||
self._internal_loop.add_reader(
|
self._internal_loop.add_reader(
|
||||||
sock.fileno(), self.__socket_read_handler, (if_name, sock))
|
sock.fileno(), self.__socket_read_handler, (if_name, sock))
|
||||||
=======
|
|
||||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
|
|
||||||
socket.IPPROTO_UDP)
|
|
||||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
||||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
||||||
# Set SO_BINDTODEVICE
|
|
||||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE,
|
|
||||||
if_name.encode())
|
|
||||||
sock.bind(("", self._local_port or 0))
|
|
||||||
self._internal_loop.add_reader(sock.fileno(),
|
|
||||||
self.__socket_read_handler,
|
|
||||||
(if_name, sock))
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._broadcast_socks[if_name] = sock
|
self._broadcast_socks[if_name] = sock
|
||||||
self._local_port = self._local_port or sock.getsockname()[1]
|
self._local_port = self._local_port or sock.getsockname()[1]
|
||||||
_LOGGER.info(
|
_LOGGER.info(
|
||||||
@ -1642,14 +1239,8 @@ class MIoTLan:
|
|||||||
|
|
||||||
def __socket_read_handler(self, ctx: tuple[str, socket.socket]) -> None:
|
def __socket_read_handler(self, ctx: tuple[str, socket.socket]) -> None:
|
||||||
try:
|
try:
|
||||||
<<<<<<< HEAD
|
|
||||||
data_len, addr = ctx[1].recvfrom_into(
|
data_len, addr = ctx[1].recvfrom_into(
|
||||||
self._read_buffer, self.OT_MSG_LEN, socket.MSG_DONTWAIT)
|
self._read_buffer, self.OT_MSG_LEN, socket.MSG_DONTWAIT)
|
||||||
=======
|
|
||||||
data_len, addr = ctx[1].recvfrom_into(self._read_buffer,
|
|
||||||
self.OT_MSG_LEN,
|
|
||||||
socket.MSG_DONTWAIT)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if data_len < 0:
|
if data_len < 0:
|
||||||
# Socket error
|
# Socket error
|
||||||
_LOGGER.error('socket read error, %s, %s', ctx[0], data_len)
|
_LOGGER.error('socket read error, %s, %s', ctx[0], data_len)
|
||||||
@ -1657,13 +1248,8 @@ class MIoTLan:
|
|||||||
if addr[1] != self.OT_PORT:
|
if addr[1] != self.OT_PORT:
|
||||||
# Not ot msg
|
# Not ot msg
|
||||||
return
|
return
|
||||||
<<<<<<< HEAD
|
|
||||||
self.__raw_message_handler(
|
self.__raw_message_handler(
|
||||||
self._read_buffer[:data_len], data_len, addr[0], ctx[0])
|
self._read_buffer[:data_len], data_len, addr[0], ctx[0])
|
||||||
=======
|
|
||||||
self.__raw_message_handler(self._read_buffer[:data_len], data_len,
|
|
||||||
addr[0], ctx[0])
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
except Exception as err: # pylint: disable=broad-exception-caught
|
except Exception as err: # pylint: disable=broad-exception-caught
|
||||||
_LOGGER.error('socket read handler error, %s', err)
|
_LOGGER.error('socket read handler error, %s', err)
|
||||||
|
|
||||||
@ -1682,7 +1268,6 @@ class MIoTLan:
|
|||||||
if data_len == self.OT_PROBE_LEN or device.subscribed:
|
if data_len == self.OT_PROBE_LEN or device.subscribed:
|
||||||
device.keep_alive(ip=ip, if_name=if_name)
|
device.keep_alive(ip=ip, if_name=if_name)
|
||||||
# Manage device subscribe status
|
# Manage device subscribe status
|
||||||
<<<<<<< HEAD
|
|
||||||
if (
|
if (
|
||||||
self._enable_subscribe
|
self._enable_subscribe
|
||||||
and data_len == self.OT_PROBE_LEN
|
and data_len == self.OT_PROBE_LEN
|
||||||
@ -1692,13 +1277,6 @@ class MIoTLan:
|
|||||||
device.supported_wildcard_sub = (
|
device.supported_wildcard_sub = (
|
||||||
int(data[28]) == self.OT_SUPPORT_WILDCARD_SUB)
|
int(data[28]) == self.OT_SUPPORT_WILDCARD_SUB)
|
||||||
sub_ts = struct.unpack('>I', data[20:24])[0]
|
sub_ts = struct.unpack('>I', data[20:24])[0]
|
||||||
=======
|
|
||||||
if (self._enable_subscribe and data_len == self.OT_PROBE_LEN and
|
|
||||||
data[16:20] == b"MSUB" and data[24:27] == b"PUB"):
|
|
||||||
device.supported_wildcard_sub = (int(
|
|
||||||
data[28]) == self.OT_SUPPORT_WILDCARD_SUB)
|
|
||||||
sub_ts = struct.unpack(">I", data[20:24])[0]
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
sub_type = int(data[27])
|
sub_type = int(data[27])
|
||||||
if (device.supported_wildcard_sub and sub_type in [0, 1, 4] and
|
if (device.supported_wildcard_sub and sub_type in [0, 1, 4] and
|
||||||
sub_ts != device.sub_ts):
|
sub_ts != device.sub_ts):
|
||||||
@ -1718,19 +1296,13 @@ class MIoTLan:
|
|||||||
_LOGGER.warning('invalid message, no id, %s, %s', did, msg)
|
_LOGGER.warning('invalid message, no id, %s, %s', did, msg)
|
||||||
return
|
return
|
||||||
# Reply
|
# Reply
|
||||||
<<<<<<< HEAD
|
|
||||||
req: Optional[_MIoTLanRequestData] = (
|
req: Optional[_MIoTLanRequestData] = (
|
||||||
self._pending_requests.pop(msg['id'], None))
|
self._pending_requests.pop(msg['id'], None))
|
||||||
=======
|
|
||||||
req: Optional[_MIoTLanRequestData] = self._pending_requests.pop(
|
|
||||||
msg["id"], None)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if req:
|
if req:
|
||||||
if req.timeout:
|
if req.timeout:
|
||||||
req.timeout.cancel()
|
req.timeout.cancel()
|
||||||
req.timeout = None
|
req.timeout = None
|
||||||
if req.handler is not None:
|
if req.handler is not None:
|
||||||
<<<<<<< HEAD
|
|
||||||
self._main_loop.call_soon_threadsafe(
|
self._main_loop.call_soon_threadsafe(
|
||||||
req.handler, msg, req.handler_ctx)
|
req.handler, msg, req.handler_ctx)
|
||||||
return
|
return
|
||||||
@ -1750,32 +1322,6 @@ class MIoTLan:
|
|||||||
if 'siid' not in param and 'piid' not in param:
|
if 'siid' not in param and 'piid' not in param:
|
||||||
_LOGGER.debug(
|
_LOGGER.debug(
|
||||||
'invalid message, no siid or piid, %s, %s', did, msg)
|
'invalid message, no siid or piid, %s, %s', did, msg)
|
||||||
=======
|
|
||||||
self._main_loop.call_soon_threadsafe(req.handler, msg,
|
|
||||||
req.handler_ctx)
|
|
||||||
return
|
|
||||||
# Handle up link message
|
|
||||||
if "method" not in msg or "params" not in msg:
|
|
||||||
_LOGGER.debug("invalid message, no method or params, %s, %s", did,
|
|
||||||
msg)
|
|
||||||
return
|
|
||||||
# Filter dup message
|
|
||||||
if self.__filter_dup_message(did, msg["id"]):
|
|
||||||
self.send2device(did=did,
|
|
||||||
msg={
|
|
||||||
"id": msg["id"],
|
|
||||||
"result": {
|
|
||||||
"code": 0
|
|
||||||
}
|
|
||||||
})
|
|
||||||
return
|
|
||||||
_LOGGER.debug("lan message, %s, %s", did, msg)
|
|
||||||
if msg["method"] == "properties_changed":
|
|
||||||
for param in msg["params"]:
|
|
||||||
if "siid" not in param and "piid" not in param:
|
|
||||||
_LOGGER.debug("invalid message, no siid or piid, %s, %s",
|
|
||||||
did, msg)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
continue
|
continue
|
||||||
key = f'{did}/p/{param["siid"]}/{param["piid"]}'
|
key = f'{did}/p/{param["siid"]}/{param["piid"]}'
|
||||||
subs: list[_MIoTLanRegisterBroadcastData] = list(
|
subs: list[_MIoTLanRegisterBroadcastData] = list(
|
||||||
@ -1783,7 +1329,6 @@ class MIoTLan:
|
|||||||
for sub in subs:
|
for sub in subs:
|
||||||
self._main_loop.call_soon_threadsafe(
|
self._main_loop.call_soon_threadsafe(
|
||||||
sub.handler, param, sub.handler_ctx)
|
sub.handler, param, sub.handler_ctx)
|
||||||
<<<<<<< HEAD
|
|
||||||
elif (
|
elif (
|
||||||
msg['method'] == 'event_occured'
|
msg['method'] == 'event_occured'
|
||||||
and 'siid' in msg['params']
|
and 'siid' in msg['params']
|
||||||
@ -1795,16 +1340,6 @@ class MIoTLan:
|
|||||||
for sub in subs:
|
for sub in subs:
|
||||||
self._main_loop.call_soon_threadsafe(
|
self._main_loop.call_soon_threadsafe(
|
||||||
sub.handler, msg['params'], sub.handler_ctx)
|
sub.handler, msg['params'], sub.handler_ctx)
|
||||||
=======
|
|
||||||
elif (msg["method"] == "event_occured" and "siid" in msg["params"] and
|
|
||||||
"eiid" in msg["params"]):
|
|
||||||
key = f"{did}/e/{msg['params']['siid']}/{msg['params']['eiid']}"
|
|
||||||
subs: list[_MIoTLanRegisterBroadcastData] = list(
|
|
||||||
self._device_msg_matcher.iter_match(key))
|
|
||||||
for sub in subs:
|
|
||||||
self._main_loop.call_soon_threadsafe(sub.handler, msg["params"],
|
|
||||||
sub.handler_ctx)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
else:
|
else:
|
||||||
_LOGGER.debug(
|
_LOGGER.debug(
|
||||||
'invalid message, unknown method, %s, %s', did, msg)
|
'invalid message, unknown method, %s, %s', did, msg)
|
||||||
@ -1817,12 +1352,8 @@ class MIoTLan:
|
|||||||
if filter_id in self._reply_msg_buffer:
|
if filter_id in self._reply_msg_buffer:
|
||||||
return True
|
return True
|
||||||
self._reply_msg_buffer[filter_id] = self._internal_loop.call_later(
|
self._reply_msg_buffer[filter_id] = self._internal_loop.call_later(
|
||||||
<<<<<<< HEAD
|
|
||||||
5,
|
5,
|
||||||
lambda filter_id: self._reply_msg_buffer.pop(filter_id, None),
|
lambda filter_id: self._reply_msg_buffer.pop(filter_id, None),
|
||||||
=======
|
|
||||||
5, lambda filter_id: self._reply_msg_buffer.pop(filter_id, None),
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
filter_id)
|
filter_id)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@ -1855,20 +1386,11 @@ class MIoTLan:
|
|||||||
scan_time = self.__get_next_scan_time()
|
scan_time = self.__get_next_scan_time()
|
||||||
self._scan_timer = self._internal_loop.call_later(
|
self._scan_timer = self._internal_loop.call_later(
|
||||||
scan_time, self.__scan_devices)
|
scan_time, self.__scan_devices)
|
||||||
<<<<<<< HEAD
|
|
||||||
_LOGGER.debug('next scan time: %ss', scan_time)
|
_LOGGER.debug('next scan time: %ss', scan_time)
|
||||||
=======
|
|
||||||
_LOGGER.debug("next scan time: %ss", scan_time)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
def __get_next_scan_time(self) -> float:
|
def __get_next_scan_time(self) -> float:
|
||||||
if not self._last_scan_interval:
|
if not self._last_scan_interval:
|
||||||
self._last_scan_interval = self.OT_PROBE_INTERVAL_MIN
|
self._last_scan_interval = self.OT_PROBE_INTERVAL_MIN
|
||||||
<<<<<<< HEAD
|
|
||||||
self._last_scan_interval = min(
|
self._last_scan_interval = min(
|
||||||
self._last_scan_interval*2, self.OT_PROBE_INTERVAL_MAX)
|
self._last_scan_interval*2, self.OT_PROBE_INTERVAL_MAX)
|
||||||
=======
|
|
||||||
self._last_scan_interval = min(self._last_scan_interval * 2,
|
|
||||||
self.OT_PROBE_INTERVAL_MAX)
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
return self._last_scan_interval
|
return self._last_scan_interval
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -66,11 +66,7 @@ async def async_setup_entry(
|
|||||||
async_add_entities: AddEntitiesCallback,
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up a config entry."""
|
"""Set up a config entry."""
|
||||||
<<<<<<< HEAD
|
|
||||||
device_list: list[MIoTDevice] = hass.data[DOMAIN]['devices'][
|
device_list: list[MIoTDevice] = hass.data[DOMAIN]['devices'][
|
||||||
=======
|
|
||||||
device_list: list[MIoTDevice] = hass.data[DOMAIN]["devices"][
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
config_entry.entry_id]
|
config_entry.entry_id]
|
||||||
|
|
||||||
new_entities = []
|
new_entities = []
|
||||||
@ -84,25 +80,12 @@ async def async_setup_entry(
|
|||||||
# create select for light
|
# create select for light
|
||||||
new_light_select_entities = []
|
new_light_select_entities = []
|
||||||
for miot_device in device_list:
|
for miot_device in device_list:
|
||||||
<<<<<<< HEAD
|
|
||||||
# Add it to all devices with light entities, because some bathroom heaters and clothes drying racks also have lights.
|
# Add it to all devices with light entities, because some bathroom heaters and clothes drying racks also have lights.
|
||||||
# if "device:light" in miot_device.spec_instance.urn:
|
# if "device:light" in miot_device.spec_instance.urn:
|
||||||
if miot_device.entity_list.get("light", []):
|
if miot_device.entity_list.get("light", []):
|
||||||
device_id = list(miot_device.device_info.get("identifiers"))[0][1]
|
device_id = list(miot_device.device_info.get("identifiers"))[0][1]
|
||||||
new_light_select_entities.append(
|
new_light_select_entities.append(
|
||||||
LightCommandSendMode(hass=hass, device_id=device_id))
|
LightCommandSendMode(hass=hass, device_id=device_id))
|
||||||
=======
|
|
||||||
if "device:light" in miot_device.spec_instance.urn:
|
|
||||||
if miot_device.entity_list.get("light", []):
|
|
||||||
device_id = list(
|
|
||||||
miot_device.device_info.get("identifiers"))[0][1]
|
|
||||||
light_entity_id = miot_device.gen_device_entity_id(DOMAIN)
|
|
||||||
new_light_select_entities.append(
|
|
||||||
LightCommandSendMode(hass=hass,
|
|
||||||
light_entity_id=light_entity_id,
|
|
||||||
device_id=device_id))
|
|
||||||
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
if new_light_select_entities:
|
if new_light_select_entities:
|
||||||
async_add_entities(new_light_select_entities)
|
async_add_entities(new_light_select_entities)
|
||||||
|
|
||||||
@ -117,13 +100,8 @@ class Select(MIoTPropertyEntity, SelectEntity):
|
|||||||
|
|
||||||
async def async_select_option(self, option: str) -> None:
|
async def async_select_option(self, option: str) -> None:
|
||||||
"""Change the selected option."""
|
"""Change the selected option."""
|
||||||
<<<<<<< HEAD
|
|
||||||
await self.set_property_async(
|
await self.set_property_async(
|
||||||
value=self.get_vlist_value(description=option))
|
value=self.get_vlist_value(description=option))
|
||||||
=======
|
|
||||||
await self.set_property_async(value=self.get_vlist_value(
|
|
||||||
description=option))
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def current_option(self) -> Optional[str]:
|
def current_option(self) -> Optional[str]:
|
||||||
@ -136,34 +114,19 @@ class LightCommandSendMode(SelectEntity, RestoreEntity):
|
|||||||
then send other color temperatures and brightness or send them all at the same time.
|
then send other color temperatures and brightness or send them all at the same time.
|
||||||
The default is to send one by one."""
|
The default is to send one by one."""
|
||||||
|
|
||||||
<<<<<<< HEAD
|
|
||||||
def __init__(self, hass: HomeAssistant, device_id: str):
|
def __init__(self, hass: HomeAssistant, device_id: str):
|
||||||
=======
|
|
||||||
def __init__(self, hass: HomeAssistant, light_entity_id: str,
|
|
||||||
device_id: str):
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.hass = hass
|
self.hass = hass
|
||||||
self._device_id = device_id
|
self._device_id = device_id
|
||||||
self._attr_name = "Command Send Mode"
|
self._attr_name = "Command Send Mode"
|
||||||
<<<<<<< HEAD
|
|
||||||
self.entity_id = f"select.light_{device_id}_command_send_mode"
|
self.entity_id = f"select.light_{device_id}_command_send_mode"
|
||||||
self._attr_unique_id = self.entity_id
|
self._attr_unique_id = self.entity_id
|
||||||
=======
|
|
||||||
self._attr_unique_id = f"{light_entity_id}_command_send_mode"
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
self._attr_options = [
|
self._attr_options = [
|
||||||
"Send One by One", "Send Turn On First", "Send Together"
|
"Send One by One", "Send Turn On First", "Send Together"
|
||||||
]
|
]
|
||||||
self._attr_device_info = {"identifiers": {(DOMAIN, device_id)}}
|
self._attr_device_info = {"identifiers": {(DOMAIN, device_id)}}
|
||||||
<<<<<<< HEAD
|
|
||||||
self._attr_current_option = self._attr_options[0]
|
self._attr_current_option = self._attr_options[0]
|
||||||
self._attr_entity_category = EntityCategory.CONFIG
|
self._attr_entity_category = EntityCategory.CONFIG
|
||||||
=======
|
|
||||||
self._attr_current_option = self._attr_options[0] # 默认选项
|
|
||||||
self._attr_entity_category = (EntityCategory.CONFIG
|
|
||||||
) # **重点:告诉 HA 这是配置类实体**
|
|
||||||
>>>>>>> 83899f8 (fomatted code)
|
|
||||||
|
|
||||||
async def async_select_option(self, option: str):
|
async def async_select_option(self, option: str):
|
||||||
if option in self._attr_options:
|
if option in self._attr_options:
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user