8000 examples/bluetooth: Add helpers for decoding advertising payloads. · rlangoy/micropython@3436223 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3436223

Browse files
jimmodpgeorge
authored andcommitted
examples/bluetooth: Add helpers for decoding advertising payloads.
Extracts name and service UUID fields.
1 parent e873d35 commit 3436223

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

examples/bluetooth/ble_advertising.py

Lines changed: 37 additions & 0 deletions
< 8000 td data-grid-cell-id="diff-30f6d484e142300928e9207e8f5f576be98a6cd804d556e790155408d1273453-48-58-2" data-line-anchor="diff-30f6d484e142300928e9207e8f5f576be98a6cd804d556e790155408d1273453R58" data-selected="false" role="gridcell" style="background-color:var(--diffBlob-additionLine-bgColor, var(--diffBlob-addition-bgColor-line));padding-right:24px" tabindex="-1" valign="top" class="focusable-grid-cell diff-text-cell right-side-diff-cell left-side">+
i += 1 + payload[i]
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from micropython import const
44
import struct
5+
import bluetooth
56

67
# Advertising payloads are repeated packets of the following form:
78
# 1 byte data length (N + 1)
@@ -46,3 +47,39 @@ def _append(adv_type, value):
4647
_append(_ADV_TYPE_APPEARANCE, struct.pack('<h', appearance))
4748

4849
return payload
50+
51+
52+
def decode_field(payload, adv_type):
53+
i = 0
54+
result = []
55+
while i + 1 < len(payload):
56+
if payload[i + 1] == adv_type:
57+
result.append(payload[i + 2:i + payload[i] + 1])
58
59+
return result
60+
61+
62+
def decode_name(payload):
63+
n = decode_field(payload, _ADV_TYPE_NAME)
64+
return str(n[0], 'utf-8') if n else ''
65+
66+
67+
def decode_services(payload):
68+
services = []
69+
for u in decode_field(payload, _ADV_TYPE_UUID16_COMPLETE):
70+
services.append(bluetooth.UUID(struct.unpack('<h', u)[0]))
71+
for u in decode_field(payload, _ADV_TYPE_UUID32_COMPLETE):
72+
services.append(bluetooth.UUID(struct.unpack('<d', u)[0]))
73+
for u in decode_field(payload, _ADV_TYPE_UUID128_COMPLETE):
74+
services.append(bluetooth.UUID(u))
75+
return services
76+
77+
78+
def demo():
79+
payload = advertising_payload(name='micropython', services=[bluetooth.UUID(0x181A), bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')])
80+
print(payload)
81+
print(decode_name(payload))
82+
print(decode_services(payload))
83+
84+
if __name__ == '__main__':
85+
demo()

0 commit comments

Comments
 (0)
0