Python first version
implementation of the python program, with parser and crc verification
This commit is contained in:
1 parent
93054253e6
commit
c6b299e8ed
6 files changed
+117
No files matched your search
@@ -0,0 +1,73 @@
|
||||
from serial.tools import list_ports
|
||||
from serial import Serial
|
||||
import struct
|
||||
|
||||
def main() -> None:
|
||||
try:
|
||||
print("Hello from bench-data-connector!")
|
||||
choice = None
|
||||
ports = list(list_ports.comports())
|
||||
for index, port in enumerate(ports):
|
||||
print(f"{index}: {port.device} {port.description}")
|
||||
try:
|
||||
choice = int(input("Choose a port to connect: "))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
while choice is None or choice >= len(ports):
|
||||
|
||||
try:
|
||||
choice = int(input("Unknown port. Try again : "))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
|
||||
selected_port = ports[choice].device
|
||||
print(f"Selected port : {selected_port}")
|
||||
except KeyboardInterrupt:
|
||||
print("\n")
|
||||
exit(0)
|
||||
|
||||
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
|
||||
if not payload:
|
||||
continue
|
||||
crc = ser.read(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é")
|
||||
|
||||
def crc16_ccitt(data: bytes) -> int:
|
||||
crc = 0xFFFF
|
||||
|
||||
for byte in data:
|
||||
crc ^= byte << 8
|
||||
|
||||
for _ in range(8):
|
||||
if crc & 0x8000:
|
||||
crc = (crc << 1) ^ 0x1021
|
||||
else:
|
||||
crc <<= 1
|
||||
|
||||
crc &= 0xFFFF
|
||||
|
||||
return crc
|
||||
|
||||
|
||||
def start_sync(ser: Serial) -> None:
|
||||
previous = None
|
||||
while True:
|
||||
byte = ser.read(1)
|
||||
if not byte :
|
||||
continue
|
||||
if previous == b"\xEF" and byte == b"\xBE" :
|
||||
return
|
||||
previous = byte
|
||||
|
||||
Reference in new issue
Block a user