#!/usr/bin/env python3

import serial
import time

#ser = serial.Serial('/dev/serial/by-id/usb-1a86_USB2.0-Serial-if00-port0', 230400)
ser = serial.Serial('/dev/serial/by-id/usb-Silicon_Labs_CP2102_USB_to_UART_Bridge_Controller_0001-if00-port0', 250000)
#while True:
#    ser.write(bytes(range(256)))
start = time.time()

last_val = None
run = 0
total_errors = 0
rx_bytes = 0
last_print = time.time()
while True:
    bytes = ser.read(256)
    for byte in bytes:
        if last_val is not None and byte != (last_val + 1) % 256:
            if run > 0:
                print(f'{time.time()-start:>8.3f} {run} {last_val:02x} {byte:02x}')
                run = 0
                total_errors += 1
        else:
            run += 1
        rx_bytes += 1

        if time.time() - last_print > 5:
            last_print = time.time()
            print(f'{time.time()-start:>8.3f} {run} [all good] err={total_errors}@rx={rx_bytes}B',
            f'(rate 1/{rx_bytes/total_errors:.5g})' if total_errors > 0 else 'rate unknown')
        last_val = byte

#while True:
#    data = ser.read_until(b'\0')
#    print(f'{time.time()-start:>8.3f} {len(data)}')

# while True:
#     data = ser.read(256)
#     print('YES' if b'\0' in data else 'NO ', data)
