Example - copy and change it
Easy Verified
Source: examples/widget_showcase.py View full code
Widgets: Gauge, Status, Chart, Button, Toggle, Select, Slider, Text, Camera, Files
You'll need: Just a computer to start; a Pi camera for a real picture
What we've checked: Tested with a fake connection, including a check that it uses every widget the frontend can draw. Started on a Pi Zero W against the dev server and connected, and its dashboard (controls, camera streaming the test pattern) seen in real Chrome against a real server. Run on the Pi 3A+ against production (2026-09-28), under its own throwaway identity: a file listed in the Files section was downloaded and then deleted, confirmed peer to peer over a real direct connection. Most examples show one idea. This one is the menu: each kind of widget, in one short program, each with a comment saying what it is for. Copy the part you want.
You'll need
A Raspberry Pi or any computer with Python 3.10 or newer
Nothing to wire: this one is a menu of everything the dashboard can draw
No Pi yet?
Nothing here needs a Pi: follow the steps below on your computer. The camera shows a moving test pattern.
Build it
This project assumes you've registered the device (see Getting Started ).
On your Pi, or on your computer, install the SDK: pip install thepihub.
Press View full code above and copy it into a file called widget_showcase.py, or press to copy a command that creates it.
Running it
Run it:
python widget_showcase.py
Then open your dashboard . Four sections appear: readouts, controls, a camera and files. Open each one.
Try changing this
Press every button, move the slider, flip the toggle and submit a greeting. Watch what happens on the dashboard.
Pick your favourite widget and copy it into the Greenhouse example.
The educational bit
Which widget would you use for a light switch? For the temperature of a room? For a volume control? For a photo of your garden?
Safety notes
Nothing to wire and nothing to break: a good place to let a child click around.
What next
Pick the widgets you like and copy them into your own program.
Add real hardware with Button and LED .
See a real picture: put a camera on it with Live camera .
Under the hood
The rest of this page is for when you want to know how it works.
Four programs, four sections
readouts = Program(id="readouts", name="Showcase: Readouts")
controls = Program(id="controls", name="Showcase: Controls")
camera_section = Program(id="camera", name="Showcase: Camera")
files_section = Program(id="files", name="Showcase: Files")
Each Program becomes a section on the dashboard, with a heading made from its name. You never say where anything goes: you say what each widget is, and the dashboard lays them out. Gauges and statuses become tiles, buttons share a row, toggles, selects, sliders and text settings become slim rows, and a chart or a video gets a line to itself.
Readouts: the device talks, the dashboard shows
A Gauge is one number (.set(22.5)), a Status is a word that the dashboard colours (Online is green, Warning amber, Offline red), and a Chart is several numbers sent together (.set_values({...})), drawn over time as one small panel each. The numbers here are made up and drift smoothly, so you can watch them move; replace _read_conditions() with a real sensor.
Controls: the dashboard talks back
A Button runs your code:
@widget.handler
def pressed(command):
print("pressed")
controls.info("Lights: On") # shows in the Notification history
Give buttons a group= and they sit under a small heading. The showcase has two groups of three, and they are two rows.
A Toggle , a Select , a Slider and a Text are settings. The dashboard changes them, the device checks the value (a bad one is refused with a warning), saves it so it survives a restart, publishes it back so every open page agrees, and then calls your apply function, which is where you act on it. Text is the odd one out: a 3-line box, full width with its own label above it rather than beside it, that doesn't send anything while you type - only when you press its Submit button, the same "commit only on an explicit gesture" idea a Slider already uses when you let go of the handle.
Camera
The Camera is a live picture that goes straight from the device to your browser, only while someone is watching, with buttons to take a snapshot, record and go full screen. It is the same widget the Bird Box uses. Without a Pi camera the picture is a moving test pattern (a bright bar sweeping across a gradient, so you can see it is live); on a Pi with a camera it is the real camera.
There is also a plain Video widget (the picture without the buttons). The showcase leaves it out on purpose: a device streams one camera at a time and every video widget for it plays that stream, so a Video next to a Camera would just play in step with it.
Files
The Files widget lists one or more folders on the device and downloads what is in them, straight to your own machine - peer to peer, so it needs the video extras and a direct connection, the same as the Camera's live picture. The showcase points it at the Camera's own Videos and Photos folders:
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 appears without a page reload
Every file starts checked, so "Download Selected" grabs everything by default - untick what you do not want first. It asks Chrome or Edge for a folder once and writes every file into it as it arrives; elsewhere it falls back to the browser's own downloads, one at a time. Two checkboxes, Download and Delete , both on by default, say what the button does. Both on: files are downloaded, and each is only deleted off the device once its full byte count has actually arrived. Download only: you keep both copies. Delete only: the button becomes Delete Selected , which removes the checked files from the device without fetching them (to clear space), after one "cannot be undone" confirmation, and it does not need the direct connection. Starting a download stops any live video first (a small Pi cannot do both for long: a long file with video running made a Pi Zero W drop the connection), so press play again afterwards. Downloads also go one at a time: start several (a folder, or the Videos and the Photos together) and the rest wait their turn. On a Pi Zero W that is also watching with a camera trap, a big file can still drop the connection: switch the trap's Armed toggle off for large downloads (not yet tried on a Pi Zero 2 W). A Select all / Deselect all box above each folder's list checks or unchecks every file, and each row has its own trash button, which asks "Delete?" and removes just that file whatever the two boxes say.
Notifications
info, warning and error appear on the dashboard. A warning stays until someone acknowledges it. The showcase raises one when the temperature crosses a line, once, not on every reading.
Keeping it complete
This program is meant to stay a full list. A test compares it with the widgets the frontend registers, and fails when a widget is added to the platform without a place here (or without a written reason for leaving it out, as with the plain Video).
← Back to Projects """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
Create widget_showcase.py from a terminal Paste this into a terminal on your Pi (over SSH is fine). It writes the whole program to widget_showcase.py in the folder you are in.
cat > widget_showcase.py << 'EOF'
"""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
EOF