Decoding payload

Packets had been decoded and the dataclass added to have a cleaner
structure.
This commit is contained in:
Martin Girard committed 2026-09-16 10:32:25 +02:00
1 parent c6b299e8ed
commit 96cc366595
1 file changed
+31 -4
@@ -1,7 +1,20 @@
from serial.tools import list_ports from serial.tools import list_ports
from serial import Serial from serial import Serial
from dataclasses import dataclass
import struct import struct
DATA_STRUCT = struct.Struct("<BIf")
@dataclass
class SensorData:
data_type:int
timestamp:int
value:float
@classmethod
def from_bytes(cls, payload: bytes):
data_type, timestamp, value = DATA_STRUCT.unpack(payload)
return cls(data_type=data_type, timestamp=timestamp, value=value)
def main() -> None: def main() -> None:
try: try:
print("Hello from bench-data-connector!") print("Hello from bench-data-connector!")
@@ -31,18 +44,32 @@ def main() -> None:
with Serial(selected_port,baudrate=115200,timeout=1) as ser: with Serial(selected_port,baudrate=115200,timeout=1) as ser:
while True: while True:
start_sync(ser) start_sync(ser)
print("paquet trouvé") #print("paquet trouvé")
payload = ser.read(9) # 9 corresponds to the payload size of the data frame print(DATA_STRUCT.size)
payload = read_exactly(ser, DATA_STRUCT.size)
if not payload: if not payload:
continue continue
crc = ser.read(2) crc = read_exactly(ser, 2)
if not crc: if not crc:
continue continue
received_crc = struct.unpack("<H", crc)[0] received_crc = struct.unpack("<H", crc)[0]
calculated_crc = crc16_ccitt(payload) calculated_crc = crc16_ccitt(payload)
if calculated_crc != received_crc: if calculated_crc != received_crc:
continue continue
print("paquet sécurisé") #print("paquet sécurisé")
print(SensorData.from_bytes(payload))
def read_exactly(ser: Serial, size: int) ->bytes | None:
data = bytearray()
while len(data) < size:
packet_exact = ser.read(size - len(data))
if not packet_exact:
return None
data.extend(packet_exact)
return bytes(data)
def crc16_ccitt(data: bytes) -> int: def crc16_ccitt(data: bytes) -> int:
crc = 0xFFFF crc = 0xFFFF