-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgap.py
55 lines (47 loc) · 1.65 KB
/
gap.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
import binascii
import struct
# Generic Access Profile
# BT Spec V4.0, Volume 3, Part C, Section 18
GAP_FLAGS = 0x01
GAP_UUID_16BIT_INCOMPLETE = 0x02
GAP_UUID_16BIT_COMPLETE = 0x03
GAP_UUID_128BIT_INCOMPLETE = 0x06
GAP_UUID_128BIT_COMPLETE = 0x07
GAP_NAME_INCOMPLETE = 0x08
GAP_NAME_COMPLETE = 0x09
GAP_TX_POWER = 0x0A
class AdvertisingData:
def __init__(self, withData=b''):
self.data = bytes(withData)
self._parseData()
def addItem(self, tag, value):
newdata = self.data + struct.pack("<BB", 1+len(value), tag) + bytes(value)
if len(newdata) <= 31:
self.data = newdata
self.tags[tag] = value
else:
raise IndexError("Supplied advertising data too long (%d bytes total)", len(newdata))
return self
def __iter__(self):
'''Use: for (tag,value) in obj:'''
ofs = 0
maxlen = len(self.data)
while ofs < maxlen:
if maxlen - ofs < 2:
raise IndexError("Advertising data too short")
(ll, tag) = struct.unpack("<BB", self.data[ofs:ofs+2])
if ll==0 or ofs+1+ll > maxlen:
raise IndexError("Bad length byte 0x%02X in advertising data" % ll)
yield (tag, self.data[ofs+2:ofs+1+ll])
ofs = ofs + 1 + ll
def _parseData(self):
self.tags={}
for (tag,value) in self:
self.tags[tag] = value
def __str__(self):
return repr(self.tags) # TODO...
if __name__ == '__main__':
a = AdvertisingData().addItem(GAP_FLAGS, b'11').addItem(GAP_NAME_COMPLETE, b'ThisIsMyName')
print( binascii.b2a_hex(a.data) )
for x in a:
print (repr(x))