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 import Serial
from dataclasses import dataclass
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:
try:
print("Hello from bench-data-connector!")
@@ -31,18 +44,32 @@ def main() -> None:
with Serial(selected_port,baudrate=115200,timeout=1) as ser:
while True:
start_sync(ser)
print("paquet trouvé")
payload = ser.read(9) # 9 corresponds to the payload size of the data frame
#print("paquet trouvé")
print(DATA_STRUCT.size)
payload = read_exactly(ser, DATA_STRUCT.size)
if not payload:
continue
crc = ser.read(2)
crc = read_exactly(ser, 2)
if not crc:
continue
received_crc = struct.unpack("<H", crc)[0]
calculated_crc = crc16_ccitt(payload)
if calculated_crc != received_crc:
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:
crc = 0xFFFF