Skip to content

2.9 Keeping time and Lab 2: A non-root C++ systemd service

In Section 1.1, we saw that sensor data only becomes meaningful information when it is stamped with accurate physical units and an accurate timestamp. Network security also depends on knowing the correct date and time: when your gateway connects to an HTTPS server or an mqtts:// broker over TLS 1.31 (Section 15.6), the TLS handshake verifies that the server’s X.509 certificate falls between its Not Before and Not After validity dates.2 If your gateway starts after a long power cut with its clock set to an old saved time (or to the date its OS image was built), TLS connections can fail with a certificate-not-yet-valid error.


Why most gateways do not know the time at power-on

Section titled “Why most gateways do not know the time at power-on”

On a desktop PC or laptop, a CR2032 lithium coin cell on the motherboard powers a crystal oscillator and a Real-Time Clock (RTC) circuit (CMOS clock) 24 hours a day, even when the computer is unplugged from the wall.

To reduce bill-of-materials cost and board area, most embedded Linux boards omit a battery-backed RTC:

  • Raspberry Pi 1 through Raspberry Pi 4 (and Pi Zero 2 W): Have no on-board Real-Time Clock hardware and no battery connector. When power is removed, the board stops counting time. At boot, systemd sets the clock to the later of its own build date and the time that systemd-timesyncd last saved (the timestamp of /var/lib/systemd/timesync/clock).3 4 The clock therefore does not go back to 1970-01-01 and timestamps do not run backwards, but the time is wrong by the length of the power outage until NTP corrects it. Up to Bookworm, Raspberry Pi OS also ran a service called fake-hwclock, which saved the time to /etc/fake-hwclock.data every hour and at shutdown for the same purpose.5

  • BeagleBone Black (TI AM335x): The AM335x SoC actually contains an internal RTC block on the silicon die,6 but the board has no backup coin cell fitted by default, so time is still lost when 5 V power is removed.

  • Raspberry Pi 5: Includes a real RTC inside its DA9091 Power Management IC alongside a dedicated 2-pin J5 battery connector for an optional rechargeable ML2020 lithium coin cell.7

  • Off-grid / Offline Raspberry Pi 4 Gateways (Assignment 1): When a Raspberry Pi 4 gateway is deployed in a field, marine, or industrial location where internet connectivity may be unavailable at boot, we attach an external temperature-compensated I²C Real-Time Clock (specifically the Maxim / Analog Devices DS32318 with a CR2032 backup battery) to the I²C1 bus (Pins 3 & 5). Writing a C++ class to control the DS3231 over /dev/i2c-1 is the subject of Assignment 1 and Chapter 8.9


Network Time Protocol (NTP) with timedatectl and systemd-timesyncd

Section titled “Network Time Protocol (NTP) with timedatectl and systemd-timesyncd”

Whenever your gateway has an active internet or campus network connection, it synchronises its system clock automatically over UDP port 123 using the Network Time Protocol (NTP)10 (explored alongside hardware timestamping and chrony in Chapter 15).

On modern Raspberry Pi OS (Bookworm and Trixie), you do not need the legacy ntpd or ntpdate packages; lightweight SNTP synchronisation is built directly into systemd via the systemd-timesyncd.service daemon4 and controlled through timedatectl:11

Terminal window
derek@rpi:~ $ timedatectl status
Local time: Sat 2026-11-07 20:15:42 GMT
Universal time: Sat 2026-11-07 20:15:42 UTC
RTC time: n/a
Time zone: Europe/Dublin (GMT, +0000)
System clock synchronized: yes
NTP service: active
RTC in local TZ: no

Look at the third line: RTC time: n/a confirms that our Raspberry Pi 4 has no hardware RTC attached yet, while System clock synchronized: yes confirms that systemd-timesyncd has locked onto an upstream NTP server. You can inspect the exact NTP server, round-trip delay, and clock jitter using timedatectl timesync-status:

