from adafruit_macropad import MacroPad
import usb_cdc
import time

macropad = MacroPad()
serial = usb_cdc.data

def exec_command (data):
    global muted
    try:
        print(data)
        command,option = data.split()
    except:
        command = ""
        option = ""
    print("cmd: {} | opt: {}".format(command, option))
    if command == 'mute':
        muted = True if option == 'yes' else False
        print('muted: {}'.format(muted))

timer=2
in_data=bytearray()
muted=False

while True:
    key_event = macropad.keys.events.get()
    if muted:
        macropad.pixels[1] = (255,0,0)
    else:
        macropad.pixels[1] = (0,255,0)

    if key_event:
        if key_event.pressed:
            if key_event.key_number == 1:
                print('get key 1')
                serial.write(bytearray('mute\r\n'))

    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
