import machine
import time
import random
import select  # For non-blocking input
import sys



# Define pins for the RGB LED
led_red = machine.PWM(machine.Pin(10))   # GPIO pin for red
led_green = machine.PWM(machine.Pin(11))  # GPIO pin for green
led_blue = machine.PWM(machine.Pin(12))   # GPIO pin for blue

# Set PWM frequency
led_red.freq(1000)
led_green.freq(1000)
led_blue.freq(1000)

# Function to convert 0-255 RGB to 0-65535
def rgb_255_to_16bit(r, g, b):
    return (
        int(r * 65535 / 255), 
        int(g * 65535 / 255), 
        int(b * 65535 / 255)
    )

# Function to set RGB LED color for common anode
def set_color(red, green, blue):
    led_red.duty_u16(65535 - red)
    led_green.duty_u16(65535 - green)
    led_blue.duty_u16(65535 - blue)

# Function to turn off the RGB LED
def turn_off_led():
    set_color(0, 0, 0)

# Test sequence
def test_leds():
    print("Testing LEDs...")
    print("Displaying Red")
    set_color(65535, 0, 0)
    time.sleep(1)

    print("Displaying Green")
    set_color(0, 65535, 0)
    time.sleep(1)

    print("Displaying Blue")
    set_color(0, 0, 65535)
    time.sleep(1)

    turn_off_led()
    print("LED test completed. Turning off LED.")

# Function to generate random beautiful colors rhythmically
def random_rhythm_colors():
    print("No input detected. Switching to random color mode.")
    for _ in range(10):  # Run for 10 cycles (adjustable)
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)
        set_color(*rgb_255_to_16bit(r, g, b))
        time.sleep(5)  # Stay on color for 0.5 seconds
    print("Returning to input mode.")

# Non-blocking input handler
def check_user_input():
    if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
        return sys.stdin.read().strip()  # Read user input if available
    return None  # Return None if no input


# Main program
test_leds()  # Run the test sequence once

print("Input RGB value in format 'R,G,B' (0-255):")
current_color = (0, 0, 0)  # Default color
last_input_time = time.time()  # Record the time of the last input

while True:
    # Periodically check for user input
    user_input = check_user_input()
    if user_input:
        print(f"Received input: {user_input}")  # Debug: show received input
        last_input_time = time.time()  # Reset the inactivity timer
        try:
            r, g, b = map(int, user_input.split(","))
            if 0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255:
                current_color = rgb_255_to_16bit(r, g, b)
                set_color(*current_color)
                print(f"Set color to RGB({r}, {g}, {b})")
            else:
                print("Error: RGB values must be between 0 and 255.")
        except ValueError:
            print("Invalid input. Enter values in format 'R,G,B' (e.g., 255,128,64).")
    
    # Check inactivity timer
    if time.time() - last_input_time > 3:
        print("3 seconds of inactivity detected. Activating random colors.")  # Debug
        random_rhythm_colors()
        last_input_time = time.time()  # Reset the timer after random colors

    time.sleep(0.1)  # Add a small delay to avoid high CPU usage
