# cPy - console application communicating with Esp32 through USB
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-04-02  initial release

import	time
from	serial	import	Serial			

# ============================ UsbSerial ===============================

class UsbSerial:
    
    def __init__(self, port='/dev/ttyUSB0', baud=115200):
        self.comm    = Serial(port=port, baudrate=baud, timeout=0, exclusive=True)
        self.buff_rx = b''
        
        
    def writeLn(self, s):
        if s[-1] != '\n': s += '\n'
        self.comm.write(s.encode())
        
        
    # return received line as string or None
    def readLn(self):
        res = None
        while ch := self.comm.read():
            if ch == b'\r': continue
            if ch == b'\n':
                if self.buff_rx: 
                    res, self.buff_rx = self.buff_rx, b''
                    return res.decode()
            else: self.buff_rx += ch
            
# ============================= main ================================

def main():
    comm = UsbSerial()
    while True:
        if s_rx := comm.readLn():
            comm.writeLn(s_rx)						# echo it to Esp32
            print(s_rx)
        time.sleep(0.1)
    
    
main()

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