|
2 | 2 |
|
3 | 3 | from micropython import const
|
4 | 4 | import struct
|
| 5 | +import bluetooth |
5 | 6 |
|
6 | 7 | # Advertising payloads are repeated packets of the following form:
|
7 | 8 | # 1 byte data length (N + 1)
|
@@ -46,3 +47,39 @@ def _append(adv_type, value):
|
46 | 47 | _append(_ADV_TYPE_APPEARANCE, struct.pack('<h', appearance))
|
47 | 48 |
|
48 | 49 | 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 | <
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]
| 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