-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathconnection.py
More file actions
1255 lines (1052 loc) · 42.5 KB
/
connection.py
File metadata and controls
1255 lines (1052 loc) · 42.5 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 asyncio
import contextlib
import functools
import hashlib
import logging
import struct
import time
import traceback
from collections import deque
from collections.abc import Awaitable, Callable, Collection, Coroutine, MutableSequence
from dataclasses import dataclass
from enum import StrEnum, auto
from functools import cached_property
from typing import Any, Literal, Self
import ecdsa
from bleak import BleakClient
from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.backends.device import BLEDevice
from bleak.exc import BleakError
from bleak_retry_connector import (
MAX_CONNECT_ATTEMPTS,
BleakNotFoundError,
establish_connection,
)
from . import keydata
from .encryption import EncryptionStrategy, Type1Encryption, Type7Encryption
from .exceptions import (
AuthErrors,
ConnectionTimeout,
FailedToAuthenticate,
MaxConnectionAttemptsReached,
MaxReconnectAttemptsReached,
PacketParseError,
PacketReceiveError,
UnsupportedBluetoothProtocol,
)
from .frame_assembler import (
EncPacketAssembler,
PassthroughAssembler,
RawHeaderAssembler,
SimplePacketAssembler,
)
from .listeners import ListenerGroup, ListenerRegistry
from .logging_util import ConnectionLogger, LogOptions, caller_chain
from .packet import Packet
from .props.utils import classproperty
MAX_RECONNECT_ATTEMPTS = 2
MAX_CONNECTION_ATTEMPTS = 10
# `BleakClient.disconnect()` can block until the connect timeout (default 20s) when a
# write-with-response is still pending on the transport after a mid-auth BLE drop
# (notably through an ESPHome proxy). Left unbounded it stalls `async_unload_entry`
# long enough for HA to mark the entry `FAILED_UNLOAD`, so cap every disconnect.
DISCONNECT_TIMEOUT = 5.0
_BT_PROTOCOL_UUIDS = {
"rfcomm": {
"notify": "00000003-0000-1000-8000-00805f9b34fb",
"write": "00000002-0000-1000-8000-00805f9b34fb",
},
"nordic_uart": {
"notify": "6e400003-b5a3-f393-e0a9-e50e24dcca9e",
"write": "6e400002-b5a3-f393-e0a9-e50e24dcca9e",
},
}
def _state_in(states: "Collection[ConnectionState | str]"):
return cached_property(lambda self: self in states)
def _combine_state(
prop: cached_property[bool], states: "Collection[ConnectionState | str]"
):
return cached_property(lambda self: prop.__get__(self) or self in states)
class ConnectionState(StrEnum):
NOT_CONNECTED = auto()
CREATED = auto()
ESTABLISHING_CONNECTION = auto()
CONNECTED = auto()
PUBLIC_KEY_EXCHANGE = auto()
PUBLIC_KEY_RECEIVED = auto()
REQUESTING_SESSION_KEY = auto()
SESSION_KEY_RECEIVED = auto()
REQUESTING_AUTH_STATUS = auto()
AUTH_STATUS_RECEIVED = auto()
AUTHENTICATING = auto()
AUTHENTICATED = auto()
ERROR_TIMEOUT = auto()
ERROR_NOT_FOUND = auto()
ERROR_BLEAK = auto()
ERROR_PACKET_PARSE = auto()
ERROR_SEND_REQUEST = auto()
ERROR_UNKNOWN = auto()
ERROR_AUTH_FAILED = auto()
ERROR_TOO_MANY_ERRORS = auto()
RECONNECTING = auto()
ERROR_MAX_RECONNECT_ATTEMPTS_REACHED = auto()
DISCONNECTING = auto()
DISCONNECTED = auto()
# helper state descriptor flags
connection_error = _state_in(
[
ERROR_TIMEOUT,
ERROR_NOT_FOUND,
ERROR_BLEAK,
]
)
is_error = _combine_state(
connection_error,
[
ERROR_MAX_RECONNECT_ATTEMPTS_REACHED,
ERROR_AUTH_FAILED,
ERROR_TOO_MANY_ERRORS,
ERROR_UNKNOWN,
],
)
received_session_key = _state_in(
[
SESSION_KEY_RECEIVED,
REQUESTING_AUTH_STATUS,
AUTH_STATUS_RECEIVED,
AUTHENTICATING,
AUTHENTICATED,
]
)
is_connected = _state_in(
[
CONNECTED,
PUBLIC_KEY_EXCHANGE,
PUBLIC_KEY_RECEIVED,
REQUESTING_SESSION_KEY,
SESSION_KEY_RECEIVED,
REQUESTING_AUTH_STATUS,
AUTH_STATUS_RECEIVED,
AUTHENTICATING,
]
)
is_connecting = _combine_state(
is_connected,
[ESTABLISHING_CONNECTION, RECONNECTING],
)
authenticated = _state_in([AUTHENTICATED])
is_terminal = _combine_state(
is_error,
[
AUTHENTICATED,
DISCONNECTED,
NOT_CONNECTED,
],
)
@classproperty
@functools.cache
def step_order(self):
return [
ConnectionState.CONNECTED,
ConnectionState.PUBLIC_KEY_EXCHANGE,
ConnectionState.PUBLIC_KEY_RECEIVED,
ConnectionState.REQUESTING_SESSION_KEY,
ConnectionState.SESSION_KEY_RECEIVED,
ConnectionState.REQUESTING_AUTH_STATUS,
ConnectionState.AUTH_STATUS_RECEIVED,
ConnectionState.AUTHENTICATING,
ConnectionState.AUTHENTICATED,
]
@cached_property
def step_index(self):
if self in self.step_order:
return self.step_order.index(self)
return None
type DisconnectListener = Callable[[Exception | type[Exception] | None], None]
type ConnectionStateListener = Callable[[ConnectionState], None]
type PacketReceivedListener = Callable[[bytes], None]
type PacketParsedListener = Callable[[Packet], None]
type DataReceivedListener = Callable[[bytes, ConnectionState], None]
type DataSendListener = Callable[[bytes], None]
class _ConnectionListeners(ListenerRegistry):
on_packet_received: ListenerGroup[PacketReceivedListener]
on_disconnect: ListenerGroup[DisconnectListener]
on_connection_state_change: ListenerGroup[ConnectionStateListener]
on_packet_parsed: ListenerGroup[PacketParsedListener]
on_data_received: ListenerGroup[DataReceivedListener]
on_data_send: ListenerGroup[DataSendListener]
class Connection:
"""Manages client creation, authentification and sends the packets to parse back"""
@dataclass
class Options:
"""Connection options configurable from HA."""
timeout: int = 20
bluez_start_notify: bool = False
_listeners = _ConnectionListeners.create()
def __init__(
self,
ble_dev: BLEDevice,
dev_sn: str,
user_id: str,
data_parse: Callable[[Packet], Awaitable[bool]],
packet_parse: Callable[[bytes], Awaitable[Packet]],
packet_version: int = 0x03,
encrypt_type: int = 7,
auth_header_dst: int = 0x35,
) -> None:
self._ble_dev = ble_dev
self._address = ble_dev.address
self._dev_sn = dev_sn
self._user_id = user_id
self._data_parse = data_parse
self._packet_parse = packet_parse
self._packet_version = packet_version
self._encrypt_type = encrypt_type
self._encryption: EncryptionStrategy | None = None
self._initial_session_key: bytes = b""
self._simple_assembler = SimplePacketAssembler()
self._options = Connection.Options()
self._errors = 0
self._last_errors = deque(maxlen=10)
self._disconnect_log: deque[dict[str, Any]] = deque(maxlen=10)
self._client = None
self._connected = asyncio.Event()
self._disconnected = asyncio.Event()
self._retry_on_disconnect = False
self._retry_on_disconnect_delay = 10
self._auth_header_dst = auth_header_dst
self._tasks: set[asyncio.Task] = set()
self._call_later_handles: dict[str, asyncio.TimerHandle] = {}
self._logger = ConnectionLogger(self)
self._state_changed = asyncio.Event()
self._state_exception: Exception | type[Exception] | None = None
self._last_exception: Exception | type[Exception] | None = None
self._reconnect_task: asyncio.Task | None = None
self._connection_attempt: int = 0
self._reconnect_attempt: int = 0
self._reconnect = True
self._connection_state: ConnectionState = None # pyright: ignore[reportAttributeAccessIssue]
self._state_reason: str | None = None
self._set_state(ConnectionState.CREATED)
@property
def is_connected(self) -> bool:
return self._client is not None and self._client.is_connected
def _add_listener(self, collection: MutableSequence[Callable], listener: Callable):
collection.append(listener)
def _unlisten():
collection.remove(value=listener)
return _unlisten
def on_disconnect(self, listener: DisconnectListener):
"""
Add disconnect listener
Parameters
----------
listener
Listener that will be called on disconnect that receives exception as a
param if one occured before device disconnected
Return
-------
Function to remove this listener
"""
return self._listeners.on_disconnect.add(listener)
def on_state_change(self, listener: ConnectionStateListener):
return self._listeners.on_connection_state_change.add(listener)
def on_packet_data_received(self, listener: PacketReceivedListener):
return self._listeners.on_packet_received.add(listener)
def on_packet_parsed(self, listener: PacketParsedListener):
return self._listeners.on_packet_parsed.add(listener)
def on_data_received(self, listener: DataReceivedListener):
return self._listeners.on_data_received.add(listener)
def on_data_send(self, listener: DataSendListener):
return self._listeners.on_data_send.add(listener)
def _notify_disconnect(self, exception: Exception | type[Exception] | None = None):
if exception is None:
exception = self._last_exception
self._listeners.on_disconnect(exception)
def ble_dev(self) -> BLEDevice:
return self._ble_dev
def with_logging_options(self, options: LogOptions):
self._logger.set_options(options)
return self
def with_disabled_reconnect(self, is_disabled: bool = True):
self._reconnect = not is_disabled
return self
def update_ble_device(self, ble_dev: BLEDevice):
self._ble_dev = ble_dev
def with_options(self, options: "Connection.Options"):
"""Set connection options."""
self._options = options
return self
async def connect(
self,
max_attempts: int | None = None,
):
if self._state.is_connecting:
return
max_attempts = (
max_attempts if max_attempts is not None else MAX_CONNECT_ATTEMPTS
)
self._connection_attempt += 1
if max_attempts != 0 and self._connection_attempt > max_attempts:
self._connection_attempt = 0
err = MaxConnectionAttemptsReached(
last_error=self._last_exception,
attempts=MAX_CONNECTION_ATTEMPTS,
)
self._set_state(ConnectionState.ERROR_MAX_RECONNECT_ATTEMPTS_REACHED, err)
self._notify_disconnect(self._last_exception)
raise err
self._connected.clear()
self._disconnected.clear()
error = None
try:
if self.is_connected:
self._logger.warning("Device is already connected")
return
self._set_state(ConnectionState.ESTABLISHING_CONNECTION)
self._logger.info("Connecting to device")
# max_attempts=0 means unlimited at Connection level, but
# establish_connection needs a real retry count for BLE-level
# attempts (e.g. when adapter slots are contested).
ble_attempts = max_attempts if max_attempts != 0 else MAX_CONNECT_ATTEMPTS
self._client = await establish_connection(
BleakClient,
self.ble_dev(),
self._ble_dev.name,
disconnected_callback=self.disconnected,
ble_device_callback=self.ble_dev,
max_attempts=ble_attempts,
timeout=self._options.timeout,
)
except TimeoutError as e:
error = e
self._set_state(
ConnectionState.ERROR_TIMEOUT,
ConnectionTimeout().with_traceback(e.__traceback__),
)
except BleakNotFoundError as e:
error = e
self._set_state(ConnectionState.ERROR_NOT_FOUND, e)
except BleakError as e:
error = e
self._set_state(ConnectionState.ERROR_BLEAK, e)
if error is not None:
await self._disconnect_client()
self._logger.error("Failed to connect to the device: %s", error)
self._last_errors.append(f"Failed to connect to the device: {error}")
self.disconnected()
return
self._set_state(ConnectionState.CONNECTED)
self._logger.info("Connected")
self._errors = 0
self._retry_on_disconnect = self._reconnect
self._logger.info("Init completed, starting auth routine...")
await self.initBleSessionKey()
def disconnected(self, *args, **kwargs) -> None:
# Traces the trigger: an unsolicited bleak drop shows bleak/asyncio frames here,
# whereas a drop we requested shows our own `disconnect` chain.
trigger = caller_chain()
self._logger.warning("Disconnected from device (%s)", trigger)
self._client = None
# NOTE(gnox): don't trigger disconnect/reconnect logic while
# establish_connection is still retrying internally (bleak_retry_connector
# manages its own retries and will raise on final failure)
if self._state is ConnectionState.ESTABLISHING_CONNECTION:
return
if not self._retry_on_disconnect:
if self._reconnect_task:
self._reconnect_task.cancel()
self._connected.set()
self._disconnected.set()
if self._state is not ConnectionState.DISCONNECTING:
self._notify_disconnect()
self._set_state(ConnectionState.DISCONNECTED, reason=trigger)
return
if self._reconnect_task is not None:
return
loop = asyncio.get_running_loop()
self._reconnect_task = self._add_task(self.reconnect(), loop)
def _reconnect_done(task: asyncio.Task[None]):
self._reconnect_task = None
with contextlib.suppress(asyncio.CancelledError):
if exc := task.exception():
raise exc
self._reconnect_task.add_done_callback(_reconnect_done)
async def reconnect(self) -> None:
# Wait before reconnect
if self._reconnect_attempt == 0:
self._retry_on_disconnect_delay = 10
self._reconnect_attempt += 1
if self._reconnect_attempt > MAX_RECONNECT_ATTEMPTS:
self._logger.error(
"Could not reconnect after %d attempts", MAX_RECONNECT_ATTEMPTS
)
self._set_state(
ConnectionState.ERROR_MAX_RECONNECT_ATTEMPTS_REACHED,
MaxReconnectAttemptsReached(
attempts=MAX_RECONNECT_ATTEMPTS,
last_error=self._last_exception,
),
)
self._notify_disconnect(self._last_exception)
self._reconnect_attempt = 0
return
self._logger.warning(
"Reconnecting to the device in %d seconds, attempt: %d/%d...",
self._retry_on_disconnect_delay,
self._reconnect_attempt,
MAX_RECONNECT_ATTEMPTS,
)
await asyncio.sleep(self._retry_on_disconnect_delay)
if not self._retry_on_disconnect:
self._logger.warning("Reconnect is aborted")
return
self._retry_on_disconnect_delay += 10
self._set_state(ConnectionState.RECONNECTING)
await self.connect()
async def _disconnect_client(self) -> None:
if self._client is None or not self._client.is_connected:
return
trigger = caller_chain()
self._logger.debug("Disconnecting BLE client (%s)", trigger)
outcome = "ok"
try:
async with asyncio.timeout(DISCONNECT_TIMEOUT):
await self._client.disconnect()
except (EOFError, BleakError) as e:
outcome = f"already_down: {e}"
self._logger.warning("Disconnect failed (already down): %s", e)
except TimeoutError:
outcome = "timeout"
self._logger.warning(
"BleakClient.disconnect() did not return within %ss (%s); continuing "
"with local cleanup (write-with-response likely still pending after a "
"mid-auth BLE drop)",
DISCONNECT_TIMEOUT,
trigger,
)
except (OSError, RuntimeError) as e:
outcome = f"transport_broken: {e}"
self._logger.warning(
"BleakClient.disconnect() raised %s (%s); the BLE transport is broken, "
"continuing with local cleanup",
type(e).__name__,
trigger,
)
self._disconnect_log.append(
{"time": time.time(), "trigger": trigger, "outcome": outcome}
)
@property
def disconnect_log(self) -> list[dict[str, Any]]:
"""Recent BLE client disconnect outcomes, for diagnostics"""
return list(self._disconnect_log)
async def disconnect(self, reason: str | None = None) -> None:
self._logger.info("Disconnecting from device (%s)", reason or "no reason given")
self._retry_on_disconnect = False
self._reconnect_attempt = 0
self._cancel_tasks()
if self._client is not None and self._client.is_connected:
self._set_state(ConnectionState.DISCONNECTING, reason=reason)
await self._disconnect_client()
self._client = None
if self._state == ConnectionState.DISCONNECTING:
self._set_state(ConnectionState.DISCONNECTED, reason=reason)
async def _disconnect_error(self, state: ConnectionState, exc: Exception):
self._set_state(state, exc)
await self._disconnect_client()
raise exc
@staticmethod
def _auth_handler(expected_state: ConnectionState):
def decorator(
fn: Callable[
["Connection", BleakGATTCharacteristic, bytearray], Awaitable[None]
],
):
@functools.wraps(fn)
async def wrapper(
self: Self,
characteristic: BleakGATTCharacteristic,
recv_data: bytearray,
):
if self._client is None or not self._client.is_connected:
return
if self._state != expected_state:
return
try:
await fn(self, characteristic, recv_data)
except Exception as e: # noqa: BLE001
await self._disconnect_error(ConnectionState.ERROR_AUTH_FAILED, e)
return wrapper
return decorator
async def wait_connected(self, timeout: int = 20):
"""Will release when connection is happened and authenticated"""
last_state = self._state
if self.is_connected:
return
try:
await asyncio.wait_for(self._connected.wait(), timeout=timeout)
except TimeoutError as e:
last_state = self._state
self._set_state(ConnectionState.ERROR_TIMEOUT, e)
if self._state is not ConnectionState.AUTHENTICATED:
self._set_state(
self._state,
FailedToAuthenticate(
f"Could not connect to device, state: {last_state}"
),
)
async def wait_until_authenticated_or_error(
self, raise_on_error: bool = False, return_exc: bool = False
):
while not self._state.is_terminal:
await self._state_changed.wait()
if (
self._state is ConnectionState.ERROR_MAX_RECONNECT_ATTEMPTS_REACHED
and raise_on_error
):
assert isinstance(self._state_exception, MaxReconnectAttemptsReached)
raise (
self._state_exception.last_error
if self._state_exception.last_error is not None
else self._state_exception
)
if self._state_exception is not None and raise_on_error:
raise self._state_exception
if self._state is ConnectionState.DISCONNECTED:
if return_exc:
return self._last_state, self._state_exception
return self._last_state
if return_exc:
return self._state, self._state_exception
return self._state
async def observe_connection(self):
while True:
yield self._state
await self._state_changed.wait()
async def wait_disconnected(self):
"""Will release when client got disconnected from the device"""
if not self.is_connected:
return
await self._disconnected.wait()
async def add_error(self, exception: Exception):
tb = traceback.format_tb(exception.__traceback__)
self._logger.error("Captured exception: %s:\n%s", exception, "".join(tb))
self._errors += 1
self._last_exception = exception
if self._errors > 5:
# Too much errors happened - let's reconnect
self._errors = 0
self._set_state(ConnectionState.ERROR_TOO_MANY_ERRORS, exception)
if self._client is not None and self._client.is_connected:
self._logger.warning("Client disconnected after encountering 5 errors")
await self._disconnect_client()
def _reset_error_counter(self):
self._errors = 0
@property
def _state(self) -> ConnectionState:
return self._connection_state
@_state.setter
def _state(self, value: ConnectionState):
self._last_state = self._connection_state
self._connection_state = value
self._state_changed.set()
self._state_changed.clear()
self._listeners.on_connection_state_change(value)
@property
def state_reason(self) -> str | None:
return self._state_reason
def _set_state(
self,
state: ConnectionState,
exc: Exception | type[Exception] | None = None,
reason: str | None = None,
):
self._state_exception = exc
if exc is not None:
self._last_exception = exc
self._state_reason = reason
self._state = state
if state.is_error:
self._notify_disconnect(exc)
def set_state(
self, state: ConnectionState, exc: Exception | type[Exception] | None = None
) -> None:
self._set_state(state, exc)
def _get_characteristics(self, char_type: Literal["write", "notify"]):
assert self._client is not None
for uuids in _BT_PROTOCOL_UUIDS.values():
if (
uuid := self._client.services.get_characteristic(uuids[char_type])
) is not None:
return uuid
characteristic_list = [
f"{c.uuid} {c.description} {c.properties}"
for c in self._client.services.characteristics.values()
]
raise UnsupportedBluetoothProtocol("write", characteristic_list)
@cached_property
def _notify_characteristic(self):
return self._get_characteristics("notify")
@cached_property
def _write_characteristic(self):
return self._get_characteristics("write")
async def genSessionKey(self, seed: bytes, srand: bytes):
"""Implements the necessary part of the logic, rest is skipped"""
data_num = [0, 0, 0, 0]
# Using seed and predefined key to get first 2 numbers
pos = seed[0] * 0x10 + ((seed[1] - 1) & 0xFF) * 0x100
data_num[0] = struct.unpack("<Q", keydata.get8bytes(pos))[0]
pos += 8
data_num[1] = struct.unpack("<Q", keydata.get8bytes(pos))[0]
# Getting the last 2 numbers from srand
srand_len = len(srand)
# lower_srand_len = srand_len & 0xFFFFFFFF
if srand_len < 0x20:
srand_len = 0
else:
raise NotImplementedError
# Just putting srand in there byte-by-byte
data_num[2] = struct.unpack("<Q", srand[0:8])[0]
data_num[3] = struct.unpack("<Q", srand[8:16])[0]
# Converting data numbers to 32 bytes
data = b""
data += struct.pack("<Q", data_num[0])
data += struct.pack("<Q", data_num[1])
data += struct.pack("<Q", data_num[2])
data += struct.pack("<Q", data_num[3])
# Hashing data to get the session key
return hashlib.md5(data).digest()
async def parseSimple(self, data: bytes) -> bytes | None:
"""Deserializes bytes stream into the simple bytes"""
self._listeners.on_data_received(data, self._connection_state)
self._logger.log_filtered(
LogOptions.ENCRYPTED_PAYLOADS,
"parseSimple: Data: %r",
data,
)
try:
return self._simple_assembler.parse(data)
except PacketParseError as e:
error_msg = "parseSimple: Unable to parse simple packet: %r"
self._logger.error(error_msg, str(e))
self._last_errors.append(error_msg % str(e))
raise
async def parseEncPackets(self, data: bytes) -> list[Packet]:
"""Deserializes bytes stream into a list of Packets"""
self._listeners.on_data_received(data, self._connection_state)
self._logger.log_filtered(
LogOptions.ENCRYPTED_PAYLOADS,
"parseEncPackets: Data: %r",
data,
)
frame_assembler = (
self._frame_assembler
if self._connection_state.received_session_key
else self._create_frame_assembler()
)
decoded_payloads = await frame_assembler.reassemble(data)
packets = []
for payload in decoded_payloads:
try:
self._listeners.on_packet_received(payload)
packet = await self._packet_parse(payload)
self._listeners.on_packet_parsed(packet)
self._logger.log_filtered(
LogOptions.DECRYPTED_PAYLOADS,
"decrypted payload: '%s'",
payload,
)
self._logger.log_filtered(
LogOptions.PACKETS,
"Parsed packet: %s",
packet,
)
if not Packet.is_invalid(packet):
packets.append(packet)
except Exception as e: # noqa: BLE001
await self.add_error(e)
return packets
async def sendRequest(self, send_data: bytes, response_handler=None):
self._logger.log_filtered(LogOptions.CONNECTION_DEBUG, "Sending: %r", send_data)
self._listeners.on_data_send(send_data)
# In case exception happens we need to try again
err = None
for retry in range(4):
try:
await self._sendRequest(send_data, response_handler)
except Exception as e: # noqa: BLE001
if self._client is None or not self._client.is_connected:
# The BLE link dropped mid-request - e.g. BlueZ raising "Remote peer
# disconnected" synchronously from start_notify. bleak does not
# always fire its disconnected callback for a synchronous GATT
# failure, so nothing else would drive a reconnect and
# `wait_until_authenticated_or_error` hangs forever.
self._logger.warning(
"BLE link lost while sending request (%s); reconnecting", e
)
self.disconnected()
return
self._logger.log_filtered(
LogOptions.CONNECTION_DEBUG,
(
"Exception occured when sending request on try %d: %s, "
"retrying in %d seconds"
),
retry,
str(e),
retry + 1,
level=logging.WARNING,
)
if err is None:
err = e
await asyncio.sleep(retry + 1)
continue
else:
return
await self.add_error(err)
async def _start_notify(self, callback: Callable):
kwargs = {}
if self._options.bluez_start_notify:
kwargs["bluez"] = {"use_start_notify": True}
await self._client.start_notify(self._notify_characteristic, callback, **kwargs)
async def _sendRequest(self, send_data: bytes, response_handler=None):
# Make sure the connection is here, otherwise just skipping
if self._client is None or not self._client.is_connected:
self._logger.log_filtered(
LogOptions.CONNECTION_DEBUG,
"Skip sending: disconnected: %r",
send_data,
)
return
if response_handler:
await self._start_notify(response_handler)
await self._client.write_gatt_char(
self._write_characteristic, bytearray(send_data)
)
async def sendPacket(
self, packet: Packet, response_handler=None, wait_for_response: bool = True
):
self._logger.log_filtered(
LogOptions.CONNECTION_DEBUG, "Sending packet: %r", packet
)
frame_assembler = (
self._frame_assembler
if self._connection_state.received_session_key
else self._create_frame_assembler()
)
to_send = await frame_assembler.encode(packet)
if frame_assembler.write_with_response and wait_for_response:
await self.sendRequest(to_send, response_handler)
elif self._client is not None and self._client.is_connected:
await self._client.write_gatt_char(
self._write_characteristic, bytearray(to_send), response=False
)
async def replyPacket(self, packet: Packet):
"""Copy and change the packet to be reply packet and sends it back to device"""
# Found it's necesary to send back the packets, otherwise device will not send
# moar info then strict minimum - which just about power params, but not configs
# & advanced params
reply_packet = Packet(
packet.dst, # Switching src to dst
packet.src, # Switching dst to src
packet.cmd_set,
packet.cmd_id,
packet.payload,
0x01,
0x01, # Replacing 0 with 1
packet.version,
packet.seq,
packet.product_id,
)
# Running reply asynchroneously
self._add_task(self.sendPacket(reply_packet))
async def initBleSessionKey(self):
match self._encrypt_type:
case 0:
await self._type_0_session()
case 1:
await self._type_1_session()
case _:
await self._ecdh_key_exchange()
async def _type_0_session(self):
self._encryption = None
await self._start_notify(self.listenForDataHandler)
await self.send_auth_status_packet()
await self.autoAuthentication()
async def _type_1_session(self):
session_key = hashlib.md5(self._dev_sn.encode()).digest()
iv = hashlib.md5(self._dev_sn[::-1].encode()).digest()
self._encryption = Type1Encryption(session_key, iv)
await self._start_notify(self.listenForDataHandler)
await self.send_auth_status_packet()
await self.autoAuthentication()
async def _ecdh_key_exchange(self):
self._set_state(ConnectionState.PUBLIC_KEY_EXCHANGE)
self._logger.log_filtered(
LogOptions.CONNECTION_DEBUG, "initBleSessionKey: Pub key exchange"
)
self._private_key = ecdsa.SigningKey.generate(curve=ecdsa.SECP160r1)
self._public_key: ecdsa.VerifyingKey = self._private_key.get_verifying_key() # pyright: ignore[reportAttributeAccessIssue]
to_send = SimplePacketAssembler.encode(
# Payload contains some weird prefix and generated public key
b"\x01\x00" + self._public_key.to_string(),
)
# Device public key is sent as response, process will continue on device
# response in handler
await self.sendRequest(to_send, self.initBleSessionKeyHandler)
@_auth_handler(ConnectionState.PUBLIC_KEY_EXCHANGE)
async def initBleSessionKeyHandler(
self, characteristic: BleakGATTCharacteristic, recv_data: bytearray
):
data = await self.parseSimple(bytes(recv_data))
if data is None:
return
self._set_state(ConnectionState.PUBLIC_KEY_RECEIVED)
await self._client.stop_notify(self._notify_characteristic)
if len(data) < 3:
raise PacketParseError(
"Incorrect size of the returned pub key data: " + data.hex()
)
# status = data[1]
ecdh_type_size = getEcdhTypeSize(data[2])
self._dev_pub_key = ecdsa.VerifyingKey.from_string(
data[3 : ecdh_type_size + 3], curve=ecdsa.SECP160r1
)
# Generating shared key from our private key and received device public key
# NOTE: The device will do the same with it's private key and our public key to
# generate the # same shared key value and use it to encrypt/decrypt using
# symmetric encryption algorithm
shared_key = ecdsa.ECDH(
ecdsa.SECP160r1, self._private_key, self._dev_pub_key
).generate_sharedsecret_bytes()
# Set Initialization Vector from digest of the original shared key
iv = hashlib.md5(shared_key).digest()
self._encryption = Type7Encryption(shared_key[:16], iv)
await self.getKeyInfoReq()
async def getKeyInfoReq(self):
self._set_state(ConnectionState.REQUESTING_SESSION_KEY)
self._logger.log_filtered(
LogOptions.CONNECTION_DEBUG, "getKeyInfoReq: Receiving session key"
)
to_send = SimplePacketAssembler.encode(
b"\x02", # command to get key info to make the shared key
)
await self.sendRequest(to_send, self.getKeyInfoReqHandler)
@_auth_handler(ConnectionState.REQUESTING_SESSION_KEY)
async def getKeyInfoReqHandler(
self, characteristic: BleakGATTCharacteristic, recv_data: bytearray