"""A simulated sensor board: 4 ADC channels, 4 LEDs, a threshold event.

    python examples/sensor_board.py                   # serve on tcp://:9000
    python examples/sensor_board.py COM5              # or a serial port
"""

import math
import random
import sys
import threading
import time
from typing import Annotated, NamedTuple

import ufp
from ufp import f32, u8, u16, unit

board = ufp.Device("SensorBoard")

Volts = Annotated[f32, unit("V")]
THRESHOLD = 3.0
leds = [False] * 4


class Reading(NamedTuple):
    raw: Annotated[u16, "12-bit ADC code"]
    voltage: Volts


def voltage(channel: int) -> float:
    """Each channel is a slow sine wave plus noise, between 0 and 3.3 V."""
    v = 1.65 + 1.5 * math.sin(2 * math.pi * 0.15 * (channel + 1) * time.time()) + random.gauss(0, 0.02)
    return min(max(v, 0.0), 3.3)


@board.function
def read_adc(channel: Annotated[u8, "ADC channel, 0-3"]) -> Reading:
    """Read one ADC channel."""
    if not 0 <= channel < 4:
        raise ufp.RemoteError(0x80, f"no channel {channel}")
    v = voltage(channel)
    return Reading(round(v / 3.3 * 4095), v)


@board.function
def set_led(led: u8, on: bool) -> None:
    """Switch an LED on or off."""
    leds[led] = on  # an IndexError here reaches the host as EXEC_FAILED
    board.log(f"LED {led} {'on' if on else 'off'}")


@board.function(returns="samples")
def read_samples(channel: u8, count: u16) -> list[Volts]:
    """Burst-read up to 200 samples."""
    return [voltage(channel) for _ in range(min(count, 200))]


@board.event
def threshold_exceeded(channel: u8, voltage: Volts):
    """A channel rose above 3.0 V."""


def simulate():
    """Watch the channels in the background and fire threshold_exceeded."""
    def loop():
        above = [False] * 4
        while True:
            for ch in range(4):
                v = voltage(ch)
                if v > THRESHOLD and not above[ch]:
                    threshold_exceeded(ch, v)
                above[ch] = v > THRESHOLD
            time.sleep(0.05)
    threading.Thread(target=loop, daemon=True).start()


if __name__ == "__main__":
    target = sys.argv[1] if len(sys.argv) > 1 else "tcp://:9000"
    simulate()
    print(f"{board} serving on {target}  (Ctrl-C to stop)")
    try:
        board.serve(target)
    except KeyboardInterrupt:
        pass
