Projects

Build it in an afternoon. Watch it come alive

A button that lights an LED. A live-feed camera in a bird box. A weather station for the garden. Pick one, build it on a Saturday, and see it live from your dashboard.

No Pi yet? Every project here runs on your own computer first, with pretend pins and a test-pattern camera, so you can see it work before you buy anything.

Start here

  • Easy Verified

    Button and LED

    A push button shows Pressed live, and a toggle lights an LED.

    You'll need:
    A Pi, a push button, an LED, a 330 ohm resistor and jumper wires

    Button and LED

    apps/gpio_panel.py

    """GPIO Panel - a button in and an LED out, on the dashboard: the smallest complete example of digital inputs and outputs.
    
    **What it does.** A push button on one pin shows on the dashboard as "Pressed" or "Released", live. A Toggle on the
    dashboard switches an LED on another pin. That is all of digital I/O: read a pin, drive a pin. To make your own,
    copy this file and change what the two pins mean (a door switch, a relay, a buzzer, a float switch).
    
    **Nothing pihub-specific touches the pins.** They are plain gpiozero (`Button`, `LED`): the app only connects a
    gpiozero event to a dashboard component and a dashboard component to a gpiozero call. gpiozero is the whole GPIO
    story; pihub adds nothing to it except `prepare_pins()`, which lets a virtual environment find Raspberry Pi OS's pin
    driver.
    
    **Hardware.** A Raspberry Pi (any model with the 40-pin header), a push button and an LED:
    
        Button  one leg -> GPIO 17 (pin 11)     the other leg -> GND (pin 9)        (no resistor: the Pi's own pull-up is on)
        LED     GPIO 27 (pin 13) -> 330 ohm -> LED anode (long leg); LED cathode (short leg) -> GND (pin 14)
    
    An LED needs its resistor: a pin gives about 3.3 V and cannot limit the current itself. For something that draws more
    than a few mA (a relay board, a buzzer, a motor), a pin cannot drive it directly: use a transistor or a relay board
    made for 3.3 V logic, as the motion trap does for its infrared light. Never connect a pin to more than 3.3 V.
    
    **The LED starts off** every time the app starts, and goes off again when it stops, whatever the Toggle was left on:
    an output that quietly comes back on after a power cut is not what most things you would switch want. (The Toggle is
    not saved, for the same reason.)
    
    **Run it.** Just run it:
    
        .venv/bin/python apps/gpio_panel.py
    
    The first time, it prints a link and a short code: open the link while you are logged in, approve it, and answer `y`
    when the terminal asks you to confirm the account. That makes the Pi yours, and the platform gives it its id. Every run
    after that connects straight away. (`pihub setup` does the same linking on its own, if you would rather do that first.)
    
    **No hardware?** `--simulate` uses gpiozero's pretend pins, so it runs on any computer; press "Test press" on the
    dashboard to press the pretend button; the Toggle drives a pretend LED. `pip install "thepihub[gpio]"`
    if gpiozero is missing (Raspberry Pi OS already has it; a venv made without `--system-site-packages` does not). The pin
    driver, `lgpio`, comes from Raspberry Pi OS (`python3-lgpio`) and is found from a venv as well.
    """
    
    from __future__ import annotations
    
    import argparse
    import signal
    import time
    from typing import Any, List, Optional
    
    from pihub import Device, Program
    
    
    PROGRAM_ID = "gpio-panel"
    PRESSED, RELEASED = "Pressed", "Released"
    TEST_PRESS_SECONDS = 0.3
    
    
    class GpioPanel:
        """The dashboard section: a Status for the button, a Toggle for the LED. `button` is a gpiozero `Button`, `led` a gpiozero `LED`
        (or anything with `when_pressed`, `when_released`, `is_pressed` and `on()`, `off()`). Build it before `device.start()`, then call `start()`."""
    
        def __init__(self, device: Device, button: Any, led: Any, *, simulated_press: Optional[Any] = None) -> None:
            self.device = device
            self.button = button
            self.led = led
            self.program = Program(id=PROGRAM_ID, name="GPIO Panel")
    
            self.state = self.program.output(id="button", type="Status")
            button.when_pressed = lambda: self.state.set(PRESSED)
            button.when_released = lambda: self.state.set(RELEASED)
    
            # persist=False: the LED is off at every start, so the Toggle must not remember "on" (see the docstring at the top).
            self.light = self.program.setting("led", "Toggle", default=False, title="LED", persist=False, apply=self._light_changed)
    
            if simulated_press is not None:
                press = self.program.command(id="test-press", type="Button")
                press.handler(lambda command: self.test_press(simulated_press))
            device.add_program(self.program)
    
        def start(self) -> None:
            """After `device.start()`: show where the button is now, and make sure the LED is off."""
            self.led.off()
            self.state.set(PRESSED if self.button.is_pressed else RELEASED)
    
        def close(self) -> None:
            self.led.off()
    
        def _light_changed(self, value: Any) -> None:
            self.led.on() if value else self.led.off()
    
        @staticmethod
        def test_press(pin: Any) -> None:
            """Press and release the pretend button, by driving its mock pin the way a real one would go: low while pressed (pull-up wiring)."""
            pin.drive_low()
            time.sleep(TEST_PRESS_SECONDS)
            pin.drive_high()
    
    
    def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("--server", help="the platform to register with the first time (default: $PIHUB_SERVER, else https://thepihub.com); ignored once registered")
        parser.add_argument("--simulate", action="store_true", help="no hardware: pretend GPIO pins, and a Test press button on the dashboard")
        parser.add_argument("--button-pin", type=int, default=17, help="the GPIO the button is wired to, the other leg to GND (default: 17)")
        parser.add_argument("--led-pin", type=int, default=27, help="the GPIO the LED (through its resistor) is wired to (default: 27)")
        return parser.parse_args(argv)
    
    
    def build(args: argparse.Namespace, transport: Any = None) -> GpioPanel:
        """The device, its button and LED, and the panel, NOT yet started. `transport` is for tests."""
        try:
            from gpiozero import LED, Button, GPIOZeroError
            from gpiozero import Device as Pins
        except ImportError:
            raise SystemExit('error: this app needs gpiozero: pip install "thepihub[gpio]" (Raspberry Pi OS has it for its own Python)')
        from pihub.gpio import PIN_DRIVER_HELP, prepare_pins
    
        if args.button_pin == args.led_pin:
            raise SystemExit("error: the button and the LED cannot use the same pin")
        if args.simulate:
            from gpiozero.pins.mock import MockFactory
    
            Pins.pin_factory = MockFactory()
        else:
            prepare_pins()  # a venv without system packages: the pin driver is Raspberry Pi OS's own
    
        try:
            # At a terminal, the first run links this machine by code and the platform assigns its id; every run after connects at once.
            device = Device(transport=transport, server=args.server)
        except ValueError as error:
            raise SystemExit(f"error: {error}")
    
        try:
            button = Button(args.button_pin, bounce_time=0.05)  # pulled up by the Pi; pressed = connected to GND; bounce_time ignores contact chatter
            led = LED(args.led_pin)
        except (GPIOZeroError, OSError) as error:
            raise SystemExit(f"error: {PIN_DRIVER_HELP} ({error})")
        return GpioPanel(device, button, led, simulated_press=button.pin if args.simulate else None)
    
    
    def main(argv: Optional[List[str]] = None) -> None:
        args = parse_args(argv)
        panel = build(args)
        panel.device.start()
        panel.start()
        print(f"{panel.device.id} is online{' (simulated: press Test press on the dashboard)' if args.simulate else ''}. Ctrl+C to stop.")
        signal.signal(signal.SIGTERM, signal.default_int_handler)  # a service stop (systemd) ends the loop like Ctrl+C, so the LED is switched off
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            pass
        finally:
            print("Stopping...")
            panel.close()
            panel.device.stop()
            panel.button.close()
            panel.led.close()
    
    
    if __name__ == "__main__":
        main()  # pragma: no cover
    

