# cpy - usb master, print incoming numbers (strings) through /dev/ttyACM0
#     mpy_ads1115.py generator loaded in Esp32s2 as main.py (test: $ picocom /dev/ttyACM0)
# copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2024-12-11  initial release

import  os;             os.system('clear')
import  asyncio
from    ve_aio_serial   import  Serial

port = '/dev/ttyACM0'

# ===================================== Main ======================================

class Main:

    def __init__(self):
        self.n_items    = 0                                 # printed items on line
        self.timeout    = 0                                 # receive timeout detect
        asyncio.run(self.aioInit())


    # set-up aio loop and aio tasks
    async def aioInit(self):
        try:
            async with asyncio.TaskGroup() as self.tg:
                self.ser = Serial(self, port, on_rx=self.onSerRx)   # self.tg required by Serial()
                self.tg.create_task(self.taskMonitor())
        except* Exception as exc:
            print(exc.exceptions)
            print('taskgroup terminated')


    # monitor task, check on UsbRx timeout
    async def taskMonitor(self):
        while True:
            self.timeout += 1
            if self.timeout >= 5:
                self.timeout = 0
                print('usb Rx timeout')
            await asyncio.sleep(1)


    # on string receive, callback function
    def onSerRx(self, s):
        self.timeout = 0                            # reset timeout detect
        try:    res = int(s)                        # interpret s_rx as int
        except: res = 'err'
        print(f'{res:6}', end='', flush=True)
        self.n_items += 1
        if self.n_items >= 10:
            self.n_items = 0
            print()


    # required by Serial()
    def doCommand(self, cmd):
        print('doCommand:', cmd)
        

try:
    Main()
except KeyboardInterrupt:
    print('terminated by Ctrl-c')

# =================================== End ========================================
