knaxuslearn · build · ship

Projects / Temperature logger / Phase 3

Phase 3 of 4 · about 2.5 hours

Run it as a service

You end with the logger installed on the board as a service that starts at boot, comes back after a crash, stops cleanly when asked, and writes its messages to the system log.

Step 3.1: What a service is (about 15 minutes)

Right now the logger runs only while your SSH session is open. Close the laptop and it stops. A logger has to start when the board powers on, with nobody logged in, and keep going.

On Debian, programs that run like that are services, and systemd runs them. systemd is the first program Linux starts, and it starts everything else. You describe a service in a short text file called a unit, and systemd takes care of starting it, restarting it, and collecting its output. It sends a program the signal SIGTERM when it wants it to stop, and if the program has not stopped after a while, SIGKILL, which cannot be refused.

systemd asks politely with SIGTERM first, and only then uses SIGKILL.

Step 3.2: Stop cleanly (about 30 minutes)

Python's default answer to SIGTERM is to die on the spot, and to Ctrl-C it raises KeyboardInterrupt wherever the program happens to be. Because every reading is committed on its own, the database is fine either way. But it is better to finish what you are doing, close the database and say why you stopped.

Here is the whole of logger.py with that added:

"""Take a temperature reading every INTERVAL seconds and keep it in SQLite."""
import os
import signal
import sqlite3
import threading
import time
from datetime import datetime, timezone

import sensor

DB_PATH = os.environ.get("DB_PATH", "readings.db")
INTERVAL = float(os.environ.get("INTERVAL", "10"))
# systemd-timesyncd creates this file once the clock has been set from the network.
CLOCK_FLAG = os.environ.get("CLOCK_FLAG", "/run/systemd/timesync/synchronized")

SCHEMA = """
CREATE TABLE IF NOT EXISTS readings (
    id       INTEGER PRIMARY KEY,
    taken_at TEXT    NOT NULL,  -- UTC, like 2026-11-24T09:30:00Z
    clock_ok INTEGER NOT NULL,  -- 1 if the clock had been set from the network
    raw      INTEGER NOT NULL,
    celsius  REAL    NOT NULL
);
"""


def open_db(path):
    db = sqlite3.connect(path)
    db.executescript(SCHEMA)
    return db


def utc_now():
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def plausible(raw):
    """0 or 4095 means a loose wire or a short, not a temperature."""
    return 10 < raw < 4085


def take_reading(db):
    raw = sensor.read_steady()
    if not plausible(raw):
        print(f"sensor fault: raw={raw}, not saved", flush=True)
        return
    celsius = round(sensor.volts_to_celsius(sensor.raw_to_volts(raw)), 2)
    clock_ok = 1 if os.path.exists(CLOCK_FLAG) else 0
    taken_at = utc_now()
    with db:  # commits when the block ends
        db.execute(
            "INSERT INTO readings (taken_at, clock_ok, raw, celsius) VALUES (?, ?, ?, ?)",
            (taken_at, clock_ok, raw, celsius),
        )
    print(f"{taken_at} {celsius:.2f} C (raw {raw}, clock_ok {clock_ok})", flush=True)


stop = threading.Event()


def ask_to_stop(signum, frame):
    print(f"got {signal.Signals(signum).name}, stopping", flush=True)
    stop.set()


