Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

bluetooth - Unable to unpack

I am getting below errors while parsing BLE packet. Any suggestion how to fix this?

Packet b'x04>+x02x01x03x01xd7xd3Axc9xaexf5x1fx02x01x06x03x03xaaxfex17x16xaaxfex00xd8x8bx9cxc7<:xe7Gxefexbcx00x00x00x00x15xd1x00x00xaf'

Traceback (most recent call last):
File "BluetoothWiliot.py", line 95, in <module>
    dataString = parse_events(sock, 100)
File "BluetoothWiliot.py", line 47, in parse_events
    print(struct.unpack("B", bytes(pkt[3])))
**struct.error: unpack requires a buffer of 1 bytes**


Traceback (most recent call last):
File "BluetoothWiliot.py", line 95, in <module>
    dataString = parse_events(sock, 100)
File "BluetoothWiliot.py", line 47, in parse_events
    print(struct.unpack("B", pkt[3]))

**TypeError: a bytes-like object is required, not 'int'**

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

int.from_bytes is normally my go to function for these situations but there are a number of options:

$ python3
Python 3.7.3 (default, Jul 25 2020, 13:03:44) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> pkt = b'x04>+x02x01x03x01xd7xd3Axc9xaexf5x1fx02x01x06x03x03xaaxfex17x16xaaxfex00xd8x8bx9cxc7<:xe7Gxefexbcx00x00x00x00x15xd1x00x00xaf'
>>> pkt[3]
2
>>> int.from_bytes([pkt[3]], byteorder='little', signed=False)
2
>>> struct.unpack_from('B', pkt, 3)
(2,)
>>> struct.unpack('B',pkt[3:3+1])
(2,)
>>> struct.unpack('B', bytes([pkt[3]]))
(2,)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...