"""UFP host demo.

    python examples/demo.py                        # board simulated in-process
    python examples/demo.py tcp://localhost:9000   # sensor_board.py in another terminal
    python examples/demo.py COM5                   # real hardware
"""

import sys
import time

import ufp

if len(sys.argv) > 1:
    target = sys.argv[1]
else:
    import sensor_board
    sensor_board.simulate()
    target = sensor_board.board

with ufp.connect(target) as board:
    # Discovery happened in connect(): the board describes itself.
    print(board.describe(), "\n")

    # Functions are plain method calls; multiple returns are named tuples.
    raw, volts = board.read_adc(0)
    print(f"read_adc(0)       -> raw={raw}, voltage={volts:.3f} V")
    r = board.read_adc(channel=1)
    print(f"read_adc(1)       -> {r}")
    samples = board.read_samples(2, count=5)
    print(f"read_samples(2,5) -> {[round(s, 3) for s in samples]}")

    # Device-side exceptions become ufp.RemoteError.
    try:
        board.read_adc(7)
    except ufp.RemoteError as e:
        print(f"read_adc(7)       -> {e}")

    # Events: decorate a handler. The device's log() is an event too.
    @board.on("threshold_exceeded")
    def alarm(channel, voltage):
        print(f"  ! channel {channel} crossed {voltage:.2f} V")
        board.set_led(channel, True)  # handlers may call back into the device

    board.on("log", lambda level, msg: print(f"  [device] {msg}"))

    print(f"\nping: {board.ping() * 1000:.2f} ms. Listening for events for 8 s...")
    time.sleep(8)
    print(f"done ({board.dropped} notifications dropped)")
