custom_components/xiaomi_miot_raw/__init__.py
async def async_update(self):
        """Fetch state from the device."""
        def pre_process_data(key, value):
            try:
                if key in self._ctrl_params_new:
                    if f := self._ctrl_params_new[key].get('value_ratio'):
                        return round(value * f , 3)
                    if 'value_list' in self._ctrl_params_new[key]:
                        if s := self.get_key_by_value(self._ctrl_params_new[key]['value_list'], value):
                            return s
                    elif (('status' in key and 'switch_status' not in key) \
                        or 'state' in key \
                        or 'fault' in key) \
                        and type(value) == int:
                        if s := self.get_key_by_value(self._ctrl_params_new[key], value):
                            return s
                return value
            except KeyError:
                return None

        # On state change some devices doesn't provide the new state immediately.
        if self._update_instant is False or self._skip_update:
            self._skip_update = False
            self._delay_update = 0
            return
        if self._delay_update != 0:
            await asyncio.sleep(self._delay_update)
            self._delay_update = 0
        try:
            if not self._cloud:
                response = await self.hass.async_add_job(
                    partial(self._device.get_properties_for_mapping, max_properties=self._max_properties)
                )
                self._available = True

                statedict={}
                props_with_4004 = []
                for r in response:
                    if r['code'] == 0:
                        statedict[r['did']] = pre_process_data(r['did'], r['value'])
                    elif r['code'] == 9999:
                        persistent_notification.async_create(
                            self._hass,
                            f"您添加的设备: **{self._name}** ，\n"
                            f"在获取个状态时，\n"
                            f"返回 **-9999** 错误。\n"
                            "请考虑通过云端接入此设备来解决此问题。",
                            "设备不支持本地接入")
                    else:
                        statedict[r['did']] = None
                        if r['code'] == -4004 and not self._err4004_notified:
                            props_with_4004.append(r['did'])
                        else:
                            _LOGGER.info("Error getting %s 's property '%s' (code: %s)", self._name, r['did'], r['code'])
                if not self._err4004_notified:
                    if len(props_with_4004) == len(response):
                        self._assumed_state = True
                        self._skip_update = True
                        # _LOGGER.warn("设备不支持状态反馈")
                        if not self._err4004_notified:
                            persistent_notification.async_create(
                                self._hass,
                                f"您添加的设备: **{self._name}** ，\n"
                                f"在获取 {len(response)} 个状态时，\n"
                                f"全部返回 **-4004** 错误。\n"
                                "请考虑通过云端接入此设备来解决此问题。",
                                "设备可能不受支持")
                            self._err4004_notified = True
                            del props_with_4004
                    elif len(props_with_4004) != 0:
                        _LOGGER.warn(f"Device {self._name} returns unknown error for property {props_with_4004}. If you encounter issues about this device, try enabling Cloud Access.")
                        self._err4004_notified = True
                        del props_with_4004

            else:
                _LOGGER.info(f"{self._name} is updating from cloud.")

                a = await self._cloud_instance.get_props(self._body_for_update_cloud, self._cloud.get("server_location"))

                dict1 = {}
                statedict = {}
                if a:
                    if a['code'] != 0:
                        _LOGGER.error(f"Error updating {self._name} from cloud: {a}")
                        return None
                    if all(item['code'] == -704042011 for item in a['result']):
                        if self._available == True or self._available == None:
                            if OFFLINE_NOTIFY:
                                persistent_notification.async_create(
                                    self._hass,
                                    f"请注意，云端接入设备 **{self._name}** 已离线。",
                                    "Xiaomi MIoT - 设备离线")
                            else:
                                _LOGGER.warn(f"请注意，云端接入设备 **{self._name}** 已离线。")
                        self._available = False
                    else:
                        self._available = True

                    for item in a['result']:
                        # TODO handle -704030013 (Unreadable property)
                        dict1.setdefault(item['siid'], {})
                        dict1[item['siid']][item['piid']] = item.get('value')

                    for key, value in self._mapping.items():
                        if 'aiid' in value:
                            continue
                        statedict[key] = pre_process_data(key, dict1[value['siid']][value['piid']])

                else:
                    pass

            self._fail_count = 0
            self._state_attrs.update(statedict)
            self._handle_platform_specific_attrs()
            self.publish_updates()

        except DeviceException as ex:
            if self._fail_count < 3:
                self._fail_count += 1
                _LOGGER.info("Got exception while fetching %s 's state: %s. Count %d", self._name, ex, self._fail_count)
            else:
                self._available = False
                _LOGGER.error("Got exception while fetching %s 's state: %s", self._name, ex)