Terminal window
derek@rpi:~ $ timedatectl timesync-status
Server: 193.1.219.116 (2.debian.pool.ntp.org)
Poll interval: 34min 8s (min: 32s; max 34min 8s)
Leap: normal
Version: 4
Stratum: 2
Reference: 892B1C0A
Precision: 1us (-20)
Root distance: 14.210ms (max: 5s)
Offset: +412us
Delay: 8.104ms
Jitter: 185us
Packet count: 14

Setting the timezone or manual clock when offline

Section titled “Setting the timezone or manual clock when offline”

To configure your timezone or set the clock manually on an isolated lab network where NTP cannot reach the internet:

Terminal window
# 1. Set the gateway timezone to Dublin (handles Irish Standard Time / GMT transitions automatically):
derek@rpi:~ $ sudo timedatectl set-timezone Europe/Dublin
# 2. To set the clock manually when offline, you MUST disable NTP auto-sync first,
# otherwise timedatectl refuses with "Automatic time synchronization is enabled":
derek@rpi:~ $ sudo timedatectl set-ntp false
derek@rpi:~ $ sudo timedatectl set-time '2026-11-07 20:20:00'
# 3. Re-enable automatic NTP sync once network access is restored:
derek@rpi:~ $ sudo timedatectl set-ntp true

Figure 2.19 shows what the clock reads after a power-off with each time source, and what a wrong clock does to TLS and to your sensor timestamps until NTP corrects it. Its second view is the architecture of Lab 2 below.

Figure 2.19

What time does the gateway think it is?

Choose the clock source, the outage and when NTP is reachable.

Board and clock
Clock at boot
2026 Nov 08 09:20:00
True time 2026 Nov 09 10:00:00
Error
24.7 hours behind
fake-hwclock restored its last hourly save, so the clock is behind by the whole outage plus the time since that save.
First TLS connection
Succeeds
The clock is inside the certificate's validity period.
Readings with the wrong time
12 (one every 5 s)
Until NTP steps the clock 61 s after boot.
journalctl (excerpt): look for the jump in the timestamps
2026 Nov 08 09:20:00 rpi kernel: Booting Linux on physical CPU 0x0
2026 Nov 08 09:20:12 rpi sensor-logger[612]: reading 1: 46.2 C
2026 Nov 08 09:21:12 rpi sensor-logger[612]: TLS handshake with broker.local:8883 succeeded
2026 Nov 09 10:01:13 rpi systemd-timesyncd[401]: Contacted time server 193.1.219.116:123 (2.debian.pool.ntp.org).
2026 Nov 09 10:01:13 rpi systemd-timesyncd[401]: Initial clock synchronization to 2026 Nov 09 10:01:13.
2026 Nov 09 10:01:17 rpi sensor-logger[612]: TLS handshake with broker.local:8883 succeeded

Order a service that needs the right time after time-sync.target (with systemd-time-wait-sync.service enabled) so that it does not connect before the clock is set. Newer systemd releases also move the clock forward at boot to the last time systemd-timesyncd saved, which removes the 1970 case but not the outage.

Figure 2.19. The gateway’s clock at boot with no RTC, a saved clock (labelled fake-hwclock in the figure), a DS3231 or the Raspberry Pi 5 RTC, and the effect of the error on TLS certificate checks and sensor timestamps; and the Lab 2 architecture. RTC drift figures are typical values.


Lab 2: Running a C++ sensor-logging and LED daemon under a non-root systemd service

Section titled “Lab 2: Running a C++ sensor-logging and LED daemon under a non-root systemd service”

In this laboratory exercise, you will bring together every concept from Chapter 2: power and thermal inspection (vcgencmd, /sys/class/thermal/), sysfs LED control (/sys/class/leds/), least-privilege user and group management (useradd, gpio group, udev rules), RAM-backed volatile storage (/run), and systemd service supervision (systemctl, journalctl).

