# cPy - USB  <-->  Serial loop back test
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-07-14  initial release

import	serial				# (venv) pip install pyserial
import	time

# documentation:
#    https://pyserial.readthedocs.io/en/latest/pyserial.html

# ======================== test UART communication ============================

# Insert a USB to serial converter and connect Tx with Rx (or not)
def testLoopback(port):
    try:
        comm = serial.Serial(port, timeout=2)				# open serial / USB port
        count = 1
        while True:
            b_tx = f'count = {count}\r\n'.encode()			# send count @ 2 sec
            print('Tx:', b_tx)
            comm.write(b_tx)
            for _ in range(20):
                if b_rx := comm.read_all():					# if data received
                    print('Rx:', b_rx)						# print it
                time.sleep(0.1)
            count += 1
    except serial.serialutil.SerialException:
        print('Exception, unable to connect to:', port)
        

testLoopback('/dev/ttyUSB0')

# ================================== end =====================================
