mirror of
https://github.com/XiaoMi/ha_xiaomi_home.git
synced 2026-01-17 15:41:15 +08:00
fomatted code
This commit is contained in:
parent
006a445e3a
commit
5dc6f400c2
@ -80,7 +80,11 @@ 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 = []
|
||||||
@ -106,9 +110,14 @@ 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
|
||||||
@ -149,8 +158,13 @@ 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':
|
||||||
@ -176,6 +190,7 @@ 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_
|
||||||
@ -183,6 +198,11 @@ 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)
|
||||||
@ -190,8 +210,14 @@ 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())
|
||||||
@ -245,9 +271,14 @@ 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.
|
||||||
@ -285,6 +316,7 @@ 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({
|
||||||
@ -296,6 +328,18 @@ 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
|
||||||
@ -318,6 +362,7 @@ 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(
|
||||||
@ -334,16 +379,33 @@ 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({
|
||||||
@ -357,6 +419,14 @@ 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
|
||||||
@ -379,6 +449,7 @@ 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(
|
||||||
@ -389,10 +460,23 @@ 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)
|
||||||
@ -403,6 +487,18 @@ 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(
|
||||||
@ -416,17 +512,30 @@ 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,10 +99,17 @@ 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
|
||||||
@ -165,14 +172,20 @@ 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
|
||||||
@ -188,6 +201,19 @@ 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:
|
||||||
@ -202,12 +228,22 @@ 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.
|
||||||
@ -221,11 +257,20 @@ 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:
|
||||||
@ -256,6 +301,7 @@ 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)
|
||||||
@ -266,6 +312,16 @@ 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)
|
||||||
|
|
||||||
@ -307,9 +363,16 @@ 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,
|
||||||
@ -327,6 +390,7 @@ 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(
|
||||||
@ -338,6 +402,19 @@ 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,
|
||||||
@ -355,24 +432,42 @@ 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
|
||||||
@ -380,6 +475,11 @@ 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']
|
||||||
|
|
||||||
@ -401,9 +501,14 @@ 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={
|
||||||
@ -419,6 +524,7 @@ 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', []):
|
||||||
@ -442,6 +548,32 @@ 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
|
||||||
|
|
||||||
@ -450,10 +582,16 @@ 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:
|
||||||
@ -481,6 +619,7 @@ 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']] = {
|
||||||
@ -512,10 +651,48 @@ 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():
|
||||||
@ -527,6 +704,19 @@ 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,
|
||||||
@ -538,6 +728,7 @@ 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 = {
|
||||||
@ -546,16 +737,29 @@ 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)
|
||||||
@ -580,6 +784,7 @@ 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,
|
||||||
@ -606,17 +811,79 @@ 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:
|
||||||
@ -624,21 +891,27 @@ class MIoTHttpClient:
|
|||||||
devices.update(result)
|
devices.update(result)
|
||||||
return devices
|
return devices
|
||||||
|
|
||||||
async def get_devices_async(
|
async def get_devices_async(self,
|
||||||
self, home_ids: Optional[list[str]] = None
|
home_ids: Optional[list[str]] = None
|
||||||
) -> dict[str, dict]:
|
) -> dict[str, dict]:
|
||||||
homeinfos = await self.get_homeinfos_async()
|
homeinfos = await self.get_homeinfos_async()
|
||||||
homes: dict[str, dict[str, Any]] = {}
|
homes: dict[str, dict[str, Any]] = {}
|
||||||
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'],
|
||||||
@ -666,9 +939,44 @@ 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'],
|
||||||
@ -683,6 +991,29 @@ 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:
|
||||||
@ -700,9 +1031,15 @@ 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)
|
||||||
@ -718,10 +1055,17 @@ 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:
|
||||||
@ -729,8 +1073,16 @@ 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]
|
||||||
@ -759,7 +1111,11 @@ 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)
|
||||||
@ -787,9 +1143,11 @@ class MIoTHttpClient:
|
|||||||
self._get_prop_timer = None
|
self._get_prop_timer = None
|
||||||
return True
|
return True
|
||||||
|
|
||||||
async def get_prop_async(
|
async def get_prop_async(self,
|
||||||
self, did: str, siid: int, piid: int, immediately: bool = False
|
did: str,
|
||||||
) -> Any:
|
siid: int,
|
||||||
|
piid: int,
|
||||||
|
immediately: bool = False) -> Any:
|
||||||
if immediately:
|
if immediately:
|
||||||
return await self.__get_prop_async(did, siid, piid)
|
return await self.__get_prop_async(did, siid, piid)
|
||||||
key: str = f'{did}.{siid}.{piid}'
|
key: str = f'{did}.{siid}.{piid}'
|
||||||
@ -798,8 +1156,17 @@ 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(
|
||||||
@ -814,6 +1181,7 @@ 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
|
||||||
@ -822,6 +1190,13 @@ 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']
|
||||||
|
|
||||||
@ -830,6 +1205,7 @@ 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
|
||||||
@ -838,12 +1214,18 @@ 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']
|
||||||
|
|
||||||
async def action_async(
|
async def action_async(self, did: str, siid: int, aiid: int,
|
||||||
self, did: str, siid: int, aiid: int, in_list: list[dict]
|
in_list: list[dict]) -> dict:
|
||||||
) -> dict:
|
|
||||||
"""
|
"""
|
||||||
params = {"did": "xxxx", "siid": 2, "aiid": 1, "in": []}
|
params = {"did": "xxxx", "siid": 2, "aiid": 1, "in": []}
|
||||||
"""
|
"""
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -71,7 +71,6 @@ from .miot_mdns import MipsService, MipsServiceState
|
|||||||
from .common import (
|
from .common import (
|
||||||
randomize_float, load_yaml_file, gen_absolute_path, MIoTMatcher)
|
randomize_float, load_yaml_file, gen_absolute_path, MIoTMatcher)
|
||||||
|
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
@ -164,6 +163,7 @@ 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,13 +171,25 @@ 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
|
||||||
@ -202,8 +214,13 @@ 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
|
||||||
@ -216,27 +233,48 @@ 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
|
||||||
@ -250,8 +288,13 @@ 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()
|
||||||
@ -302,8 +345,17 @@ 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:
|
||||||
@ -315,15 +367,21 @@ 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())
|
||||||
@ -336,10 +394,21 @@ 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)
|
||||||
@ -351,6 +420,20 @@ 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)
|
||||||
|
|
||||||
@ -368,6 +451,7 @@ 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 (
|
||||||
@ -375,6 +459,14 @@ 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,
|
||||||
@ -411,6 +503,7 @@ 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 (
|
||||||
@ -424,6 +517,18 @@ 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)
|
||||||
@ -502,6 +607,7 @@ 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
|
||||||
@ -518,6 +624,23 @@ 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)
|
||||||
@ -540,6 +663,7 @@ 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
|
||||||
@ -554,6 +678,18 @@ 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:
|
||||||
@ -606,14 +742,23 @@ 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')
|
||||||
|
|
||||||
@ -683,7 +828,11 @@ 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)
|
||||||
@ -701,9 +850,14 @@ 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:
|
||||||
@ -718,8 +872,15 @@ 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
|
||||||
@ -748,6 +909,7 @@ 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
|
||||||
@ -759,6 +921,19 @@ 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:
|
||||||
@ -767,8 +942,12 @@ 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
|
||||||
@ -789,6 +968,7 @@ 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
|
||||||
@ -800,6 +980,19 @@ 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:
|
||||||
@ -808,16 +1001,23 @@ 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
|
||||||
async def get_prop_async(
|
async def get_prop_async(self,
|
||||||
self, did: str, siid: int, piid: int, timeout_ms: int = 10000
|
did: str,
|
||||||
) -> Any:
|
siid: int,
|
||||||
|
piid: int,
|
||||||
|
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}]
|
||||||
@ -854,14 +1054,71 @@ 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={
|
||||||
@ -869,6 +1126,7 @@ 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)
|
||||||
@ -892,6 +1150,41 @@ 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']
|
||||||
@ -900,9 +1193,14 @@ 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 {}
|
||||||
|
|
||||||
@ -913,20 +1211,30 @@ 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(
|
async def __call_api_async(self,
|
||||||
self, did: str, msg: dict, timeout_ms: int = 10000
|
did: str,
|
||||||
) -> dict:
|
msg: dict,
|
||||||
|
timeout_ms: int = 10000) -> dict:
|
||||||
|
|
||||||
def call_api_handler(msg: dict, fut: asyncio.Future):
|
def call_api_handler(msg: dict, fut: asyncio.Future):
|
||||||
self._main_loop.call_soon_threadsafe(
|
self._main_loop.call_soon_threadsafe(
|
||||||
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
|
||||||
@ -938,6 +1246,17 @@ 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)
|
||||||
@ -958,11 +1277,19 @@ 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()
|
||||||
@ -975,9 +1302,16 @@ 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,
|
||||||
@ -1023,9 +1357,11 @@ class MIoTLan:
|
|||||||
handler_ctx: Any = None,
|
handler_ctx: Any = None,
|
||||||
timeout_ms: Optional[int] = None
|
timeout_ms: Optional[int] = None
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|
||||||
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'},
|
||||||
@ -1040,6 +1376,25 @@ 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)
|
||||||
@ -1069,16 +1424,34 @@ 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
|
||||||
@ -1098,6 +1471,7 @@ 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
|
||||||
}
|
}
|
||||||
@ -1105,6 +1479,13 @@ 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():
|
||||||
@ -1117,9 +1498,14 @@ 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:
|
||||||
@ -1130,9 +1516,16 @@ 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)
|
||||||
|
|
||||||
@ -1203,6 +1596,7 @@ 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)
|
||||||
@ -1213,6 +1607,19 @@ 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(
|
||||||
@ -1235,8 +1642,14 @@ 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)
|
||||||
@ -1244,14 +1657,18 @@ 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)
|
||||||
|
|
||||||
def __raw_message_handler(
|
def __raw_message_handler(self, data: bytearray, data_len: int, ip: str,
|
||||||
self, data: bytearray, data_len: int, ip: str, if_name: str
|
if_name: str) -> None:
|
||||||
) -> None:
|
|
||||||
if data[:2] != self.OT_HEADER:
|
if data[:2] != self.OT_HEADER:
|
||||||
return
|
return
|
||||||
# Keep alive message
|
# Keep alive message
|
||||||
@ -1265,6 +1682,7 @@ 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
|
||||||
@ -1274,12 +1692,16 @@ 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 (
|
if (device.supported_wildcard_sub and sub_type in [0, 1, 4] and
|
||||||
device.supported_wildcard_sub
|
sub_ts != device.sub_ts):
|
||||||
and sub_type in [0, 1, 4]
|
|
||||||
and sub_ts != device.sub_ts
|
|
||||||
):
|
|
||||||
device.subscribed = False
|
device.subscribed = False
|
||||||
device.subscribe()
|
device.subscribe()
|
||||||
if data_len > self.OT_PROBE_LEN:
|
if data_len > self.OT_PROBE_LEN:
|
||||||
@ -1296,13 +1718,19 @@ 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
|
||||||
@ -1322,6 +1750,32 @@ 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(
|
||||||
@ -1329,6 +1783,7 @@ 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']
|
||||||
@ -1340,6 +1795,16 @@ 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)
|
||||||
@ -1352,14 +1817,17 @@ 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
|
||||||
|
|
||||||
def __sendto(
|
def __sendto(self, if_name: Optional[str], data: bytes, address: str,
|
||||||
self, if_name: Optional[str], data: bytes, address: str, port: int
|
port: int) -> None:
|
||||||
) -> None:
|
|
||||||
if if_name is None:
|
if if_name is None:
|
||||||
# Broadcast
|
# Broadcast
|
||||||
for if_n, sock in self._broadcast_socks.items():
|
for if_n, sock in self._broadcast_socks.items():
|
||||||
@ -1387,11 +1855,20 @@ 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,7 +66,11 @@ 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 = []
|
||||||
@ -80,12 +84,25 @@ 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)
|
||||||
|
|
||||||
@ -100,8 +117,13 @@ 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]:
|
||||||
@ -114,19 +136,34 @@ 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