You will write a C++17 gateway daemon, gateway-thermal-monitor, that:

  1. Runs continuously in the background as a dedicated, unprivileged system user (sensorsvc), never as root.
  2. Reads the SoC die temperature from /sys/class/thermal/thermal_zone0/temp every 5 seconds.
  3. Drives the onboard green ACT LED via /sys/class/leds/ACT/ using a custom udev group-permission rule: showing the heartbeat pattern during normal operation, and switching to a 5 Hz warning flash (100 ms on, 100 ms off) if the temperature exceeds a configurable threshold.12
  4. Writes a compact JSON status snapshot atomically to the RAM-backed /run/gateway-thermal/ tmpfs directory (which causes no microSD wear), writes log messages to systemd-journald, and shuts down cleanly on SIGTERM when systemd stops the service.

Step 1: Verify gateway power, thermals, and time

Section titled “Step 1: Verify gateway power, thermals, and time”

SSH into your Raspberry Pi 4 (or Pi 5) gateway and verify that your power supply is healthy (throttled=0x0), your clock is synchronised via NTP, and the thermal and LED sysfs nodes exist:

Terminal window
derek@rpi:~ $ vcgencmd get_throttled
throttled=0x0
derek@rpi:~ $ timedatectl status | grep "synchronized"
System clock synchronized: yes
derek@rpi:~ $ cat /sys/class/thermal/thermal_zone0/temp
45820
derek@rpi:~ $ ls -l /sys/class/leds/ACT/

Step 2: Create the unprivileged sensorsvc user and udev LED rule

Section titled “Step 2: Create the unprivileged sensorsvc user and udev LED rule”

By default, /sys/class/leds/ACT/trigger, delay_on, and delay_off are owned by root:root (-rw-r--r--). Instead of running our C++ program as root, let us create a locked system account named sensorsvc, add it to the gpio group, and install a udev rule that grants the gpio group write access to /sys/class/leds/:

Terminal window
# 1. Create the locked system account (no password, no login shell):
derek@rpi:~ $ sudo useradd --system --no-create-home --shell /usr/sbin/nologin sensorsvc
derek@rpi:~ $ sudo usermod -aG gpio sensorsvc
derek@rpi:~ $ id sensorsvc
uid=995(sensorsvc) gid=991(sensorsvc) groups=991(sensorsvc),993(gpio)
# 2. Create /etc/udev/rules.d/99-gateway-leds.rules so 'gpio' group can write LED triggers & delays:
derek@rpi:~ $ sudo tee /etc/udev/rules.d/99-gateway-leds.rules > /dev/null << 'EOF'
SUBSYSTEM=="leds", ACTION=="add|change", RUN+="/bin/chgrp -R gpio /sys%p", RUN+="/bin/chmod -R g=u /sys%p"
EOF
# 3. Reload and trigger udev rules immediately:
derek@rpi:~ $ sudo udevadm control --reload-rules
derek@rpi:~ $ sudo udevadm trigger --subsystem-match=leds
# 4. Verify that /sys/class/leds/ACT/trigger is now group-owned by 'gpio' and group-writable (-rw-rw-r--):
derek@rpi:~ $ ls -l /sys/class/leds/ACT/trigger
-rw-rw-r-- 1 root gpio 4096 Nov 7 20:30 /sys/class/leds/ACT/trigger

Step 3: Write and compile the C++17 gateway-thermal-monitor daemon

Section titled “Step 3: Write and compile the C++17 gateway-thermal-monitor daemon”

Create a working directory ~/lab2 and save the following C++17 program as ~/lab2/gateway_thermal_monitor.cpp:

