"""Live HC-SR04 distance animation for the XIAO RP2040 (reads the board's serial output).

Run:  python distance_visualizer.py [COM12]
Zones match the board's LED: < 10 cm red, 10-20 cm blue, > 20 cm green.
Mouse wheel / + / - : zoom the scale (30..400 cm).   Esc: quit.
"""
import math
import re
import sys
import threading
import time
import tkinter as tk

import serial

PORT = sys.argv[1] if len(sys.argv) > 1 else "COM12"
W, H = 1000, 560
SENSOR_X, TRACK_Y = 120, 250            # sensor position / centre line of the beam
TRACK_X1 = W - 60                       # right end of the distance track
ZONES = [(0, 10, "#ff4d5e", "TOO CLOSE"), (10, 20, "#4d8dff", "NEAR"), (20, 1e9, "#3ddc84", "CLEAR")]
BG, FG, DIM = "#0f1218", "#e8ecf2", "#5a6475"
NUM = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*cm")

latest = {"cm": None, "t": 0.0, "status": "connecting to " + PORT}


def reader():
    """Background thread: keep the serial port open and store the newest reading."""
    while True:
        try:
            with serial.Serial(PORT, 115200, timeout=1) as s:
                latest["status"] = "live on " + PORT
                while True:
                    line = s.readline().decode(errors="ignore")
                    if not line:
                        continue
                    m = NUM.match(line)
                    latest["cm"] = float(m.group(1)) if m else None    # None = no echo
                    latest["t"] = time.time()
        except serial.SerialException:
            latest["status"] = PORT + " not available (close other serial monitors) - retrying"
            latest["cm"] = None
            time.sleep(1)


def zone(cm):
    return next(z for z in ZONES if z[0] <= cm < z[1])


