-
Notifications
You must be signed in to change notification settings - Fork 62
/
device.py
4817 lines (4184 loc) · 178 KB
/
device.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
# Copyright 2021-2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from __future__ import annotations
import asyncio
from collections.abc import Iterable
from contextlib import (
asynccontextmanager,
AsyncExitStack,
closing,
)
import copy
from dataclasses import dataclass, field
from enum import Enum, IntEnum
import functools
import json
import logging
import secrets
import sys
from typing import (
Any,
Callable,
ClassVar,
Dict,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
cast,
overload,
TYPE_CHECKING,
)
from typing_extensions import Self
from pyee import EventEmitter
from .colors import color
from .att import ATT_CID, ATT_DEFAULT_MTU, ATT_PDU
from .gatt import Characteristic, Descriptor, Service
from .hci import (
HCI_AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P_192_TYPE,
HCI_AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P_256_TYPE,
HCI_CENTRAL_ROLE,
HCI_PERIPHERAL_ROLE,
HCI_COMMAND_STATUS_PENDING,
HCI_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES_ERROR,
HCI_DISPLAY_YES_NO_IO_CAPABILITY,
HCI_DISPLAY_ONLY_IO_CAPABILITY,
HCI_EXTENDED_INQUIRY_MODE,
HCI_GENERAL_INQUIRY_LAP,
HCI_INVALID_HCI_COMMAND_PARAMETERS_ERROR,
HCI_KEYBOARD_ONLY_IO_CAPABILITY,
HCI_LE_1M_PHY,
HCI_LE_1M_PHY_BIT,
HCI_LE_2M_PHY,
HCI_LE_CODED_PHY,
HCI_LE_CODED_PHY_BIT,
HCI_LE_EXTENDED_CREATE_CONNECTION_COMMAND,
HCI_LE_RAND_COMMAND,
HCI_LE_READ_PHY_COMMAND,
HCI_LE_SET_PHY_COMMAND,
HCI_MITM_NOT_REQUIRED_GENERAL_BONDING_AUTHENTICATION_REQUIREMENTS,
HCI_MITM_NOT_REQUIRED_NO_BONDING_AUTHENTICATION_REQUIREMENTS,
HCI_MITM_REQUIRED_GENERAL_BONDING_AUTHENTICATION_REQUIREMENTS,
HCI_MITM_REQUIRED_NO_BONDING_AUTHENTICATION_REQUIREMENTS,
HCI_NO_INPUT_NO_OUTPUT_IO_CAPABILITY,
HCI_OPERATION_CANCELLED_BY_HOST_ERROR,
HCI_R2_PAGE_SCAN_REPETITION_MODE,
HCI_REMOTE_USER_TERMINATED_CONNECTION_ERROR,
HCI_SUCCESS,
HCI_WRITE_LE_HOST_SUPPORT_COMMAND,
HCI_Accept_Connection_Request_Command,
HCI_Authentication_Requested_Command,
HCI_Command_Status_Event,
HCI_Constant,
HCI_Create_Connection_Cancel_Command,
HCI_Create_Connection_Command,
HCI_Connection_Complete_Event,
HCI_Disconnect_Command,
HCI_Encryption_Change_Event,
HCI_Error,
HCI_IO_Capability_Request_Reply_Command,
HCI_Inquiry_Cancel_Command,
HCI_Inquiry_Command,
HCI_IsoDataPacket,
HCI_LE_Accept_CIS_Request_Command,
HCI_LE_Add_Device_To_Resolving_List_Command,
HCI_LE_Advertising_Report_Event,
HCI_LE_BIGInfo_Advertising_Report_Event,
HCI_LE_Clear_Resolving_List_Command,
HCI_LE_Connection_Update_Command,
HCI_LE_Create_Connection_Cancel_Command,
HCI_LE_Create_Connection_Command,
HCI_LE_Create_CIS_Command,
HCI_LE_Periodic_Advertising_Create_Sync_Command,
HCI_LE_Periodic_Advertising_Create_Sync_Cancel_Command,
HCI_LE_Periodic_Advertising_Report_Event,
HCI_LE_Periodic_Advertising_Terminate_Sync_Command,
HCI_LE_Enable_Encryption_Command,
HCI_LE_Extended_Advertising_Report_Event,
HCI_LE_Extended_Create_Connection_Command,
HCI_LE_Rand_Command,
HCI_LE_Read_PHY_Command,
HCI_LE_Read_Remote_Features_Command,
HCI_LE_Reject_CIS_Request_Command,
HCI_LE_Remove_Advertising_Set_Command,
HCI_LE_Set_Address_Resolution_Enable_Command,
HCI_LE_Set_Advertising_Data_Command,
HCI_LE_Set_Advertising_Enable_Command,
HCI_LE_Set_Advertising_Parameters_Command,
HCI_LE_Set_Advertising_Set_Random_Address_Command,
HCI_LE_Set_CIG_Parameters_Command,
HCI_LE_Set_Data_Length_Command,
HCI_LE_Set_Default_PHY_Command,
HCI_LE_Set_Extended_Scan_Enable_Command,
HCI_LE_Set_Extended_Scan_Parameters_Command,
HCI_LE_Set_Extended_Scan_Response_Data_Command,
HCI_LE_Set_Extended_Advertising_Data_Command,
HCI_LE_Set_Extended_Advertising_Enable_Command,
HCI_LE_Set_Extended_Advertising_Parameters_Command,
HCI_LE_Set_Host_Feature_Command,
HCI_LE_Set_Periodic_Advertising_Enable_Command,
HCI_LE_Set_PHY_Command,
HCI_LE_Set_Random_Address_Command,
HCI_LE_Set_Scan_Enable_Command,
HCI_LE_Set_Scan_Parameters_Command,
HCI_LE_Set_Scan_Response_Data_Command,
HCI_PIN_Code_Request_Reply_Command,
HCI_PIN_Code_Request_Negative_Reply_Command,
HCI_Read_BD_ADDR_Command,
HCI_Read_RSSI_Command,
HCI_Reject_Connection_Request_Command,
HCI_Remote_Name_Request_Command,
HCI_Switch_Role_Command,
HCI_Set_Connection_Encryption_Command,
HCI_StatusError,
HCI_SynchronousDataPacket,
HCI_User_Confirmation_Request_Negative_Reply_Command,
HCI_User_Confirmation_Request_Reply_Command,
HCI_User_Passkey_Request_Negative_Reply_Command,
HCI_User_Passkey_Request_Reply_Command,
HCI_Write_Class_Of_Device_Command,
HCI_Write_Extended_Inquiry_Response_Command,
HCI_Write_Inquiry_Mode_Command,
HCI_Write_LE_Host_Support_Command,
HCI_Write_Local_Name_Command,
HCI_Write_Scan_Enable_Command,
HCI_Write_Secure_Connections_Host_Support_Command,
HCI_Write_Simple_Pairing_Mode_Command,
Address,
OwnAddressType,
LeFeature,
LeFeatureMask,
Phy,
phy_list_to_bits,
)
from .host import Host
from .gap import GenericAccessService
from .core import (
BT_BR_EDR_TRANSPORT,
BT_CENTRAL_ROLE,
BT_LE_TRANSPORT,
BT_PERIPHERAL_ROLE,
AdvertisingData,
ConnectionParameterUpdateError,
CommandTimeoutError,
ConnectionPHY,
InvalidStateError,
)
from .utils import (
AsyncRunner,
CompositeEventEmitter,
EventWatcher,
setup_event_forwarding,
composite_listener,
deprecated,
experimental,
)
from .keys import (
KeyStore,
PairingKeys,
)
from .pairing import PairingConfig
from . import gatt_client
from . import gatt_server
from . import smp
from . import sdp
from . import l2cap
from . import core
if TYPE_CHECKING:
from .transport.common import TransportSource, TransportSink
# -----------------------------------------------------------------------------
# Logging
# -----------------------------------------------------------------------------
logger = logging.getLogger(__name__)
# -----------------------------------------------------------------------------
# Constants
# -----------------------------------------------------------------------------
# fmt: off
# pylint: disable=line-too-long
DEVICE_MIN_SCAN_INTERVAL = 25
DEVICE_MAX_SCAN_INTERVAL = 10240
DEVICE_MIN_SCAN_WINDOW = 25
DEVICE_MAX_SCAN_WINDOW = 10240
DEVICE_MIN_LE_RSSI = -127
DEVICE_MAX_LE_RSSI = 20
DEVICE_MIN_EXTENDED_ADVERTISING_SET_HANDLE = 0x00
DEVICE_MAX_EXTENDED_ADVERTISING_SET_HANDLE = 0xEF
DEVICE_DEFAULT_ADDRESS = '00:00:00:00:00:00'
DEVICE_DEFAULT_ADVERTISING_INTERVAL = 1000 # ms
DEVICE_DEFAULT_ADVERTISING_DATA = ''
DEVICE_DEFAULT_NAME = 'Bumble'
DEVICE_DEFAULT_INQUIRY_LENGTH = 8 # 10.24 seconds
DEVICE_DEFAULT_CLASS_OF_DEVICE = 0
DEVICE_DEFAULT_SCAN_RESPONSE_DATA = b''
DEVICE_DEFAULT_DATA_LENGTH = (27, 328, 27, 328)
DEVICE_DEFAULT_SCAN_INTERVAL = 60 # ms
DEVICE_DEFAULT_SCAN_WINDOW = 60 # ms
DEVICE_DEFAULT_CONNECT_TIMEOUT = None # No timeout
DEVICE_DEFAULT_CONNECT_SCAN_INTERVAL = 60 # ms
DEVICE_DEFAULT_CONNECT_SCAN_WINDOW = 60 # ms
DEVICE_DEFAULT_CONNECTION_INTERVAL_MIN = 15 # ms
DEVICE_DEFAULT_CONNECTION_INTERVAL_MAX = 30 # ms
DEVICE_DEFAULT_CONNECTION_MAX_LATENCY = 0
DEVICE_DEFAULT_CONNECTION_SUPERVISION_TIMEOUT = 720 # ms
DEVICE_DEFAULT_CONNECTION_MIN_CE_LENGTH = 0 # ms
DEVICE_DEFAULT_CONNECTION_MAX_CE_LENGTH = 0 # ms
DEVICE_DEFAULT_L2CAP_COC_MTU = l2cap.L2CAP_LE_CREDIT_BASED_CONNECTION_DEFAULT_MTU
DEVICE_DEFAULT_L2CAP_COC_MPS = l2cap.L2CAP_LE_CREDIT_BASED_CONNECTION_DEFAULT_MPS
DEVICE_DEFAULT_L2CAP_COC_MAX_CREDITS = l2cap.L2CAP_LE_CREDIT_BASED_CONNECTION_DEFAULT_INITIAL_CREDITS
DEVICE_DEFAULT_ADVERTISING_TX_POWER = (
HCI_LE_Set_Extended_Advertising_Parameters_Command.TX_POWER_NO_PREFERENCE
)
DEVICE_DEFAULT_PERIODIC_ADVERTISING_SYNC_SKIP = 0
DEVICE_DEFAULT_PERIODIC_ADVERTISING_SYNC_TIMEOUT = 5.0
# fmt: on
# pylint: enable=line-too-long
# As specified in 7.8.56 LE Set Extended Advertising Enable command
DEVICE_MAX_HIGH_DUTY_CYCLE_CONNECTABLE_DIRECTED_ADVERTISING_DURATION = 1.28
# -----------------------------------------------------------------------------
# Classes
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
@dataclass
class Advertisement:
# Attributes
address: Address
rssi: int = HCI_LE_Extended_Advertising_Report_Event.RSSI_NOT_AVAILABLE
is_legacy: bool = False
is_anonymous: bool = False
is_connectable: bool = False
is_directed: bool = False
is_scannable: bool = False
is_scan_response: bool = False
is_complete: bool = True
is_truncated: bool = False
primary_phy: int = 0
secondary_phy: int = 0
tx_power: int = (
HCI_LE_Extended_Advertising_Report_Event.TX_POWER_INFORMATION_NOT_AVAILABLE
)
sid: int = 0
data_bytes: bytes = b''
# Constants
TX_POWER_NOT_AVAILABLE: ClassVar[int] = (
HCI_LE_Extended_Advertising_Report_Event.TX_POWER_INFORMATION_NOT_AVAILABLE
)
RSSI_NOT_AVAILABLE: ClassVar[int] = (
HCI_LE_Extended_Advertising_Report_Event.RSSI_NOT_AVAILABLE
)
def __post_init__(self) -> None:
self.data = AdvertisingData.from_bytes(self.data_bytes)
@classmethod
def from_advertising_report(cls, report) -> Optional[Advertisement]:
if isinstance(report, HCI_LE_Advertising_Report_Event.Report):
return LegacyAdvertisement.from_advertising_report(report)
if isinstance(report, HCI_LE_Extended_Advertising_Report_Event.Report):
return ExtendedAdvertisement.from_advertising_report(report)
return None
# -----------------------------------------------------------------------------
class LegacyAdvertisement(Advertisement):
@classmethod
def from_advertising_report(cls, report):
return cls(
address=report.address,
rssi=report.rssi,
is_legacy=True,
is_connectable=report.event_type
in (
HCI_LE_Advertising_Report_Event.ADV_IND,
HCI_LE_Advertising_Report_Event.ADV_DIRECT_IND,
),
is_directed=report.event_type
== HCI_LE_Advertising_Report_Event.ADV_DIRECT_IND,
is_scannable=report.event_type
in (
HCI_LE_Advertising_Report_Event.ADV_IND,
HCI_LE_Advertising_Report_Event.ADV_SCAN_IND,
),
is_scan_response=report.event_type
== HCI_LE_Advertising_Report_Event.SCAN_RSP,
data_bytes=report.data,
)
# -----------------------------------------------------------------------------
class ExtendedAdvertisement(Advertisement):
@classmethod
def from_advertising_report(cls, report):
# fmt: off
# pylint: disable=line-too-long
return cls(
address = report.address,
rssi = report.rssi,
is_legacy = report.event_type & (1 << HCI_LE_Extended_Advertising_Report_Event.LEGACY_ADVERTISING_PDU_USED) != 0,
is_anonymous = report.address.address_type == HCI_LE_Extended_Advertising_Report_Event.ANONYMOUS_ADDRESS_TYPE,
is_connectable = report.event_type & (1 << HCI_LE_Extended_Advertising_Report_Event.CONNECTABLE_ADVERTISING) != 0,
is_directed = report.event_type & (1 << HCI_LE_Extended_Advertising_Report_Event.DIRECTED_ADVERTISING) != 0,
is_scannable = report.event_type & (1 << HCI_LE_Extended_Advertising_Report_Event.SCANNABLE_ADVERTISING) != 0,
is_scan_response = report.event_type & (1 << HCI_LE_Extended_Advertising_Report_Event.SCAN_RESPONSE) != 0,
is_complete = (report.event_type >> 5 & 3) == HCI_LE_Extended_Advertising_Report_Event.DATA_COMPLETE,
is_truncated = (report.event_type >> 5 & 3) == HCI_LE_Extended_Advertising_Report_Event.DATA_INCOMPLETE_TRUNCATED_NO_MORE_TO_COME,
primary_phy = report.primary_phy,
secondary_phy = report.secondary_phy,
tx_power = report.tx_power,
sid = report.advertising_sid,
data_bytes = report.data
)
# fmt: on
# -----------------------------------------------------------------------------
class AdvertisementDataAccumulator:
def __init__(self, passive=False):
self.passive = passive
self.last_advertisement = None
self.last_data = b''
def update(self, report):
advertisement = Advertisement.from_advertising_report(report)
if advertisement is None:
return None
result = None
if advertisement.is_scan_response:
if (
self.last_advertisement is not None
and not self.last_advertisement.is_scan_response
):
# This is the response to a scannable advertisement
result = Advertisement.from_advertising_report(report)
result.is_connectable = self.last_advertisement.is_connectable
result.is_scannable = True
result.data = AdvertisingData.from_bytes(self.last_data + report.data)
self.last_data = b''
else:
if (
self.passive
or (not advertisement.is_scannable)
or (
self.last_advertisement is not None
and not self.last_advertisement.is_scan_response
)
):
# Don't wait for a scan response
result = Advertisement.from_advertising_report(report)
self.last_data = report.data
self.last_advertisement = advertisement
return result
# -----------------------------------------------------------------------------
class AdvertisingType(IntEnum):
# fmt: off
# pylint: disable=line-too-long
UNDIRECTED_CONNECTABLE_SCANNABLE = 0x00 # Undirected, connectable, scannable
DIRECTED_CONNECTABLE_HIGH_DUTY = 0x01 # Directed, connectable, non-scannable
UNDIRECTED_SCANNABLE = 0x02 # Undirected, non-connectable, scannable
UNDIRECTED = 0x03 # Undirected, non-connectable, non-scannable
DIRECTED_CONNECTABLE_LOW_DUTY = 0x04 # Directed, connectable, non-scannable
# fmt: on
@property
def has_data(self) -> bool:
return self in (
AdvertisingType.UNDIRECTED_CONNECTABLE_SCANNABLE,
AdvertisingType.UNDIRECTED_SCANNABLE,
AdvertisingType.UNDIRECTED,
)
@property
def is_connectable(self) -> bool:
return self in (
AdvertisingType.UNDIRECTED_CONNECTABLE_SCANNABLE,
AdvertisingType.DIRECTED_CONNECTABLE_HIGH_DUTY,
AdvertisingType.DIRECTED_CONNECTABLE_LOW_DUTY,
)
@property
def is_scannable(self) -> bool:
return self in (
AdvertisingType.UNDIRECTED_CONNECTABLE_SCANNABLE,
AdvertisingType.UNDIRECTED_SCANNABLE,
)
@property
def is_directed(self) -> bool:
return self in (
AdvertisingType.DIRECTED_CONNECTABLE_HIGH_DUTY,
AdvertisingType.DIRECTED_CONNECTABLE_LOW_DUTY,
)
@property
def is_high_duty_cycle_directed_connectable(self):
return self == AdvertisingType.DIRECTED_CONNECTABLE_HIGH_DUTY
# -----------------------------------------------------------------------------
@dataclass
class LegacyAdvertiser:
device: Device
advertising_type: AdvertisingType
own_address_type: OwnAddressType
peer_address: Address
auto_restart: bool
async def start(self) -> None:
# Set/update the advertising data if the advertising type allows it
if self.advertising_type.has_data:
await self.device.send_command(
HCI_LE_Set_Advertising_Data_Command(
advertising_data=self.device.advertising_data
),
check_result=True,
)
# Set/update the scan response data if the advertising is scannable
if self.advertising_type.is_scannable:
await self.device.send_command(
HCI_LE_Set_Scan_Response_Data_Command(
scan_response_data=self.device.scan_response_data
),
check_result=True,
)
# Set the advertising parameters
await self.device.send_command(
HCI_LE_Set_Advertising_Parameters_Command(
advertising_interval_min=self.device.advertising_interval_min,
advertising_interval_max=self.device.advertising_interval_max,
advertising_type=int(self.advertising_type),
own_address_type=self.own_address_type,
peer_address_type=self.peer_address.address_type,
peer_address=self.peer_address,
advertising_channel_map=7,
advertising_filter_policy=0,
),
check_result=True,
)
# Enable advertising
await self.device.send_command(
HCI_LE_Set_Advertising_Enable_Command(advertising_enable=1),
check_result=True,
)
async def stop(self) -> None:
# Disable advertising
await self.device.send_command(
HCI_LE_Set_Advertising_Enable_Command(advertising_enable=0),
check_result=True,
)
# -----------------------------------------------------------------------------
@dataclass
class AdvertisingEventProperties:
is_connectable: bool = True
is_scannable: bool = False
is_directed: bool = False
is_high_duty_cycle_directed_connectable: bool = False
is_legacy: bool = False
is_anonymous: bool = False
include_tx_power: bool = False
def __int__(self) -> int:
properties = (
HCI_LE_Set_Extended_Advertising_Parameters_Command.AdvertisingProperties(0)
)
if self.is_connectable:
properties |= properties.CONNECTABLE_ADVERTISING
if self.is_scannable:
properties |= properties.SCANNABLE_ADVERTISING
if self.is_directed:
properties |= properties.DIRECTED_ADVERTISING
if self.is_high_duty_cycle_directed_connectable:
properties |= properties.HIGH_DUTY_CYCLE_DIRECTED_CONNECTABLE_ADVERTISING
if self.is_legacy:
properties |= properties.USE_LEGACY_ADVERTISING_PDUS
if self.is_anonymous:
properties |= properties.ANONYMOUS_ADVERTISING
if self.include_tx_power:
properties |= properties.INCLUDE_TX_POWER
return int(properties)
@classmethod
def from_advertising_type(
cls: Type[AdvertisingEventProperties],
advertising_type: AdvertisingType,
) -> AdvertisingEventProperties:
return cls(
is_connectable=advertising_type.is_connectable,
is_scannable=advertising_type.is_scannable,
is_directed=advertising_type.is_directed,
is_high_duty_cycle_directed_connectable=advertising_type.is_high_duty_cycle_directed_connectable,
is_legacy=True,
is_anonymous=False,
include_tx_power=False,
)
# -----------------------------------------------------------------------------
@dataclass
class PeriodicAdvertisement:
address: Address
sid: int
tx_power: int = (
HCI_LE_Periodic_Advertising_Report_Event.TX_POWER_INFORMATION_NOT_AVAILABLE
)
rssi: int = HCI_LE_Periodic_Advertising_Report_Event.RSSI_NOT_AVAILABLE
is_truncated: bool = False
data_bytes: bytes = b''
# Constants
TX_POWER_NOT_AVAILABLE: ClassVar[int] = (
HCI_LE_Periodic_Advertising_Report_Event.TX_POWER_INFORMATION_NOT_AVAILABLE
)
RSSI_NOT_AVAILABLE: ClassVar[int] = (
HCI_LE_Periodic_Advertising_Report_Event.RSSI_NOT_AVAILABLE
)
def __post_init__(self) -> None:
self.data = (
None if self.is_truncated else AdvertisingData.from_bytes(self.data_bytes)
)
# -----------------------------------------------------------------------------
@dataclass
class BIGInfoAdvertisement:
address: Address
sid: int
num_bis: int
nse: int
iso_interval: int
bn: int
pto: int
irc: int
max_pdu: int
sdu_interval: int
max_sdu: int
phy: Phy
framed: bool
encrypted: bool
@classmethod
def from_report(cls, address: Address, sid: int, report) -> Self:
return cls(
address,
sid,
report.num_bis,
report.nse,
report.iso_interval,
report.bn,
report.pto,
report.irc,
report.max_pdu,
report.sdu_interval,
report.max_sdu,
Phy(report.phy),
report.framing != 0,
report.encryption != 0,
)
# -----------------------------------------------------------------------------
# TODO: replace with typing.TypeAlias when the code base is all Python >= 3.10
AdvertisingChannelMap = HCI_LE_Set_Extended_Advertising_Parameters_Command.ChannelMap
# -----------------------------------------------------------------------------
@dataclass
class AdvertisingParameters:
# pylint: disable=line-too-long
advertising_event_properties: AdvertisingEventProperties = field(
default_factory=AdvertisingEventProperties
)
primary_advertising_interval_min: int = DEVICE_DEFAULT_ADVERTISING_INTERVAL
primary_advertising_interval_max: int = DEVICE_DEFAULT_ADVERTISING_INTERVAL
primary_advertising_channel_map: (
HCI_LE_Set_Extended_Advertising_Parameters_Command.ChannelMap
) = (
AdvertisingChannelMap.CHANNEL_37
| AdvertisingChannelMap.CHANNEL_38
| AdvertisingChannelMap.CHANNEL_39
)
own_address_type: OwnAddressType = OwnAddressType.RANDOM
peer_address: Address = Address.ANY
advertising_filter_policy: int = 0
advertising_tx_power: int = DEVICE_DEFAULT_ADVERTISING_TX_POWER
primary_advertising_phy: Phy = Phy.LE_1M
secondary_advertising_max_skip: int = 0
secondary_advertising_phy: Phy = Phy.LE_1M
advertising_sid: int = 0
enable_scan_request_notifications: bool = False
primary_advertising_phy_options: int = 0
secondary_advertising_phy_options: int = 0
# -----------------------------------------------------------------------------
@dataclass
class PeriodicAdvertisingParameters:
# TODO implement this class
pass
# -----------------------------------------------------------------------------
@dataclass
class AdvertisingSet(EventEmitter):
device: Device
advertising_handle: int
auto_restart: bool
random_address: Optional[Address]
advertising_parameters: AdvertisingParameters
advertising_data: bytes
scan_response_data: bytes
periodic_advertising_parameters: Optional[PeriodicAdvertisingParameters]
periodic_advertising_data: bytes
selected_tx_power: int = 0
enabled: bool = False
def __post_init__(self) -> None:
super().__init__()
async def set_advertising_parameters(
self, advertising_parameters: AdvertisingParameters
) -> None:
# Compliance check
if (
not advertising_parameters.advertising_event_properties.is_legacy
and advertising_parameters.advertising_event_properties.is_connectable
and advertising_parameters.advertising_event_properties.is_scannable
):
logger.warning(
"non-legacy extended advertising event properties may not be both "
"connectable and scannable"
)
response = await self.device.send_command(
HCI_LE_Set_Extended_Advertising_Parameters_Command(
advertising_handle=self.advertising_handle,
advertising_event_properties=int(
advertising_parameters.advertising_event_properties
),
primary_advertising_interval_min=(
int(advertising_parameters.primary_advertising_interval_min / 0.625)
),
primary_advertising_interval_max=(
int(advertising_parameters.primary_advertising_interval_min / 0.625)
),
primary_advertising_channel_map=int(
advertising_parameters.primary_advertising_channel_map
),
own_address_type=advertising_parameters.own_address_type,
peer_address_type=advertising_parameters.peer_address.address_type,
peer_address=advertising_parameters.peer_address,
advertising_tx_power=advertising_parameters.advertising_tx_power,
advertising_filter_policy=(
advertising_parameters.advertising_filter_policy
),
primary_advertising_phy=advertising_parameters.primary_advertising_phy,
secondary_advertising_max_skip=(
advertising_parameters.secondary_advertising_max_skip
),
secondary_advertising_phy=(
advertising_parameters.secondary_advertising_phy
),
advertising_sid=advertising_parameters.advertising_sid,
scan_request_notification_enable=(
1 if advertising_parameters.enable_scan_request_notifications else 0
),
),
check_result=True,
)
self.selected_tx_power = response.return_parameters.selected_tx_power
self.advertising_parameters = advertising_parameters
async def set_advertising_data(self, advertising_data: bytes) -> None:
# pylint: disable=line-too-long
await self.device.send_command(
HCI_LE_Set_Extended_Advertising_Data_Command(
advertising_handle=self.advertising_handle,
operation=HCI_LE_Set_Extended_Advertising_Data_Command.Operation.COMPLETE_DATA,
fragment_preference=HCI_LE_Set_Extended_Advertising_Parameters_Command.SHOULD_NOT_FRAGMENT,
advertising_data=advertising_data,
),
check_result=True,
)
self.advertising_data = advertising_data
async def set_scan_response_data(self, scan_response_data: bytes) -> None:
# pylint: disable=line-too-long
if (
scan_response_data
and not self.advertising_parameters.advertising_event_properties.is_scannable
):
logger.warning(
"ignoring attempt to set non-empty scan response data on non-scannable "
"advertising set"
)
return
await self.device.send_command(
HCI_LE_Set_Extended_Scan_Response_Data_Command(
advertising_handle=self.advertising_handle,
operation=HCI_LE_Set_Extended_Advertising_Data_Command.Operation.COMPLETE_DATA,
fragment_preference=HCI_LE_Set_Extended_Advertising_Parameters_Command.SHOULD_NOT_FRAGMENT,
scan_response_data=scan_response_data,
),
check_result=True,
)
self.scan_response_data = scan_response_data
async def set_periodic_advertising_parameters(
self, advertising_parameters: PeriodicAdvertisingParameters
) -> None:
# TODO: send command
self.periodic_advertising_parameters = advertising_parameters
async def set_periodic_advertising_data(self, advertising_data: bytes) -> None:
# TODO: send command
self.periodic_advertising_data = advertising_data
async def set_random_address(self, random_address: Address) -> None:
await self.device.send_command(
HCI_LE_Set_Advertising_Set_Random_Address_Command(
advertising_handle=self.advertising_handle,
random_address=(random_address or self.device.random_address),
),
check_result=True,
)
async def start(
self, duration: float = 0.0, max_advertising_events: int = 0
) -> None:
"""
Start advertising.
Args:
duration: How long to advertise for, in seconds. Use 0 (the default) for
an unlimited duration, unless this advertising set is a High Duty Cycle
Directed Advertisement type.
max_advertising_events: Maximum number of events to advertise for. Use 0
(the default) for an unlimited number of advertisements.
"""
await self.device.send_command(
HCI_LE_Set_Extended_Advertising_Enable_Command(
enable=1,
advertising_handles=[self.advertising_handle],
durations=[round(duration * 100)],
max_extended_advertising_events=[max_advertising_events],
),
check_result=True,
)
self.enabled = True
self.emit('start')
async def start_periodic(self, include_adi: bool = False) -> None:
await self.device.send_command(
HCI_LE_Set_Periodic_Advertising_Enable_Command(
enable=1 | (2 if include_adi else 0),
advertising_handles=self.advertising_handle,
),
check_result=True,
)
self.emit('start_periodic')
async def stop(self) -> None:
await self.device.send_command(
HCI_LE_Set_Extended_Advertising_Enable_Command(
enable=0,
advertising_handles=[self.advertising_handle],
durations=[0],
max_extended_advertising_events=[0],
),
check_result=True,
)
self.enabled = False
self.emit('stop')
async def stop_periodic(self) -> None:
await self.device.send_command(
HCI_LE_Set_Periodic_Advertising_Enable_Command(
enable=0,
advertising_handles=self.advertising_handle,
),
check_result=True,
)
self.emit('stop_periodic')
async def remove(self) -> None:
await self.device.send_command(
HCI_LE_Remove_Advertising_Set_Command(
advertising_handle=self.advertising_handle
),
check_result=True,
)
del self.device.extended_advertising_sets[self.advertising_handle]
def on_termination(self, status: int) -> None:
self.enabled = False
self.emit('termination', status)
# -----------------------------------------------------------------------------
class PeriodicAdvertisingSync(EventEmitter):
class State(Enum):
INIT = 0
PENDING = 1
ESTABLISHED = 2
CANCELLED = 3
ERROR = 4
LOST = 5
TERMINATED = 6
_state: State
sync_handle: Optional[int]
advertiser_address: Address
sid: int
skip: int
sync_timeout: float # Sync timeout, in seconds
filter_duplicates: bool
status: int
advertiser_phy: int
periodic_advertising_interval: int
advertiser_clock_accuracy: int
def __init__(
self,
device: Device,
advertiser_address: Address,
sid: int,
skip: int,
sync_timeout: float,
filter_duplicates: bool,
) -> None:
super().__init__()
self._state = self.State.INIT
self.sync_handle = None
self.device = device
self.advertiser_address = advertiser_address
self.sid = sid
self.skip = skip
self.sync_timeout = sync_timeout
self.filter_duplicates = filter_duplicates
self.status = HCI_SUCCESS
self.advertiser_phy = 0
self.periodic_advertising_interval = 0
self.advertiser_clock_accuracy = 0
self.data_accumulator = b''
@property
def state(self) -> State:
return self._state
@state.setter
def state(self, state: State) -> None:
logger.debug(f'{self} -> {state.name}')
self._state = state
self.emit('state_change')
async def establish(self) -> None:
if self.state != self.State.INIT:
raise InvalidStateError('sync not in init state')
options = HCI_LE_Periodic_Advertising_Create_Sync_Command.Options(0)
if self.filter_duplicates:
options |= (
HCI_LE_Periodic_Advertising_Create_Sync_Command.Options.DUPLICATE_FILTERING_INITIALLY_ENABLED
)
response = await self.device.send_command(
HCI_LE_Periodic_Advertising_Create_Sync_Command(
options=options,
advertising_sid=self.sid,
advertiser_address_type=self.advertiser_address.address_type,
advertiser_address=self.advertiser_address,
skip=self.skip,
sync_timeout=int(self.sync_timeout * 100),
sync_cte_type=0,
)
)
if response.status != HCI_Command_Status_Event.PENDING:
raise HCI_StatusError(response)
self.state = self.State.PENDING
async def terminate(self) -> None:
if self.state in (self.State.INIT, self.State.CANCELLED, self.State.TERMINATED):
return
if self.state == self.State.PENDING:
self.state = self.State.CANCELLED
response = await self.device.send_command(
HCI_LE_Periodic_Advertising_Create_Sync_Cancel_Command(),
)
if response.status == HCI_SUCCESS:
if self in self.device.periodic_advertising_syncs:
self.device.periodic_advertising_syncs.remove(self)
return
if self.state in (self.State.ESTABLISHED, self.State.ERROR, self.State.LOST):
self.state = self.State.TERMINATED
await self.device.send_command(
HCI_LE_Periodic_Advertising_Terminate_Sync_Command(
sync_handle=self.sync_handle
)
)
self.device.periodic_advertising_syncs.remove(self)
def on_establishment(
self,
status,
sync_handle,
advertiser_phy,
periodic_advertising_interval,
advertiser_clock_accuracy,
) -> None:
self.status = status
if self.state == self.State.CANCELLED:
# Somehow, we receive an established event after trying to cancel, most
# likely because the cancel command was sent too late, when the sync was
# already established, but before the established event was sent.
# We need to automatically terminate.
logger.debug(
"received established event for cancelled sync, will terminate"
)
self.state = self.State.ESTABLISHED
AsyncRunner.spawn(self.terminate())
return
if status == HCI_SUCCESS:
self.sync_handle = sync_handle
self.advertiser_phy = advertiser_phy
self.periodic_advertising_interval = periodic_advertising_interval