first commit
This commit is contained in:
22
test/protocol.py
Normal file
22
test/protocol.py
Normal file
@@ -0,0 +1,22 @@
|
||||
def sum16(data: bytes) -> int:
|
||||
return sum(data) & 0xFFFF
|
||||
|
||||
|
||||
def build_frame(cmd: int, device_id: int, payload: bytes = b"") -> bytes:
|
||||
frame = bytearray()
|
||||
frame += b'\x23\xA9' # 帧头
|
||||
frame += b'\x00\x00' # 长度占位
|
||||
frame += device_id.to_bytes(4, 'little')
|
||||
frame += bytes([cmd])
|
||||
frame += payload
|
||||
|
||||
length = len(frame) + 2 # 加上校验和
|
||||
frame[2:4] = length.to_bytes(2, 'big')
|
||||
|
||||
s = sum16(frame)
|
||||
frame += s.to_bytes(2, 'big')
|
||||
return bytes(frame)
|
||||
|
||||
|
||||
def parse_device_id(frame: bytes) -> int:
|
||||
return int.from_bytes(frame[4:8], 'little')
|
||||
Reference in New Issue
Block a user