class App:
    def __init__(self, root):
        self.c = tk.Canvas(root, width=W, height=H, bg=BG, highlightthickness=0)
        self.c.pack(fill="both", expand=True)
        self.scale_cm = 50.0             # cm shown across the track
        self.shown = None                # smoothed distance being drawn
        self.waves = []                  # wave fronts: x positions moving right
        self.history = []                # (time, cm) for the bottom graph
        self.last_wave = 0.0
        root.bind("<MouseWheel>", lambda e: self.zoom(0.85 if e.delta > 0 else 1.18))
        root.bind("+", lambda e: self.zoom(0.85))
        root.bind("=", lambda e: self.zoom(0.85))
        root.bind("-", lambda e: self.zoom(1.18))
        root.bind("<Escape>", lambda e: root.destroy())
        self.tick()

    def zoom(self, f):
        self.scale_cm = min(400.0, max(30.0, self.scale_cm * f))

    def x_of(self, cm):
        return SENSOR_X + 40 + (TRACK_X1 - SENSOR_X - 40) * min(cm, self.scale_cm) / self.scale_cm

    def tick(self):
        now = time.time()
        cm = latest["cm"] if now - latest["t"] < 1.0 else None
        if cm is not None:
            self.shown = cm if self.shown is None else self.shown + (cm - self.shown) * 0.25
            self.history.append((now, cm))
        self.history = [(t, d) for t, d in self.history if now - t < 10]
        self.draw(now, cm)
        self.c.after(16, self.tick)     # ~60 fps

    def draw(self, now, cm):
        c = self.c
        c.delete("all")
        live = self.shown is not None and cm is not None
        col = zone(self.shown)[2] if live else DIM

        # zone bands along the track
        for lo, hi, zc, name in ZONES:
            if lo >= self.scale_cm:
                continue
            x0, x1 = self.x_of(lo), self.x_of(min(hi, self.scale_cm))
            active = live and lo <= self.shown < hi
            c.create_rectangle(x0, TRACK_Y - 110, x1, TRACK_Y + 110, fill=zc,
                               stipple="" if active else "gray25", outline="")
            c.create_text((x0 + x1) / 2, TRACK_Y + 128, text=name, fill=zc,
                          font=("Segoe UI", 11, "bold"))

        # ruler ticks
        step = 5 if self.scale_cm <= 60 else 10 if self.scale_cm <= 150 else 50
        for d in range(0, int(self.scale_cm) + 1, step):
            x = self.x_of(d)
            c.create_line(x, TRACK_Y + 140, x, TRACK_Y + 150, fill=DIM)
            c.create_text(x, TRACK_Y + 162, text=str(d), fill=DIM, font=("Segoe UI", 9))
        c.create_text(TRACK_X1, TRACK_Y + 180, text="cm  (scroll to zoom)", fill=DIM,
                      anchor="e", font=("Segoe UI", 9))

        # sensor (two transducer "eyes")
        c.create_rectangle(SENSOR_X - 30, TRACK_Y - 60, SENSOR_X + 20, TRACK_Y + 60,
                           fill="#1d6fb8", outline="")
        for dy in (-30, 30):
            c.create_oval(SENSOR_X - 5, TRACK_Y + dy - 22, SENSOR_X + 39, TRACK_Y + dy + 22,
                          fill="#c9ced6", outline="#7d8794", width=3)
            c.create_oval(SENSOR_X + 7, TRACK_Y + dy - 10, SENSOR_X + 27, TRACK_Y + dy + 10,
                          fill="#2b2f36", outline="")
        c.create_text(SENSOR_X - 5, TRACK_Y + 78, text="HC-SR04", fill=FG, font=("Segoe UI", 10, "bold"))

        # ultrasonic wave fronts travelling to the object
        target = self.x_of(self.shown) if live else TRACK_X1
        if now - self.last_wave > 0.12:
            self.waves.append(SENSOR_X + 45)
            self.last_wave = now
        self.waves = [x + 9 for x in self.waves if x < target]
        for x in self.waves:
            r = x - SENSOR_X
            fade = 1 - (x - SENSOR_X) / max(1, target - SENSOR_X)
            if fade > 0.05:
                c.create_arc(SENSOR_X - r, TRACK_Y - r * 0.6, SENSOR_X + r, TRACK_Y + r * 0.6,
                             start=-28, extent=56, style="arc", outline=FG, width=max(1, int(4 * fade)))

        # the object / hand
        if live:
            x = self.x_of(self.shown)
            pulse = 6 * (1 + math.sin(now * 8)) if self.shown < 10 else 0
            c.create_rectangle(x, TRACK_Y - 80 - pulse, x + 26, TRACK_Y + 80 + pulse,
                               fill=FG, outline=col, width=4)
            c.create_line(SENSOR_X + 40, TRACK_Y + 100, x, TRACK_Y + 100, fill=col, width=2, arrow="both")
            lbl = "%.1f cm" % self.shown + ("  >" if self.shown > self.scale_cm else "")
            c.create_text((SENSOR_X + 40 + x) / 2, TRACK_Y + 88, text=lbl, fill=FG, font=("Segoe UI", 10))

        # big readout
        if live:
            name = zone(self.shown)[3]
            c.create_text(40, 50, text="%.1f cm" % self.shown, fill=col, anchor="w",
                          font=("Segoe UI", 40, "bold"))
            c.create_text(40, 95, text=name + "  ·  board LED: " +
                          {"TOO CLOSE": "red", "NEAR": "blue", "CLEAR": "green"}[name],
                          fill=FG, anchor="w", font=("Segoe UI", 13))
        else:
            c.create_text(40, 50, text="no echo", fill=DIM, anchor="w", font=("Segoe UI", 40, "bold"))
            c.create_text(40, 95, text="point the sensor at something", fill=DIM, anchor="w",
                          font=("Segoe UI", 13))
        c.create_text(W - 30, 30, text=latest["status"], fill=DIM, anchor="e", font=("Segoe UI", 10))

        # last 10 s graph
        gx0, gy0, gx1, gy1 = 40, H - 110, W - 40, H - 25
        c.create_rectangle(gx0, gy0, gx1, gy1, outline="#262c36")
        c.create_text(gx0 + 6, gy0 + 4, text="last 10 s", fill=DIM, anchor="nw", font=("Segoe UI", 9))
        pts = []
        for t, d in self.history:
            px = gx1 - (now - t) / 10 * (gx1 - gx0)
            py = gy1 - min(d, self.scale_cm) / self.scale_cm * (gy1 - gy0)
            pts.append((px, py, zone(d)[2]))
        for (x0, y0, _), (x1, y1, zc) in zip(pts, pts[1:]):
            c.create_line(x0, y0, x1, y1, fill=zc, width=2)


root = tk.Tk()
root.title("HC-SR04 live distance - XIAO RP2040")
threading.Thread(target=reader, daemon=True).start()
App(root)
root.mainloop()
