from adafruit_macropad import MacroPad
import usb_cdc
import time

macropad = MacroPad()
serial = usb_cdc.data

def exec_command (data):
    global timer
    try:
        command,option = data.split()
    except:
        command = ""
        option = ""
    print("cmd: {} | opt: {}".format(command, option))
    if command == 'time':
        timer = float(option)
        print("new timer: {}".format(timer))
        response = "nouveau timer : {}\r\n".format(option)
        buffer = bytearray(response)
        serial.write(buffer)
    
def blink(led, light):
    print('light: {}'.format(light))
    if light:
        macropad.pixels[led] = (33, 45, 230)
    else:
        macropad.pixels[led] = (0, 0, 0)
    print('c: {}'.format(macropad.pixels[led]))
    return False if light else True

timer=2
light=False
in_data=bytearray()

while True:
    light = blink(1, light)
    time.sleep(timer)

    if serial.in_waiting > 0:
        while(serial.in_waiting>0):
            byte = serial.read(1)
            if byte == b'\r':
                exec_command(in_data.decode("utf-8"))
                in_data = bytearray()
            else:
                in_data += byte
