forked from XiaoMi/ha_xiaomi_home
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiot_client.py
More file actions
2040 lines (1919 loc) · 84.3 KB
/
Copy pathmiot_client.py
File metadata and controls
2040 lines (1919 loc) · 84.3 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
# -*- coding: utf-8 -*-
"""
Copyright (C) 2024 Xiaomi Corporation.
The ownership and intellectual property rights of Xiaomi Home Assistant
Integration and related Xiaomi cloud service API interface provided under this
license, including source code and object code (collectively, "Licensed Work"),
are owned by Xiaomi. Subject to the terms and conditions of this License, Xiaomi
hereby grants you a personal, limited, non-exclusive, non-transferable,
non-sublicensable, and royalty-free license to reproduce, use, modify, and
distribute the Licensed Work only for your use of Home Assistant for
non-commercial purposes. For the avoidance of doubt, Xiaomi does not authorize
you to use the Licensed Work for any other purpose, including but not limited
to use Licensed Work to develop applications (APP), Web services, and other
forms of software.
You may reproduce and distribute copies of the Licensed Work, with or without
modifications, whether in source or object form, provided that you must give
any other recipients of the Licensed Work a copy of this License and retain all
copyright and disclaimers.
Xiaomi provides the Licensed Work on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied, including, without
limitation, any warranties, undertakes, or conditions of TITLE, NO ERROR OR
OMISSION, CONTINUITY, RELIABILITY, NON-INFRINGEMENT, MERCHANTABILITY, or
FITNESS FOR A PARTICULAR PURPOSE. In any event, you are solely responsible
for any direct, indirect, special, incidental, or consequential damages or
losses arising from the use or inability to use the Licensed Work.
Xiaomi reserves all rights not expressly granted to you in this License.
Except for the rights expressly granted by Xiaomi under this License, Xiaomi
does not authorize you in any form to use the trademarks, copyrights, or other
forms of intellectual property rights of Xiaomi and its affiliates, including,
without limitation, without obtaining other written permission from Xiaomi, you
shall not use "Xiaomi", "Mijia" and other words related to Xiaomi or words that
may make the public associate with Xiaomi in any form to publicize or promote
the software or hardware devices that use the Licensed Work.
Xiaomi has the right to immediately terminate all your authorization under this
License in the event:
1. You assert patent invalidation, litigation, or other claims against patents
or other intellectual property rights of Xiaomi or its affiliates; or,
2. You make, have made, manufacture, sell, or offer to sell products that knock
off Xiaomi or its affiliates' products.
MIoT client instance.
"""
from copy import deepcopy
from typing import Any, Callable, Optional, final
import asyncio
import json
import logging
import time
import traceback
from dataclasses import dataclass
from enum import Enum, auto
from homeassistant.core import HomeAssistant
from homeassistant.components import zeroconf
# pylint: disable=relative-beyond-top-level
from .common import MIoTMatcher, slugify_did
from .const import (
DEFAULT_CTRL_MODE, DEFAULT_INTEGRATION_LANGUAGE, DEFAULT_NICK_NAME, DOMAIN,
MIHOME_CERT_EXPIRE_MARGIN, NETWORK_REFRESH_INTERVAL,
OAUTH2_CLIENT_ID, SUPPORT_CENTRAL_GATEWAY_CTRL,
DEFAULT_COVER_DEAD_ZONE_WIDTH)
from .miot_cloud import MIoTHttpClient, MIoTOauthClient
from .miot_error import MIoTClientError, MIoTErrorCode
from .miot_mips import (
MIoTDeviceState, MipsCloudClient, MipsDeviceState,
MipsLocalClient)
from .miot_lan import MIoTLan
from .miot_network import MIoTNetwork
from .miot_storage import MIoTCert, MIoTStorage
from .miot_mdns import MipsService, MipsServiceState
from .miot_i18n import MIoTI18n
_LOGGER = logging.getLogger(__name__)
REFRESH_PROPS_DELAY = 0.2
REFRESH_PROPS_RETRY_DELAY = 3
REFRESH_CLOUD_DEVICES_DELAY = 6
REFRESH_CLOUD_DEVICES_RETRY_DELAY = 60
REFRESH_GATEWAY_DEVICES_DELAY = 3
@dataclass
class MIoTClientSub:
"""MIoT client subscription."""
topic: Optional[str]
handler: Callable[[dict, Any], None]
handler_ctx: Any = None
def __str__(self) -> str:
return f'{self.topic}, {id(self.handler)}, {id(self.handler_ctx)}'
class CtrlMode(Enum):
"""MIoT client control mode."""
AUTO = 0
CLOUD = auto()
@staticmethod
def load(mode: str) -> 'CtrlMode':
if mode == 'auto':
return CtrlMode.AUTO
if mode == 'cloud':
return CtrlMode.CLOUD
raise MIoTClientError(f'unknown ctrl mode, {mode}')
class MIoTClient:
"""MIoT client instance."""
# pylint: disable=unused-argument
# pylint: disable=broad-exception-caught
# pylint: disable=inconsistent-quotes
_main_loop: asyncio.AbstractEventLoop
_uid: str
_entry_id: str
_entry_data: dict
_cloud_server: str
_ctrl_mode: CtrlMode
# MIoT network monitor
_network: MIoTNetwork
# MIoT storage client
_storage: MIoTStorage
# MIoT mips service
_mips_service: MipsService
# MIoT oauth client
_oauth: MIoTOauthClient
# MIoT http client
_http: MIoTHttpClient
# MIoT i18n client
_i18n: MIoTI18n
# MIoT cert client
_cert: MIoTCert
# User config, store in the .storage/xiaomi_home
_user_config: dict
# Multi local mips client, key=group_id
_mips_local: dict[str, MipsLocalClient]
# Cloud mips client
_mips_cloud: MipsCloudClient
# MIoT lan client
_miot_lan: MIoTLan
# Device list load from local storage, {did: <info>}
_device_list_cache: dict[str, dict]
# Device list obtained from cloud, {did: <info>}
_device_list_cloud: dict[str, dict]
# Device list obtained from gateway, {did: <info>}
_device_list_gateway: dict[str, dict]
# Device list scanned from LAN, {did: <info>}
_device_list_lan: dict[str, dict]
# Device list update timestamp
_device_list_update_ts: int
_sub_source_list: dict[str, Optional[str]]
_sub_tree: MIoTMatcher
_sub_device_state: dict[str, MipsDeviceState]
_mips_local_state_changed_timers: dict[str, asyncio.TimerHandle]
_refresh_token_timer: Optional[asyncio.TimerHandle]
_refresh_cert_timer: Optional[asyncio.TimerHandle]
_refresh_cloud_devices_timer: Optional[asyncio.TimerHandle]
# Refresh prop
_refresh_props_list: dict[str, dict]
_refresh_props_timer: Optional[asyncio.TimerHandle]
_refresh_props_retry_count: int
# Persistence notify handler, params: notify_id, title, message
_persistence_notify: Callable[[str, Optional[str], Optional[str]], None]
# Device list changed notify
_show_devices_changed_notify_timer: Optional[asyncio.TimerHandle]
# Display devices changed notify
_display_devs_notify: list[str]
_display_notify_content_hash: Optional[int]
# Display binary mode
_display_binary_text: bool
_display_binary_bool: bool
def __init__(
self,
entry_id: str,
entry_data: dict,
network: MIoTNetwork,
storage: MIoTStorage,
mips_service: MipsService,
miot_lan: MIoTLan,
loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
# MUST run in a running event loop
self._main_loop = loop or asyncio.get_running_loop()
# Check params
if not isinstance(entry_data, dict):
raise MIoTClientError('invalid entry data')
if 'uid' not in entry_data or 'cloud_server' not in entry_data:
raise MIoTClientError('invalid entry data content')
if not isinstance(network, MIoTNetwork):
raise MIoTClientError('invalid miot network')
if not isinstance(storage, MIoTStorage):
raise MIoTClientError('invalid miot storage')
if not isinstance(mips_service, MipsService):
raise MIoTClientError('invalid mips service')
self._entry_id = entry_id
self._entry_data = entry_data
self._uid = entry_data['uid']
self._cloud_server = entry_data['cloud_server']
self._ctrl_mode = CtrlMode.load(
entry_data.get('ctrl_mode', DEFAULT_CTRL_MODE))
self._network = network
self._storage = storage
self._mips_service = mips_service
self._oauth = None
self._http = None
self._i18n = None
self._cert = None
self._user_config = None
self._mips_local = {}
self._mips_cloud = None
self._miot_lan = miot_lan
self._device_list_cache = {}
self._device_list_cloud = {}
self._device_list_gateway = {}
self._device_list_lan = {}
self._device_list_update_ts = 0
self._sub_source_list = {}
self._sub_tree = MIoTMatcher()
self._sub_device_state = {}
self._mips_local_state_changed_timers = {}
self._refresh_token_timer = None
self._refresh_cert_timer = None
self._refresh_cloud_devices_timer = None
# Refresh prop
self._refresh_props_list = {}
self._refresh_props_timer = None
self._refresh_props_retry_count = 0
self._persistence_notify = None
self._show_devices_changed_notify_timer = None
self._display_devs_notify = entry_data.get(
'display_devices_changed_notify', ['add', 'del', 'offline'])
self._display_notify_content_hash = None
self._display_binary_text = 'text' in entry_data.get(
'display_binary_mode', ['text'])
self._display_binary_bool = 'bool' in entry_data.get(
'display_binary_mode', ['text'])
async def init_async(self) -> None:
# Load user config and check
self._user_config = await self._storage.load_user_config_async(
uid=self._uid, cloud_server=self._cloud_server)
if not self._user_config:
# Integration need to be add again
raise MIoTClientError('load_user_config_async error')
# Hide sensitive info in printing
p_user_config: dict = deepcopy(self._user_config)
p_access_token: str = p_user_config['auth_info']['access_token']
p_refresh_token: str = p_user_config['auth_info']['refresh_token']
p_mac_key: str = p_user_config['auth_info']['mac_key']
p_user_config['auth_info'][
'access_token'] = f"{p_access_token[:5]}***{p_access_token[-5:]}"
p_user_config['auth_info'][
'refresh_token'] = f"{p_refresh_token[:5]}***{p_refresh_token[-5:]}"
p_user_config['auth_info'][
'mac_key'] = f"{p_mac_key[:5]}***{p_mac_key[-5:]}"
_LOGGER.debug('user config, %s', json.dumps(p_user_config))
# MIoT i18n client
self._i18n = MIoTI18n(
lang=self._entry_data.get(
'integration_language', DEFAULT_INTEGRATION_LANGUAGE),
loop=self._main_loop)
await self._i18n.init_async()
# Load cache device list
await self.__load_cache_device_async()
# MIoT oauth client instance
self._oauth = MIoTOauthClient(
client_id=OAUTH2_CLIENT_ID,
redirect_url=self._entry_data['oauth_redirect_url'],
cloud_server=self._cloud_server,
uuid=self._entry_data["uuid"],
loop=self._main_loop)
# MIoT http client instance
self._http = MIoTHttpClient(
cloud_server=self._cloud_server,
client_id=OAUTH2_CLIENT_ID,
access_token=self._user_config['auth_info']['access_token'],
loop=self._main_loop)
# MIoT cert client
self._cert = MIoTCert(
storage=self._storage,
uid=self._uid,
cloud_server=self.cloud_server)
# MIoT cloud mips client
self._mips_cloud = MipsCloudClient(
uuid=self._entry_data['uuid'],
cloud_server=self._cloud_server,
app_id=OAUTH2_CLIENT_ID,
token=self._user_config['auth_info']['access_token'],
loop=self._main_loop)
self._mips_cloud.enable_logger(logger=_LOGGER)
self._mips_cloud.sub_mips_state(
key=f'{self._uid}-{self._cloud_server}',
handler=self.__on_mips_cloud_state_changed)
# Subscribe network status
self._network.sub_network_status(
key=f'{self._uid}-{self._cloud_server}',
handler=self.__on_network_status_changed)
await self.__on_network_status_changed(
status=self._network.network_status)
# Create multi mips local client instance according to the
# number of hub gateways
if self._ctrl_mode == CtrlMode.AUTO:
# Central hub gateway ctrl
if self._cloud_server in SUPPORT_CENTRAL_GATEWAY_CTRL:
for home_id, info in self._entry_data['home_selected'].items():
# Create local mips service changed listener
self._mips_service.sub_service_change(
key=f'{self._uid}-{self._cloud_server}',
group_id=info['group_id'],
handler=self.__on_mips_service_state_change)
service_data = self._mips_service.get_services(
group_id=info['group_id']).get(info['group_id'], None)
if not service_data:
_LOGGER.info(
'central mips service not scanned, %s', home_id)
continue
_LOGGER.info(
'central mips service scanned, %s, %s',
home_id, service_data)
mips = MipsLocalClient(
did=self._entry_data['virtual_did'],
group_id=info['group_id'],
host=service_data['addresses'][0],
ca_file=self._cert.ca_file,
cert_file=self._cert.cert_file,
key_file=self._cert.key_file,
port=service_data['port'],
home_name=info['home_name'],
loop=self._main_loop)
self._mips_local[info['group_id']] = mips
mips.enable_logger(logger=_LOGGER)
mips.on_dev_list_changed = self.__on_gw_device_list_changed
mips.sub_mips_state(
key=info['group_id'],
handler=self.__on_mips_local_state_changed)
mips.connect()
# Lan ctrl
await self._miot_lan.vote_for_lan_ctrl_async(
key=f'{self._uid}-{self._cloud_server}', vote=True)
self._miot_lan.sub_lan_state(
key=f'{self._uid}-{self._cloud_server}',
handler=self.__on_miot_lan_state_change)
if self._miot_lan.init_done:
await self.__on_miot_lan_state_change(True)
else:
self._miot_lan.unsub_lan_state(
key=f'{self._uid}-{self._cloud_server}')
if self._miot_lan.init_done:
self._miot_lan.unsub_device_state(
key=f'{self._uid}-{self._cloud_server}')
self._miot_lan.delete_devices(
devices=list(self._device_list_cache.keys()))
await self._miot_lan.vote_for_lan_ctrl_async(
key=f'{self._uid}-{self._cloud_server}', vote=False)
_LOGGER.info('init_async, %s, %s', self._uid, self._cloud_server)
async def deinit_async(self) -> None:
self._network.unsub_network_status(
key=f'{self._uid}-{self._cloud_server}')
# Cancel refresh props
if self._refresh_props_timer:
self._refresh_props_timer.cancel()
self._refresh_props_timer = None
self._refresh_props_list.clear()
self._refresh_props_retry_count = 0
# Cloud mips
self._mips_cloud.unsub_mips_state(
key=f'{self._uid}-{self._cloud_server}')
self._mips_cloud.deinit()
# Cancel refresh cloud devices
if self._refresh_cloud_devices_timer:
self._refresh_cloud_devices_timer.cancel()
self._refresh_cloud_devices_timer = None
if self._ctrl_mode == CtrlMode.AUTO:
# Central hub gateway mips
if self._cloud_server in SUPPORT_CENTRAL_GATEWAY_CTRL:
self._mips_service.unsub_service_change(
key=f'{self._uid}-{self._cloud_server}')
for mips in self._mips_local.values():
mips.on_dev_list_changed = None
mips.unsub_mips_state(key=mips.group_id)
mips.deinit()
if self._mips_local_state_changed_timers:
for timer_item in (
self._mips_local_state_changed_timers.values()):
timer_item.cancel()
self._mips_local_state_changed_timers.clear()
self._miot_lan.unsub_lan_state(
key=f'{self._uid}-{self._cloud_server}')
if self._miot_lan.init_done:
self._miot_lan.unsub_device_state(
key=f'{self._uid}-{self._cloud_server}')
self._miot_lan.delete_devices(
devices=list(self._device_list_cache.keys()))
await self._miot_lan.vote_for_lan_ctrl_async(
key=f'{self._uid}-{self._cloud_server}', vote=False)
# Cancel refresh auth info
if self._refresh_token_timer:
self._refresh_token_timer.cancel()
self._refresh_token_timer = None
if self._refresh_cert_timer:
self._refresh_cert_timer.cancel()
self._refresh_cert_timer = None
# Cancel device changed notify timer
if self._show_devices_changed_notify_timer:
self._show_devices_changed_notify_timer.cancel()
self._show_devices_changed_notify_timer = None
await self._oauth.deinit_async()
await self._http.deinit_async()
# Remove notify
self._persistence_notify(
self.__gen_notify_key('dev_list_changed'), None, None)
self.__show_client_error_notify(
message=None, notify_key='oauth_info')
self.__show_client_error_notify(
message=None, notify_key='user_cert')
self.__show_client_error_notify(
message=None, notify_key='device_cache')
self.__show_client_error_notify(
message=None, notify_key='device_cloud')
_LOGGER.info('deinit_async, %s', self._uid)
@property
def main_loop(self) -> asyncio.AbstractEventLoop:
return self._main_loop
@property
def miot_network(self) -> MIoTNetwork:
return self._network
@property
def miot_storage(self) -> MIoTStorage:
return self._storage
@property
def mips_service(self) -> MipsService:
return self._mips_service
@property
def miot_oauth(self) -> MIoTOauthClient:
return self._oauth
@property
def miot_http(self) -> MIoTHttpClient:
return self._http
@property
def miot_i18n(self) -> MIoTI18n:
return self._i18n
@property
def miot_lan(self) -> MIoTLan:
return self._miot_lan
@property
def user_config(self) -> dict:
return self._user_config
@property
def area_name_rule(self) -> Optional[str]:
return self._entry_data.get('area_name_rule', None)
@property
def cloud_server(self) -> str:
return self._cloud_server
@property
def action_debug(self) -> bool:
return self._entry_data.get('action_debug', False)
@property
def hide_non_standard_entities(self) -> bool:
return self._entry_data.get(
'hide_non_standard_entities', False)
@property
def display_devices_changed_notify(self) -> list[str]:
return self._display_devs_notify
@property
def display_binary_text(self) -> bool:
return self._display_binary_text
@property
def display_binary_bool(self) -> bool:
return self._display_binary_bool
@property
def cover_dead_zone_width(self) -> int:
return self._entry_data.get('cover_dead_zone_width',
DEFAULT_COVER_DEAD_ZONE_WIDTH)
@display_devices_changed_notify.setter
def display_devices_changed_notify(self, value: list[str]) -> None:
if set(value) == set(self._display_devs_notify):
return
self._display_devs_notify = value
if value:
self.__request_show_devices_changed_notify()
else:
self._persistence_notify(
self.__gen_notify_key('dev_list_changed'), None, None)
@property
def device_list(self) -> dict:
return self._device_list_cache
@property
def persistent_notify(self) -> Callable:
return self._persistence_notify
@persistent_notify.setter
def persistent_notify(self, func) -> None:
self._persistence_notify = func
@final
async def refresh_oauth_info_async(self) -> bool:
try:
# Load auth info
auth_info: Optional[dict] = None
user_config: dict = await self._storage.load_user_config_async(
uid=self._uid, cloud_server=self._cloud_server,
keys=['auth_info'])
if (
not user_config
or (auth_info := user_config.get('auth_info', None)) is None
):
raise MIoTClientError('load_user_config_async error')
if (
'expires_ts' not in auth_info
or 'access_token' not in auth_info
or 'refresh_token' not in auth_info
):
raise MIoTClientError('invalid auth info')
# Determine whether to update token
refresh_time = int(auth_info['expires_ts'] - time.time())
if refresh_time <= 60:
valid_auth_info = await self._oauth.refresh_access_token_async(
refresh_token=auth_info['refresh_token'])
auth_info = valid_auth_info
# Update http token
self._http.update_http_header(
access_token=valid_auth_info['access_token'])
# Update mips cloud token
self._mips_cloud.update_access_token(
access_token=valid_auth_info['access_token'])
# Update storage
if not await self._storage.update_user_config_async(
uid=self._uid, cloud_server=self._cloud_server,
config={'auth_info': auth_info}):
raise MIoTClientError('update_user_config_async error')
_LOGGER.info(
'refresh oauth info, get new access_token, %s',
auth_info)
refresh_time = int(auth_info['expires_ts'] - time.time())
if refresh_time <= 0:
raise MIoTClientError('invalid expires time')
self.__show_client_error_notify(None, 'oauth_info')
self.__request_refresh_auth_info(refresh_time)
_LOGGER.debug(
'refresh oauth info (%s, %s) after %ds',
self._uid, self._cloud_server, refresh_time)
return True
except Exception as err:
self.__show_client_error_notify(
message=self._i18n.translate(
'miot.client.invalid_oauth_info'), # type: ignore
notify_key='oauth_info')
_LOGGER.error(
'refresh oauth info error (%s, %s), %s, %s',
self._uid, self._cloud_server, err, traceback.format_exc())
return False
async def refresh_user_cert_async(self) -> bool:
try:
if self._cloud_server not in SUPPORT_CENTRAL_GATEWAY_CTRL:
return True
if not await self._cert.verify_ca_cert_async():
raise MIoTClientError('ca cert is not ready')
refresh_time = (
await self._cert.user_cert_remaining_time_async() -
MIHOME_CERT_EXPIRE_MARGIN)
if refresh_time <= 60:
user_key = await self._cert.load_user_key_async()
if not user_key:
user_key = self._cert.gen_user_key()
if not await self._cert.update_user_key_async(key=user_key):
raise MIoTClientError('update_user_key_async failed')
csr_str = self._cert.gen_user_csr(
user_key=user_key, did=self._entry_data['virtual_did'])
crt_str = await self.miot_http.get_central_cert_async(csr_str)
if not await self._cert.update_user_cert_async(cert=crt_str):
raise MIoTClientError('update user cert error')
_LOGGER.info('update_user_cert_async, %s', crt_str)
# Create cert update task
refresh_time = (
await self._cert.user_cert_remaining_time_async() -
MIHOME_CERT_EXPIRE_MARGIN)
if refresh_time <= 0:
raise MIoTClientError('invalid refresh time')
self.__show_client_error_notify(None, 'user_cert')
self.__request_refresh_user_cert(refresh_time)
_LOGGER.debug(
'refresh user cert (%s, %s) after %ds',
self._uid, self._cloud_server, refresh_time)
return True
except MIoTClientError as error:
self.__show_client_error_notify(
message=self._i18n.translate(
'miot.client.invalid_cert_info'), # type: ignore
notify_key='user_cert')
_LOGGER.error(
'refresh user cert error, %s, %s',
error, traceback.format_exc())
return False
async def set_prop_async(
self, did: str, siid: int, piid: int, value: Any
) -> bool:
if did not in self._device_list_cache:
raise MIoTClientError(f'did not exist, {did}')
# Priority local control
if self._ctrl_mode == CtrlMode.AUTO:
# Gateway control
device_gw = self._device_list_gateway.get(did, None)
if (
device_gw and device_gw.get('online', False)
and device_gw.get('specv2_access', False)
and 'group_id' in device_gw
):
mips = self._mips_local.get(device_gw['group_id'], None)
if mips is None:
_LOGGER.error(
'no gateway route, %s, try control through cloud',
device_gw)
else:
result = await mips.set_prop_async(
did=did, siid=siid, piid=piid, value=value)
_LOGGER.debug(
'gateway set prop, %s.%d.%d, %s -> %s',
did, siid, piid, value, result)
rc = (result or {}).get(
'code', MIoTErrorCode.CODE_MIPS_INVALID_RESULT.value)
if rc in [0, 1]:
return True
raise MIoTClientError(
self.__get_exec_error_with_rc(rc=rc))
# Lan control
device_lan = self._device_list_lan.get(did, None)
if device_lan and device_lan.get('online', False):
result = await self._miot_lan.set_prop_async(
did=did, siid=siid, piid=piid, value=value)
_LOGGER.debug(
'lan set prop, %s.%d.%d, %s -> %s',
did, siid, piid, value, result)
rc = (result or {}).get(
'code', MIoTErrorCode.CODE_MIPS_INVALID_RESULT.value)
if rc in [0, 1]:
return True
raise MIoTClientError(
self.__get_exec_error_with_rc(rc=rc))
# Cloud control
device_cloud = self._device_list_cloud.get(did, None)
if device_cloud and device_cloud.get('online', False):
result = await self._http.set_prop_async(
params=[
{'did': did, 'siid': siid, 'piid': piid, 'value': value}
])
_LOGGER.debug(
'cloud set prop, %s.%d.%d, %s -> %s',
did, siid, piid, value, result)
if result and len(result) == 1:
rc = result[0].get(
'code', MIoTErrorCode.CODE_MIPS_INVALID_RESULT.value)
if rc in [0, 1]:
return True
if rc in [-704010000, -704042011]:
# Device remove or offline
_LOGGER.error('device may be removed or offline, %s', did)
self._main_loop.create_task(
await self.__refresh_cloud_device_with_dids_async(
dids=[did]))
raise MIoTClientError(
self.__get_exec_error_with_rc(rc=rc))
# Show error message
raise MIoTClientError(
f'{self._i18n.translate("miot.client.device_exec_error")}, '
f'{self._i18n.translate("error.common.-10007")}')
def request_refresh_prop(
self, did: str, siid: int, piid: int
) -> None:
if did not in self._device_list_cache:
raise MIoTClientError(f'did not exist, {did}')
key: str = f'{did}|{siid}|{piid}'
if key in self._refresh_props_list:
return
self._refresh_props_list[key] = {
'did': did, 'siid': siid, 'piid': piid}
if self._refresh_props_timer:
return
self._refresh_props_timer = self._main_loop.call_later(
REFRESH_PROPS_DELAY, lambda: self._main_loop.create_task(
self.__refresh_props_handler()))
async def get_prop_async(self, did: str, siid: int, piid: int) -> Any:
if did not in self._device_list_cache:
raise MIoTClientError(f'did not exist, {did}')
# NOTICE: Since there are too many request attributes and obtaining
# them directly from the hub or device will cause device abnormalities,
# so obtaining the cache from the cloud is the priority here.
try:
if self._network.network_status:
result = await self._http.get_prop_async(
did=did, siid=siid, piid=piid)
if result:
return result
except Exception as err: # pylint: disable=broad-exception-caught
# Catch all exceptions
_LOGGER.error(
'client get prop from cloud error, %s, %s',
err, traceback.format_exc())
if self._ctrl_mode == CtrlMode.AUTO:
# Central hub gateway
device_gw = self._device_list_gateway.get(did, None)
if (
device_gw and device_gw.get('online', False)
and device_gw.get('specv2_access', False)
and 'group_id' in device_gw
):
mips = self._mips_local.get(device_gw['group_id'], None)
if mips is None:
_LOGGER.error('no gw route, %s', device_gw)
else:
return await mips.get_prop_async(
did=did, siid=siid, piid=piid)
# Lan
device_lan = self._device_list_lan.get(did, None)
if device_lan and device_lan.get('online', False):
return await self._miot_lan.get_prop_async(
did=did, siid=siid, piid=piid)
# _LOGGER.error(
# 'client get prop failed, no-link, %s.%d.%d', did, siid, piid)
return None
async def action_async(
self, did: str, siid: int, aiid: int, in_list: list
) -> list:
if did not in self._device_list_cache:
raise MIoTClientError(f'did not exist, {did}')
device_gw = self._device_list_gateway.get(did, None)
# Priority local control
if self._ctrl_mode == CtrlMode.AUTO:
if (
device_gw and device_gw.get('online', False)
and device_gw.get('specv2_access', False)
and 'group_id' in device_gw
):
mips = self._mips_local.get(
device_gw['group_id'], None)
if mips is None:
_LOGGER.error('no gw route, %s', device_gw)
else:
result = await mips.action_async(
did=did, siid=siid, aiid=aiid, in_list=in_list)
rc = (result or {}).get(
'code', MIoTErrorCode.CODE_MIPS_INVALID_RESULT.value)
if rc in [0, 1]:
return result.get('out', [])
raise MIoTClientError(
self.__get_exec_error_with_rc(rc=rc))
# Lan control
device_lan = self._device_list_lan.get(did, None)
if device_lan and device_lan.get('online', False):
result = await self._miot_lan.action_async(
did=did, siid=siid, aiid=aiid, in_list=in_list)
_LOGGER.debug(
'lan action, %s, %s, %s -> %s', did, siid, aiid, result)
rc = (result or {}).get(
'code', MIoTErrorCode.CODE_MIPS_INVALID_RESULT.value)
if rc in [0, 1]:
return result.get('out', [])
raise MIoTClientError(
self.__get_exec_error_with_rc(rc=rc))
# Cloud control
device_cloud = self._device_list_cloud.get(did, None)
if device_cloud and device_cloud.get('online', False):
result: dict = await self._http.action_async(
did=did, siid=siid, aiid=aiid, in_list=in_list)
if result:
rc = result.get(
'code', MIoTErrorCode.CODE_MIPS_INVALID_RESULT.value)
if rc in [0, 1]:
return result.get('out', [])
if rc in [-704010000, -704042011]:
# Device remove or offline
_LOGGER.error('device removed or offline, %s', did)
self._main_loop.create_task(
await self.__refresh_cloud_device_with_dids_async(
dids=[did]))
raise MIoTClientError(
self.__get_exec_error_with_rc(rc=rc))
# TODO: Show error message
_LOGGER.error(
'client action failed, %s.%d.%d', did, siid, aiid)
return []
def sub_prop(
self, did: str, handler: Callable[[dict, Any], None],
siid: Optional[int] = None, piid: Optional[int] = None,
handler_ctx: Any = None
) -> bool:
if did not in self._device_list_cache:
raise MIoTClientError(f'did not exist, {did}')
topic = (
f'{did}/p/'
f'{"#" if siid is None or piid is None else f"{siid}/{piid}"}')
self._sub_tree[topic] = MIoTClientSub(
topic=topic, handler=handler, handler_ctx=handler_ctx)
_LOGGER.debug('client sub prop, %s', topic)
return True
def unsub_prop(
self, did: str, siid: Optional[int] = None, piid: Optional[int] = None
) -> bool:
topic = (
f'{did}/p/'
f'{"#" if siid is None or piid is None else f"{siid}/{piid}"}')
if self._sub_tree.get(topic=topic):
del self._sub_tree[topic]
_LOGGER.debug('client unsub prop, %s', topic)
return True
def sub_event(
self, did: str, handler: Callable[[dict, Any], None],
siid: Optional[int] = None, eiid: Optional[int] = None,
handler_ctx: Any = None
) -> bool:
if did not in self._device_list_cache:
raise MIoTClientError(f'did not exist, {did}')
topic = (
f'{did}/e/'
f'{"#" if siid is None or eiid is None else f"{siid}/{eiid}"}')
self._sub_tree[topic] = MIoTClientSub(
topic=topic, handler=handler, handler_ctx=handler_ctx)
_LOGGER.debug('client sub event, %s', topic)
return True
def unsub_event(
self, did: str, siid: Optional[int] = None, eiid: Optional[int] = None
) -> bool:
topic = (
f'{did}/e/'
f'{"#" if siid is None or eiid is None else f"{siid}/{eiid}"}')
if self._sub_tree.get(topic=topic):
del self._sub_tree[topic]
_LOGGER.debug('client unsub event, %s', topic)
return True
def sub_device_state(
self, did: str, handler: Callable[[str, MIoTDeviceState, Any], None],
handler_ctx: Any = None
) -> bool:
"""Call callback handler in main loop"""
if did not in self._device_list_cache:
raise MIoTClientError(f'did not exist, {did}')
self._sub_device_state[did] = MipsDeviceState(
did=did, handler=handler, handler_ctx=handler_ctx)
_LOGGER.debug('client sub device state, %s', did)
return True
def unsub_device_state(self, did: str) -> bool:
self._sub_device_state.pop(did, None)
_LOGGER.debug('client unsub device state, %s', did)
return True
async def remove_device_async(self, did: str) -> None:
if did not in self._device_list_cache:
return
sub_from = self._sub_source_list.pop(did, None)
# Unsub
if sub_from:
self.__unsub_from(sub_from, did)
# Storage
await self._storage.save_async(
domain='miot_devices',
name=f'{self._uid}_{self._cloud_server}',
data=self._device_list_cache)
# Update notify
self.__request_show_devices_changed_notify()
async def remove_device2_async(self, did_tag: str) -> None:
for did in self._device_list_cache:
d_tag = slugify_did(cloud_server=self._cloud_server, did=did)
if did_tag == d_tag:
await self.remove_device_async(did)
break
def __get_exec_error_with_rc(self, rc: int) -> str:
err_msg: str = self._i18n.translate(
key=f'error.common.{rc}') # type: ignore
if not err_msg:
err_msg = f'{self._i18n.translate(key="error.common.-10000")}, '
err_msg += f'code={rc}'
return (
f'{self._i18n.translate(key="miot.client.device_exec_error")}, '
+ err_msg)
@final
def __gen_notify_key(self, name: str) -> str:
return f'{DOMAIN}-{self._uid}-{self._cloud_server}-{name}'
@final
def __request_refresh_auth_info(self, delay_sec: int) -> None:
if self._refresh_token_timer:
self._refresh_token_timer.cancel()
self._refresh_token_timer = None
self._refresh_token_timer = self._main_loop.call_later(
delay_sec, lambda: self._main_loop.create_task(
self.refresh_oauth_info_async()))
@final
def __request_refresh_user_cert(self, delay_sec: int) -> None:
if self._refresh_cert_timer:
self._refresh_cert_timer.cancel()
self._refresh_cert_timer = None
self._refresh_cert_timer = self._main_loop.call_later(
delay_sec, lambda: self._main_loop.create_task(
self.refresh_user_cert_async()))
@final
def __unsub_from(self, sub_from: str, did: str) -> None:
mips: Any = None
if sub_from == 'cloud':
mips = self._mips_cloud
elif sub_from == 'lan':
mips = self._miot_lan
elif sub_from in self._mips_local:
mips = self._mips_local[sub_from]
if mips is not None:
try:
mips.unsub_prop(did=did)
mips.unsub_event(did=did)
except RuntimeError as e:
if 'Event loop is closed' in str(e):
# Ignore unsub exception when loop is closed
pass
else:
raise
@final
def __sub_from(self, sub_from: str, did: str) -> None:
mips = None
if sub_from == 'cloud':
mips = self._mips_cloud
elif sub_from == 'lan':
mips = self._miot_lan
elif sub_from in self._mips_local:
mips = self._mips_local[sub_from]
if mips is not None:
mips.sub_prop(did=did, handler=self.__on_prop_msg)
mips.sub_event(did=did, handler=self.__on_event_msg)
@final
def __update_device_msg_sub(self, did: str) -> None:
if did not in self._device_list_cache:
return
from_old: Optional[str] = self._sub_source_list.get(did, None)
from_new: Optional[str] = None
if self._ctrl_mode == CtrlMode.AUTO:
if (
did in self._device_list_gateway
and self._device_list_gateway[did].get('online', False)
and self._device_list_gateway[did].get('push_available', False)