# cpy - rPi print numbers from ads1115 i2c driver
# copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2024-12-12  initial release

import  os;             os.system('clear')
import	asyncio
from	smbus2			import	SMBus			# full python implementation
from	rpi_ads1115		import	Ads1115

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

class Main:

    def __init__(self):
        self.n_items    = 0                                 # printed items on line
        self.i2c		= SMBus(1)
        self.adc 		= Ads1115(self.i2c)
        asyncio.run(self.aioInit())


    # set-up aio loop and aio tasks
    async def aioInit(self):
        try:
            async with asyncio.TaskGroup() as self.tg:
                self.tg.create_task(self._task())			# collect i2c data
        except* Exception as exc:
            print(exc.exceptions)
            print('taskgroup terminated')


    # task collecting i2c data @ 30 Hz and printing @  Hz
    async def _task(self):
        while True:
            for _ in range(3):
                await asyncio.sleep(0.033)
                self.adc.get()
            print(f'{self.adc.getAvg():6}', end='', flush=True)
            self.n_items += 1
            if self.n_items >= 10:
                self.n_items = 0
                print()


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

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