Projects / Temperature logger / Phase 4
Phase 4 of 4 · about 2.5 hours
Survive anything, and share it
You end with a database that comes through crashes and power cuts undamaged, checked by killing the logger 200 times, and a web page with the latest reading, an hourly summary and a CSV download.
Step 4.1: What happens when the power goes (about 25 minutes)
When a program writes to a file, the data does not go to the SD card straight away. Linux keeps it in memory and writes it out a few seconds later, because that is much faster. If the power goes in between, that data is gone, and if it goes in the middle of writing, a file can be left half old and half new.
SQLite is built to cope with this. It writes changes so that a transaction is either all there or not there at all, and when you open the database after a crash, it finishes or undoes whatever was in progress. It does that by asking the operating system to push the data all the way to the card at the right moments, with a call named fsync, and by keeping a journal of changes on the side.
SD cards add their own trouble. A card has its own small computer inside that moves data around, and cheap cards do not always tell the truth about when data is safe. No software can fully fix a card that says "written" before it has written. Use a good card, and if power cuts are common where the logger lives, a small battery backup that gives the board time to shut down.
Step 4.2: WAL, and how hard to try (about 20 minutes)
Add two lines to open_db in logger.py, so it reads:
def open_db(path):
db = sqlite3.connect(path)
db.execute("PRAGMA journal_mode=WAL") # readers never block the writer, or the other way round
db.execute("PRAGMA synchronous=FULL") # a commit is on the card before execute returns
db.executescript(SCHEMA)
return db
journal_mode=WAL (write-ahead log) changes how SQLite keeps its journal. New data is added to a separate file, readings.db-wal, and moved into the main file now and then. The gain for us is that a program reading the database, such as the web page in Step 4.4, never blocks the logger from writing, and the logger never blocks the reader. You will see the -wal and -shm files next to the database. Leave them alone, and never copy the database file without them while the logger is running.
synchronous=FULL tells SQLite to wait for the data to reach the card at every commit. That is slower, but we commit one small row every ten seconds, so the cost is nothing. The faster setting, NORMAL, never corrupts a WAL database either, but it can lose the last few commits in a power cut.
Step 4.3: Kill it 200 times (about 30 minutes)
You cannot cut the power to your laptop 200 times, but you can kill a program 200 times at random moments, and that tests most of the same code. Create crash_test.py:
"""Kill the logger at random moments and check that the database is never damaged."""
import os
import random
import signal
import sqlite3
import subprocess
import sys
import time
DB = "crash_test.db"
ROUNDS = int(sys.argv[1]) if len(sys.argv) > 1 else 200
for name in (DB, DB + "-wal", DB + "-shm"):
if os.path.exists(name):
os.remove(name)
env = dict(os.environ, DB_PATH=DB, INTERVAL="0.01", SAMPLES="1") # as fast as it goes
random.seed(2)
saved = 0
for round_number in range(1, ROUNDS + 1):
logger = subprocess.Popen([sys.executable, "logger.py"], env=env, stdout=subprocess.DEVNULL)
time.sleep(random.uniform(0.1, 0.6))
logger.send_signal(signal.SIGKILL) # no warning, no clean up: like a crash
logger.wait()
db = sqlite3.connect(DB)
check = db.execute("PRAGMA integrity_check").fetchone()[0]
count, last_id = db.execute("SELECT count(*), max(id) FROM readings").fetchone()
db.close()
if check != "ok" or count < saved or count != last_id:
print(f"round {round_number}: FAIL integrity={check} count={count} last_id={last_id}")
sys.exit(1)
saved = count
print(f"{ROUNDS} kills, {saved} readings, database ok every time")
Each round starts the logger as fast as it goes, one raw reading per steady reading and a reading every 10 ms, waits a random time, and kills it with SIGKILL, which gives it no chance to finish anything. Then it opens the database and checks three things: SQLite's own integrity_check says the file is sound, no saved reading has gone missing, and the ids run from 1 with no gaps, which means no half-saved row slipped in.
With fake_adc.py running:
ADC_PATH=/tmp/fake_adc python3 crash_test.py
200 kills, 2034 readings, database ok every time
It takes about a minute, most of it spent waiting for SQLite to push each commit to disk. Be clear about what this shows. A killed program leaves its data in Linux's memory, and Linux still writes it out, so this tests SQLite's handling of a program dying mid-write. A power cut also loses what Linux had not written yet, and that is the part synchronous=FULL covers. If you want to test that too, do it on the board: run the logger, pull the power cable a few times, and run PRAGMA integrity_check after each boot.
Step 4.4: A web page (about 40 minutes)
Logging into the board to run a query gets old. Python's standard library has a small web server, which is plenty for one page that a few people look at. Create serve.py:
"""A small web page with the latest reading, an hourly summary and a CSV download."""
import json
import os
import sqlite3
from contextlib import closing
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
DB_PATH = os.environ.get("DB_PATH", "readings.db")
PORT = int(os.environ.get("PORT", "8080"))
HOURLY = """
SELECT substr(taken_at, 1, 13) || ':00', count(*), min(celsius), round(avg(celsius), 2), max(celsius)
FROM readings WHERE clock_ok = 1
GROUP BY 1 ORDER BY 1 DESC LIMIT 24
"""
def connect():
return sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)
def latest(db):
row = db.execute(
"SELECT taken_at, celsius, clock_ok FROM readings ORDER BY id DESC LIMIT 1"
).fetchone()
return None if row is None else {"taken_at": row[0], "celsius": row[1], "clock_ok": bool(row[2])}
def page(db):
now = latest(db)
head = "<p>No readings yet.</p>" if now is None else (
f"<p><strong>{now['celsius']:.1f} °C</strong> at {now['taken_at']}</p>"
)
rows = "".join(
f"<tr><td>{hour}</td><td>{count}</td><td>{low:.2f}</td><td>{avg:.2f}</td><td>{high:.2f}</td></tr>"
for hour, count, low, avg, high in db.execute(HOURLY)
)
return (
"<!doctype html><meta charset=utf-8><meta http-equiv=refresh content=30>"
"<title>Temperature</title><h1>Temperature</h1>" + head +
"<table border=1 cellpadding=4><tr><th>Hour (UTC)<th>Readings<th>Min<th>Avg<th>Max</tr>"
+ rows + "</table><p><a href=/readings.csv?hours=24>Last 24 hours as CSV</a></p>"
)
def csv_rows(db, hours):
yield "taken_at,clock_ok,celsius\n"
query = (
"SELECT taken_at, clock_ok, celsius FROM readings "
"WHERE taken_at >= strftime('%Y-%m-%dT%H:%M:%SZ', 'now', ?) ORDER BY id"
)
for taken_at, clock_ok, celsius in db.execute(query, (f"-{hours} hours",)):
yield f"{taken_at},{clock_ok},{celsius}\n"
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = urlparse(self.path)
with closing(connect()) as db:
if url.path == "/":
self.reply(200, "text/html; charset=utf-8", page(db))
elif url.path == "/latest.json":
self.reply(200, "application/json", json.dumps(latest(db)))
elif url.path == "/readings.csv":
try:
hours = int(parse_qs(url.query).get("hours", ["24"])[0])
except ValueError:
hours = 24
hours = max(1, min(hours, 24 * 366))
self.reply(200, "text/csv; charset=utf-8", "".join(csv_rows(db, hours)))
else:
self.reply(404, "text/plain; charset=utf-8", "not found\n")
def reply(self, status, content_type, body):
data = body.encode()
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
if __name__ == "__main__":
print(f"serving {DB_PATH} on port {PORT}", flush=True)
ThreadingHTTPServer(("", PORT), Handler).serve_forever()
It answers three addresses:
/is a page with the latest reading and a table of the last 24 hours, newest first.<meta http-equiv=refresh content=30>makes the browser reload it every 30 seconds./latest.jsonis the latest reading as JSON, for another program to read./readings.csv?hours=24is every reading from the last so many hours, as CSV, ready for a spreadsheet.
Each request opens its own read-only connection, and closing makes sure it is closed afterwards. ThreadingHTTPServer answers each request in its own thread, so one slow download does not hold up everyone else. The hours value comes from whoever typed the address, so it is checked: anything that is not a number becomes 24, and it is kept between 1 hour and a year. It reaches the query as a ? parameter, never pasted into the SQL text.
Try it on your laptop with the logger running against the pretend ADC:
ADC_PATH=/tmp/fake_adc INTERVAL=1 CLOCK_FLAG=/tmp/synced python3 logger.py
python3 serve.py
In a third terminal:
curl -s localhost:8080/latest.json
curl -s "localhost:8080/readings.csv?hours=1"
{"taken_at": "2026-11-24T09:28:49Z", "celsius": 22.18, "clock_ok": true}
taken_at,clock_ok,celsius
2026-11-24T09:28:46Z,1,22.04
2026-11-24T09:28:47Z,1,22.0
2026-11-24T09:28:48Z,1,22.09
2026-11-24T09:28:49Z,1,22.18
Open http://localhost:8080/ in your browser for the page itself.
Step 4.5: Run the page as a service (about 20 minutes)
Create templogger-web.service:
[Unit]
Description=Temperature logger web page
After=templogger.service
[Service]
Type=simple
User=templogger
Environment=DB_PATH=/var/lib/templogger/readings.db
Environment=PORT=8080
WorkingDirectory=/opt/templogger
ExecStart=/usr/bin/python3 /opt/templogger/serve.py
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
It runs as the same user, so it can read the database. Copy the new files to the board and install both services:
scp sensor.py logger.py serve.py templogger.service templogger-web.service [email protected]:
ssh [email protected]
sudo cp sensor.py logger.py serve.py /opt/templogger/
sudo cp templogger.service templogger-web.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl restart templogger
sudo systemctl enable --now templogger-web
The logger needs a restart to pick up the WAL setting. Now open http://192.168.7.2:8080/ on your laptop.
Pitfall: the page has no password, and it listens on every network the board is connected to. Over the USB cable only your laptop can reach it. If you connect the board to your home network with an Ethernet cable, anyone on that network can see your temperatures. That is fine for temperatures. It would not be fine for anything private.
Step 4.6: How long will it run? (about 15 minutes)
A logger is meant to be forgotten about, so check what it uses up. Each row is about 50 bytes in the database, with its share of the index. At one reading every 10 seconds that is 8,640 rows a day, under half a megabyte, or about 160 MB a year. An 8 GB card holds decades of it.
Wear is the other limit. Flash memory wears out after a number of writes, and the card spreads writes across its cells to make that last. A commit every 10 seconds, each some kilobytes once the journal and the file system are counted, adds up to roughly a hundred megabytes of writes a day. A decent card is rated for many times its own size in writes, so that is years of service. If you take readings every second instead, the writes go up ten times. Then it is worth keeping several readings in memory and committing them together, accepting that a power cut loses the readings not yet committed.
Check your own numbers on the board after a day:
ls -lh /var/lib/templogger/
sqlite3 /var/lib/templogger/readings.db "SELECT count(*) FROM readings;"
Phase 4 done
The logger keeps its data through crashes and power cuts, and anyone you choose can see the readings in a browser. The questions from the start now have answers. A nonsense reading is refused, the logger is honest about what it does not know, it comes back after a crash, and the log survives a power cut. The reading travels from a wire on a breadboard to a web page, and you wrote every step.