"""
This is a simple program that runs in a loop, looking for character data over the
UART0 line which happens to be hooked up to the MicroUSB to UART circuit on these
dev kits.
"""
import os
import random
import serial
import time

ESP32_PORT= '/dev/cu.SLAB_USBtoUART' if os.uname().sysname == "Darwin" else "/dev/ttyUSB0"

COLORS = {
    "red": "0,255,0,0;\n",
    "blue": "0,125,204,223;\n",
    "yellow": "0,120,153,23;\n",
    "purple": "0,255,0,153;\n"
}

def main():
    print(f"Connecting to {ESP32_PORT}....")
    print("Sending color commands")
    try:
        with serial.Serial(ESP32_PORT, 115200, timeout=1) as serial_conn:
            while True:
                if serial_conn.is_open:
                    color = random.choice(list(COLORS.keys()))
                    print(f"Setting color: {color.upper()}")
                    serial_conn.write(COLORS[color].encode('ascii'))
                    time.sleep(0.1)
                    if serial_conn.in_waiting:
                        # print(f"Found {serial_conn.in_waiting} bytes waiting in input buffer!")
                        print(serial_conn.readlines())
                    time.sleep(2)
    except KeyboardInterrupt:
        print("Exiting program")

    exit(0)

if __name__ == "__main__":
    main()