def main():
    signal.signal(signal.SIGTERM, ask_to_stop)  # what systemctl stop sends
    signal.signal(signal.SIGINT, ask_to_stop)   # Ctrl-C
    db = open_db(DB_PATH)
    print(f"logging every {INTERVAL:g} s to {DB_PATH}", flush=True)
    next_due = time.monotonic()
    while not stop.is_set():
        take_reading(db)
        next_due += INTERVAL
        now = time.monotonic()
        if now > next_due:  # we fell behind, say after a long pause: skip, do not catch up
            missed = int((now - next_due) // INTERVAL) + 1
            next_due += missed * INTERVAL
            print(f"fell behind: skipped {missed} reading(s)", flush=True)
        stop.wait(next_due - now)  # like sleep, but a signal ends it early
    db.close()
    print("stopped", flush=True)


if __name__ == "__main__":
    main()

signal.signal sets ask_to_stop to run when the signal arrives. All it does is set an Event, a flag the loop checks. The sleep is now stop.wait(...), which waits for the flag with a time limit. It returns as soon as the flag is set, so the logger stops at once, even in the middle of a ten-second wait.

Test it. Start the logger with a ten-second interval, and from another terminal send it SIGTERM:

ADC_PATH=/tmp/fake_adc python3 logger.py
pkill -TERM -f logger.py
logging every 10 s to readings.db
2026-11-24T09:26:30Z 22.04 C (raw 1639, clock_ok 0)
got SIGTERM, stopping
stopped

It stopped in a few milliseconds, with its exit status 0.

Step 3.3: Install it (about 30 minutes)

A service should not run as root, the user that can do anything, or as your own login. Give it a user of its own that can do nothing else. On the board:

sudo useradd --system --no-create-home templogger
sudo mkdir -p /opt/templogger

From your laptop, copy the code over and move it into place:

scp sensor.py logger.py [email protected]:
ssh [email protected] sudo cp sensor.py logger.py /opt/templogger/

The new user must be able to read the ADC. Check the file's permissions on the board:

ls -l /sys/bus/iio/devices/iio:device0/in_voltage0_raw

If the last group of letters includes r, as in -rw-r--r--, anyone can read it and you are done. If not, note the group named in the listing. You will give the service that group in the next step.

Step 3.4: The unit file (about 30 minutes)

Create templogger.service on your laptop:

[Unit]
Description=Temperature logger
Documentation=file:///opt/templogger/logger.py

[Service]
Type=simple
User=templogger
Environment=DB_PATH=/var/lib/templogger/readings.db
Environment=INTERVAL=10
StateDirectory=templogger
WorkingDirectory=/opt/templogger
ExecStart=/usr/bin/python3 /opt/templogger/logger.py
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

Read it line by line:

  • User=templogger runs it as the new user.
  • Environment= sets the same variables you have been using. On the board, the database goes in /var/lib/templogger.
  • StateDirectory=templogger tells systemd to create /var/lib/templogger and give it to the service's user. You do not have to make the folder or fix its owner.
  • Restart=on-failure restarts the logger if it crashes or is killed, after waiting RestartSec=5 seconds. A clean exit, as after systemctl stop, is left alone.
  • WantedBy=multi-user.target means "start this at boot, when the system is up".

If the ADC file was not readable by everyone in Step 3.3, add a line under [Service] with the group it belongs to, such as SupplementaryGroups=iio.

Check the file for mistakes before installing it. systemd-analyze reads a unit and complains about anything it does not understand:

systemd-analyze verify ./templogger.service

It prints nothing when the file is fine. Copy it to the board and turn it on:

scp templogger.service [email protected]:
ssh [email protected]
sudo cp templogger.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now templogger

daemon-reload tells systemd to read its unit files again. enable makes the service start at every boot, and --now starts it straight away as well.

Step 3.5: Break it on purpose (about 30 minutes)

A service is only as good as its recovery. Look at it first:

systemctl status templogger

You should see active (running) and the last few lines it printed. Now kill it the hard way, as a crash would:

sudo pkill -KILL -f /opt/templogger/logger.py
sleep 6
systemctl status templogger

It should be running again, with a new process number and a start time a few seconds ago. Now stop it properly, and check that it stays stopped:

sudo systemctl stop templogger
systemctl status templogger

You should see inactive (dead). Start it again with sudo systemctl start templogger. Then the real test:

sudo reboot

Wait a minute, log in again, and check that systemctl status templogger says it is running, and that new readings are arriving:

sqlite3 /var/lib/templogger/readings.db "SELECT * FROM readings ORDER BY id DESC LIMIT 3;"

If the board has no network after a reboot, the newest readings will have clock_ok set to 0. That is Step 2.5 working.

Step 3.6: Read its messages (about 15 minutes)

Everything the logger prints goes to the system journal, with the time and the service's name. That is why every print has flush=True: without it Python holds output back in a buffer when it is not writing to a terminal, and the journal would get it in late bursts.

journalctl -u templogger -n 20
journalctl -u templogger -f

The first shows the last 20 lines. The second follows new lines as they arrive, like tail -f. Press Ctrl-C to stop following. Kill the logger again and watch the journal: you will see it die, systemd note the failure, and five seconds later the logging every 10 s line as it starts again.

Phase 3 done

The logger now runs by itself from power-on, gets back up after a crash, and keeps a record of what happened. You can unplug your laptop and walk away.