In the garden

  • Easy Verified

    Greenhouse

    Two gauges, a button and a warning.

    You'll need:
    Just a computer to start; a sensor to make it real

    Greenhouse

    examples/greenhouse.py

    """Greenhouse - two Gauges, a Button that runs your code, and notifications.
    
    Copy this file anywhere and run it:
    
        python greenhouse.py
    
    If this is the first time you have connected from this device, it prints a link and a code: open the link
    while logged in to ThePiHub and approve it, then answer y when the terminal asks you to confirm the account.
    The device is yours and gets its id. Every run after that connects straight away. Ctrl+C stops it.
    """
    
    from __future__ import annotations
    
    import time
    from typing import Optional
    
    from pihub import Device, Program
    from pihub.device import Transport
    from pihub.protocol.messages import CommandMessage
    
    
    def main(transport: Optional[Transport] = None) -> Device:
        # `transport` is for the tests. Left out, the device connects to the real server.
        device = Device(transport=transport)
    
        greenhouse = Program(id="greenhouse", name="Greenhouse")
    
        temperature = greenhouse.output(id="temperature", type="Gauge")
        humidity = greenhouse.output(id="humidity", type="Gauge")
        water_plants = greenhouse.command(id="waterPlants", type="Button")
    
        @water_plants.handler
        def water(command: CommandMessage) -> None:
            # Your code goes here (open a valve, switch a pump). Then tell the dashboard.
            print("Water plants pressed")  # shows here, in the terminal
            greenhouse.info("Plants watered")  # and in the dashboard's Notification history
    
        device.add_program(greenhouse)
        device.start()
    
        # Replace these with real sensor readings.
        temperature.set(24.0)
        humidity.set(38.0)
    
        # A warning shows on the dashboard until someone acknowledges it.
        greenhouse.warning("Soil moisture low")
    
        return device
    
    
    if __name__ == "__main__":
        device = main()  # pragma: no cover
        print(f"{device.id} is online. Ctrl+C to stop.")  # pragma: no cover
        try:  # pragma: no cover
            while True:
                time.sleep(1)
        except KeyboardInterrupt:  # pragma: no cover
            pass
        finally:  # pragma: no cover
            device.stop()
    
  • Easy Verified

    Weather station

    Three gauges and a live chart.

    You'll need:
    Just a computer to start; a sensor to make it real

    Weather station

    examples/weather_station.py

    """Weather Station - Gauges and a Chart, updated every few seconds.
    
    Copy this file anywhere and run it:
    
        python weather_station.py
    
    If this is the first time you have connected from this device, it prints a link and a code: open the link
    while logged in to ThePiHub and approve it, then answer y when the terminal asks you to confirm the account.
    The device is yours and gets its id. Every run after that connects straight away. Ctrl+C stops it.
    
    The readings are random numbers standing in for a sensor: replace `_read_conditions()`.
    """
    
    from __future__ import annotations
    
    import random
    import time
    from typing import Dict, Optional
    
    from pihub import Device, Program
    from pihub.device import Transport
    
    
    def _read_conditions() -> Dict[str, float]:
        """Random readings, standing in for real sensor hardware."""
        return {
            "temperature": round(random.uniform(15.0, 30.0), 1),
            "humidity": round(random.uniform(30.0, 90.0), 1),
            "pressure": round(random.uniform(980.0, 1050.0), 1),
        }
    
    
    def main(transport: Optional[Transport] = None, cycles: Optional[int] = None, interval: float = 2.0) -> Device:
        """`transport` and `cycles` are for the tests: left out, it connects to the real server and runs until Ctrl+C."""
        device = Device(transport=transport)
    
        weather = Program(id="weather", name="Weather Station")
    
        temperature = weather.output(id="temperature", type="Gauge")
        humidity = weather.output(id="humidity", type="Gauge")
        pressure = weather.output(id="pressure", type="Gauge")
        conditions = weather.output(id="conditions", type="Chart")
    
        device.add_program(weather)
        device.start()
    
        done = 0
        try:
            while cycles is None or done < cycles:
                readings = _read_conditions()
    
                # One value per Gauge.
                temperature.set(readings["temperature"])
                humidity.set(readings["humidity"])
                pressure.set(readings["pressure"])
    
                # Several values at once, for the Chart.
                conditions.set_values(readings)
    
                done += 1
                if interval:
                    time.sleep(interval)
        except KeyboardInterrupt:  # pragma: no cover
            pass
        finally:
            device.stop()
    
        return device
    
    
    if __name__ == "__main__":
        main()  # pragma: no cover
    