~/lab2/gateway_thermal_monitor.cpp
// EEN1071 Lab 2: Non-root systemd thermal monitor and sysfs LED controller
#include <chrono>
#include <csignal>
#include <cstdio>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <thread>
namespace {
// A signal handler may only do async-signal-safe work, so it sets a flag
// and the main loop does the logging and the clean-up.
volatile std::sig_atomic_t g_stop_signal = 0;
void signal_handler(int signum) {
g_stop_signal = signum;
}
// Write a value to a sysfs file. With attempts > 1, retry every 50 ms: the
// kernel creates delay_on and delay_off as root:root, and the udev rule
// changes their group a short time later.
bool write_sysfs(const std::string& path, const std::string& value, int attempts = 1) {
for (int i = 0; i < attempts; ++i) {
std::ofstream ofs(path);
if (ofs.is_open()) {
ofs << value << std::flush;
return ofs.good();
}
if (i + 1 < attempts) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
std::cerr << "ERROR: Cannot open " << path << " for writing (check udev/group permissions)." << std::endl;
return false;
}
double read_soc_temp_celsius() {
std::ifstream ifs("/sys/class/thermal/thermal_zone0/temp");
long millidegrees = 0;
if (ifs >> millidegrees) {
return static_cast<double>(millidegrees) / 1000.0;
}
return -1.0;
}
} // namespace
int main(int argc, char* argv[]) {
// Default alert threshold: 60.0 C (pass a lower value like 40.0 on the CLI to test the alarm state!)
double alert_threshold_c = 60.0;
if (argc > 1) {
alert_threshold_c = std::stod(argv[1]);
}
std::signal(SIGTERM, signal_handler);
std::signal(SIGINT, signal_handler);
const std::string led_base = "/sys/class/leds/ACT/";
const std::string status_file = "/run/gateway-thermal/status.json";
const std::string status_tmp = status_file + ".tmp";
std::cout << "Starting gateway-thermal-monitor (alert threshold: "
<< std::fixed << std::setprecision(1) << alert_threshold_c << " C)" << std::endl;
std::string current_mode = "";
while (g_stop_signal == 0) {
double temp_c = read_soc_temp_celsius();
bool is_alert = (temp_c >= alert_threshold_c);
std::string target_mode = is_alert ? "alert" : "normal";
// Only update the sysfs LED trigger when the state changes:
if (target_mode != current_mode) {
if (is_alert) {
std::cout << "ALERT: SoC temperature (" << temp_c << " C) >= threshold ("
<< alert_threshold_c << " C)! Switching ACT LED to fast 5 Hz timer." << std::endl;
if (write_sysfs(led_base + "trigger", "timer")) {
// Retry for up to 1 s while udev gives the new delay files to the gpio group:
write_sysfs(led_base + "delay_on", "100", 20);
write_sysfs(led_base + "delay_off", "100", 20);
}
} else {
std::cout << "STATE: SoC temperature (" << temp_c << " C) normal. "
<< "Setting ACT LED trigger to heartbeat." << std::endl;
write_sysfs(led_base + "trigger", "heartbeat");
}
current_mode = target_mode;
}
// Log periodic telemetry to stdout (captured by systemd-journald):
std::cout << "TELEMETRY: temp_c=" << std::fixed << std::setprecision(2) << temp_c
<< " state=" << current_mode << std::endl;
// Write the latest state to tmpfs (no SD card wear). Write a temporary file and
// rename it, so that a reader never sees a half-written status.json:
std::ofstream json_out(status_tmp, std::ios::trunc);
if (json_out.is_open()) {
std::time_t now = std::time(nullptr);
json_out << "{\n"
<< " \"timestamp_epoch\": " << now << ",\n"
<< " \"temperature_c\": " << std::fixed << std::setprecision(2) << temp_c << ",\n"
<< " \"threshold_c\": " << alert_threshold_c << ",\n"
<< " \"state\": \"" << current_mode << "\"\n"
<< "}\n";
json_out.close();
std::rename(status_tmp.c_str(), status_file.c_str());
}
// Sleep for 5 seconds in 200 ms increments so SIGTERM responds within 200 ms:
for (int i = 0; i < 25 && g_stop_signal == 0; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
}
// Restore the default SD card activity trigger (mmc0) on clean shutdown:
std::cout << "Received signal " << g_stop_signal << "; restoring ACT LED trigger to [mmc0] before exit." << std::endl;
write_sysfs(led_base + "trigger", "mmc0");
return 0;
}

Compile the daemon with g++ and install the binary into /usr/local/bin/:

Terminal window
derek@rpi:~ $ mkdir -p ~/lab2 && cd ~/lab2
# (Save gateway_thermal_monitor.cpp)
derek@rpi:~/lab2 $ g++ -std=c++17 -O2 -Wall -Wextra gateway_thermal_monitor.cpp -o gateway-thermal-monitor
derek@rpi:~/lab2 $ sudo install -m 0755 -o root -g root gateway-thermal-monitor /usr/local/bin/gateway-thermal-monitor

Step 4: Create and enable the systemd service unit

Section titled “Step 4: Create and enable the systemd service unit”

Create the service definition file at /etc/systemd/system/gateway-thermal.service. Notice how RuntimeDirectory=gateway-thermal instructs systemd to automatically create /run/gateway-thermal/ in tmpfs (RAM) owned by sensorsvc:sensorsvc before starting the binary, and clean it up when stopped.13

/etc/systemd/system/gateway-thermal.service
[Unit]
Description=EEN1071 Lab 2 Gateway Thermal Monitor and LED Daemon
[Service]
Type=simple
User=sensorsvc
Group=sensorsvc
SupplementaryGroups=gpio
# Automatically create /run/gateway-thermal in tmpfs (RAM) owned by sensorsvc:
RuntimeDirectory=gateway-thermal
RuntimeDirectoryMode=0755
# Pass 60.0 C as the alert threshold (change to 35.0 to test the fast-blink alarm!):
ExecStart=/usr/local/bin/gateway-thermal-monitor 60.0
Restart=on-failure
RestartSec=3s
StandardOutput=journal
StandardError=journal
SyslogIdentifier=gateway-thermal
# Security sandboxing:
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target

Reload systemd, enable and start the service, and inspect both journalctl and the RAM-backed status file:

Terminal window
derek@rpi:~/lab2 $ sudo systemctl daemon-reload
derek@rpi:~/lab2 $ sudo systemctl enable --now gateway-thermal.service
derek@rpi:~/lab2 $ systemctl status gateway-thermal.service
● gateway-thermal.service - EEN1071 Lab 2 Gateway Thermal Monitor and LED Daemon
Loaded: loaded (/etc/systemd/system/gateway-thermal.service; enabled; preset: enabled)
Active: active (running) since Sat 2026-11-07 20:35:10 GMT; 8s ago
Main PID: 1842 (gateway-thermal)
Tasks: 1 (limit: 4915)
CPU: 14ms
CGroup: /system.slice/gateway-thermal.service
└─1842 /usr/local/bin/gateway-thermal-monitor 60.0
Nov 07 20:35:10 rpi gateway-thermal[1842]: Starting gateway-thermal-monitor (alert threshold: 60.0 C)
Nov 07 20:35:10 rpi gateway-thermal[1842]: STATE: SoC temperature (46.3 C) normal. Setting ACT LED trigger to heartbeat.
Nov 07 20:35:10 rpi gateway-thermal[1842]: TELEMETRY: temp_c=46.30 state=normal
# Inspect the JSON status file, which is in tmpfs under /run:
derek@rpi:~/lab2 $ cat /run/gateway-thermal/status.json
{
"timestamp_epoch": 1794083715,
"temperature_c": 46.30,
"threshold_c": 60.00,
"state": "normal"
}

Step 5: Verify crash recovery and clean shutdown

Section titled “Step 5: Verify crash recovery and clean shutdown”
  1. Test Restart=on-failure resilience: Simulate an unexpected crash by sending SIGKILL (-9) to the daemon’s PID and watching journalctl -u gateway-thermal -f in a second SSH terminal:
    Terminal window
    sudo kill -9 $(systemctl show --property MainPID --value gateway-thermal.service)
    Verify that systemd detects the abnormal exit and restarts a fresh instance automatically after 3 seconds (RestartSec=3s).14
  2. Test the thermal alert threshold: Edit /etc/systemd/system/gateway-thermal.service to change 60.0 to 35.0 (below your board’s current idle temperature), run sudo systemctl daemon-reload && sudo systemctl restart gateway-thermal.service, and confirm that the green ACT LED switches from a double-pulse heartbeat to a rapid 5 Hz warning flash.
  3. Test clean SIGTERM handling: Run sudo systemctl stop gateway-thermal.service and confirm in journalctl -u gateway-thermal -n 5 that the daemon logged the SIGTERM (signal 15) and restored the ACT LED trigger to [mmc0].
Concept Match

Match the board to how it keeps time while unpowered

Quiz
Select 0/1

A Raspberry Pi 4 gateway with no RTC boots with no internet access. Its connection to an mqtts:// broker on the local network fails with a certificate-not-yet-valid error. Why?

Quiz
Select 0/1

In Lab 2, why does the service write status.json to /run/gateway-thermal/ rather than to a directory on the root partition?

Quiz
Select 0/2

In Step 5 of Lab 2, which results show that the service is set up correctly?

  1. E. Rescorla, “The Transport Layer Security (TLS) Protocol Version 1.3,” IETF RFC 8446, Aug. 2018. Available: rfc-editor.org/rfc/rfc8446. ↩

  2. D. Cooper, S. Santesson, S. Farrell, S. Boeyen, R. Housley, and W. Polk, “Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile,” IETF RFC 5280, May 2008, sec. 4.1.2.5. Available: rfc-editor.org/rfc/rfc5280. ↩

  3. The systemd project, systemd(1), systemd manual pages. Available: freedesktop.org/software/systemd/man/latest/systemd.html. ↩

  4. The systemd project, systemd-timesyncd.service(8), systemd manual pages. Available: freedesktop.org/software/systemd/man/latest/systemd-timesyncd.service.html. ↩ ↩2

  5. Debian Project, fake-hwclock(8), Debian manpages (bookworm). Available: manpages.debian.org/bookworm/fake-hwclock. ↩

  6. Texas Instruments, AM335x Sitara Processors, data sheet, Rev. L (feature list: Real-Time Clock). Available: ti.com/product/AM3358. ↩

  7. Raspberry Pi Ltd, Raspberry Pi hardware, Raspberry Pi documentation. Available: raspberrypi.com/documentation/computers/raspberry-pi.html. ↩

  8. Analog Devices (Maxim Integrated), DS3231: Extremely Accurate I²C-Integrated RTC/TCXO/Crystal, data sheet. Available: analog.com/en/products/ds3231.html. ↩

  9. D. Molloy, Exploring Raspberry Pi: Interfacing to the Real World with Embedded Linux. Indianapolis, IN, USA: Wiley, 2016, ch. 8, ISBN 978-1-119-18868-1. ↩

  10. D. Mills, J. Martin, Ed., J. Burbank, and W. Kasch, “Network Time Protocol Version 4: Protocol and Algorithms Specification,” IETF RFC 5905, June 2010. Available: rfc-editor.org/rfc/rfc5905. ↩

  11. The systemd project, timedatectl(1), systemd manual pages. Available: freedesktop.org/software/systemd/man/latest/timedatectl.html. ↩

  12. The Linux Kernel documentation, LED handling under Linux. Available: docs.kernel.org/leds/leds-class.html. ↩

  13. The systemd project, systemd.exec(5), systemd manual pages. Available: freedesktop.org/software/systemd/man/latest/systemd.exec.html. ↩

  14. The systemd project, systemd.service(5), systemd manual pages. Available: freedesktop.org/software/systemd/man/latest/systemd.service.html. ↩