-
Notifications
You must be signed in to change notification settings - Fork 2
/
adafruit_ble_beacon.py
184 lines (140 loc) · 5.35 KB
/
adafruit_ble_beacon.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
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries
# SPDX-FileCopyrightText: Copyright (c) 2022 Alec Delaney for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_ble_beacon`
================================================================================
BLE Location Beacon for CircuitPython
* Author(s): Alec Delaney
Implementation Notes
--------------------
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://circuitpython.org/downloads
"""
import struct
from micropython import const
import _bleio
from adafruit_ble.advertising import Advertisement, AdvertisingDataField
try:
from typing import Optional, Union, Type, Tuple, Sequence
except ImportError:
pass
__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/tekktrik/Adafruit_CircuitPython_BLE_Beacon.git"
_MANUFACTURING_DATA_ADT = const(0xFF)
_APPLE_COMPANY_ID = const(0x004C)
_IBEACON_TYPE = const(0x02)
_IBEACON_LENGTH = const(0x15)
class MultiStruct(AdvertisingDataField):
"""`struct` encoded data in an Advertisement."""
def __init__(self, struct_format: str, *, advertising_data_type: int) -> None:
self._format = struct_format
self._adt = advertising_data_type
def __get__(
self, obj: Optional["Advertisement"], cls: Type["Advertisement"]
) -> Optional[Union[Tuple, "MultiStruct"]]:
if obj is None:
return self
if self._adt not in obj.data_dict:
return None
return struct.unpack(self._format, obj.data_dict[self._adt])
def __set__(self, obj: "Advertisement", value: Sequence) -> None:
obj.data_dict[self._adt] = struct.pack(self._format, *value)
class _BeaconAdvertisement(Advertisement):
"""Advertisement for location beacons like iBeacon"""
path_loss_const: float = 3
"""The path loss constant, typically between 2-4"""
@property
def uuid(self) -> bytes:
"""The UUID of the beacon"""
raise NotImplementedError("Must be implemented in beacon subclass")
@uuid.setter
def uuid(self, uuid: bytes) -> None:
raise NotImplementedError("Must be implemented in beacon subclass")
@property
def distance(self) -> float:
"""The approximate distance to the beacon, in meters"""
return 10 ** ((self.beacon_tx_power - self.rssi) / (10 * self.path_loss_const))
@property
def beacon_tx_power(self) -> int:
"""The beacon TX power"""
raise NotImplementedError("Must be implemented in beacon subclass")
@beacon_tx_power.setter
def beacon_tx_power(self, power: int) -> None:
raise NotImplementedError("Must be implemented in beacon subclass")
# pylint: disable=invalid-name
class iBeaconAdvertisement(_BeaconAdvertisement):
"""An iBeacon advertisement"""
match_prefixes = (
struct.pack(
"<BHBB",
_MANUFACTURING_DATA_ADT,
_APPLE_COMPANY_ID,
_IBEACON_TYPE,
_IBEACON_LENGTH,
),
)
_data_format = ">HBBQQHHb"
_beacon_data = MultiStruct(_data_format, advertising_data_type=0xFF)
_uuid_msb_index = 3
_uuid_lsb_index = 4
_major_index = 5
_minor_index = 6
_beacon_tx_power_index = 7
def __init__(self, *, entry: Optional[_bleio.ScanEntry] = None) -> None:
super().__init__(entry=entry)
if not entry:
self._init_struct()
@property
def uuid(self) -> bytes:
"""The UUID of the beacon"""
uuid_msb = self._get_struct_index(self._uuid_msb_index)
uuid_lsb = self._get_struct_index(self._uuid_lsb_index)
return struct.pack(">QQ", uuid_msb, uuid_lsb)
@uuid.setter
def uuid(self, uuid: bytes) -> None:
uuid_msb, uuid_lsb = struct.unpack(">QQ", uuid)
self._set_struct_index(self._uuid_msb_index, uuid_msb)
self._set_struct_index(self._uuid_lsb_index, uuid_lsb)
@property
def major(self) -> int:
"""The major store number for the beacon"""
return self._get_struct_index(self._major_index)
@major.setter
def major(self, number: int) -> None:
self._set_struct_index(self._major_index, number)
@property
def minor(self) -> int:
"""The minor store number for the beacon"""
return self._get_struct_index(self._minor_index)
@minor.setter
def minor(self, number: int) -> None:
self._set_struct_index(self._minor_index, number)
@property
def beacon_tx_power(self) -> int:
"""The beacon TX power"""
return self._get_struct_index(self._beacon_tx_power_index)
@beacon_tx_power.setter
def beacon_tx_power(self, power: int) -> None:
self._set_struct_index(self._beacon_tx_power_index, power)
def _set_struct_index(self, index: int, value: int) -> int:
current_beacon_data = list(self._beacon_data)
current_beacon_data[index] = value
self._beacon_data = current_beacon_data
def _get_struct_index(self, index: int) -> int:
temp_tuple = self._beacon_data
return temp_tuple[index]
def _init_struct(self) -> None:
apple_id_flipped = struct.unpack(">H", struct.pack("<H", _APPLE_COMPANY_ID))[0]
self._beacon_data = (
apple_id_flipped,
_IBEACON_TYPE,
_IBEACON_LENGTH,
0,
0,
0,
0,
0,
)