# Week 11 Networking - XIAO RP2040 side of the XIAO <-> ESP32 UART link (MicroPython, save as main.py).
# Wiring: XIAO D6 (TX, GPIO0) -> ESP32 GPIO16 (RX2)
#         XIAO D7 (RX, GPIO1) <- ESP32 GPIO17 (TX2)
#         XIAO GND <-> ESP32 GND          (both boards 3.3 V logic: direct wires, no resistors)
# Servo signal -> D4 (GPIO6), red -> 5V, brown -> GND.  D1 (GPIO27) touched to GND sends "T".
# Messages are text lines ending in "\n", 9600 baud.
#   "S" from ESP32  -> servo toggles 90 <-> 0 deg
#   D1 -> GND       -> send "T" (ESP32 toggles its LED)
#   anything typed in this board's USB serial monitor is sent to the ESP32 too.
import machine, select, sys, time

uart = machine.UART(0, baudrate=9600, tx=machine.Pin(0), rx=machine.Pin(1))   # D6 / D7
servo = machine.PWM(machine.Pin(6))      # D4
servo.freq(50)
btn = machine.Pin(27, machine.Pin.IN, machine.Pin.PULL_UP)                     # D1


def servo_to(d):
    servo.duty_ns(int((500 + 2000 * d / 180) * 1000))     # 500-2500 us = 0-180 deg


def send(msg):
    uart.write(msg + "\n")
    print("TX -> ESP32:", msg)


deg = 90
servo_to(deg)
print("XIAO UART ready @ 9600 (TX=D6, RX=D7)")

usb = select.poll()
usb.register(sys.stdin, select.POLLIN)
rx_buf, usb_buf, last_btn = b"", "", 1
while True:
    # from the ESP32
    if uart.any():
        rx_buf += uart.read()
        while b"\n" in rx_buf:
            line, rx_buf = rx_buf.split(b"\n", 1)
            msg = line.decode().strip()
            if not msg:
                continue
            print("RX <- ESP32:", msg)
            if msg == "S":
                deg = 0 if deg == 90 else 90
                servo_to(deg)
                print("servo ->", deg, "deg")

    # typed in the USB serial monitor
    if usb.poll(0):
        ch = sys.stdin.read(1)
        if ch in "\r\n":
            if usb_buf:
                send(usb_buf)
            usb_buf = ""
        else:
            usb_buf += ch

    # D1 -> GND: one "T" per touch
    b = btn.value()
    if b == 0 and last_btn == 1:
        send("T")
        time.sleep_ms(30)                # debounce
    last_btn = b
    time.sleep_ms(5)
