|
| 1 | +import struct |
| 2 | +import serial |
| 3 | + |
| 4 | +SCALING_FACTOR = 1000 # Same scaling factor as on the Arduino |
| 5 | + |
| 6 | + |
| 7 | +def read_serial_data(ser): |
| 8 | + while ser.in_waiting: |
| 9 | + start_byte = ser.read(1) |
| 10 | + if start_byte == b"\xAA": # Check for start byte |
| 11 | + main_var_id = ser.read(1) # Main variable ID (as byte) |
| 12 | + data_type = ser.read(1) # Data type byte |
| 13 | + |
| 14 | + if data_type == b"\x01": # Fixed-point integer type |
| 15 | + fixed_point_value = struct.unpack("<i", ser.read(4))[ |
| 16 | + 0 |
| 17 | + ] # Read 4-byte integer |
| 18 | + value = fixed_point_value / SCALING_FACTOR # Convert to float |
| 19 | + elif data_type == b"\x02": # Char array type |
| 20 | + value = b"" |
| 21 | + while True: |
| 22 | + char = ser.read(1) |
| 23 | + if char == b"\x00": # Null terminator |
| 24 | + break |
| 25 | + value += char |
| 26 | + value = value.decode("utf-8") # Decode as a UTF-8 string |
| 27 | + |
| 28 | + params_length = struct.unpack("<B", ser.read(1))[0] # Params length |
| 29 | + |
| 30 | + params = [] |
| 31 | + if params_length > 0: |
| 32 | + for _ in range(params_length): |
| 33 | + param_id = ser.read(1) # Read each param variable ID as a byte |
| 34 | + params.append(param_id) |
| 35 | + |
| 36 | + end_byte = ser.read(1) |
| 37 | + if end_byte == b"\xFF": # Ensure proper packet termination |
| 38 | + data = { |
| 39 | + "main_var_id": ord(main_var_id), |
| 40 | + "value": value, |
| 41 | + "params": [ |
| 42 | + ord(param) for param in params |
| 43 | + ], # Will be an empty list if no params |
| 44 | + } |
| 45 | + print(data) |
| 46 | + else: |
| 47 | + print("Error: End byte not found. Invalid packet.") |
| 48 | + else: |
| 49 | + print("Error: Start byte not found. Invalid packet.") |
| 50 | + |
| 51 | + |
| 52 | +# Connect to serial port |
| 53 | +# ser = serial.Serial('/dev/ttyUSB0', 9600) |
| 54 | +# Connect to serial port |
| 55 | +ser = serial.Serial("/dev/tty.usbserial-1450", 115200) |
| 56 | + |
| 57 | +while True: |
| 58 | + read_serial_data(ser) |
0 commit comments