# remoteblink.py

# Raspberry Pi Pico - LED Blinker with Remote Control

# Toy demonstration of remote communication implementing a command language
# to control a real-time LED blinker.

import time

# Import modules provided in the 'CircuitPython/remote/' code folder.  These
# files should be copied to the top-level directory of the CIRCUITPY filesystem
# on the Pico.
import led
import remote

#---------------------------------------------------------------
# Initialize global objects.

# LED interface object.
blinker = led.Blinker()

# Communication interface and callbacks.
remote  = remote.RemoteSerial()

def default_handler(msgtype, *args):
    print(f"Warning: received unknown message {msgtype} {args}")

def help_handler(*args):
    print("Usage: rate <Hz>")
    
remote.add_handler('rate', blinker.set_rate)
remote.add_handler('help', help_handler)
remote.add_default_handler(default_handler)

#---------------------------------------------------------------
# Main event loop to run each non-preemptive thread.

last_clock = time.monotonic_ns()

while True:
    # read the current nanosecond clock
    now = time.monotonic_ns()
    elapsed = now - last_clock
    last_clock = now

    # poll each thread
    remote.poll(elapsed)    
    blinker.poll(elapsed)
