forked from al-one/hass-xiaomi-miot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice.py
More file actions
1489 lines (1336 loc) · 54.2 KB
/
device.py
File metadata and controls
1489 lines (1336 loc) · 54.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import copy
import re
from typing import TYPE_CHECKING, Optional, Callable
from datetime import timedelta
from functools import cached_property
from homeassistant.core import HomeAssistant
from homeassistant.const import CONF_HOST, CONF_TOKEN, CONF_MODEL, CONF_USERNAME, EntityCategory
from homeassistant.util import dt
from homeassistant.components import persistent_notification
from homeassistant.helpers.event import async_call_later, async_track_time_interval
import homeassistant.helpers.device_registry as dr
from .const import (
DOMAIN,
DEVICE_CUSTOMIZES,
GLOBAL_CONVERTERS,
MIOT_LOCAL_MODELS,
DEFAULT_NAME,
CONF_CONN_MODE,
DEFAULT_CONN_MODE,
)
from .hass_entry import HassEntry
from .hass_entity import XEntity, BasicEntity, convert_unique_id
from .converters import (
BaseConv, InfoConv, MiotPropConv,
MiotPropValueConv, MiotActionConv,
AttrConv, MiotTargetPositionConv,
)
from .coordinator import DataCoordinator
from .miot_spec import MiotSpec, MiotProperty, MiotResults, MiotResult
from .miio2miot import Miio2MiotHelper
from .mini_miio import AsyncMiIO
from .xiaomi_cloud import MiotCloud, MiCloudException
from .utils import (
CustomConfigHelper,
get_customize_via_model,
get_value,
DeviceException,
is_offline_exception,
update_attrs_with_suffix,
)
from .templates import template
if TYPE_CHECKING:
from . import BasicEntity
InfoConverter = InfoConv().with_option(
icon='mdi:information',
device_class='update',
entity_category=EntityCategory.DIAGNOSTIC,
)
class DeviceInfo:
def __init__(self, data: dict):
self.data = data
def get(self, key, default=None):
return self.data.get(key, default)
@property
def did(self):
return self.data.get('did', '')
@cached_property
def unique_id(self):
if mac := self.mac:
return dr.format_mac(mac).lower()
return self.did
@property
def name(self):
return self.data.get('name') or DEFAULT_NAME
@cached_property
def model(self):
return self.miio_info.model or ''
@cached_property
def mac(self):
return self.data.get('mac') or self.miio_info.mac_address or ''
@property
def host(self):
return self.data.get('localip') or self.data.get(CONF_HOST) or ''
@property
def token(self):
primary_token = self.data.get(CONF_TOKEN) or ''
# For Yi cameras and similar devices, the top-level token may not be valid hex
# Check if token is valid hexadecimal, otherwise try extra.token
if primary_token:
try:
bytes.fromhex(primary_token)
return primary_token
except ValueError:
# Primary token is not valid hex, try extra.token
pass
extra_token = self.data.get('extra', {}).get('token', '')
if extra_token:
try:
bytes.fromhex(extra_token)
return extra_token
except ValueError:
# Extra token is also not valid hex, fall through to miio_info.token
pass
return self.miio_info.token
@cached_property
def pid(self):
pid = self.data.get('pid')
if pid is not None:
try:
pid = int(pid)
except Exception:
pid = None
return pid
@property
def urn(self):
return self.data.get('urn') or self.data.get('spec_type') or ''
@property
def parent_id(self):
return self.data.get('parent_id', '')
@property
def extra(self):
return self.data.get('extra') or {}
@cached_property
def firmware_version(self):
return self.miio_info.firmware_version
@cached_property
def hardware_version(self):
return self.miio_info.hardware_version
@cached_property
def home_name(self):
return self.data.get('home_name', '')
@cached_property
def room_name(self):
return self.data.get('room_name', '')
@cached_property
def home_room(self):
return f'{self.home_name} {self.room_name}'.strip()
@cached_property
def miio_info(self):
info = self.data
data = info.get('miio_info') or {
'ap': {'ssid': info.get('ssid'), 'bssid': info.get('bssid'), 'rssi': info.get('rssi')},
'netif': {'localIp': self.host, 'gw': '', 'mask': ''},
'fw_ver': self.extra.get('fw_version', ''),
'hw_ver': info.get('hw_ver', ''),
'mac': info.get('mac', ''),
'model': info.get(CONF_MODEL, ''),
'token': info.get(CONF_TOKEN, ''),
}
return MiioInfo(data)
class Device(CustomConfigHelper):
spec: Optional['MiotSpec'] = None
cloud: Optional['MiotCloud'] = None
local: Optional['MiotDevice'] = None
miio2miot: Optional['Miio2MiotHelper'] = None
available = True
miot_entity = None
miot_results = None
_local_fails = 0
_local_state = None
_cloud_fails = 0
_cloud_state = None
_proxy_device = None
_miot_mapping = None
_exclude_miot_services = None
_exclude_miot_properties = None
_unreadable_properties = None
_unsub_purge = None
def __init__(self, info: DeviceInfo, entry: HassEntry):
self.data = {}
self.info = info
self.hass = entry.hass
self.entry = entry
self.cloud = entry.cloud
self.props: dict = {}
self.entities: dict[str, 'BasicEntity'] = {}
self.listeners: list[Callable] = []
self.converters: list[BaseConv] = []
self.coordinators: list[DataCoordinator] = []
self.main_coordinators: list[DataCoordinator] = []
self.log = logging.getLogger(f'{__name__}.{self.model}')
async def async_init(self):
if not self.cloud_only:
self.local = MiotDevice.from_device(self)
spec = await self.get_spec()
if spec and self.local and not self.cloud_only:
self.miio2miot = Miio2MiotHelper.from_model(self.hass, self.model, spec)
mps = self.custom_config_list('miio_properties')
if mps and self.miio2miot:
self.miio2miot.extend_miio_props(mps)
if self.info.pid not in [18]:
""" not proxy device """
elif parent := await self.get_parent_device():
if parent.use_local:
self.local = parent.local
self._proxy_device = parent if self.local else None
self.log.info('Proxy local device: %s', self.local)
self._exclude_miot_services = self.custom_config_list('exclude_miot_services', [])
self._exclude_miot_properties = self.custom_config_list('exclude_miot_properties', [])
self._unreadable_properties = self.custom_config_bool('unreadable_properties')
if not self.coordinators:
await self.init_coordinators()
if not self._unsub_purge:
self._unsub_purge = async_track_time_interval(self.hass, self.async_purge_entities, timedelta(hours=12))
async def async_unload(self):
for coo in self.coordinators:
await coo.async_shutdown()
self.spec = None
self.hass.data[DOMAIN].setdefault('miot_specs', {}).pop(self.model, None)
if self._unsub_purge:
self._unsub_purge()
self._unsub_purge = None
@cached_property
def did(self):
return self.info.did
@property
def name(self):
return self.info.name
@cached_property
def model(self):
return self.info.model
@cached_property
def name_model(self):
return f'{self.name}({self.model})'
@cached_property
def unique_id(self):
if self.entry.get_config(CONF_TOKEN):
return self.info.unique_id
return f'{self.info.unique_id}-{self.entry.id}'
@cached_property
def app_link(self):
uid = self.cloud.user_id if self.cloud else ''
if not self.did:
return ''
return f'mihome://device?uid={uid}&did={self.did}'
@property
def conn_mode(self):
if not self.entry.get_config(CONF_USERNAME):
return 'local'
return self.entry.get_config(CONF_CONN_MODE) or DEFAULT_CONN_MODE
@property
def local_only(self):
return self.conn_mode == 'local'
@property
def cloud_only(self):
return self.conn_mode == 'cloud'
@property
def sw_version(self):
swv = self.info.firmware_version
if self.info.hardware_version:
swv = f'{swv}@{self.info.hardware_version}'
updater = self.data.get('updater')
emoji = {
'local': '🛜',
'cloud': '☁️',
}.get(updater)
if emoji:
swv = f'{swv} {emoji}'
elif updater:
swv = f'{swv} ({updater})'
return swv
@property
def identifiers(self):
return {(DOMAIN, self.unique_id)}
@property
def hass_device_info(self):
via_device = None
if self._proxy_device:
via_device = next(iter(self._proxy_device.identifiers))
return {
'identifiers': self.identifiers,
'name': self.name,
'model': self.model,
'manufacturer': (self.model or 'Xiaomi').split('.', 1)[0],
'sw_version': self.sw_version,
'suggested_area': self.info.room_name,
'via_device': via_device,
'configuration_url': f'https://home.miot-spec.com/s/{self.model}',
}
@property
def customizes(self):
return get_customize_via_model(self.model)
def custom_config(self, key=None, default=None):
cfg = self.customizes
return cfg if key is None else cfg.get(key, default)
@cached_property
def extend_miot_specs(self):
if self.cloud_only:
# only for local mode
return None
ext = self.custom_config('extend_miot_specs')
if ext and isinstance(ext, str):
ext = DEVICE_CUSTOMIZES.get(ext, {}).get('extend_miot_specs')
else:
ext = self.custom_config_list('extend_miot_specs')
if ext and isinstance(ext, list):
return ext
return None
async def get_spec(self) -> Optional[MiotSpec]:
if self.spec:
return self.spec
dat = self.hass.data[DOMAIN].setdefault('miot_specs', {})
obj = dat.get(self.model)
if not obj:
trans_options = self.custom_config_bool('trans_options', self.entry.get_config('trans_options'))
urn = await self.get_urn()
obj = await MiotSpec.async_from_type(self.hass, urn, trans_options=trans_options)
dat[self.model] = obj
if obj:
self.spec = copy.copy(obj)
if not self.cloud_only:
if ext := self.extend_miot_specs:
self.spec.extend_specs(services=ext)
self.init_converters()
return self.spec
async def get_urn(self):
urn = self.custom_config('miot_type')
if not urn:
urn = self.info.urn
if not urn:
urn = await MiotSpec.async_get_model_type(self.hass, self.model)
self.info.data['urn'] = urn
return urn
@property
def hass_device(self):
dev_reg = dr.async_get(self.hass)
return dev_reg.async_get_device(self.identifiers)
@property
def hass_device_disabled(self):
if dev := self.hass_device:
return dev.disabled_by
return None
def add_converter(self, conv: BaseConv, force=False):
if conv in self.converters:
return
if not force and self.find_converter(conv.full_name):
self.log.info('Converter for %s already exists. Ignored.', conv.full_name)
return
self.converters.append(conv)
def add_converter_by_property(self, prop: MiotProperty, domain=None, option=None, cls=None, **kwargs):
if not cls:
cls = MiotPropConv
conv = cls(prop.full_name, domain=domain, prop=prop, **kwargs)
if option:
conv.with_option(**option)
self.add_converter(conv)
return conv
def find_converter(self, full_name):
for c in self.converters:
if c.full_name == full_name:
return c
return None
def init_converters(self):
self.add_converter(InfoConverter)
self.dispatch_info()
if not self.spec:
return
appends = self.custom_config_list('append_converters') or []
for cfg in [*GLOBAL_CONVERTERS, *appends]:
cls = cfg.get('class')
kwargs = cfg.get('kwargs', {})
if services := cfg.get('services'):
for service in self.spec.get_services(*services, excludes=self._exclude_miot_services):
conv = None
if cls and hasattr(cls, 'service'):
conv = cls(service=service, **kwargs)
if not getattr(conv, 'prop', None) and getattr(conv, 'main_props', None):
self.log.info('Converter has no main props: %s', conv)
conv = None
elif exists := self.find_converter(conv.full_name):
conv = exists # for append_converters
else:
self.add_converter(conv, True)
self.log.debug('Add converter: %s', conv)
for pc in cfg.get('converters') or []:
if not (names := pc.get('props')):
continue
only_format = pc.get('only_format')
exclude_format = pc.get('exclude_format')
for p in names:
if '.' in p or pc.get('all_services'):
props = self.spec.get_properties(p, only_format=only_format, exclude_format=exclude_format)
else:
props = service.get_properties(p, only_format=only_format, exclude_format=exclude_format)
if not props:
continue
for prop in props:
attr = pc.get('attr', prop.full_name)
c = pc.get('class', MiotPropConv)
d = pc.get('domain', None)
ac = c(attr, domain=d, prop=prop, desc=pc.get('desc'))
self.add_converter(ac)
self.log.debug('Add converter: %s', [ac, pc])
if conv and ac.full_name not in conv.attrs:
conv.attrs.append(ac.full_name)
for d in [
'button', 'sensor', 'binary_sensor', 'switch', 'number', 'select', 'text',
'number_select', 'scanner', 'target_position',
]:
pls = self.custom_config_list(f'{d}_properties') or []
if not pls:
continue
for prop in self.spec.get_properties(*pls):
if d == 'number_select':
if prop.value_range:
d = 'number'
elif prop.value_list:
d = 'select'
else:
self.log.warning(f'Unsupported customize entity: %s for %s', d, prop.full_name)
continue
platform = {
'scanner': 'device_tracker',
'tracker': 'device_tracker',
'target_position': 'cover',
}.get(d) or d
if platform == 'button':
if prop.value_list:
for pv in prop.value_list:
val = pv.get('value')
des = pv.get('description') or val
attr = f'{prop.full_name}-{val}'
conv = MiotPropValueConv(attr, platform, prop=prop, value=val, description=des)
self.add_converter(conv)
elif prop.is_bool:
conv = MiotPropValueConv(prop.full_name, platform, prop=prop, value=True)
self.add_converter(conv)
elif platform == 'number' and not prop.value_range:
self.log.warning(f'Unsupported customize entity: %s for %s', platform, prop.full_name)
continue
elif d == 'target_position' and not prop.value_range:
self.log.warning(f'Unsupported customize entity: %s for %s', d, prop.full_name)
continue
else:
conv_cls = {
'target_position': MiotTargetPositionConv,
}.get(d) or MiotPropConv
conv = conv_cls(prop.full_name, platform, prop=prop)
conv.with_option(
entity_type=None if platform == d else d,
)
self.add_converter(conv)
for d in ['button', 'text', 'select']:
als = self.custom_config_list(f'{d}_actions') or []
if not als:
continue
for srv in self.spec.services.values():
for action in srv.get_actions(*als):
self.add_converter(MiotActionConv(action.full_name, d, action=action))
for d in ['sensor', 'binary_sensor']:
for attr in self.custom_config_list(f'{d}_attributes') or []:
self.add_converter(AttrConv(attr, d))
async def init_coordinators(self):
if dby := self.hass_device_disabled:
self.log.debug('Device disabled by: %s', dby)
return
interval = 60
interval = self.entry.get_config('scan_interval') or interval
interval = self.custom_config_integer('interval_seconds') or interval
lst = await self.init_miot_coordinators(interval)
if self.cloud_statistics_commands:
lst.append(
DataCoordinator(self, self.update_cloud_statistics, update_interval=timedelta(seconds=interval*10)),
)
if self.miio_cloud_records:
seconds = self.custom_config_integer('miio_cloud_records_interval') or interval*10
lst.append(
DataCoordinator(self, self.update_miio_cloud_records, update_interval=timedelta(seconds=seconds)),
)
if self.miio_cloud_props:
lst.append(
DataCoordinator(self, self.update_miio_cloud_props, update_interval=timedelta(seconds=interval*2)),
)
if self.custom_miio_properties:
lst.append(
DataCoordinator(self, self.update_miio_props, update_interval=timedelta(seconds=interval)),
)
if self.custom_miio_commands:
lst.append(
DataCoordinator(self, self.update_miio_commands, update_interval=timedelta(seconds=interval)),
)
self.coordinators.extend(lst)
idx = 0
for coo in lst:
idx += 1
await coo.async_setup(index=idx)
async def init_miot_coordinators(self, interval=60):
lst = []
if not self.spec:
return lst
all_mapping = {**self.miot_mapping()}
chunks = self.custom_config_list('chunk_coordinators') or []
if self.miio2miot:
chunks = []
def update_factory(mapping, notify=False, chunk_services=None):
async def _update():
result = await self.update_miot_status(mapping, chunk_services=chunk_services)
if notify:
for entity in self.entities.values():
if isinstance(entity, XEntity):
continue
if not isinstance(entity, BasicEntity):
continue
if not hasattr(entity, 'async_update_from_device'):
continue
await entity.async_update_from_device()
return result
return _update
index = 0
for chunk in chunks:
index += 1
inter = chunk.get('interval', interval)
props = chunk.get('props')
if not props:
continue
if isinstance(props, str):
props = props.split(',')
mapping = self.spec.services_mapping(
excludes=self._exclude_miot_services,
include_properties=props,
exclude_properties=self._exclude_miot_properties,
unreadable_properties=self._unreadable_properties,
) or {}
for k in mapping.keys():
all_mapping.pop(k, None)
notify = chunk.get('notify')
chunk_services = chunk.get('chunk_services', 0)
coo = DataCoordinator(
self, update_factory(mapping, notify, chunk_services=chunk_services),
name=f'chunk_{index}',
update_interval=timedelta(seconds=inter),
)
lst.append(coo)
if notify or not self.main_coordinators:
self.main_coordinators.append(coo)
if all_mapping:
chunk_services = self.custom_config_integer('chunk_services')
coo = DataCoordinator(
self, update_factory(all_mapping, True, chunk_services=chunk_services),
name='miot_status',
update_interval=timedelta(seconds=interval),
)
lst.append(coo)
if not self.main_coordinators:
self.main_coordinators.append(coo)
self.log.debug('Miot coordinators: %s', [*chunks, all_mapping])
return lst
async def update_status(self):
for coo in self.coordinators:
await coo.async_request_refresh()
async def update_main_status(self):
for coo in self.main_coordinators:
await coo.async_request_refresh()
async def update_all_status(self, _=None):
all = []
for coo in self.coordinators:
await coo.async_request_refresh()
all.append(coo.name)
self.log.info('Update all coordinators: %s', all)
def add_entities(self, domain):
for conv in self.converters:
if conv.domain != domain:
continue
unique = f'{domain}.{convert_unique_id(conv)}'
entity = self.entities.get(unique)
if entity:
continue
cls = XEntity.CLS.get(domain)
if entity_type := conv.option.get('entity_type'):
cls = XEntity.CLS.get(entity_type) or cls
adder = self.entry.adders.get(domain)
if not (cls and adder):
self.log.warning('Entity class/adder not found: %s', [domain, conv.attr, cls, adder])
continue
entity = cls(self, conv)
self.add_entity(entity, unique)
adder([entity], update_before_add=False)
self.log.info('New entity: %s', entity)
if domain == 'button':
self.dispatch_info()
async_call_later(self.hass, 5, self.update_all_status)
def add_entity(self, entity: 'BasicEntity', unique=None):
if unique is None:
unique = entity.unique_id
if unique in self.entities:
return None
self.entities[unique] = entity
return entity
def add_listener(self, handler: Callable):
if handler not in self.listeners:
self.listeners.append(handler)
def remove_listener(self, handler: Callable):
if handler in self.listeners:
self.listeners.remove(handler)
def dispatch(self, data: dict, only_info=False, log=True):
if log:
self.log.info('Device updated: %s', {**data, 'only_info': only_info})
for handler in self.listeners:
handler(data, only_info=only_info)
def dispatch_info(self):
info = {}
InfoConverter.decode(self, info, None)
self.dispatch(info, only_info=True, log=False)
def decode(self, data: dict | list) -> dict:
"""Decode data from device."""
payload = {}
if not isinstance(data, list):
data = [data]
for value in data:
self.decode_one(payload, value)
return payload
def decode_one(self, payload: dict, value: dict):
if not isinstance(value, dict):
self.log.warning('Value is not dict: %s', value)
return
if value.get('code', 0):
return
siid = value.get('siid')
piid = value.get('piid')
if siid and piid:
mi = MiotSpec.unique_prop(siid, piid=piid)
for conv in self.converters:
if conv.mi == mi:
conv.decode(self, payload, value.get('value'))
def decode_attrs(self, value: dict):
if not isinstance(value, dict):
self.log.warning('Value is not dict: %s', value)
return
payload = {}
for conv in self.converters:
val = get_value(value, conv.attr, None, ':')
if val is not None:
conv.decode(self, payload, val)
return payload
def encode(self, value: dict) -> dict:
"""Encode data from hass to device."""
payload = {}
for k, v in value.items():
for conv in self.converters:
if conv.full_name == k:
conv.encode(self, payload, v)
return payload
async def async_write(self, payload: dict):
"""Send command to device."""
data = self.encode(payload)
self.log.info('Device write data: %s', [payload, data])
result = None
method = data.get('method')
success = None
try:
if method == 'update_status':
result = await self.update_main_status()
if method == 'set_properties':
params = data.get('params', [])
result = await self.async_set_properties(params)
success = True if result else False
if err := MiotResults(result).has_error:
success = False
self.log.warning('Device write error: %s', [payload, data, err])
if method == 'action':
param = data.get('param', {})
siid = param['siid']
aiid = param['aiid']
ins = param.get('in') or []
result = await self.async_call_action(siid, aiid, ins)
success = result.is_success
except (DeviceException, MiCloudException) as exc:
success = False
self.log.exception('Device write failed: %s', [exc, payload, data])
self.log.info('Device write result: %s', [payload, result])
if success:
self.dispatch(payload)
return result
@property
def use_local(self):
if self.cloud_only:
return False
if not self.local:
return False
if self.local_only:
return True
if self.miio2miot:
return True
if self.custom_config_bool('miot_local'):
return True
if self.model in MIOT_LOCAL_MODELS:
return True
if self._proxy_device:
return True
return False
@property
def use_cloud(self):
if self.local_only:
return False
if not self.cloud:
return False
if self.cloud_only:
return True
if self.use_local:
return False
if self.custom_config_bool('miot_cloud'):
return True
return True
@property
def auto_cloud(self):
if not self.cloud:
return False
return self.custom_config_bool('auto_cloud')
async def get_parent_device(self):
if not (pid := self.info.parent_id):
return None
info = await self.entry.get_cloud_device(pid)
if not info:
return None
return await self.entry.new_device(info)
def miot_mapping(self):
if self._miot_mapping:
return self._miot_mapping
if not self.spec:
return None
if dic := self.custom_config_json('miot_mapping'):
self.spec.set_custom_mapping(dic)
self._miot_mapping = dic
return dic
mapping = self.spec.services_mapping(
excludes=self._exclude_miot_services,
exclude_properties=self._exclude_miot_properties,
unreadable_properties=self._unreadable_properties,
) or {}
self._miot_mapping = mapping
return mapping
async def update_miot_status(
self,
mapping=None,
use_local=None,
use_cloud=None,
auto_cloud=None,
check_lan=None,
max_properties=None,
chunk_services=None,
) -> MiotResults:
results = []
self.miot_results = MiotResults()
if use_local is None:
use_local = False if use_cloud else self.use_local
if use_cloud is None:
use_cloud = False if use_local else self.use_cloud
if auto_cloud is None:
auto_cloud = self.auto_cloud
if check_lan is None:
check_lan = self.custom_config_bool('check_lan')
if mapping is None:
mapping = self.miot_mapping()
if not mapping:
use_local = False
use_cloud = False
self.log.debug('Update miot status: %s', {
'use_local': [use_local, self.use_local, self.local],
'use_cloud': [use_cloud, self.use_cloud, self.auto_cloud],
'mapping': mapping,
})
if use_local:
try:
if self.miio2miot:
results = await self.miio2miot.async_get_miot_props(self.local, mapping)
if attrs := self.miio2miot.entity_attrs():
self.props.update(attrs)
self.dispatch(self.decode_attrs(attrs))
else:
if not max_properties:
max_properties = self.custom_config_integer('chunk_properties')
if not max_properties:
max_properties = self.local.get_max_properties(mapping)
maps = []
if chunk_services:
for service in self.spec.get_services(excludes=self._exclude_miot_services):
mapp = service.mapping(
excludes=self._exclude_miot_properties,
unreadable_properties=self._unreadable_properties,
) or {}
if mapp:
maps.append(mapp)
else:
maps.append(mapping)
for mapp in maps:
res = await self.local.async_get_properties_for_mapping(
max_properties=max_properties,
did=self.did,
mapping=mapp,
)
results.extend(res)
self.available = True
self._local_fails = 0
self._local_state = True
self.miot_results.updater = 'local'
self.miot_results.set_results(results, mapping)
except (DeviceException, OSError) as exc:
self._local_fails += 1
local_state = self._local_fails < 3
log = self.log.error
if auto_cloud:
use_cloud = self.cloud
log = self.log.warning
else:
self.miot_results.errors = exc
self.available = local_state
if self._local_state is False:
log = self.log.info
self._local_state = local_state
props_count = len(mapping)
log(
'%s: %s, mapping: %s, max_properties: %s/%s',
self.name, exc, mapping, max_properties or props_count, props_count
)
if use_cloud:
try:
self.miot_results.updater = 'cloud'
results = await self.cloud.async_get_properties_for_mapping(self.did, mapping)
if results is None:
raise MiCloudException('Cloud API returned None response, possible timeout or empty data')
if check_lan and self.local:
await self.local.async_info()
self.available = True
self._cloud_fails = 0
self._cloud_state = True
self.miot_results.set_results(results, mapping)
except MiCloudException as exc:
self._cloud_fails += 1
self._cloud_state = self._cloud_fails <= 3
self.miot_results.errors = exc
if not self._cloud_state:
self.available = False
self.log.error('Cloud request failed %s times, marking unavailable. %s', self._cloud_fails, exc)
else:
self.log.info('Cloud request failed (%sth time), will retry. %s', self._cloud_fails, exc)
if results and self.miot_results.is_empty:
self.log.warning(
'Got invalid miot result while fetching the state: %s, mapping: %s',
results, mapping,
)
if self.miot_results.updater != self.data.get('updater'):
dev_reg = dr.async_get(self.hass)
if dev := dev_reg.async_get_device(self.identifiers):
self.data['updater'] = self.miot_results.updater
dev_reg.async_update_device(dev.id, sw_version=self.sw_version)
self.log.info('State updater: %s', self.sw_version)
if results:
self.miot_results.to_attributes(self.props)
self.data['updated'] = dt.now()
self.dispatch(self.decode(results))
self.dispatch_info()
await self.offline_notify()
return self.miot_results
async def offline_notify(self):
result = self.miot_results
is_offline = not result.is_valid and result.errors and is_offline_exception(result.errors)
offline_devices = self.hass.data[DOMAIN].setdefault('offline_devices', {})
notification_id = f'{DOMAIN}-devices-offline'
if not is_offline:
self.data.pop('offline_times', None)
if offline_devices.pop(self.info.unique_id, None) and not offline_devices:
persistent_notification.async_dismiss(self.hass, notification_id)
return
offline_times = self.data.setdefault('offline_times', 0)
if not self.custom_config_bool('ignore_offline'):
offline_times += 1
odd = offline_devices.get(self.info.unique_id) or {}
if odd:
odd.update({
'occurrences': offline_times,
})
elif offline_times >= 5:
odd = {
'device': self,
'occurrences': offline_times,
}
offline_devices[self.info.unique_id] = odd
tip = f'Some devices cannot be connected in the LAN, please check their IP ' \
f'and make sure they are in the same subnet as the HA.\n\n' \
f'一些设备无法通过局域网连接,请检查它们的IP,并确保它们和HA在同一子网。\n'
for d in offline_devices.values():
device = d.get('device')
if not device:
continue
tip += f'\n - {device.name_model}: {device.info.host}'
tip += '\n\n'
url = 'https://github.com/al-one/hass-xiaomi-miot/search' \
'?type=issues&q=%22Unable+to+discover+the+device%22'
tip += f'[Known issues]({url})'
url = 'https://github.com/al-one/hass-xiaomi-miot/issues/500#offline'
tip += f' | [了解更多]({url})'
persistent_notification.async_create(
self.hass,
tip,
'Devices offline',
notification_id,
)
self.data['offline_times'] = offline_times