Fetch state from the device.
Fetch state from the device.
Fetch state from the device .
async def async_update(self):
        def pre_process_data(key, value):
            try:
                if key in self._ctrl_params_new:
                    if f := self._ctrl_params_new[key].get('value_ratio'):
                        return round(value * f , 3)
                    if 'value_list' in self._ctrl_params_new[key]:
                        if s := self.get_key_by_value(self._ctrl_params_new[key]['value_list'], value):
                            return s
                    elif (('status' in key and 'switch_status' not in key) \
                        or 'state' in key \
                        or 'fault' in key) \
                        and type(value) == int:
                        if s := self.get_key_by_value(self._ctrl_params_new[key], value):
                            return s
                return value
            except KeyError:
                return None
        if self._update_instant is False or self._skip_update:
            self._skip_update = False
            self._delay_update = 0
            return
        if self._delay_update != 0:
            await asyncio.sleep(self._delay_update)
            self._delay_update = 0
        try:
            if not self._cloud:
                response = await self.hass.async_add_job(
                    partial(self._device.get_properties_for_mapping, max_properties=self._max_properties)
                )
                self._available = True
                statedict={}
                props_with_4004 = []
                for r in response:
                    if r['code'] == 0:
                        statedict[r['did']] = pre_process_data(r['did'], r['value'])
                    elif r['code'] == 9999:
                        persistent_notification.async_create(
                            self._hass,
                            f"您添加的设备: **{self._name}** ，\n"
                            f"在获取个状态时，\n"
                            f"返回 **-9999** 错误。\n"
                            "请考虑通过云端接入此设备来解决此问题。",
                            "设备不支持本地接入")
                    else:
                        statedict[r['did']] = None
                        if r['code'] == -4004 and not self._err4004_notified:
                            props_with_4004.append(r['did'])
                        else:
                            _LOGGER.info("Error getting %s 's property '%s' (code: %s)", self._name, r['did'], r['code'])
                if not self._err4004_notified:
                    if len(props_with_4004) == len(response):
                        self._assumed_state = True
                        self._skip_update = True
                        if not self._err4004_notified:
                            persistent_notification.async_create(
                                self._hass,
                                f"您添加的设备: **{self._name}** ，\n"
                                f"在获取 {len(response)} 个状态时，\n"
                                f"全部返回 **-4004** 错误。\n"
                                "请考虑通过云端接入此设备来解决此问题。",
                                "设备可能不受支持")
                            self._err4004_notified = True
                            del props_with_4004
                    elif len(props_with_4004) != 0:
                        _LOGGER.warn(f"Device {self._name} returns unknown error for property {props_with_4004}. If you encounter issues about this device, try enabling Cloud Access.")
                        self._err4004_notified = True
                        del props_with_4004
            else:
                _LOGGER.info(f"{self._name} is updating from cloud.")
                a = await self._cloud_instance.get_props(self._body_for_update_cloud, self._cloud.get("server_location"))
                dict1 = {}
                statedict = {}
                if a:
                    if a['code'] != 0:
                        _LOGGER.error(f"Error updating {self._name} from cloud: {a}")
                        return None
                    if all(item['code'] == -704042011 for item in a['result']):
                        if self._available == True or self._available == None:
                            if OFFLINE_NOTIFY:
                                persistent_notification.async_create(
                                    self._hass,
                                    f"请注意，云端接入设备 **{self._name}** 已离线。",
                                    "Xiaomi MIoT - 设备离线")
                            else:
                                _LOGGER.warn(f"请注意，云端接入设备 **{self._name}** 已离线。")
                        self._available = False
                    else:
                        self._available = True
                    for item in a['result']:
                        dict1.setdefault(item['siid'], {})
                        dict1[item['siid']][item['piid']] = item.get('value')
                    for key, value in self._mapping.items():
                        if 'aiid' in value:
                            continue
                        statedict[key] = pre_process_data(key, dict1[value['siid']][value['piid']])
                else:
                    pass
            self._fail_count = 0
            self._state_attrs.update(statedict)
            self._handle_platform_specific_attrs()
            self.publish_updates()
        except DeviceException as ex:
            if self._fail_count < 3:
                self._fail_count += 1
                _LOGGER.info("Got exception while fetching %s 's state: %s. Count %d", self._name, ex, self._fail_count)
            else:
                self._available = False
                _LOGGER.error("Got exception while fetching %s 's state: %s", self._name, ex)
