A local dashboard
Show your sensor readings on a web page served from your own network, with no cloud account: a small tested Python service, or a Home Assistant MQTT sensor configured in YAML.
You will learn
- Subscribe to a topic tree with wildcards and keep the latest value per device
- Serve readings on a local web page without exposing it beyond your own computer by default
- Treat MQTT topics and payloads as untrusted input: validate numbers and escape names
- Configure the same sensor in Home Assistant with availability and stale-data handling
Your ESP32-C5 now publishes readings and an online/offline status to a broker on your own computer (lesson 7). This lesson turns those messages into something you can look at on a phone or laptop, without signing up to anything. You get two routes. The first is a Python service of about 160 lines that you can read end to end, tested in CI against a real broker. The second is Home Assistant, if you already run it, configured in YAML with each key checked against its current documentation.
What the service does
The service subscribes to fieldguide/+/status and fieldguide/+/temperature, so every device that follows lesson 7’s topic layout appears on its own. It keeps the latest status, the latest temperature, the last 60 readings and the time of the last reading per device. The web page refreshes every 10 s and shows a row per device with a small line chart. /api/state returns the same data as JSON for other programs.
Reading messages safely
Anything that can reach your broker can publish to these topics, so the service treats every message as untrusted input. The update method checks the topic has exactly three levels, accepts only online and offline as status, and keeps a temperature only if it parses as a finite number:
# target: host sdk: python tier: 2
# examples/l09-local-dashboard/host/dashboard.py (excerpt)
class State:
"""Latest status and readings per device. MQTT callbacks write, HTTP handlers read."""
def __init__(self) -> None:
self._lock = threading.Lock()
self._devices: dict[str, dict] = {}
def update(self, topic: str, payload: bytes) -> None:
parts = topic.split("/")
if len(parts) != 3 or parts[0] != "fieldguide":
return
device, kind = parts[1], parts[2]
text = payload.decode("utf-8", errors="replace").strip()
with self._lock:
d = self._devices.setdefault(device, {"status": "unknown", "temperature": None, "history": [], "updated": None})
if kind == "status" and text in ("online", "offline"):
d["status"] = text
elif kind == "status" and text == "":
d["status"] = "unknown" # retained status cleared
elif kind == "temperature":
try:
value = float(text)
except ValueError:
return # ignore anything that is not a number
if not math.isfinite(value):
return
d["temperature"] = value
d["history"] = (d["history"] + [value])[-HISTORY:]
d["updated"] = time.time()
def snapshot(self) -> dict[str, dict]:
with self._lock:
return json.loads(json.dumps(self._devices))
Two threads touch the state: paho’s network thread writes, and the web server’s threads read. The lock makes each update and each snapshot atomic, and the snapshot returns a copy so the page never sees a half-written device.
The device name comes from the topic, which means a stranger controls it. If the page inserted it as it is, a name such as <img src=x onerror=alert(1)> would run script in your browser. html.escape() turns it into harmless text:
# target: host sdk: python tier: 2
# examples/l09-local-dashboard/host/dashboard.py (excerpt)
def render(devices: dict[str, dict]) -> str:
rows = []
for name in sorted(devices):
d = devices[name]
temp = "waiting" if d["temperature"] is None else f"{d['temperature']:.1f} °C"
age = "" if d["updated"] is None else f"{time.time() - d['updated']:.0f} s ago"
rows.append(f"<tr><td>{html.escape(name)}</td><td class='{html.escape(d['status'])}'>{html.escape(d['status'])}</td>"
f"<td>{temp}</td><td>{sparkline(d['history'])}</td><td>{age}</td></tr>")
body = "\n".join(rows) or "<tr><td colspan='5'>No devices yet. Is the broker running and the sensor publishing?</td></tr>"
Staying connected
The MQTT side is short because paho does the hard part. According to its documentation, loop_start() runs loop_forever() in a background thread, which reconnects by itself when reconnect_on_failure is true, the default. The wait between attempts starts at 1 s and doubles up to 120 s, the same back-off idea as lesson 6.
# target: host sdk: python tier: 2
# examples/l09-local-dashboard/host/dashboard.py (excerpt)
def start(host: str, port: int, http_bind: str = "127.0.0.1", http_port: int = 8080) -> tuple[mqtt.Client, ThreadingHTTPServer, State]:
"""Connect to the broker, subscribe, and serve HTTP in a background thread."""
state = State()
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=f"dashboard-{os.getpid()}")
if os.environ.get("MQTT_USERNAME"):
client.username_pw_set(os.environ["MQTT_USERNAME"], os.environ.get("MQTT_PASSWORD"))
def on_connect(c, userdata, flags, reason_code, properties):
if not reason_code.is_failure:
c.subscribe(TOPICS) # subscribing here means a reconnect subscribes again
client.on_connect = on_connect
client.on_message = lambda c, ud, msg: state.update(msg.topic, msg.payload)
client.connect(host, port, keepalive=30)
client.loop_start() # paho reconnects by itself if the broker goes away
server = ThreadingHTTPServer((http_bind, http_port), make_handler(state))
threading.Thread(target=server.serve_forever, daemon=True).start()
return client, server, state
Note where the subscription happens. paho connects with a clean session by default for MQTT 3.1.1, and the MQTT standard says a clean session, subscriptions included, ends with the network connection. If you subscribed once after connect(), a broker restart would leave you connected but deaf. Subscribing in on_connect renews the subscriptions after every reconnect.
The web server binds to 127.0.0.1 unless you set HTTP_BIND. That means only the computer running it can open the page. Set HTTP_BIND=0.0.0.0 in .env to reach it from a phone on your network. The page has no login, so anyone on that network can then read your readings.
Fresh and stale data
Lesson 7 publishes temperature without the retain flag and status with it. The dashboard shows why. When the service starts, the broker immediately sends the retained status of every device, so the rows appear at once with online or offline. The temperature column says waiting until the next reading arrives, at most 10 s later. A retained temperature would have filled the column immediately, possibly with a value from a sensor that died yesterday. The “Updated” column shows the age of the last reading, so a silent sensor is visible even before its will fires.
Run it
cd examples/l09-local-dashboard/host
cp .env.example .env # set MQTT_USERNAME / MQTT_PASSWORD for a broker user
python dashboard.py # then open http://127.0.0.1:8080/
Add a user for the dashboard to the broker’s password file with mosquitto_passwd passwd dashboard, without -c, so the sensor’s user stays. The .env file is gitignored, and the script reads it at start-up without any extra package. The only dependency outside the standard library is paho-mqtt 2.x. The web server is Python’s http.server, whose documentation warns that it is not recommended for production because it only implements basic security checks. That is acceptable on your own computer and is another reason for the default binding.
Test it without hardware
host/dashboard_test.py runs in our CI against a throwaway Mosquitto broker. It plays the part of the sensor and checks the page from the outside, through HTTP:
# target: host sdk: python tier: 2
# examples/l09-local-dashboard/host/dashboard_test.py (excerpt)
def main() -> int:
sensor = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="fake-sensor")
sensor.connect(HOST, PORT)
sensor.loop_start()
# Retained status published BEFORE the dashboard starts: the dashboard must still see it.
sensor.publish("fieldguide/c5-a1b2c3/status", "online", qos=1, retain=True).wait_for_publish(5)
client, server, _ = dashboard.start(HOST, PORT, "127.0.0.1", 0) # port 0: any free port
base = f"http://127.0.0.1:{server.server_address[1]}"
api = base + "/api/state"
s = wait_for(lambda st: st.get("c5-a1b2c3", {}).get("status") == "online", api)
print("retained status reached a dashboard that started later:", s["c5-a1b2c3"]["status"])
for v in ("21.4", "21.6", "not-a-number", "nan", "21.9"):
sensor.publish("fieldguide/c5-a1b2c3/temperature", v, qos=0).wait_for_publish(5)
s = wait_for(lambda st: st["c5-a1b2c3"]["temperature"] == 21.9, api)
assert s["c5-a1b2c3"]["history"] == [21.4, 21.6, 21.9], s
print("readings stored, bad payloads ignored:", s["c5-a1b2c3"]["history"])
# A device name is untrusted input from the network: it must be escaped in the HTML.
bad = "<img src=x onerror=alert(1)>"
sensor.publish(f"fieldguide/{bad}/temperature", "20.0").wait_for_publish(5)
wait_for(lambda st: bad in st, api)
page = fetch(base + "/")
assert "21.9 °C" in page and "<img src=x onerror=alert(1)>" in page and bad not in page, page
print("page renders readings and escapes device names")
The first check is the retained-status behaviour: the status is published before the dashboard starts, and the dashboard still shows it. Then come five readings, two of them invalid, and a hostile device name. Run it yourself with MQTT_HOST and MQTT_PORT pointing at your broker.
The Home Assistant route
If you already run Home Assistant on your network, it can show the same sensor next to your other devices. Its MQTT integration handles the broker connection, which you set up in the user interface when you add the integration. The sensor itself can be declared in YAML under the mqtt: key of configuration.yaml:
mqtt:
sensor:
- name: "Workbench C5 chip temperature"
unique_id: "fieldguide_c5_a1b2c3_temperature"
state_topic: "fieldguide/c5-a1b2c3/temperature"
unit_of_measurement: "°C"
device_class: temperature
state_class: measurement
suggested_display_precision: 1
expire_after: 60 # no reading for 60 s: the state becomes unavailable
availability:
- topic: "fieldguide/c5-a1b2c3/status"
payload_available: "online"
payload_not_available: "offline"
device:
identifiers: ["fieldguide_c5_a1b2c3"]
name: "Workbench C5"
model: "ESP32-C5-DevKitC-1"
What each key does, according to Home Assistant’s MQTT sensor documentation:
state_topicis the only required key: the topic whose payload becomes the state.unique_ididentifies the entity. Thedeviceblock, which groups entities under one device, only works whenunique_idis set and needsidentifiersorconnections.availabilitymarks the entity unavailable when the status topic saysoffline.onlineandofflineare also the defaults for the two payload keys, so they are written out here only for clarity.expire_aftermakes the state unavailable when no reading arrives for that many seconds. The documentation advises against retaining the state payload when you use it, which matches lesson 7’s choice.device_class,state_classandunit_of_measurementdescribe the value as a temperature measurement in degrees Celsius, anddevice_classalso picks the icon.suggested_display_precisionsets the number of decimals shown.
Replace c5-a1b2c3 with your device name from the serial log, then reload manually configured MQTT entities (the integration provides an mqtt.reload action) or restart Home Assistant. Our CI checks that this file parses as YAML. It does not run Home Assistant, so this part of the lesson is tier 1.
Which route to pick
| Job | Route | Why |
|---|---|---|
| Learn how the pieces fit, change the page freely | dashboard.py |
One file, standard library plus paho, tested in CI |
| Combine this sensor with devices you already run in Home Assistant | Home Assistant | The sensor becomes one more entity beside the rest |
| Feed readings to another program on your network | dashboard.py /api/state |
Plain JSON, no MQTT client needed in that program |
The two routes can run side by side. Both are ordinary MQTT subscribers, so the broker sends each of them its own copy of every message, and neither knows the other exists. Start with the Python service to see exactly what arrives, then add Home Assistant if you already use it.
For makers
Run dashboard.py on the same computer as the broker and keep the default 127.0.0.1 binding until you need your phone. Give the dashboard its own broker user. If you already have Home Assistant, use the YAML route. Either way, nothing leaves your network.
For product teams
A dashboard is a security boundary. Put authentication in front of any page served beyond one machine, and serve it over HTTPS. Restrict which clients may publish to the sensor topics with broker access-control lists, because the dashboard trusts topic names for display. Cap the number of devices and the history kept, since anyone who can publish can otherwise grow memory without limit. For a fleet, store readings in a time-series database rather than in process memory, and alert on stale data, not only on offline.
Exercise
- Publish
fieldguide/test/temperaturewith a few values frommosquitto_puband watch a new row appear. Then publishnanand confirm it is ignored. - Change
HISTORYto 360 to keep an hour of readings at the lesson 7 rate, and rename the column header to match. - Add an “age” check to
render()that colours the temperature grey when the last reading is older than 60 s.
Summary
- A wildcard subscription such as
fieldguide/+/temperaturepicks up every device that follows the topic layout. - Topic names and payloads are untrusted: validate numbers, accept only known status words, and escape anything shown in HTML.
- Subscribe in
on_connect, because a clean session forgets subscriptions when the connection drops. - Retain status, not readings. Show the age of the last reading, or use
expire_afterin Home Assistant. - Bind local services to
127.0.0.1by default and open them to the network only on purpose.
Further reading
- Home Assistant MQTT Sensor documentation, with every configuration key.
- Home Assistant MQTT integration documentation, for broker setup and the device block.
- Paho MQTT Python client: client module, Eclipse Foundation.
- MQTT Version 3.1.1, OASIS Standard, section 3.1.2.4 on clean sessions.
- Python
http.serverdocumentation, including its warning about production use.