Watch the wildlife

  • Medium Unverified

    Live camera

    A live camera on your dashboard, in about 20 lines.

    You'll need:
    A computer, or a Pi with a camera

    Live camera

    examples/birdbox.py

    """Bird Box - the Camera component: live video with buttons to record and take a snapshot.
    
    Copy this file anywhere and run it:
    
        python birdbox.py
    
    If this is the first time you have connected from this device, it prints a link and a code: open the link
    while logged in to ThePiHub and approve it, then answer y when the terminal asks you to confirm the account.
    The device is yours and gets its id. Every run after that connects straight away. Ctrl+C stops it.
    
    On a Raspberry Pi with a camera this shows the Pi's camera; anywhere else, a moving test pattern. Where the Pi has a hardware video encoder it does the encoding; where it has none (a Pi 5), the CPU does, at the CPU's cost. Either way the picture streams, you can take snapshots and
    you can record.
    It needs the video pieces (the plain `pip install thepihub` brings PyAV; on a 32-bit Pi there is no pip build of PyAV, so install it with apt (`sudo apt install python3-picamera2 python3-av python3-aiortc`) and create the virtualenv with `--system-site-packages`).
    The camera only runs while someone is watching or recording. Pictures go to ~/thepihub-snapshots
    and recordings to ~/thepihub-recordings, on this device.
    """
    
    from __future__ import annotations
    
    import time
    from typing import Optional
    
    from pihub import Device, Program
    from pihub.device import Transport
    from pihub.video import best_camera_source
    
    
    def main(transport: Optional[Transport] = None) -> Device:
        # `transport` is for the tests. Left out, the device connects to the real server.
        device = Device(transport=transport)
    
        birdbox = Program(id="birdbox", name="Bird Box")
    
        # The Camera component draws the video with its own buttons: stream, snapshot, record, full screen.
        camera = birdbox.output(id="camera", type="Camera")
        camera.use(best_camera_source())  # the Pi's camera (hardware or software encoding); anywhere else, a moving test pattern
        camera.recorder_if_possible()  # adds the Record button when the camera can be recorded
    
        temperature = birdbox.output(id="temperature", type="Gauge")
    
        # The camera has nothing to do while nobody is watching: these say when someone starts or stops.
        @birdbox.on_first_user_connected
        def viewer_arrived(payload: dict) -> None:
            birdbox.info("Viewer connected")
    
        @birdbox.on_last_user_disconnected
        def viewers_left(payload: dict) -> None:
            birdbox.info("Last viewer disconnected")
    
        device.add_program(birdbox)
        device.start()
    
        temperature.set(22.5)  # replace with a real sensor reading
    
        return device
    
    
    if __name__ == "__main__":
        device = main()  # pragma: no cover
        print(f"{device.id} is online. Ctrl+C to stop.")  # pragma: no cover
        try:  # pragma: no cover
            while True:
                time.sleep(1)
        except KeyboardInterrupt:  # pragma: no cover
            pass
        finally:  # pragma: no cover
            device.stop()
    
  • Medium Verified

    Bird Box Live

    A camera you can leave running, watched from anywhere.

    You'll need:
    A Pi, a camera (NoIR for night) and a bird box

    Bird Box Live

    apps/birdbox_live.py

    """Bird Box, networked - the same Program/widget shape as
    `examples/birdbox.py`, but against a real ThePiHub server instead of
    `ConsoleTransport`. Kept out of `examples/` deliberately: that folder is
    tested reference material (`tests/examples/test_birdbox.py`), not a
    place for a real, personal device app.
    
    Just run it:
    
        .venv/bin/python apps/birdbox_live.py
    
    The first time, it prints a link and a short code: open the link while you are
    logged in, approve it, and answer `y` when the terminal asks you to confirm the
    account. That makes this Pi yours, and the platform gives it its id (saved to
    ~/.config/thepihub/config.json). Every run after that connects straight away.
    (`pihub setup` does the same linking on its own, and `pihub install` links and
    installs it as a service in one go.)
    
    Point it at another server with --server if needed.
    """
    
    from __future__ import annotations
    
    import argparse
    import signal
    import time
    
    from pihub import Device, Program
    from pihub.video import (
        best_camera_source,
        CameraUnavailable,
        watch_camera_colour,
    )
    
    
    
    def parse_args() -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument("--server", help="the platform to register with the first time (default: $PIHUB_SERVER, else https://thepihub.com); ignored once registered")
        parser.add_argument(
            "--snapshot-dir",
            default="~/thepihub-snapshots",
            help="where the Snapshot button saves pictures, on this device (default: ~/thepihub-snapshots)",
        )
        parser.add_argument(
            "--recordings-dir",
            default="~/thepihub-recordings",
            help="where the Record button saves video, on this device (default: ~/thepihub-recordings; a USB stick's mount point works)",
        )
        # Video size, frame rate and bitrate are settings on the dashboard (Device Information), remembered on the Pi. A value given here wins over the
        # remembered one, and stops that setting being saved: a change made on the dashboard then lasts only until this program restarts.
        parser.add_argument("--size", help="video size, WIDTHxHEIGHT (default: the dashboard setting, else 640x480)")
        parser.add_argument("--fps", type=int, help="video frames per second (default: the dashboard setting, else 15)")
        parser.add_argument(
            "--bitrate",
            type=int,
            help="target video bitrate in bits per second, for the hardware encoder (default: the dashboard setting, else 1000000)",
        )
        parser.add_argument(
            "--tuning",
            metavar="NAME",
            help="a libcamera tuning file for the camera, e.g. imx219_noir for a NoIR camera, whose picture is otherwise strongly pink "
            "(default: the one saved by `pihub camera setup`, else the camera's own)",
        )
        parser.add_argument(
            "--software-encoder",
            action="store_true",
            help="encode the video on the CPU instead of the Pi's hardware encoder (about 14x the CPU; a Pi 5 has no hardware encoder, and does this by itself)",
        )
        parser.add_argument(
            "--test-pattern",
            action="store_true",
            help="a moving test pattern instead of the Pi camera (for a machine with no camera; streams, records and snapshots like a camera)",
        )
        return parser.parse_args()
    
    
    def main() -> None:
        args = parse_args()
    
        # No transport passed: device.start() below connects with the secret saved by an earlier registration. On the very first run there
        # is none, so, at a terminal, it links this machine by code (the platform assigns the id) and carries on.
        try:
            device = Device(server=args.server)
        except ValueError as error:
            raise SystemExit(f"error: {error}")
    
        birdbox = Program(id="birdbox", name="Bird Box")
        # The Camera component: the video with its own controls on the dashboard (stream, snapshot, record, full screen). The SDK answers them.
        camera = birdbox.output(id="camera", type="Camera")
        temperature = birdbox.output(id="temperature", type="Gauge")
    
        # Live video: the camera is NOT started here. It starts when someone presses "Start camera" on the
        # dashboard, and stops when they stop, close the page, or stop watching. 640x480 at 15 fps, H.264.
        size = None
        if args.size:
            try:
                size = tuple(int(part) for part in args.size.lower().split("x"))
                if len(size) != 2:
                    raise ValueError
            except ValueError:
                raise SystemExit(f"error: --size must look like 640x480, not {args.size!r}")
        try:
            # The Pi's hardware encoder (about 5% of a Pi 3A+ at 640x480, against about 57% for the CPU); else the Pi camera encoded on the CPU (a Pi 5 has no hardware encoder,
            # or --software-encoder); with --test-pattern a moving pattern (encoded, as the hardware's is, so it can be recorded too).
            camera_source = best_camera_source(
                size=size, fps=args.fps, bitrate=args.bitrate, tuning=args.tuning, software_encoder=args.software_encoder, test_pattern=args.test_pattern
            )
        except CameraUnavailable as error:
            raise SystemExit(f"error: {error}")
        print(f"video: {camera_source.description}")
        camera.use(camera_source, snapshot_directory=args.snapshot_dir)  # Snapshot: a picture saved on this device, from the stream if it is running
        # Record: to this device's own storage, from the same encode as the stream (so an encoded source: the hardware encoder or libx264 on the CPU, not the raw-frame fallback). Its settings are under
        # Device Information > Video; stopping the stream or closing the page never stops a recording.
        recorder = camera.recorder_if_possible(directory=args.recordings_dir)
        # A NoIR camera is pink until it is told. If the picture is strongly pink and that was never done, say so ONCE as a warning from Device
        # Information (where the camera's settings, including "Camera is NoIR", are), which the dashboard shows there and asks the user to acknowledge
        # (a real camera only: a test pattern's colours mean nothing).
        watch_camera_colour(camera_source, device.information.warning)
    
        @birdbox.on_first_user_connected
        def viewer_arrived(payload: dict) -> None:
            print(">>> A viewer opened the dashboard")
    
        @birdbox.on_last_user_disconnected
        def viewers_left(payload: dict) -> None:
            print(">>> The last viewer left")
    
        # Files: the same folders the Camera itself writes to, so a recording or a snapshot can be pulled straight to
        # your own machine, peer to peer, without SSH or pulling the SD card.
        files_program = Program(id="files", name="Files")
        files = files_program.output(id="files", type="Files")
        files.add_folder("Photos", camera.snapshot_directory)
        if recorder is not None:
            files.add_folder("Videos", recorder.store.directory)
            recorder.on_saved(lambda _recording: files.publish())  # a finished recording shows up without a page reload
    
        device.add_program(birdbox)
        device.add_program(files_program)
        device.start()  # connects, sends registration, starts receiving - all automatic
    
        # (The SDK publishes the camera's streamId itself: nothing to set here.)
        temperature.set(22.5)
    
        print(f"{device.id} is online. Ctrl+C to stop.")
        # A service stop (systemd) sends SIGTERM, not Ctrl+C. Left alone, SIGTERM kills the program at once and the cleanup in `finally`
        # below never runs. Treating it as Ctrl+C makes both ways of stopping do the same cleanup:
        # a recording in progress is finished (not left half written) and the connection is closed.
        signal.signal(signal.SIGTERM, signal.default_int_handler)
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            pass
        finally:
            print("Stopping...")
            if recorder is not None:
                recorder.close()  # finishes a recording in progress
            device.stop()
    
    
    if __name__ == "__main__":
        main()  # pragma: no cover
    
  • Harder Unverified

    Motion Trap

    Records only when something moves.

    You'll need:
    A Pi with a camera and a PIR motion sensor. Optional: an infrared light for night

    Motion Trap

    apps/motion_trap.py

    """Motion Trap - records video whenever a motion sensor sees something move.
    
    **What it does.** A PIR motion sensor watches; when it fires, the camera starts recording to this Pi's own storage
    and the dashboard gets a notice ("Motion detected: recording"). Every further movement keeps it going; once nothing
    has moved for "Keep recording after motion" seconds (10 by default), the recording stops and a second notice says what
    was saved. Live video works all the while, from the same encode.
    
    **Nothing glows at the wildlife.** An infrared light (for a NoIR camera at night) is on exactly while the camera is:
    switched on just before it opens, so the first frames are lit, and off when it closes, whatever opened it (a
    recording, the live video, a snapshot, or pre-roll, which keeps the camera running all the time the trap is armed, and is on
    by default). The Pi's own
    lights are switched off while the app runs (see "Board lights" below). A visible LED that lights on motion is
    available for setting the sensor up (`--led-pin 27`), and is off unless asked for.
    
    On the dashboard: the camera (live video, Record, Snapshot and full screen buttons, "REC" while recording), an **Armed** toggle (off: motion is ignored), a **Motion** status, a **Sensor** status (what the PIR's output is now: Active or Quiet; with `--detector both` or `frames` also a **Picture change** gauge, how much of the picture is changing, in percent) and a **Test
    motion** button, which does exactly what the sensor does, and a **Files** section listing the Photos and Videos
    folders - download one, or "Download all" straight to your own machine, peer to peer. Under Device Information >
    Video: pre-roll (keep the seconds BEFORE the motion; on by default at 5 s, and it keeps the camera, and so the infrared light,
    running all the time the trap is armed; set it to 0 to turn it off), the storage limits, the longest recording, and "Keep recording after motion".
    
    **Hardware.** A Raspberry Pi with a camera (the Pi's hardware H.264 encoder does the encoding where there is one, any Pi before the Pi 5; without one the CPU does, which
    has not yet been tried on a Pi 5; a NoIR camera for night), an HC-SR501-style PIR sensor (its output is 3.3 V logic, safe for a GPIO pin), and optionally an
    infrared illuminator and a setup LED:
    
        PIR     VCC -> pin 2 (5 V)     OUT -> GPIO 17 (pin 11)     GND -> pin 6
        IR      GPIO 22 (pin 15) -> 1 kohm -> base of an NPN transistor (2N2222 or similar); emitter -> GND (pin 9);
                collector -> the illuminator's minus; the illuminator's plus -> 5 V (pin 4)
        LED     GPIO 27 (pin 13) -> 330 ohm -> LED anode; LED cathode -> pin 14 (GND)      (setup only: --led-pin 27)
    
    An illuminator draws far more than a GPIO pin can give (about 16 mA), hence the transistor: never wire one straight to
    a pin. Use one that can be switched, not one with its own light sensor that turns itself on in the dark. 940 nm is
    invisible to animals; 850 nm shows a faint red glow but lights further for a NoIR camera.
    
    **Seeing movement in the picture (optional).** `--detector both` makes the camera confirm what the sensor reports: it compares small pictures (4 a second) and
    only starts a recording when enough of the picture changes for long enough, so a moth in front of the lens does not. `--detector frames` uses the picture alone, with
    no sensor wired. Under Device Information > Video, "Movement area" (the share of the picture that must change) and "Movement must last" tune it, and each notice says how
    much of the picture changed, which is how to set them from what the trap really sees. It costs the camera a second, small picture (about 3% of a Pi Zero W's CPU) and keeps
    the camera, and so the infrared light, on all the time the trap is armed, even with pre-roll off. In the dark an infrared-lit picture shows insects as large bright blobs, so
    `both` is the safer choice at night, and `frames` suits daylight.
    
    **A brighter picture in the dark (optional).** A NoIR camera in a dark garden is limited by the camera, not by this program. Measured on a Pi Zero with an IMX219 and a
    mains infrared light at about 0.6 lux: the auto-exposure had already reached its longest exposure (about 120 ms) and almost its highest gain (9.8 of about 10.7), so a lower
    `--fps` or a higher exposure target changed nothing. What software can still do is lift the picture with the camera's own controls, which run in the image processor before the
    encoder and so cost no CPU:
    
        --exposure-value 2   aim the auto-exposure this many stops brighter (2 is four times)
        --long-exposure      let the auto-exposure prefer a long exposure to a high gain: brighter, but a moving animal blurs
        --brightness 0.1     add to every pixel (0.1 is about 25 of 255): the largest effect here, but it is a lift, not new light, so black becomes dark grey
    
    Those three are the NIGHT settings. Left on all day they blow the picture out and blur whatever moves, so `--night-lux 3` applies them only when the camera's own light reading
    (its "lux" metadata) is below 3, and puts the camera's own defaults back when it is above 6: twice the threshold, so a reading near it cannot make the picture flicker between the
    two. A change also needs two readings in a row (one every 30 seconds), so a car's headlights or a torch does not switch it; only the first reading after the camera opens acts at once.
    Without `--night-lux` the night settings are always on.
    
    Lux is the camera's estimate, not a meter: it is calibrated for the sensor's own tuning, and a NoIR camera counts infrared as light, so choose the threshold from your own camera.
    `--camera-log FILE` appends the exposure time, gain and lux (and day or night) every 30 seconds: read it at dusk and dawn, then set `--night-lux` between the two. If the exposure and
    the gain are both at their limits, only more light will help.
    
    **Board lights.** Once per Pi, `sudo .venv/bin/pihub board-leds allow` lets the app switch the Pi's own green (and
    red) LEDs off while it runs; they come back when it stops. Without that the dashboard says they are still on.
    `--board-leds on` leaves them alone.
    
    **Run it.** Just run it:
    
        .venv/bin/python apps/motion_trap.py
    
    The first time, it prints a link and a short code: open the link while you are logged in, approve it, and answer `y`
    when the terminal asks you to confirm the account. That makes the Pi yours, and the platform gives it its id. Every run
    after that connects straight away. (`pihub setup` does the same linking on its own, if you would rather do that first.)
    
    **No hardware?** `--simulate` uses gpiozero's pretend pins and a moving test pattern for the camera, so the whole
    thing runs on any computer; press Test motion on the dashboard to set it off. `pip install "thepihub[gpio]"` if gpiozero
    is missing (Raspberry Pi OS already has it; a venv made without `--system-site-packages` does not). The pin driver,
    `lgpio`, comes from Raspberry Pi OS (`python3-lgpio`) and is found from a venv as well.
    
    Recordings go to ~/thepihub-recordings (`--directory` to change it, a USB stick's mount point for example).
    """
    
    from __future__ import annotations
    
    import argparse
    import logging
    import signal
    import threading
    import time
    from datetime import datetime
    from pathlib import Path
    from typing import Any, Callable, Dict, List, Optional
    
    from pihub import Device, Program, StringProperty
    from pihub.video import CameraUnavailable, EncodedTestPatternSource, best_camera_source
    
    logger = logging.getLogger(__name__)
    
    DEFAULT_HOLD_SECONDS = 10
    DEFAULT_PRE_ROLL_SECONDS = 5  # a trap should catch the start of what set it off, so pre-roll is on unless the dashboard or --pre-roll says otherwise
    PROGRAM_ID = "motion-trap"
    HOLD_SETTING = "video-hold-seconds"
    TICK_SECONDS = 0.2
    
    # Seeing movement in the picture (`--detector both|frames`): small greyscale pictures, compared with the last one.
    DETECTORS = ("pir", "both", "frames")
    SAMPLES_PER_SECOND = 4
    PIXEL_CHANGE = 25  # a pixel counts as changed when its brightness (the picture's average taken off) moves by more than this, out of 255
    DEFAULT_AREA_PERCENT = 2.0  # the share of the picture that must change: a measured still scene reads 0%, a hand waved in front of it 25-60%
    DEFAULT_MOVEMENT_SECONDS = 1.0  # ... for this long without a break
    AREA_SETTING = "video-movement-area"
    MOVEMENT_SECONDS_SETTING = "video-movement-seconds"
    
    NOT_ARMED, WATCHING, MOTION = "Not armed", "Watching", "Motion"
    
    
    class FrameMotion:
        """Movement seen by comparing one small greyscale picture with the last. No camera needed: `update` takes any 2-D array of brightness values.
    
        A picture counts as "changed" when at least `area_percent` of its pixels differ from the last picture's (after each picture's average brightness is taken off, so
        auto-exposure or a cloud changing the whole picture does not count). Movement is CONFIRMED once pictures have kept changing for `seconds` without a break, which is
        what lets a moth (a few pixels, for a moment) through unnoticed and an animal (a large part of the picture, for a while) not. `active` is whether it is confirmed
        now; `peak_percent` is the most the picture changed since the change began.
        """
    
        def __init__(self, area_percent: float = DEFAULT_AREA_PERCENT, seconds: float = DEFAULT_MOVEMENT_SECONDS, pixel_change: int = PIXEL_CHANGE) -> None:
            self.area_percent = float(area_percent)
            self.seconds = float(seconds)
            self.pixel_change = int(pixel_change)
            self.reset()
    
        def reset(self) -> None:
            self._previous: Any = None
            self._since: Optional[float] = None
            self.changed_percent = 0.0
            self.peak_percent = 0.0
            self.active = False
    
        def update(self, picture: Any, now: float) -> bool:
            """Compare `picture` with the last one, at time `now` (seconds). Returns `active`."""
            import numpy as np
    
            current = np.asarray(picture).astype(np.int16)
            current -= int(current.mean())
            previous, self._previous = self._previous, current
            if previous is None or previous.shape != current.shape:
                self.active = False
                return False
            self.changed_percent = float((np.abs(current - previous) > self.pixel_change).mean() * 100)
            if self.changed_percent >= self.area_percent:
                if self._since is None:
                    self._since, self.peak_percent = now, 0.0
                self.peak_percent = max(self.peak_percent, self.changed_percent)
                self.active = now - self._since >= self.seconds
            else:
                self._since = None
                self.active = False
            return self.active
    
    
    class MotionTrap:
        """The trap's logic, apart from the command line, so a test can drive it: `sensor` is a gpiozero `MotionSensor` (or anything with
        `is_active` and `when_motion`; None with `detector="frames"`, which needs none); `detector` is `pir` (the sensor alone, as ever), `both` (the sensor, confirmed by
        the picture) or `frames` (the picture alone), see `FrameMotion`; `led` (the setup LED, lit on motion) and `ir_light` (on while the camera is) are anything with `on()`
        and `off()`, or None; `board_leds` is a `pihub.board_leds.BoardLeds`, or None to leave the Pi's own lights alone. Build it before
        `device.start()`, then call `start()`."""
    
        def __init__(
            self,
            device: Device,
            source: Any,
            sensor: Any,
            led: Any = None,
            *,
            detector: str = "pir",
            movement_area_percent: Optional[float] = None,
            movement_seconds: Optional[float] = None,
            ir_light: Any = None,
            board_leds: Any = None,
            directory: str = "~/thepihub-recordings",
            hold_seconds: Optional[float] = None,
            pre_roll_seconds: Optional[float] = None,
            clock: Callable[[], float] = time.monotonic,
            **recorder_options: Any,
        ) -> None:
            self.device = device
            self.sensor = sensor
            self.led = led
            self.ir_light = ir_light
            self.board_leds = board_leds
            self._clock = clock
            # One lock across a whole trigger and a whole ending: motion arriving while a recording is being stopped must start the next one,
            # not find it "still recording" and let the stop end it.
            self._lock = threading.RLock()
            self._deadline: Optional[float] = None  # while motion is "on": when it ends if nothing else moves
            self._stop = threading.Event()
            self._thread: Optional[threading.Thread] = None
            self._watcher: Optional[threading.Thread] = None
            self.hold_seconds = float(DEFAULT_HOLD_SECONDS if hold_seconds is None else hold_seconds)
            self._hold_given = hold_seconds is not None
            if detector not in DETECTORS:
                raise ValueError(f"detector must be one of {', '.join(DETECTORS)}")
            if detector != "pir" and getattr(source, "motion_frames", True) is False:  # a test pattern has no flag: it always offers them
                raise ValueError("this video source cannot give the small pictures that --detector needs")
            self.source = source
            self.detector = detector
            self._area_given = movement_area_percent is not None
            self._movement_seconds_given = movement_seconds is not None
            self.frame_motion: Optional[FrameMotion] = (
                None if detector == "pir"
                else FrameMotion(DEFAULT_AREA_PERCENT if movement_area_percent is None else movement_area_percent,
                                 DEFAULT_MOVEMENT_SECONDS if movement_seconds is None else movement_seconds)
            )
            self._holding_camera = False
    
            self.program = Program(id=PROGRAM_ID, name="Motion Trap")
            # The Camera component: live video, Snapshot and Record on the dashboard, and the recorder this app drives from the sensor.
            self.camera = self.program.output(id="camera", type="Camera").use(source)
            if ir_light is not None:
                source.add_power_listener(lambda on: ir_light.on() if on else ir_light.off())  # lit exactly while the camera is open
            self.recorder = self.camera.recorder(directory=directory, pre_roll_seconds=pre_roll_seconds, **recorder_options)
            if pre_roll_seconds is None:
                # Pre-roll on by default. set_pre_roll (not the constructor argument) so this is only the slider's starting value: a value
                # saved from the dashboard still wins, and the slider still saves what you change it to. It also means, while armed, that the
                # camera (and so the infrared light) stays on, which is what lets a NoIR camera light the seconds before the motion.
                self.recorder.set_pre_roll(DEFAULT_PRE_ROLL_SECONDS)
            # Files: the same folders the camera itself writes to, so a saved recording or snapshot can be pulled
            # straight to your own machine, peer to peer, without SSH or pulling the SD card.
            self.files_program = Program(id="files", name="Files")
            self.files = self.files_program.output(id="files", type="Files")
            self.files.add_folder("Photos", self.camera.snapshot_directory)
            self.files.add_folder("Videos", self.recorder.store.directory)
            self.recorder.on_saved(lambda _recording: self.files.publish())  # a finished recording shows up without a page reload
            self.status = self.program.output(id="motion", type="Status")
            # What the two ways of seeing movement are reading right now, for setting them up: the sensor's output, and (with `both` or `frames`) how much of the picture is changing.
            self.sensor_state = self.program.output(id="sensor", type="Status", properties=[StringProperty("title", default="Sensor")])
            self.picture_change = (
                None if detector == "pir"
                else self.program.output(id="picture-change", type="Gauge", properties=[StringProperty("title", default="Picture change"), StringProperty("units", default="%")])
            )
            self._shown_sensor: Optional[str] = None
            self._shown_change: Optional[float] = None
            self.armed = self.program.setting("armed", "Toggle", default=True, title="Armed", apply=self._armed_changed)
            test = self.program.command(id="test-motion", type="Button")
            test.handler(lambda command: self.trigger("button"))
            self.recorder.on_add_settings(self._add_hold_setting)  # in Device Information's Video group, after the recorder's own
            if detector == "pir":
                sensor.when_motion = lambda: self.trigger("sensor")  # `both` and `frames` decide from the picture (and, for `both`, whether the sensor is active)
            device.add_program(self.program)
            device.add_program(self.files_program)
    
        def _add_hold_setting(self, section: Any) -> None:
            def apply(value: Any) -> None:
                self.hold_seconds = float(value)
    
            widget = section.setting(
                HOLD_SETTING, "Slider", default=self.hold_seconds, title="Keep recording after motion", units="s",
                minimum=min(5, self.hold_seconds), maximum=max(300, self.hold_seconds), step=5, apply=apply, persist=not self._hold_given, group="Video",
            )
            apply(widget.value)
            if self.frame_motion is None:
                return
            detector = self.frame_motion
    
            def apply_area(value: Any) -> None:
                detector.area_percent = float(value)
    
            def apply_seconds(value: Any) -> None:
                detector.seconds = float(value)
    
            area = section.setting(
                AREA_SETTING, "Slider", default=detector.area_percent, title="Movement area", units="%",
                minimum=0.5, maximum=max(25.0, detector.area_percent), step=0.5, apply=apply_area, persist=not self._area_given, group="Video",
            )
            apply_area(area.value)
            seconds = section.setting(
                MOVEMENT_SECONDS_SETTING, "Slider", default=detector.seconds, title="Movement must last", units="s",
                minimum=0.5, maximum=max(5.0, detector.seconds), step=0.5, apply=apply_seconds, persist=not self._movement_seconds_given, group="Video",
            )
            apply_seconds(seconds.value)
    
        # -- running ---------------------------------------------------------------------------------------------------------------
    
        def start(self) -> None:
            """After `device.start()`: the Pi's own lights off, arm (if the Armed toggle is on) and start the hold timer."""
            if self.board_leds is not None:
                from pihub.board_leds import ALLOW_COMMAND
    
                refused = self.board_leds.switch_off()
                if refused:
                    self.program.info(f"The Pi's own lights are still on ({', '.join(refused)}). To let this app switch them off, run once on the Pi: {ALLOW_COMMAND}")
            self._armed_changed(self.armed.value)
            self._show_sensor()
            self._thread = threading.Thread(target=self._run, daemon=True, name="motion-trap")
            self._thread.start()
            if self.frame_motion is not None:
                self._watcher = threading.Thread(target=self._watch, daemon=True, name="motion-trap-pictures")
                self._watcher.start()
    
        def close(self) -> None:
            self._stop.set()
            if self._thread is not None:
                self._thread.join()
            if self._watcher is not None:
                self._watcher.join()
            self._end_motion()
            self._release_camera()
            self.recorder.close()
            if self.board_leds is not None:
                self.board_leds.restore()
    
        def _run(self) -> None:
            while not self._stop.wait(TICK_SECONDS):
                self._show_sensor()
                self.tick()
    
        def _show_sensor(self) -> None:
            """Publish the sensor's output on the dashboard, when it changes."""
            state = "Not used" if self.sensor is None else ("Active" if self.sensor.is_active else "Quiet")
            if state != self._shown_sensor:
                self._shown_sensor = state
                self.sensor_state.set(state)
    
        def _watch(self) -> None:
            while not self._stop.wait(1.0 / SAMPLES_PER_SECOND):
                self.sample()
    
        def sample(self) -> None:
            """One look at the camera, with `detector` both or frames: compare its small picture with the last, and start (or keep) the motion when the picture has
            really been moving. With `both`, the sensor must also be active to START one."""
            detector = self.frame_motion
            if detector is None or not self.armed.value:
                return
            picture = self.source.grab_motion_frame()
            if picture is None:
                return
            moving = detector.update(picture, self._clock())
            change = round(detector.changed_percent, 1)
            if self.picture_change is not None and change != self._shown_change:
                self._shown_change = change
                self.picture_change.set(change)
            if moving:
                if self._deadline is not None or self.detector == "frames" or self.sensor.is_active:
                    self.trigger("frames", f" (the picture changed {detector.peak_percent:.0f}%)")
    
        # -- the path --------------------------------------------------------------------------------------------------------------
    
        def trigger(self, cause: str = "sensor", detail: str = "") -> bool:
            """Motion (from the sensor, or the Test motion button): LED on, recording (if not already), and the hold timer (re)started.
            Returns False if the trap is not armed."""
            if not self.armed.value:
                return False
            with self._lock:
                starting = self._deadline is None
                self._deadline = self._clock() + self.hold_seconds
                if starting:
                    if self.led is not None:
                        self.led.on()
                    self.status.set(MOTION)
                if not self.recorder.recording:
                    try:
                        self.recorder.start(reason="test" if cause == "button" else "motion")
                    except (CameraUnavailable, OSError) as error:
                        self.program.warning(f"Motion detected, but the recording did not start: {error}")
                    else:
                        self.program.info(f"Motion detected{detail}: recording" if cause != "button" else "Test motion: recording")
            return True
    
        def tick(self) -> None:
            """Keep the motion going while the sensor still sees it; end it once `hold_seconds` have passed with nothing."""
            with self._lock:
                if self._deadline is None:
                    return
                now = self._clock()
                if self._still_moving():
                    self._deadline = now + self.hold_seconds
                    return
                if now < self._deadline:
                    return
                self._end_motion()
    
        def _still_moving(self) -> bool:
            """The sensor still sees it (or, with `both` or `frames`, the picture is still changing)."""
            if self.frame_motion is not None:
                return self.frame_motion.active
            return bool(self.sensor.is_active)
    
        def _hold_camera(self) -> None:
            """Pictures only come from an open camera, and pre-roll (which usually holds it) can be off: so hold it ourselves while armed."""
            if self._holding_camera:
                return
            try:
                self.source.start()
            except CameraUnavailable as error:
                self.program.warning(f"Armed, but the camera could not be opened to watch for movement: {error}")
                return
            self._holding_camera = True
    
        def _release_camera(self) -> None:
            if self._holding_camera:
                self._holding_camera = False
                self.source.stop()
    
        def _end_motion(self) -> None:
            with self._lock:
                was_on = self._deadline is not None
                self._deadline = None
                if was_on:
                    if self.led is not None:
                        self.led.off()
                    self.status.set(WATCHING if self.armed.value else NOT_ARMED)
                self.recorder.stop()  # the recorder sends "Recording saved: ..." itself
    
        def _armed_changed(self, value: Any) -> None:
            if self.frame_motion is not None:
                self.frame_motion.reset()
                if value:
                    self._hold_camera()
                else:
                    self._release_camera()
            if value:
                self.status.set(WATCHING)
                try:
                    self.recorder.arm()  # holds the camera while pre-roll is on (the default)
                except CameraUnavailable as error:
                    self.program.warning(f"Armed, but pre-roll could not start: {error}")
            else:
                self.recorder.disarm()
                self._end_motion()
                self.status.set(NOT_ARMED)
    
    
    # -- a brighter picture in the dark ---------------------------------------------------------------------------------------------
    # What this does, and why, is in the module's docstring ("A brighter picture in the dark"). In short: a hook the camera calls each time it opens sets the NIGHT controls
    # (or, with --night-lux, the camera's own defaults until it is dark), and a small thread reads the camera's lux every 30 seconds to switch between them.
    
    AE_EXPOSURE_MODE_LONG = 2  # libcamera's AeExposureMode: 0 Normal, 1 Short, 2 Long
    CAMERA_LOG_SECONDS = 30.0  # how often the camera is read: for the log and for the day/night decision
    FIRST_READING_SECONDS = 5.0  # after the camera opens, wait this long for its auto-exposure to settle, then read once
    NIGHT_END_FACTOR = 2.0  # night ends when the lux is this many times the threshold: the gap (hysteresis) stops a reading near the threshold flickering
    NIGHT_CONFIRM_READINGS = 2  # a change needs this many readings in a row, so headlights or a torch for one reading do not switch it
    
    
    class NightSwitch:
        """Decides, from the camera's lux readings one at a time, whether it is night. No camera needed: `update` takes a number.
    
        Night begins when the lux falls BELOW `night_lux` and ends when it rises to `night_lux * NIGHT_END_FACTOR` or more. Either change needs
        `NIGHT_CONFIRM_READINGS` readings in a row that want it, except the first reading after the camera opens (`first=True`), which acts at once because
        the picture has been wrong since the camera opened and nothing earlier is worth waiting for. A reading with no lux (None) changes nothing.
        It starts as day, and keeps its state when the camera closes and opens again, so a reopen at night does not spend its first seconds as day."""
    
        def __init__(self, night_lux: float) -> None:
            self.night_lux = night_lux
            self.night = False
            self._streak = 0
    
        def update(self, lux: Optional[float], first: bool = False) -> bool:
            """Take one reading; return whether it is night now."""
            if lux is None:
                return self.night
            wants_night = lux < (self.night_lux * NIGHT_END_FACTOR if self.night else self.night_lux)
            if wants_night == self.night:
                self._streak = 0
                return self.night
            self._streak += 1
            if first or self._streak >= NIGHT_CONFIRM_READINGS:
                self.night = wants_night
                self._streak = 0
            return self.night
    
    
    def camera_tuning(
        exposure_value: Optional[float] = None,
        long_exposure: bool = False,
        brightness: Optional[float] = None,
        log_path: Optional[str] = None,
        night_lux: Optional[float] = None,
    ) -> Optional[Callable[[Any], None]]:
        """An `on_open` hook for the camera source, or None when nothing was asked for.
    
        The camera closes when its last user stops and is a new object when it opens again, so the controls are set on EVERY open, before it starts. A control this
        camera does not have is skipped and a value is held to the range the camera allows, so a bad number cannot stop the trap from starting. With `night_lux`
        the night controls are set only while it is night (see `NightSwitch`) and the camera's own defaults the rest of the time; without it they are always set.
        A thread reads the camera every `CAMERA_LOG_SECONDS` while it is open, to decide day or night and/or to write the log."""
        night: Dict[str, float] = {}
        if exposure_value is not None:
            night["ExposureValue"] = exposure_value
        if long_exposure:
            night["AeExposureMode"] = AE_EXPOSURE_MODE_LONG
        if brightness is not None:
            night["Brightness"] = brightness
        if night_lux is not None and not night:
            raise ValueError("night_lux needs something to switch: an exposure value, long exposure or brightness")
        if not night and not log_path:
            return None
        switch = NightSwitch(night_lux) if night_lux is not None else None
    
        def tune(camera: Any) -> None:
            available = camera.camera_controls  # {name: (minimum, maximum, default)}
            night_controls: Dict[str, float] = {}
            for name, value in night.items():
                if name not in available:
                    logger.warning("this camera has no %s control, so it is left alone", name)
                    continue
                night_controls[name] = min(max(value, available[name][0]), available[name][1])
            day_controls = {name: available[name][2] for name in night_controls}  # what the camera does when left alone
    
            def apply(is_night: bool) -> None:
                controls = night_controls if is_night else day_controls
                if controls:
                    camera.set_controls(controls)
                    print(f"camera controls ({'night' if is_night else 'day'}): {', '.join(f'{name} {value:g}' for name, value in controls.items())}")
    
            if switch is None or switch.night:
                apply(True)  # always on, or a reopen at night: the camera is right from its first frame
            if switch is not None or log_path:
                threading.Thread(target=watch_camera, args=(camera, log_path, switch, apply), daemon=True).start()
    
        return tune
    
    
    def watch_camera(
        camera: Any, log_path: Optional[str], switch: Optional[NightSwitch], apply: Callable[[bool], None],
        every: float = CAMERA_LOG_SECONDS, samples: Optional[int] = None, first_after: float = FIRST_READING_SECONDS,
    ) -> None:
        """While `camera` is open: read its metadata, switch day and night by its lux (if `switch`), and append a line to `log_path` (if given).
    
        It ends when the camera closes (a new one starts when it opens again). One failed reading is skipped, not fatal: a trap that stopped switching because the
        camera was briefly busy would be stuck in the wrong mode all night. A log file that cannot be written is skipped the same way. `samples` and `first_after` are for tests."""
        target = Path(log_path).expanduser() if log_path else None
        first = True
        warned = False
        taken = 0
        while samples is None or taken < samples:
            time.sleep(first_after if first else every)
            taken += 1
            try:
                if not camera.started:
                    return
                metadata = camera.capture_metadata()
                if switch is not None:
                    lux = metadata.get("Lux")
                    if lux is None and not warned:
                        warned = True
                        logger.warning("this camera reports no lux, so night mode cannot switch")
                    was_night = switch.night
                    if switch.update(lux, first) != was_night:
                        apply(switch.night)
                first = False
                if target is not None:
                    mode = "" if switch is None else (", night" if switch.night else ", day")
                    line = (
                        f"{datetime.now().astimezone().isoformat(timespec='seconds')} exposure {metadata.get('ExposureTime')} us, "
                        f"analogue gain {metadata.get('AnalogueGain')}, digital gain {metadata.get('DigitalGain')}, "
                        f"frame {metadata.get('FrameDuration')} us, lux {metadata.get('Lux')}{mode}\n"
                    )
                    with target.open("a") as handle:
                        handle.write(line)
            except Exception:  # a busy camera or a full disk: skip this reading, not the whole night
                logger.debug("could not read or log the camera", exc_info=True)
    
    
    # -- the command line -----------------------------------------------------------------------------------------------------------
    
    
    def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
        parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
        parser.add_argument("--server", help="the platform to register with the first time (default: $PIHUB_SERVER, else https://thepihub.com); ignored once registered")
        parser.add_argument("--simulate", action="store_true", help="no hardware: pretend GPIO pins and a test-pattern camera")
        parser.add_argument("--directory", default="~/thepihub-recordings", help="where recordings are saved (default: ~/thepihub-recordings)")
        parser.add_argument("--pir-pin", type=int, default=17, help="the GPIO the motion sensor's output is on (default: 17)")
        parser.add_argument("--ir-pin", type=int, default=22, help="the GPIO switching the infrared light, on while the camera is (default: 22)")
        parser.add_argument("--no-ir-light", action="store_true", help="there is no infrared light: leave its pin alone")
        parser.add_argument("--led-pin", type=int, help="a visible LED lit on motion, for setting the sensor up (default: none, so nothing glows)")
        parser.add_argument("--board-leds", choices=["off", "on"], default="off",
                            help="the Pi's own lights while the app runs (default: off; needs `sudo .venv/bin/pihub board-leds allow` once)")
        # A value given here wins over the dashboard's, and stops that setting being saved (the same rule as the camera's settings).
        parser.add_argument("--hold-seconds", type=float, help=f"keep recording this long after the last motion (default: the dashboard setting, else {DEFAULT_HOLD_SECONDS})")
        parser.add_argument("--pre-roll", type=float, help=f"seconds kept from before the motion, 0 to turn it off (default: the dashboard setting, else {DEFAULT_PRE_ROLL_SECONDS})")
        parser.add_argument("--size", help="video size, WIDTHxHEIGHT (default: the dashboard setting, else 640x480)")
        parser.add_argument("--fps", type=int, help="video frames per second (default: the dashboard setting, else 15)")
        parser.add_argument("--detector", choices=DETECTORS, default="pir",
                            help="what decides there is motion: pir (the sensor, as ever), both (the sensor, confirmed by the picture changing) or frames (the picture alone, no sensor needed). Default: pir")
        parser.add_argument("--movement-area", type=float, help=f"with --detector both or frames: the percent of the picture that must change (default: the dashboard setting, else {DEFAULT_AREA_PERCENT})")
        parser.add_argument("--movement-seconds", type=float, help=f"with --detector both or frames: for how many seconds without a break (default: the dashboard setting, else {DEFAULT_MOVEMENT_SECONDS})")
        parser.add_argument("--software-encoder", action="store_true", help="encode the video on the CPU instead of the Pi's hardware encoder (a Pi 5 has none, and does this by itself)")
        parser.add_argument("--exposure-value", type=float, help="aim the auto-exposure brighter (or darker) by this many stops, e.g. 1 or 2 for a dark scene (default: leave it alone)")
        parser.add_argument("--long-exposure", action="store_true", help="let the auto-exposure prefer long exposures: brighter in the dark, but moving animals blur")
        parser.add_argument("--brightness", type=float, help="lift the whole picture, -1 to 1, e.g. 0.1 (default: leave it alone)")
        parser.add_argument("--night-lux", type=float, help="use --exposure-value, --long-exposure and --brightness only when the camera's light reading (lux) is below this, and stop at twice it (default: always on). Choose it from --camera-log")
        parser.add_argument("--camera-log", help=f"append the camera's exposure time, gain and lux to this file every {CAMERA_LOG_SECONDS:g} seconds, to see what limits the picture")
        return parser.parse_args(argv)
    
    
    def build(args: argparse.Namespace, transport: Any = None) -> MotionTrap:
        """The device, its camera, sensor and LED, and the trap, NOT yet started. `transport` is for tests."""
        try:
            from gpiozero import LED, DigitalOutputDevice, GPIOZeroError, MotionSensor
            from gpiozero import Device as Pins
        except ImportError:
            raise SystemExit('error: this app needs gpiozero: pip install "thepihub[gpio]" (Raspberry Pi OS has it for its own Python)')
        from pihub.gpio import PIN_DRIVER_HELP, prepare_pins
        size = None
        if args.size:
            try:
                size = tuple(int(part) for part in args.size.lower().split("x"))
                if len(size) != 2:
                    raise ValueError
            except ValueError:
                raise SystemExit(f"error: --size must look like 640x480, not {args.size!r}")
    
        if args.simulate:
            from gpiozero.pins.mock import MockFactory
    
            Pins.pin_factory = MockFactory()
            source = EncodedTestPatternSource(size=size, fps=args.fps)
        else:
            prepare_pins()  # a venv without system packages: the pin driver is Raspberry Pi OS's own
            try:
                # The Pi's hardware encoder where there is one; else the CPU (libx264), which is still an ENCODED source, so it records. A test pattern is never
                # chosen here: a trap that films a test pattern would be a lie (--simulate is the way to see the app without a camera).
                source = best_camera_source(
                    size=size, fps=args.fps, software_encoder=args.software_encoder, require_encoded=True, motion_frames=args.detector != "pir",
                )
                if not source.real_camera:
                    raise CameraUnavailable("there is no camera here (try --simulate to see the app without one)")
            except CameraUnavailable as error:
                raise SystemExit(f"error: {error}")
            print(f"video: {source.description}")
            try:
                tuning = camera_tuning(args.exposure_value, args.long_exposure, args.brightness, args.camera_log, args.night_lux)
            except ValueError as error:
                raise SystemExit(f"error: {error}")
            if tuning is not None:
                source.on_open = tuning  # the camera calls it each time it opens, before it starts
    
        try:
            # At a terminal, the first run links this machine by code and the platform assigns its id; every run after connects at once.
            # Device Information holds the Video settings: on even with a transport given (a test's), where it would otherwise be off.
            device = Device(transport=transport, device_information=True, server=args.server)
        except ValueError as error:
            raise SystemExit(f"error: {error}")
    
        from pihub.board_leds import BoardLeds
    
        try:
            sensor = MotionSensor(args.pir_pin) if args.detector != "frames" else None  # the picture alone needs no sensor, so no pin is claimed
            led = LED(args.led_pin) if args.led_pin is not None else None
            ir_light = None if args.no_ir_light else DigitalOutputDevice(args.ir_pin)
        except (GPIOZeroError, OSError) as error:
            raise SystemExit(f"error: {PIN_DRIVER_HELP} ({error})")
        return MotionTrap(
            device, source, sensor, led, ir_light=ir_light,
            board_leds=BoardLeds() if args.board_leds == "off" else None,
            directory=args.directory, hold_seconds=args.hold_seconds, pre_roll_seconds=args.pre_roll,
            detector=args.detector, movement_area_percent=args.movement_area, movement_seconds=args.movement_seconds,
        )
    
    
    def main(argv: Optional[List[str]] = None) -> None:
        args = parse_args(argv)
        trap = build(args)
        trap.device.start()
        trap.start()
        print(f"{trap.device.id} is online{' (simulated: press Test motion on the dashboard)' if args.simulate else ''}. Ctrl+C to stop.")
        # A service stop (systemd) sends SIGTERM, not Ctrl+C. Left alone, SIGTERM kills the program at once and the cleanup in `finally`
        # below never runs. Treating it as Ctrl+C makes both ways of stopping do the same cleanup:
        # a recording in progress is finished, the infrared light is switched off and
        # the Pi's status LEDs are given back.
        signal.signal(signal.SIGTERM, signal.default_int_handler)
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            pass
        finally:
            print("Stopping...")
            trap.close()
            trap.device.stop()
    
    
    if __name__ == "__main__":
        main()  # pragma: no cover
    