async def async_update ( self ) : def pre_process_data ( key , value ) : try : if key in self . _ctrl_params_new : if f := self . _ctrl_params_new [ key ] . get ( 'value_ratio' ) : return round ( value * f , 3 ) if 'value_list' in self . _ctrl_params_new [ key ] : if s := self . get_key_by_value ( self . _ctrl_params_new [ key ] [ 'value_list' ] , value ) : return s elif ( ( 'status' in key and 'switch_status' not in key ) or 'state' in key or 'fault' in key ) and type ( value ) == int : if s := self . get_key_by_value ( self . _ctrl_params_new [ key ] , value ) : return s return value except KeyError : return None if self . _update_instant is False or self . _skip_update : self . _skip_update = False self . _delay_update = 0 return if self . _delay_update != 0 : await asyncio . sleep ( self . _delay_update ) self . _delay_update = 0 try : if not self . _cloud : response = await self . hass . async_add_job ( partial ( self . _device . get_properties_for_mapping , max_properties = self . _max_properties ) ) self . _available = True statedict = { } props_with_4004 = [ ] for r in response : if r [ 'code' ] == 0 : statedict [ r [ 'did' ] ] = pre_process_data ( r [ 'did' ] , r [ 'value' ] ) elif r [ 'code' ] == 9999 : persistent_notification . async_create ( self . _hass , f"您添加的设备: **{self._name}** ，\n" f"在获取个状态时，\n" f"返回 **-9999** 错误。\n" "请考虑通过云端接入此设备来解决此问题。", "设备不支持本地接入") else : statedict [ r [ 'did' ] ] = None if r [ 'code' ] == - 4004 and not self . _err4004_notified : props_with_4004 . append ( r [ 'did' ] ) else : _LOGGER . info ( "Error getting %s 's property '%s' (code: %s)" , self . _name , r [ 'did' ] , r [ 'code' ] ) if not self . _err4004_notified : if len ( props_with_4004 ) == len ( response ) : self . _assumed_state = True self . _skip_update = True if not self . _err4004_notified : persistent_notification . async_create ( self . _hass , f"您添加的设备: **{self._name}** ，\n" f"在获取 {len(response)} 个状态时，\n" f"全部返回 **-4004** 错误。\n" "请考虑通过云端接入此设备来解决此问题。", "设备可能不受支持") self . _err4004_notified = True del props_with_4004 elif len ( props_with_4004 ) != 0 : _LOGGER . warn ( f"Device {self._name} returns unknown error for property {props_with_4004}. If you encounter issues about this device, try enabling Cloud Access." ) self . _err4004_notified = True del props_with_4004 else : _LOGGER . info ( f"{self._name} is updating from cloud." ) a = await self . _cloud_instance . get_props ( self . _body_for_update_cloud , self . _cloud . get ( "server_location" ) ) dict1 = { } statedict = { } if a : if a [ 'code' ] != 0 : _LOGGER . error ( f"Error updating {self._name} from cloud: {a}" ) return None if all ( item [ 'code' ] == - 704042011 for item in a [ 'result' ] ) : if self . _available == True or self . _available == None : if OFFLINE_NOTIFY : persistent_notification . async_create ( self . _hass , f"请注意，云端接入设备 **{self._name}** 已离线。", "Xiaomi MIoT - 设备离线") else : _LOGGER . warn ( f"请注意，云端接入设备 **{self._name}** 已离线。") self . _available = False else : self . _available = True for item in a [ 'result' ] : dict1 . setdefault ( item [ 'siid' ] , { } ) dict1 [ item [ 'siid' ] ] [ item [ 'piid' ] ] = item . get ( 'value' ) for key , value in self . _mapping . items ( ) : if 'aiid' in value : continue statedict [ key ] = pre_process_data ( key , dict1 [ value [ 'siid' ] ] [ value [ 'piid' ] ] ) else : pass self . _fail_count = 0 self . _state_attrs . update ( statedict ) self . _handle_platform_specific_attrs ( ) self . publish_updates ( ) except DeviceException as ex : if self . _fail_count < 3 : self . _fail_count += 1 _LOGGER . info ( "Got exception while fetching %s 's state: %s. Count %d" , self . _name , ex , self . _fail_count ) else : self . _available = False _LOGGER . error ( "Got exception while fetching %s 's state: %s" , self . _name , ex )
Fetch state from the device.
Fetch state from the device .
"""Fetch state from the device.""" # On state change some devices doesn't provide the new state immediately. # _LOGGER.warn("设备不支持状态反馈") # TODO handle -704030013 (Unreadable property)
self