-
Notifications
You must be signed in to change notification settings - Fork 755
/
miot_lan.py
1358 lines (1228 loc) · 51.3 KB
/
miot_lan.py
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 lan device control, only support MIoT SPEC-v2 WiFi devices.
"""
import json
import time
import asyncio
from dataclasses import dataclass
from enum import Enum, auto
import logging
import os
import queue
import random
import secrets
import socket
import struct
import threading
from typing import Callable, Optional, final
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
# pylint: disable=relative-beyond-top-level
from .miot_error import MIoTErrorCode
from .miot_ev import MIoTEventLoop, TimeoutHandle
from .miot_network import InterfaceStatus, MIoTNetwork, NetworkInfo
from .miot_mdns import MipsService, MipsServiceState
from .common import (
randomize_int, load_yaml_file, gen_absolute_path, MIoTMatcher)
_LOGGER = logging.getLogger(__name__)
class MIoTLanCmdType(Enum):
"""MIoT lan command."""
DEINIT = 0
CALL_API = auto()
SUB_DEVICE_STATE = auto()
UNSUB_DEVICE_STATE = auto()
REG_BROADCAST = auto()
UNREG_BROADCAST = auto()
GET_DEV_LIST = auto()
DEVICE_UPDATE = auto()
DEVICE_DELETE = auto()
NET_INFO_UPDATE = auto()
NET_IFS_UPDATE = auto()
OPTIONS_UPDATE = auto()
@dataclass
class MIoTLanCmd:
"""MIoT lan command."""
type_: MIoTLanCmdType
data: any
@dataclass
class MIoTLanCmdData:
handler: Callable[[dict, any], None]
handler_ctx: any
timeout_ms: int
@dataclass
class MIoTLanGetDevListData(MIoTLanCmdData):
...
@dataclass
class MIoTLanCallApiData(MIoTLanCmdData):
did: str
msg: dict
class MIoTLanSendBroadcastData(MIoTLanCallApiData):
...
@dataclass
class MIoTLanUnregisterBroadcastData:
key: str
@dataclass
class MIoTLanRegisterBroadcastData:
key: str
handler: Callable[[dict, any], None]
handler_ctx: any
@dataclass
class MIoTLanUnsubDeviceState:
key: str
@dataclass
class MIoTLanSubDeviceState:
key: str
handler: Callable[[str, dict, any], None]
handler_ctx: any
@dataclass
class MIoTLanNetworkUpdateData:
status: InterfaceStatus
if_name: str
@dataclass
class MIoTLanRequestData:
msg_id: int
handler: Callable[[dict, any], None]
handler_ctx: any
timeout: TimeoutHandle
class MIoTLanDeviceState(Enum):
FRESH = 0
PING1 = auto()
PING2 = auto()
PING3 = auto()
DEAD = auto()
class MIoTLanDevice:
"""MIoT lan device."""
# pylint: disable=unused-argument
OT_HEADER: int = 0x2131
OT_HEADER_LEN: int = 32
NETWORK_UNSTABLE_CNT_TH: int = 10
NETWORK_UNSTABLE_TIME_TH: int = 120000
NETWORK_UNSTABLE_RESUME_TH: int = 300
FAST_PING_INTERVAL: int = 5000
CONSTRUCT_STATE_PENDING: int = 15000
KA_INTERVAL_MIN = 10000
KA_INTERVAL_MAX = 50000
did: str
token: bytes
cipher: Cipher
ip: Optional[str]
offset: int
subscribed: bool
sub_ts: int
supported_wildcard_sub: bool
_manager: any
_if_name: Optional[str]
_sub_locked: bool
_state: MIoTLanDeviceState
_online: bool
_online_offline_history: list[dict[str, any]]
_online_offline_timer: Optional[TimeoutHandle]
_ka_timer: TimeoutHandle
_ka_internal: int
def __init__(
self, manager: any, did: str, token: str, ip: Optional[str] = None
) -> None:
self._manager: MIoTLan = manager
self.did = did
self.token = bytes.fromhex(token)
aes_key: bytes = self.__md5(self.token)
aex_iv: bytes = self.__md5(aes_key + self.token)
self.cipher = Cipher(
algorithms.AES128(aes_key), modes.CBC(aex_iv), default_backend())
self.ip = ip
self.offset = 0
self.subscribed = False
self.sub_ts = 0
self.supported_wildcard_sub = False
self._if_name = None
self._sub_locked = False
self._state = MIoTLanDeviceState.DEAD
self._online = False
self._online_offline_history = []
self._online_offline_timer = None
def ka_init_handler(ctx: any) -> None:
self._ka_internal = self.KA_INTERVAL_MIN
self.__update_keep_alive(state=MIoTLanDeviceState.DEAD)
self._ka_timer = self._manager.mev.set_timeout(
randomize_int(self.CONSTRUCT_STATE_PENDING, 0.5),
ka_init_handler, None)
_LOGGER.debug('miot lan device add, %s', self.did)
def keep_alive(self, ip: str, if_name: str) -> None:
self.ip = ip
if self._if_name != if_name:
self._if_name = if_name
_LOGGER.info(
'device if_name change, %s, %s', self._if_name, self.did)
self.__update_keep_alive(state=MIoTLanDeviceState.FRESH)
@property
def online(self) -> bool:
return self._online
@online.setter
def online(self, online: bool) -> None:
if self._online == online:
return
self._online = online
self._manager.broadcast_device_state(
did=self.did, state={
'online': self._online, 'push_available': self.subscribed})
@property
def if_name(self) -> Optional[str]:
return self._if_name
def gen_packet(
self, out_buffer: bytearray, clear_data: dict, did: str, offset: int
) -> int:
clear_bytes = json.dumps(clear_data).encode('utf-8')
padder = padding.PKCS7(algorithms.AES128.block_size).padder()
padded_data = padder.update(clear_bytes) + padder.finalize()
if len(padded_data) + self.OT_HEADER_LEN > len(out_buffer):
raise ValueError('rpc too long')
encryptor = self.cipher.encryptor()
encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
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)
out_buffer[32:data_len] = encrypted_data
msg_md5: bytes = self.__md5(out_buffer[0:data_len])
out_buffer[16:32] = msg_md5
return data_len
def decrypt_packet(self, encrypted_data: bytearray) -> dict:
data_len: int = struct.unpack('>H', encrypted_data[2:4])[0]
md5_orig: bytes = encrypted_data[16:32]
encrypted_data[16:32] = self.token
md5_calc: bytes = self.__md5(encrypted_data[0:data_len])
if md5_orig != md5_calc:
raise ValueError(f'invalid md5, {md5_orig}, {md5_calc}')
decryptor = self.cipher.decryptor()
decrypted_padded_data = decryptor.update(
encrypted_data[32:data_len]) + decryptor.finalize()
unpadder = padding.PKCS7(algorithms.AES128.block_size).unpadder()
decrypted_data = unpadder.update(
decrypted_padded_data) + unpadder.finalize()
# Some device will add a redundant \0 at the end of JSON string
decrypted_data = decrypted_data.rstrip(b'\x00')
return json.loads(decrypted_data)
def subscribe(self) -> None:
if self._sub_locked:
return
self._sub_locked = True
try:
sub_ts: int = int(time.time())
self._manager.send2device(
did=self.did,
msg={
'method': 'miIO.sub',
'params': {
'version': '2.0',
'did': self._manager.virtual_did,
'update_ts': sub_ts,
'sub_method': '.'
}
},
handler=self.__subscribe_handler,
handler_ctx=sub_ts,
timeout_ms=5000)
except Exception as err: # pylint: disable=broad-exception-caught
_LOGGER.error('subscribe device error, %s', err)
self._sub_locked = False
def unsubscribe(self) -> None:
if not self.subscribed:
return
self._manager.send2device(
did=self.did,
msg={
'method': 'miIO.unsub',
'params': {
'version': '2.0',
'did': self._manager.virtual_did,
'update_ts': self.sub_ts or 0,
'sub_method': '.'
}
},
handler=self.__unsubscribe_handler,
timeout_ms=5000)
self.subscribed = False
self._manager.broadcast_device_state(
did=self.did, state={
'online': self._online, 'push_available': self.subscribed})
def on_delete(self) -> None:
if self._ka_timer:
self._manager.mev.clear_timeout(self._ka_timer)
if self._online_offline_timer:
self._manager.mev.clear_timeout(self._online_offline_timer)
self._manager = None
self.cipher = None
_LOGGER.debug('miot lan device delete, %s', self.did)
def update_info(self, info: dict) -> None:
if (
'token' in info
and len(info['token']) == 32
and info['token'].upper() != self.token.hex().upper()
):
# Update token
self.token = bytes.fromhex(info['token'])
aes_key: bytes = self.__md5(self.token)
aex_iv: bytes = self.__md5(aes_key + self.token)
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)
return
self.subscribed = True
self.sub_ts = sub_ts
self._manager.broadcast_device_state(
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)
return
_LOGGER.info('unsubscribe success, %s, %s', self._if_name, self.did)
def __update_keep_alive(self, state: MIoTLanDeviceState) -> None:
last_state: MIoTLanDeviceState = self._state
self._state = state
if self._state != MIoTLanDeviceState.FRESH:
_LOGGER.debug('device status, %s, %s', self.did, self._state)
if self._ka_timer:
self._manager.mev.clear_timeout(self._ka_timer)
self._ka_timer = None
match state:
case MIoTLanDeviceState.FRESH:
if last_state == MIoTLanDeviceState.DEAD:
self._ka_internal = self.KA_INTERVAL_MIN
self.__change_online(True)
self._ka_timer = self._manager.mev.set_timeout(
self.__get_next_ka_timeout(), self.__update_keep_alive,
MIoTLanDeviceState.PING1)
case (
MIoTLanDeviceState.PING1
| MIoTLanDeviceState.PING2
| MIoTLanDeviceState.PING3
):
self._manager.ping(if_name=self._if_name, target_ip=self.ip)
# Fast ping
self._ka_timer = self._manager.mev.set_timeout(
self.FAST_PING_INTERVAL, self.__update_keep_alive,
MIoTLanDeviceState(state.value+1))
case MIoTLanDeviceState.DEAD:
if last_state == MIoTLanDeviceState.PING3:
self._ka_internal = self.KA_INTERVAL_MIN
self.__change_online(False)
case _:
_LOGGER.error('invalid state, %s', state)
def __get_next_ka_timeout(self) -> int:
self._ka_internal = min(self._ka_internal*2, self.KA_INTERVAL_MAX)
return randomize_int(self._ka_internal, 0.1)
def __change_online(self, online: bool) -> None:
_LOGGER.info('change online, %s, %s', self.did, online)
ts_now: int = int(time.time())
self._online_offline_history.append({'ts': ts_now, 'online': online})
if len(self._online_offline_history) > self.NETWORK_UNSTABLE_CNT_TH:
self._online_offline_history.pop(0)
if self._online_offline_timer:
self._manager.mev.clear_timeout(self._online_offline_timer)
if not online:
self.online = False
else:
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.mev.set_timeout(
self.NETWORK_UNSTABLE_RESUME_TH,
self.__online_resume_handler, None)
def __online_resume_handler(self, ctx: any) -> None:
_LOGGER.info('unstable resume threshold past, %s', self.did)
self.online = True
def __md5(self, data: bytes) -> bytes:
hasher = hashes.Hash(hashes.MD5(), default_backend())
hasher.update(data)
return hasher.finalize()
class MIoTLan:
"""MIoT lan device control."""
# pylint: disable=unused-argument
# pylint: disable=inconsistent-quotes
OT_HEADER: bytes = b'\x21\x31'
OT_PORT: int = 54321
OT_PROBE_LEN: int = 32
OT_MSG_LEN: int = 1400
OT_SUPPORT_WILDCARD_SUB: int = 0xFE
OT_PROBE_INTERVAL_MIN: int = 5000
OT_PROBE_INTERVAL_MAX: int = 45000
PROFILE_MODELS_FILE: str = 'lan/profile_models.yaml'
_main_loop: asyncio.AbstractEventLoop
_net_ifs: set[str]
_network: MIoTNetwork
_mips_service: MipsService
_enable_subscribe: bool
_lan_devices: dict[str, MIoTLanDevice]
_virtual_did: str
_probe_msg: bytes
_write_buffer: bytearray
_read_buffer: bytearray
_mev: MIoTEventLoop
_thread: threading.Thread
_queue: queue.Queue
_cmd_event_fd: os.eventfd
_available_net_ifs: set[str]
_broadcast_socks: dict[str, socket.socket]
_local_port: Optional[int]
_scan_timer: TimeoutHandle
_last_scan_interval: Optional[int]
_msg_id_counter: int
_pending_requests: dict[int, MIoTLanRequestData]
_device_msg_matcher: MIoTMatcher
_device_state_sub_map: dict[str, MIoTLanSubDeviceState]
_reply_msg_buffer: dict[str, TimeoutHandle]
_lan_state_sub_map: dict[str, Callable[[bool], asyncio.Future]]
_lan_ctrl_vote_map: dict[str, bool]
_profile_models: dict[str, dict]
_init_done: bool
def __init__(
self,
net_ifs: list[str],
network: MIoTNetwork,
mips_service: MipsService,
enable_subscribe: bool = False,
virtual_did: Optional[int] = None,
loop: Optional[asyncio.AbstractEventLoop] = None
) -> None:
if not network:
raise ValueError('network is required')
if not mips_service:
raise ValueError('mips_service is required')
self._main_loop = loop or asyncio.get_event_loop()
self._net_ifs = set(net_ifs)
self._network = network
self._network.sub_network_info(
key='miot_lan', handler=self.__on_network_info_change)
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 = virtual_did or 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'
self._probe_msg = bytes(probe_bytes)
self._read_buffer = bytearray(self.OT_MSG_LEN)
self._write_buffer = bytearray(self.OT_MSG_LEN)
self._lan_devices = {}
self._available_net_ifs = set()
self._broadcast_socks = {}
self._local_port = None
self._scan_timer = None
self._last_scan_interval = None
self._msg_id_counter = int(random.random()*0x7FFFFFFF)
self._pending_requests = {}
self._device_msg_matcher = MIoTMatcher()
self._device_state_sub_map = {}
self._reply_msg_buffer = {}
self._lan_state_sub_map = {}
self._lan_ctrl_vote_map = {}
self._init_done = False
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()))
@property
def virtual_did(self) -> str:
return self._virtual_did
@property
def mev(self) -> MIoTEventLoop:
return self._mev
@property
def init_done(self) -> bool:
return self._init_done
async def init_async(self) -> None:
if self._init_done:
_LOGGER.info('miot lan already init')
return
if len(self._net_ifs) == 0:
_LOGGER.info('no net_ifs')
return
if not any(self._lan_ctrl_vote_map.values()):
_LOGGER.info('no vote for lan ctrl')
return
if len(self._mips_service.get_services()) > 0:
_LOGGER.info('central hub gateway service exist')
return
for if_name in list(self._network.network_info.keys()):
self._available_net_ifs.add(if_name)
if len(self._available_net_ifs) == 0:
_LOGGER.info('no available net_ifs')
return
if self._net_ifs.isdisjoint(self._available_net_ifs):
_LOGGER.info('no valid net_ifs')
return
try:
self._profile_models = load_yaml_file(
yaml_file=gen_absolute_path(self.PROFILE_MODELS_FILE))
except Exception as err: # pylint: disable=broad-exception-caught
_LOGGER.error('load profile models error, %s', err)
self._profile_models = {}
self._mev = MIoTEventLoop()
self._queue = queue.Queue()
self._cmd_event_fd = os.eventfd(0, os.O_NONBLOCK)
self._mev.set_read_handler(
self._cmd_event_fd, self.__cmd_read_handler, None)
self._thread = threading.Thread(target=self.__lan_thread_handler)
self._thread.name = 'miot_lan'
self._thread.daemon = True
self._thread.start()
self._init_done = True
for handler in list(self._lan_state_sub_map.values()):
self._main_loop.create_task(handler(True))
_LOGGER.info(
'miot lan init, %s ,%s', self._net_ifs, self._available_net_ifs)
async def deinit_async(self) -> None:
if not self._init_done:
_LOGGER.info('miot lan not init')
return
self._init_done = False
self.__lan_send_cmd(MIoTLanCmdType.DEINIT, None)
self._thread.join()
self._profile_models = {}
self._lan_devices = {}
self._broadcast_socks = {}
self._local_port = None
self._scan_timer = None
self._last_scan_interval = None
self._msg_id_counter = int(random.random()*0x7FFFFFFF)
self._pending_requests = {}
self._device_msg_matcher = MIoTMatcher()
self._device_state_sub_map = {}
self._reply_msg_buffer = {}
for handler in list(self._lan_state_sub_map.values()):
self._main_loop.create_task(handler(False))
_LOGGER.info('miot lan deinit')
async def update_net_ifs_async(self, net_ifs: list[str]) -> None:
_LOGGER.info('update net_ifs, %s', net_ifs)
if not isinstance(net_ifs, list):
_LOGGER.error('invalid net_ifs, %s', net_ifs)
return
if len(net_ifs) == 0:
# Deinit lan
await self.deinit_async()
self._net_ifs = set(net_ifs)
return
available_net_ifs = set()
for if_name in list(self._network.network_info.keys()):
available_net_ifs.add(if_name)
if set(net_ifs).isdisjoint(available_net_ifs):
_LOGGER.error('no valid net_ifs, %s', net_ifs)
await self.deinit_async()
self._net_ifs = set(net_ifs)
self._available_net_ifs = available_net_ifs
return
if not self._init_done:
self._net_ifs = set(net_ifs)
await self.init_async()
return
self.__lan_send_cmd(
cmd=MIoTLanCmdType.NET_IFS_UPDATE,
data=net_ifs)
async def vote_for_lan_ctrl_async(self, key: str, vote: bool) -> None:
_LOGGER.info('vote for lan ctrl, %s, %s', key, vote)
self._lan_ctrl_vote_map[key] = vote
if not any(self._lan_ctrl_vote_map.values()):
await self.deinit_async()
return
await self.init_async()
async def update_subscribe_option(self, enable_subscribe: bool) -> None:
_LOGGER.info('update subscribe option, %s', enable_subscribe)
if not self._init_done:
self._enable_subscribe = enable_subscribe
return
return self.__lan_send_cmd(
cmd=MIoTLanCmdType.OPTIONS_UPDATE,
data={
'enable_subscribe': enable_subscribe, })
def update_devices(self, devices: dict[str, dict]) -> bool:
_LOGGER.info('update devices, %s', devices)
return self.__lan_send_cmd(
cmd=MIoTLanCmdType.DEVICE_UPDATE,
data=devices)
def delete_devices(self, devices: list[str]) -> bool:
_LOGGER.info('delete devices, %s', devices)
return self.__lan_send_cmd(
cmd=MIoTLanCmdType.DEVICE_DELETE,
data=devices)
def sub_lan_state(
self, key: str, handler: Callable[[bool], asyncio.Future]
) -> None:
self._lan_state_sub_map[key] = handler
def unsub_lan_state(self, key: str) -> None:
self._lan_state_sub_map.pop(key, None)
@final
def sub_device_state(
self, key: str, handler: Callable[[str, dict, any], None],
handler_ctx: any = None
) -> bool:
return self.__lan_send_cmd(
cmd=MIoTLanCmdType.SUB_DEVICE_STATE,
data=MIoTLanSubDeviceState(
key=key, handler=handler, handler_ctx=handler_ctx))
@final
def unsub_device_state(self, key: str) -> bool:
return self.__lan_send_cmd(
cmd=MIoTLanCmdType.UNSUB_DEVICE_STATE,
data=MIoTLanUnsubDeviceState(key=key))
@final
def sub_prop(
self, did: str, handler: Callable[[dict, any], None],
siid: int = None, piid: int = None, handler_ctx: any = None
) -> bool:
if not self._enable_subscribe:
return False
key = (
f'{did}/p/'
f'{"#" if siid is None or piid is None else f"{siid}/{piid}"}')
return self.__lan_send_cmd(
cmd=MIoTLanCmdType.REG_BROADCAST,
data=MIoTLanRegisterBroadcastData(
key=key, handler=handler, handler_ctx=handler_ctx))
@final
def unsub_prop(self, did: str, siid: int = None, piid: int = None) -> bool:
if not self._enable_subscribe:
return False
key = (
f'{did}/p/'
f'{"#" if siid is None or piid is None else f"{siid}/{piid}"}')
return self.__lan_send_cmd(
cmd=MIoTLanCmdType.UNREG_BROADCAST,
data=MIoTLanUnregisterBroadcastData(key=key))
@final
def sub_event(
self, did: str, handler: Callable[[dict, any], None],
siid: int = None, eiid: int = None, handler_ctx: any = None
) -> bool:
if not self._enable_subscribe:
return False
key = (
f'{did}/e/'
f'{"#" if siid is None or eiid is None else f"{siid}/{eiid}"}')
return self.__lan_send_cmd(
cmd=MIoTLanCmdType.REG_BROADCAST,
data=MIoTLanRegisterBroadcastData(
key=key, handler=handler, handler_ctx=handler_ctx))
@final
def unsub_event(self, did: str, siid: int = None, eiid: int = None) -> bool:
if not self._enable_subscribe:
return False
key = (
f'{did}/e/'
f'{"#" if siid is None or eiid is None else f"{siid}/{eiid}"}')
return self.__lan_send_cmd(
cmd=MIoTLanCmdType.UNREG_BROADCAST,
data=MIoTLanUnregisterBroadcastData(key=key))
@final
async def get_prop_async(
self, did: str, siid: int, piid: int, timeout_ms: int = 10000
) -> any:
result_obj = await self.__call_api_async(
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:
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:
return result_obj
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:
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)
if result_obj:
if 'result' in result_obj and 'code' in result_obj['result']:
return result_obj['result']
if 'code' in result_obj:
return result_obj
return {
'code': MIoTErrorCode.CODE_INTERNAL_ERROR.value,
'message': 'Invalid result'}
@final
async def get_dev_list_async(
self, timeout_ms: int = 10000
) -> dict[str, dict]:
if not self._init_done:
return {}
def get_device_list_handler(msg: dict, fut: asyncio.Future):
self._main_loop.call_soon_threadsafe(
fut.set_result, msg)
fut: asyncio.Future = self._main_loop.create_future()
if self.__lan_send_cmd(
MIoTLanCmdType.GET_DEV_LIST,
MIoTLanGetDevListData(
handler=get_device_list_handler,
handler_ctx=fut,
timeout_ms=timeout_ms)):
return await fut
_LOGGER.error('get_dev_list_async error, send cmd failed')
fut.set_result({})
return await fut
def ping(self, if_name: str, target_ip: str) -> None:
if not target_ip:
return
self.__sendto(
if_name=if_name, data=self._probe_msg, address=target_ip,
port=self.OT_PORT)
def send2device(
self, did: str,
msg: dict,
handler: Optional[Callable[[dict, any], None]] = None,
handler_ctx: any = None,
timeout_ms: Optional[int] = None
) -> None:
if timeout_ms and not handler:
raise ValueError('handler is required when timeout_ms is set')
device: MIoTLanDevice = self._lan_devices.get(did)
if not device:
raise ValueError('invalid device')
if not device.cipher:
raise ValueError('invalid device cipher')
if not device.if_name:
raise ValueError('invalid device if_name')
if not device.ip:
raise ValueError('invalid device ip')
in_msg = {'id': self.__gen_msg_id(), **msg}
msg_len = device.gen_packet(
out_buffer=self._write_buffer,
clear_data=in_msg,
did=did,
offset=int(time.time())-device.offset)
return self.make_request(
msg_id=in_msg['id'],
msg=self._write_buffer[0: msg_len],
if_name=device.if_name,
ip=device.ip,
handler=handler,
handler_ctx=handler_ctx,
timeout_ms=timeout_ms)
def make_request(
self,
msg_id: int,
msg: bytearray,
if_name: str,
ip: str,
handler: Callable[[dict, any], None],
handler_ctx: any = None,
timeout_ms: Optional[int] = None
) -> None:
def request_timeout_handler(req_data: MIoTLanRequestData):
self._pending_requests.pop(req_data.msg_id, None)
if req_data:
req_data.handler({
'code': MIoTErrorCode.CODE_TIMEOUT.value,
'error': 'timeout'},
req_data.handler_ctx)
timer: Optional[TimeoutHandle] = None
request_data = MIoTLanRequestData(
msg_id=msg_id,
handler=handler,
handler_ctx=handler_ctx,
timeout=timer)
if timeout_ms:
timer = self._mev.set_timeout(
timeout_ms, request_timeout_handler, request_data)
request_data.timeout = timer
self._pending_requests[msg_id] = request_data
self.__sendto(if_name=if_name, data=msg, address=ip, port=self.OT_PORT)
def broadcast_device_state(self, did: str, state: dict) -> None:
for handler in self._device_state_sub_map.values():
self._main_loop.call_soon_threadsafe(
self._main_loop.create_task,
handler.handler(did, state, handler.handler_ctx))
def __gen_msg_id(self) -> int:
if not self._msg_id_counter:
self._msg_id_counter = int(random.random()*0x7FFFFFFF)
self._msg_id_counter += 1
if self._msg_id_counter > 0x80000000:
self._msg_id_counter = 1
return self._msg_id_counter
def __lan_send_cmd(self, cmd: MIoTLanCmd, data: any) -> bool:
try:
self._queue.put(MIoTLanCmd(type_=cmd, data=data))
os.eventfd_write(self._cmd_event_fd, 1)
return True
except Exception as err: # pylint: disable=broad-exception-caught
_LOGGER.error('send cmd error, %s, %s', cmd, err)
return False
async def __call_api_async(
self, did: str, msg: dict, timeout_ms: int = 10000
) -> dict:
def call_api_handler(msg: dict, fut: asyncio.Future):
self._main_loop.call_soon_threadsafe(
fut.set_result, msg)
fut: asyncio.Future = self._main_loop.create_future()
if self.__lan_send_cmd(
cmd=MIoTLanCmdType.CALL_API,
data=MIoTLanCallApiData(
did=did,
msg=msg,
handler=call_api_handler,
handler_ctx=fut,
timeout_ms=timeout_ms)):
return await fut
fut.set_result({
'code': MIoTErrorCode.CODE_UNAVAILABLE.value,
'error': 'send cmd error'})
return await fut
def __lan_thread_handler(self) -> None:
_LOGGER.info('miot lan thread start')
self.__init_socket()
# Create scan devices timer
self._scan_timer = self._mev.set_timeout(
int(3000*random.random()), self.__scan_devices, None)
self._mev.loop_forever()
_LOGGER.info('miot lan thread exit')
def __cmd_read_handler(self, ctx: any) -> None:
fd_value = os.eventfd_read(self._cmd_event_fd)
if fd_value == 0:
return