Going further

  • Easy Verified

    Widget showcase

    Everything the dashboard can draw, in one program.

    You'll need:
    Just a computer to start; a Pi camera for a real picture

    Widget showcase

    examples/widget_showcase.py

    """Widget Showcase - every widget ThePiHub can draw, in one program you can copy from.
    
    Copy this file anywhere and run it:
    
        python widget_showcase.py
    
    If this is the first time you have connected from this device, it prints a link and a code: open the link
    while logged in to ThePiHub and approve it, then answer y when the terminal asks you to confirm the account.
    The device is yours and gets its id. Every run after that connects straight away. Ctrl+C stops it.
    
    What to look for on the dashboard. Each `Program` becomes a section with a heading, and this one makes three:
    
      Readouts   Gauge (one number), Status (a coloured word), Chart (several numbers over time).
      Controls   Button (runs your code), Toggle, Select, Slider and Text (a setting the dashboard changes and the device remembers).
      Camera     Camera (a live picture with snapshot, record and full-screen buttons), as in the Bird Box example.
      Files      Files (the Camera's Videos and Photos folders; download one, or "Download all" straight to your machine).
    
    `group=` puts widgets under a small heading inside their section: the two sets of buttons below are two groups, so they are two rows.
    Widgets of the same kind sit together on their own: gauges as tiles, buttons in a row, toggles/selects/sliders as slim rows, a chart or a
    video on a line of its own. You never lay anything out; you say what each widget is and the dashboard does the rest.
    
    The readings are made-up numbers standing in for sensors, so the gauges and the chart move: replace `_read_conditions()`.
    The picture is a moving test pattern (a bar sweeping across a gradient); on a Raspberry Pi with a camera, it is the real camera.
    The Camera needs the video pieces (the plain `pip install thepihub` brings PyAV; on a 32-bit Pi there is no pip build of PyAV, so install it with apt (`sudo apt install python3-picamera2 python3-av python3-aiortc`) and create the virtualenv with `--system-site-packages`). Files needs the same extra (a download is peer to peer, over its own DataChannel) and, like the Camera's video, only works over a direct connection.
    
    Adding a widget type to the platform? Add it here too: tests/examples/test_widget_showcase.py fails until you do.
    """
    
    from __future__ import annotations
    
    import math
    import time
    from typing import Dict, Optional
    
    from pihub import Device, Program, StringProperty
    from pihub.device import Transport
    from pihub.protocol.messages import CommandMessage
    from pihub.video import EncodedTestPatternSource, HardwareCameraSource
    
    # A temperature above this turns the Status to "Warning" and sends a warning notification (once, when it crosses).
    TOO_HOT = 28.0
    
    
    def _read_conditions(step: int) -> Dict[str, float]:
        """Made-up readings that drift smoothly, standing in for real sensor hardware."""
        return {
            "temperature": round(22.0 + 8.0 * math.sin(step / 3), 1),
            "humidity": round(60.0 + 25.0 * math.sin(step / 5), 1),
            "pressure": round(1015.0 + 20.0 * math.sin(step / 7), 1),
        }
    
    
    def main(transport: Optional[Transport] = None, cycles: Optional[int] = None, interval: float = 2.0) -> Device:
        """`transport` and `cycles` are for the tests: left out, it connects to the real server and runs until Ctrl+C."""
        device = Device(transport=transport)
    
        # ---- Section 1: Readouts. Outputs: the device pushes values, the dashboard only shows them. -------------------------------
        readouts = Program(id="readouts", name="Showcase: Readouts")
    
        # Gauge: one number. `units` is shown after it. `title` is the label (without one, the id is used).
        temperature = readouts.output(
            id="temperature", type="Gauge", properties=[StringProperty("title", default="Temperature"), StringProperty("units", default="°C")]
        )
        humidity = readouts.output(
            id="humidity", type="Gauge", properties=[StringProperty("title", default="Humidity"), StringProperty("units", default="%")]
        )
        pressure = readouts.output(
            id="pressure", type="Gauge", properties=[StringProperty("title", default="Pressure"), StringProperty("units", default="hPa")]
        )
    
        # Status: a word in a coloured pill. "Online" and "Running" are green, "Warning" amber, "Offline", "Stopped" and "Fault" red,
        # anything else grey.
        sensor_state = readouts.output(id="sensor-state", type="Status", properties=[StringProperty("title", default="Sensor")])
    
        # Chart: several values published together, drawn over time as one small panel each. Use `set_values` (not `set`) for it.
        conditions = readouts.output(id="conditions", type="Chart", properties=[StringProperty("title", default="Conditions")])
    
        # ---- Section 2: Controls. Buttons run your code; settings hold a value the dashboard can change. ------------------------------
        controls = Program(id="controls", name="Showcase: Controls")
    
        # Button: `command()` makes one, and `@handler` is the code that runs when it is pressed. `group=` puts buttons under a heading:
        # a different group is a different row.
        def button(id: str, title: str, group: str):
            widget = controls.command(id=id, type="Button", properties=[StringProperty("title", default=title)], group=group)
    
            @widget.handler
            def pressed(command: CommandMessage) -> None:
                # Your code goes here (switch a relay, open a valve). Then tell the dashboard, which keeps a Notification history.
                print(f"{title} pressed")  # shows in this terminal
                controls.info(f"{group}: {title}")  # and in the dashboard's Notification history
    
            return widget
    
        button("lights-on", "On", group="Lights")
        button("lights-off", "Off", group="Lights")
        button("lights-blink", "Blink", group="Lights")
        button("door-open", "Open", group="Doors")
        button("door-close", "Close", group="Doors")
        button("door-lock", "Lock", group="Doors")
    
        # Toggle, Select and Slider are *settings*: they show the value in force, the dashboard changes it, and the device checks it, saves it (so it
        # survives a restart), publishes it back and then calls `apply` with it. A value out of range is refused with a warning.
        # `.value` is what is set now; `.set(...)` changes it from your own code.
        controls.setting(
            "armed", "Toggle", default=False, title="Armed", group="Settings",
            apply=lambda value: print(f"Armed is now {value}"),
        )
        controls.setting(
            "mode", "Select", default="Auto", options=["Auto", "Day", "Night"], title="Mode", group="Settings",
            apply=lambda value: print(f"Mode is now {value}"),
        )
        controls.setting(
            "brightness", "Slider", default=50, minimum=0, maximum=100, step=5, units="%", title="Brightness", group="Settings",
            apply=lambda value: print(f"Brightness is now {value}"),
        )
        # Text: a free-text setting with an explicit Submit on the dashboard, not sent on every keystroke - same
        # check/save/publish/apply pipeline as Toggle/Select/Slider, just for a string. `max_length=` is optional.
        controls.setting(
            "greeting", "Text", default="Hello!", max_length=500, title="Greeting", group="Settings",
            apply=lambda value: print(f"Greeting is now {value!r}"),
        )
    
        # ---- Section 3: Camera. Peer to peer: the picture goes straight from the device to the browser, and only while someone watches. ----
        camera_section = Program(id="camera", name="Showcase: Camera")
    
        # Camera: a live picture with buttons for a snapshot, recording and full screen. `use()` says where the frames come from: the Pi's own
        # camera if there is one, otherwise a moving test pattern (a bright bar sweeping across a gradient) so you can see it is live.
        camera = camera_section.output(id="camera", type="Camera")
        camera.use(HardwareCameraSource() if HardwareCameraSource.available() else EncodedTestPatternSource())
        recorder = camera.recorder()  # adds the Record button (recordings and snapshots are saved on the device)
    
        # The camera has nothing to do while nobody is watching: these say when someone starts or stops. A program can also react to the viewer count.
        @camera_section.on_first_user_connected
        def viewer_arrived(payload: dict) -> None:
            camera_section.info("Viewer connected")
    
        @camera_section.on_last_user_disconnected
        def viewers_left(payload: dict) -> None:
            camera_section.info("Last viewer disconnected")
    
        # ---- Section 4: Files. The Camera's own folders - "Download all" saves everything in one straight to your machine, peer to peer,
        # deleting each one off the device once it has arrived (the widget's own toggle, on the dashboard, turns that off). ----------------
        files_section = Program(id="files", name="Showcase: Files")
        files = files_section.output(id="files", type="Files")
        files.add_folder("Videos", recorder.store.directory)
        files.add_folder("Photos", camera.snapshot_directory)
        recorder.on_saved(lambda _recording: files.publish())  # a finished recording shows up without a page reload
        # A snapshot has no equivalent hook yet: press the widget's own Refresh (it just asks the device to list its folders again).
    
        for program in (readouts, controls, camera_section, files_section):
            device.add_program(program)
        device.start()
    
        # ---- Notifications: `info`, `warning` and `error` appear on the dashboard; a warning stays until someone acknowledges it. ----------
        readouts.info("Showcase started")
    
        hot = False
        done = 0
        try:
            while cycles is None or done < cycles:
                readings = _read_conditions(done)
    
                # One value per Gauge.
                temperature.set(readings["temperature"])
                humidity.set(readings["humidity"])
                pressure.set(readings["pressure"])
    
                # Several values at once, for the Chart.
                conditions.set_values(readings)
    
                # A Status is just a word, and a warning is raised once when the temperature crosses the line, not on every reading.
                too_hot = readings["temperature"] > TOO_HOT
                sensor_state.set("Warning" if too_hot else "Online")
                if too_hot and not hot:
                    readouts.warning("Temperature is high")
                hot = too_hot
    
                done += 1
                if interval:
                    time.sleep(interval)
        except KeyboardInterrupt:  # pragma: no cover
            pass
        finally:
            device.stop()
    
        return device
    
    
    if __name__ == "__main__":
        main()  # pragma: no cover