from adafruit_macropad import MacroPad
import usb_cdc, asyncio

macropad = MacroPad()
timer = 1
color = 0xad20b4
led = 0

def exec_command (data):
    global timer
    command,option = data.split()
    print("cmd:{} opt:{}".format(command,option))
    if command == 'time':
        timer = float(option)

async def blink(led, color):
    macropad.pixels.brightness = 0.3
    while True:
        try:
            if  macropad.pixels[led] == (0,0,0):
                macropad.pixels[led] = color
            else:
                macropad.pixels[led] = 0x0
            print("l:{} c:{} t:{}".format(led,hex(color),timer))
            await asyncio.sleep(timer)
        except asyncio.CancelledError:
            pass

async def check_serial(task_led):
    data = bytearray()
    serial = usb_cdc.data
    # Avec le timeout, même si la ligne ne contient pas \n, elle
    # sera pris en compte
    serial.timeout = 1
    while True:
        if serial.in_waiting:
            data = serial.readline()
            print("serial data received")
            exec_command(data.decode("utf-8"))
            task_led.cancel()
        await asyncio.sleep(0)

async def main():
    t_led = asyncio.create_task(blink(led, color))
    t_serial = asyncio.create_task(check_serial(t_led))
    await asyncio.gather(t_led, t_serial)

asyncio.run(main())
