16 · Python auf Linux-SBC-Beispiele
Dieses Kapitel ist das SBC-Pendant zu arduino-examples.md, micropython-examples.md, esp-idf-examples.md, stm32-hal-examples.md und pico-sdk-examples.md: dieselben zehn Szenarien, portiert auf CPython unter Linux (Raspberry Pi OS, Armbian, generisches ARM-/x86-Linux).
Diese Beispiele sprechen den rbAmp direkt über die rohe I²C-Registerschnittstelle an. Sie sind für dienstartige Integrationen unter Linux gedacht — Home-Assistant-Gateways, OpenWrt-Router, Docker- bzw. k3s-Container, eigene IoT-Brücken —, bei denen Python das richtige Werkzeug ist und direkter Registerzugriff genügt.
Für eine bequemere, strukturierte Schnittstelle verwenden Sie das Python-Paket rbamp (siehe Tabelle der Client-Bibliotheken in der README). Das Paket kapselt die Registerdetails hinter einer Klasse RbAmp mit benannten Methoden (dev.voltage, dev.latch_period(), dev.read_period_snapshot() usw.), einem Energieakkumulator je Kanal (RbAmpEnergy), einer asyncio-Variante mit async for, Hilfsfunktionen für Mehrmodul-Aufbauten, HA-MQTT-Auto-Discovery und systemd-Dienstvorlagen in den mitgelieferten Beispielen sowie einer CLI rbamp (rbamp scan / read --watch / period). Dasselbe Paket läuft unverändert auf MicroPython — siehe Tabelle der Client-Bibliotheken in der README. Die meisten Projekte sollten mit dem Paket beginnen und nur bei Bedarf auf die Roh-API zurückgreifen.
Worin sich Linux von einem Mikrocontroller unterscheidet
Der größte Unterschied: Linux erledigt bereits viel Arbeit, die die Bare-Metal-Beispiele von Hand verdrahten. Sie initialisieren den I²C-Controller nicht, Sie synchronisieren die Wanduhr nicht, und Sie kämpfen nicht um gesicherten Speicher über Neustarts hinweg. All das existiert auf Systemebene. Ihr Python-Skript übernimmt nur Messung und Geschäftslogik, sonst nichts.
Concretely:
| Anliegen | Bare-Metal-MCU | Linux-SBC |
|---|---|---|
| Initialisierung der I²C-Peripherie | i2c_init() / HAL_I2C_Init() |
Bereits durch den Kernel-Treiber erledigt (i2c-dev). Öffnen Sie /dev/i2c-N als Dateideskriptor. |
| Pull-ups | Festlegen im Platinenentwurf oder über gpio_pull_up() |
In der Hardware entschieden. Linux greift nicht darauf zu. |
| Wanduhr (UTC) | SNTP implementieren, gmtime_r() aufrufen |
systemd-timesyncd / chrony halten die Uhr automatisch synchron. time.time() liefert echte Sekunden seit der Epoche. |
| Persistenz über Neustarts hinweg | RTC-Backup-Register, NOINIT-RAM, NVM | Das Dateisystem. Verwenden Sie eine JSON-Datei, SQLite oder /var/lib/rbamp/. |
| Tiefschlaf | esp_deep_sleep_start() / HAL_PWR_EnterSTANDBYMode() |
Irrelevant. Der SBC läuft ständig; die Leerlaufkosten der CPU werden ohnehin von WLAN bzw. Ethernet dominiert. Schlafen ist hier ein fremdes Konzept. |
| DRDY-ISR | Pin-IRQ in der Firmware | Benutzerseitige Flankenereignisse über gpiod / gpiozero. Die Latenz liegt bei wenigen hundert Mikrosekunden und wird vom Kernel-Scheduling bestimmt. |
| MQTT | Wi-Fi einrichten, TCP/TLS-Stack selbst aufbauen | pip install paho-mqtt. |
| Daemon / Supervisor | Endlosschleife (while) | Eine systemd-Dienstdatei mit automatischem Neustart und Journal-Protokollierung. |
| Berechtigungen | Nicht zutreffend | Der Benutzer, der Ihr Skript ausführt, muss in den Gruppen i2c und gpio sein oder als root laufen. |
| Build-System | CMake / idf.py / CubeIDE |
pip install -r requirements.txt (oder eine pyproject.toml). |
Wenn Sie bisher Firmware geschrieben haben, lautet der gedankliche Wechsel: greifen Sie nicht mehr zu Low-Level-APIs. Das Betriebssystem stellt bereits alles als Dateien oder Standardbibliotheksaufrufe bereit.
Linux-I²C-Einrichtung (einmalig)
Die folgenden Schritte gelten für Raspberry Pi OS auf einem Raspberry Pi 3/4/5; andere SBCs (Orange Pi, BeagleBone, x86 + USB-I2C-Adapter) folgen demselben Muster mit einer anderen Busnummer.
1. I²C-Controller im Kernel aktivieren
Raspberry Pi OS — einfacher Weg:
sudo raspi-config nonint do_i2c 0 # 0 = enable
Oder bearbeiten Sie den Device-Tree manuell:
sudo nano /boot/firmware/config.txt # /boot/config.txt on older releases
# Add or uncomment the next line:
dtparam=i2c_arm=on
# Bus speed 100 kHz (recommended) — see also chapter 01:
dtparam=i2c_arm=on,i2c_arm_baudrate=100000
sudo reboot
Nach dem Neustart stellt der Kernel den Bus als Zeichengerät bereit:
ls /dev/i2c-*
# -> /dev/i2c-1
Bei Pi 4/5 können Sie zusätzliche Busse über dtoverlay=i2c-bus,bus=N-Einträge aktivieren — nützlich, wenn Sie einen eigenen I²C-Bus für den rbAmp abseits der HATs benötigen.
Andere SBCs:
- Orange Pi / NanoPi / Banana Pi: ähnliche
dtoverlay- oderextlinux.conf-Stellschrauben, je nach BSP. - BeagleBone Black:
config-pin P9.19 i2c/P9.20 i2cfür I²C-2; der Knoten ist/dev/i2c-2. - x86 / generisches Linux: ein USB-I2C-Adapter (FT232H, MCP2221A, CH341) erscheint als
/dev/i2c-N, nachdem das passende Kernelmodul geladen wurde.
2. Werkzeuge für den Kernel-Zugriff installieren (optional, aber nützlich)
sudo apt update
sudo apt install -y i2c-tools
i2cdetect -y 1 # scan bus 1
i2cdetect sollte unter der Standardadresse des rbAmp 50 anzeigen:
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
...
50: 50 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
3. Benutzerberechtigungen
Nehmen Sie Ihren Benutzer in die Gruppe i2c auf, damit Sie für jedes Skript kein sudo benötigen:
sudo usermod -aG i2c $USER
# Log out and back in for the group change to take effect.
Für DRDY- bzw. GPIO-Zugriff:
sudo usermod -aG gpio $USER # Raspberry Pi
sudo usermod -aG dialout $USER # often required for serial / USB-CDC
Verify:
groups
# -> ... i2c gpio ...
4. Python-Pakete
Verwenden Sie eine virtuelle Umgebung, um Abhängigkeiten zu isolieren:
python3 -m venv ~/venv-rbamp
source ~/venv-rbamp/bin/activate
pip install --upgrade pip
pip install smbus2 gpiozero paho-mqtt
# Optional extras used in some examples:
pip install luma.oled # SSD1306 / SH1106
pip install RPi.GPIO # alternative to gpiozero on Pi
pip install python-periphery # cross-SBC I2C / GPIO without smbus2
Für ein veröffentlichtes Projekt verwenden Sie pyproject.toml (PEP 621):
[project]
name = "my-rbamp-app"
version = "0.1.0"
dependencies = [
"smbus2>=0.4.0",
"paho-mqtt>=2.0,<3.0", # 2.x: callback API version must be passed explicitly
"gpiozero>=2.0",
]
— Version 2.0 hat das Argument für die Callback-API zu einem Pflichtargument des Konstruktors gemacht. Alle Beispiele in diesem Kapitel übergeben mqtt.CallbackAPIVersion.VERSION1, um die einfachen Legacy-Signaturen beizubehalten (on_connect(client, userdata, flags, rc, properties=None)). Wenn Sie v2 bevorzugen (mit ReasonCode + ConnectFlags), übergeben Sie CallbackAPIVersion.VERSION2 und passen die Callbacks entsprechend an.
5. Zeit
Standardmäßig hält systemd-timesyncd die Systemuhr per NTP synchron in UTC. Prüfen Sie es so:
timedatectl
# Local time: Thu 2026-05-22 18:30:01 CEST
# Universal time: Thu 2026-05-22 16:30:01 UTC
# System clock synchronized: yes
# NTP service: active
In Python rufen Sie dann time.time() (UTC-Sekunden seit der Epoche), datetime.datetime.now(timezone.utc) oder time.localtime() auf — und das ist die Wanduhr, die Sie brauchen. Kein SNTP-Code in Ihrem Skript.
6. SBC-Kurzreferenz
| SBC | I²C-Knoten | Gruppe | Hinweise zu DRDY |
|---|---|---|---|
| Raspberry Pi 3/4/5 | /dev/i2c-1 |
i2c, gpio |
gpiozero empfohlen |
| BeagleBone Black | /dev/i2c-2 |
i2c, gpio |
Adafruit_BBIO / libgpiod |
| Orange Pi 4/5 | /dev/i2c-3 (variiert) |
i2c, gpio |
OPi.GPIO oder libgpiod |
| Generisches x86 + USB-I2C | /dev/i2c-3..N |
i2c |
DRDY über den GPIO des Adapters (der FT232H unterstützt das) |
Der Rest dieses Kapitels setzt Raspberry Pi 4 / 5 und Raspberry Pi OS voraus — jedes Beispiel funktioniert aber auf jedem SBC, wenn Busnummer und GPIO-Bibliothek entsprechend ersetzt werden.
Inhaltsverzeichnis der Beispiele
| # | Titel | Schwierigkeit | Ausgang | MQTT | DRDY | Mehrere Module | Bidirektional | Anwendungsfall |
|---|---|---|---|---|---|---|---|---|
| 1 | Schnelles Lesen | minimal | Konsole | — | — | — | — | Schnelltest |
| 2 | 60-Sekunden-Energiezähler auf OLED | niedrig | SSD1306 | — | — | — | — | Gekapselter Wh-Zähler |
| 3 | Monitor für mehrere Module | niedrig | Konsole | — | — | ja (3) | — | Gesamthausüberwachung |
| 4 | Energiemonitor pro Gerät (UI3) | mittel | — | ja | — | — | — | Unterzählung in HA |
| 5 | Bidirektional auf dem Master für ein BASIC-Modul | mittel | Konsole | — | ja | — | ja (Master) | Solar-Haushalt auf BASIC-Stufe |
| 6 | Gesamte Hausbilanz | hoch | — | ja | — | ja (3) | ja | Gesamte Hausbilanz |
| 7 | Erkennung von Netzereignissen | mittel | Dateiprotokoll | — | ja | — | — | Ereignisprotokoll der Geräte |
| 8 | MQTT-Publisher mit HA-Auto-Discovery | mittel | — | ja (+disco) | — | — | optional | Sofort einsatzbereite HA-Integration |
| 9 | systemd-Daemon mit SQLite-Persistenz | mittel | journald + DB | ja | — | — | — | Produktions-Logger |
| 10 | Zeitabhängiger Tarif (TOU) mit Systemuhr | mittel | Konsole | ja | — | — | optional | Energiemessung mit Spitzen- / Nebenzeit-Tarif |
Gemeinsame Hilfsfunktionen (rbamp_io.py)
Legen Sie diese Datei neben Ihre Skripte (oder importieren Sie sie aus einem Paket). Um Platz zu sparen, wird sie in den Beispielen unten nicht wiederholt.
"""rbAmp raw-I2C helpers for Linux CPython.
Uses smbus2 — the most widely available userspace I2C library on Linux.
For older systems, ``python3-smbus`` (the official Linux i2c-tools binding)
exposes a nearly identical API.
For cross-SBC portability without smbus2, swap in python-periphery; the
helpers are thin enough to port in a few minutes.
"""
from __future__ import annotations
import struct
import time
from typing import Optional
from smbus2 import SMBus, i2c_msg
# ---------- rbAmp register addresses (subset used in the examples) ----------
REG_STATUS = 0x00
REG_COMMAND = 0x01
REG_VERSION = 0x03
REG_CT_MODEL = 0x05
REG_PERIOD_VALID = 0x07
REG_AC_FREQ = 0x20
REG_I2C_ADDRESS = 0x30
REG_U_RMS = 0x86
REG_U_PEAK = 0x8A
REG_I0_RMS = 0x8E
REG_I1_RMS = 0x92
REG_I2_RMS = 0x96
REG_P0_REAL = 0xA6
REG_PF0 = 0xB2
REG_Q0 = 0xD0
REG_PERIOD_AVG_P1 = 0xC2
REG_PERIOD_AVG_P2 = 0xC6
REG_DATA_VALID = 0xCE
REG_PERIOD_AVG_P0 = 0xDC
REG_PERIOD_MAX_P = 0xE0
REG_PERIOD_LATCH_MS= 0xEC
CMD_RESET = 0x01
CMD_LATCH_PERIOD = 0x27
class RbAmpIO:
"""Thin wrapper around an SMBus / address pair.
Holds the bus handle and the target slave address, exposing one helper
per primitive operation. Designed to be composed into larger classes
(or used directly in scripts).
"""
def __init__(self, bus: SMBus, addr: int = 0x50) -> None:
"""Bind to an already-opened SMBus and a 7-bit address.
:param bus: An ``smbus2.SMBus(N)`` instance.
:param addr: 7-bit slave address (default 0x50).
"""
self.bus = bus
self.addr = addr
# ----- I2C primitives -----
def read_u8(self, reg: int) -> int:
"""Read one byte from a register."""
return self.bus.read_byte_data(self.addr, reg)
def write_u8(self, reg: int, val: int) -> None:
"""Write one byte to a register."""
self.bus.write_byte_data(self.addr, reg, val & 0xFF)
def read_float_le(self, reg: int) -> float:
"""Read a little-endian float32 from four consecutive registers.
rbAmp supports READ auto-increment (a single burst-read is valid for
atomicity). The per-byte form below is shown for clarity. WRITE
transactions, by contrast, are byte-at-a-time only. See chapter 11.
"""
b = bytes(self.read_u8(reg + i) for i in range(4))
return struct.unpack(" int:
"""Read a little-endian uint32 from four consecutive registers."""
b = bytes(self.read_u8(reg + i) for i in range(4))
return struct.unpack(" bool:
"""Return True if the slave acks a single-byte read of REG_STATUS."""
try:
self.bus.read_byte_data(self.addr, REG_STATUS)
return True
except OSError:
return False
def wait_ready(self, timeout_s: float = 2.0) -> None:
"""Block until DATA_VALID bit 0 reads 1, or raise TimeoutError."""
deadline = time.monotonic() + timeout_s
while time.monotonic() < deadline:
try:
if self.read_u8(REG_DATA_VALID) & 0x01:
return
except OSError:
pass
time.sleep(0.05)
raise TimeoutError(f"rbAmp at 0x{self.addr:02X} not ready in {timeout_s}s")
def broadcast_latch(bus: SMBus, tick16: int, group: int = 0) -> bool:
"""Broadcast CMD_LATCH_PERIOD to rbAmp modules with GC reception enabled.
Canonical 5-byte general-call frame: A5 27 group tick_lo tick_hi.
Slaves reject any first byte != 0xA5. GC reception is opt-in per
module (FLEET_CONFIG.bit0, default OFF). See chapter 11 §6.3.2.
Returns True on ACK; False on NACK (caller must fall back to
per-module sequential snapshot).
"""
msg = i2c_msg.write(0x00, [
0xA5, # frame magic
CMD_LATCH_PERIOD, # opcode 0x27
group & 0xFF, # group_id (0 = all-call)
tick16 & 0xFF, # tick_lo
(tick16 >> 8) & 0xFF, # tick_hi
])
try:
bus.i2c_rdwr(msg)
return True
except OSError:
return False
Beispiel 1 — Schnelles Lesen (minimal)
Ziel: U, I, P, PF einmal pro Sekunde auf der Konsole ausgeben. Hardware: ein beliebiger SBC + ein rbAmp UI1 an /dev/i2c-1.
example_01.py:
#!/usr/bin/env python3
"""rbAmp quick-read smoke test."""
import time
from smbus2 import SMBus
from rbamp_io import RbAmpIO, REG_VERSION, REG_U_RMS, REG_I0_RMS, REG_P0_REAL, REG_PF0
I2C_BUS = 1
RB_ADDR = 0x50
with SMBus(I2C_BUS) as bus:
meter = RbAmpIO(bus, RB_ADDR)
meter.wait_ready() # wait for first RT window
print(f"rbAmp version: 0x{meter.read_u8(REG_VERSION):02X}")
while True:
u = meter.read_float_le(REG_U_RMS) # RMS voltage, V
i_ = meter.read_float_le(REG_I0_RMS) # RMS current, A
p = meter.read_float_le(REG_P0_REAL) # active power, W (signed)
pf = meter.read_float_le(REG_PF0) # power factor, signed
print(f"U={u:.1f}V I={i_:.3f}A P={p:+.1f}W PF={pf:+.3f}")
time.sleep(1)
Run:
python3 example_01.py
# rbAmp version: 0x04
# U=230.1V I=0.262A P=+60.2W PF=+0.998
# U=229.9V I=0.262A P=+60.1W PF=+0.998
# ...
Wenn Sie PermissionError: [Errno 13] auf /dev/i2c-1 sehen, ist Ihr Benutzer nicht in der Gruppe i2c — beheben Sie das gemäß dem Abschnitt zur Linux-Einrichtung oben.
Beispiel 2 — 60-Sekunden-Energiezähler auf OLED
Ziel: Wh-Zähler einmal pro Minute aktualisiert, angezeigt auf einem 128×64-SSD1306 am I²C-Bus des rbAmp. Hardware: SBC + rbAmp + SSD1306-OLED (0x3C) am selben Bus. Bilanzierung: unidirektional (BASIC-Stufe). Bibliothek: luma.oled für die Anzeige (pip install luma.oled).
#!/usr/bin/env python3
"""60-second energy meter on a 128x64 SSD1306, shared I2C bus."""
import time
from smbus2 import SMBus
from luma.core.interface.serial import i2c as luma_i2c
from luma.oled.device import ssd1306
from luma.core.render import canvas
from rbamp_io import (
RbAmpIO, REG_COMMAND, REG_PERIOD_VALID,
REG_PERIOD_AVG_P0, CMD_LATCH_PERIOD,
)
I2C_BUS = 1
RB_ADDR = 0x50
# luma opens its own connection but still drives /dev/i2c-1 — coexists with smbus2.
serial = luma_i2c(port=I2C_BUS, address=0x3C)
oled = ssd1306(serial, width=128, height=64)
def draw(avg_p: float, dt_s: float, total_wh: float) -> None:
"""Render the three lines."""
with canvas(oled) as c:
c.text((0, 0), f"P: {avg_p:6.1f} W", fill="white")
c.text((0, 16), f"dt: {dt_s:6.1f} s", fill="white")
c.text((0, 32), f"{total_wh:.2f} Wh", fill="white")
with SMBus(I2C_BUS) as bus:
meter = RbAmpIO(bus, RB_ADDR)
meter.wait_ready()
# Primer snapshot — discard its snapshot.
meter.write_u8(REG_COMMAND, CMD_LATCH_PERIOD)
t_prev = time.monotonic()
total_wh = 0.0
while True:
time.sleep(60)
# 1) Final snapshot — closes the period [t_prev .. now].
meter.write_u8(REG_COMMAND, CMD_LATCH_PERIOD)
t_now = time.monotonic()
time.sleep(0.05) # let firmware finalise snapshot
# 2) Verify the snapshot is fresh.
if (meter.read_u8(REG_PERIOD_VALID) & 0x01) == 0:
print("WARN: stale snapshot")
t_prev = time.monotonic()
continue
# 3) Read time-averaged power, channel 0.
avg_p = meter.read_float_le(REG_PERIOD_AVG_P0)
# 4) Energy uses the MASTER clock — same idea as on a microcontroller,
# except `time.monotonic()` is the Linux equivalent of `HAL_GetTick()`.
dt_s = t_now - t_prev
e_wh = avg_p * dt_s / 3600.0
total_wh += e_wh
t_prev = t_now
draw(avg_p, dt_s, total_wh)
print(f"avg_P={avg_p:.1f} E_period={e_wh:.3f} total={total_wh:.3f}")
Beispiel 3 — Überwachung mehrerer Module
Ziel: drei Module abfragen (Hauptzuleitung, Warmwasserbereiter, Klimaanlage) und die Summe ausgeben. Hardware: SBC + 3 × rbAmp UI1 bei 0x50, 0x51, 0x52.
#!/usr/bin/env python3
"""Round-robin polling of three rbAmp modules."""
import time
from smbus2 import SMBus
from rbamp_io import RbAmpIO, REG_U_RMS, REG_P0_REAL
I2C_BUS = 1
MODULES = [
(0x50, "Mains "),
(0x51, "Boiler"),
(0x52, "AC "),
]
with SMBus(I2C_BUS) as bus:
meters = [(RbAmpIO(bus, addr), label) for addr, label in MODULES]
# Probe every module before entering the read loop.
for meter, label in meters:
if not meter.probe():
raise SystemExit(f"{label} at 0x{meter.addr:02X} not found")
print("All modules OK")
while True:
total_p = 0.0
print("---")
for meter, label in meters:
u = meter.read_float_le(REG_U_RMS)
p = meter.read_float_le(REG_P0_REAL)
print(f"[{label}] U={u:.1f} P={p:+.1f} W")
total_p += p
print(f"TOTAL: {total_p:.1f} W")
time.sleep(2)
probe() ruft ein 1-Byte-read_byte_data auf und fängt OSError(EREMOTEIO) ab — das Linux-Gegenstück zu einem I²C-NACK.
Beispiel 4 — Energiemonitor pro Gerät (UI3)
Ziel: ein UI3-Modul mit drei Stromzangen an drei verschiedenen Lasten auf derselben Phase; unabhängige Wh-Zähler, die jede Minute an MQTT gesendet werden. Hardware: SBC + 1 × rbAmp UI3 + MQTT-Broker (Mosquitto, EMQX, HA-Mosquitto-Add-on).
#!/usr/bin/env python3
"""Per-appliance UI3 energy tracker with MQTT publishing."""
import json
import time
import paho.mqtt.client as mqtt
from smbus2 import SMBus
from rbamp_io import (
RbAmpIO, REG_COMMAND, REG_PERIOD_VALID,
REG_PERIOD_AVG_P0, REG_PERIOD_AVG_P1, REG_PERIOD_AVG_P2,
CMD_LATCH_PERIOD,
)
I2C_BUS = 1
RB_ADDR = 0x50
CH_NAMES = ("main", "heatpump", "lights")
MQTT_HOST = "192.168.1.10"
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id="rbamp-ui3")
try:
client.connect(MQTT_HOST, 1883, keepalive=60)
except OSError as e:
print(f"MQTT broker unreachable at boot ({e}); will retry in loop_start()")
client.loop_start() # paho's thread reconnects automatically
def mqtt_publish(name: str, avg_p: float, e_wh: float) -> None:
"""Publish one channel's state to MQTT."""
payload = json.dumps({"power": round(avg_p, 1), "energy": round(e_wh, 4)})
client.publish(f"rbamp/{name}/state", payload, qos=0, retain=False)
with SMBus(I2C_BUS) as bus:
meter = RbAmpIO(bus, RB_ADDR)
meter.wait_ready()
meter.write_u8(REG_COMMAND, CMD_LATCH_PERIOD) # primer
t_prev = time.monotonic()
total_wh = [0.0, 0.0, 0.0]
while True:
time.sleep(60)
meter.write_u8(REG_COMMAND, CMD_LATCH_PERIOD)
t_now = time.monotonic()
time.sleep(0.05)
if (meter.read_u8(REG_PERIOD_VALID) & 0x01) == 0:
t_prev = time.monotonic()
continue
# PERIOD_AVG_P_W per channel: I0 at 0xDC, I1 at 0xC2, I2 at 0xC6.
avg_p = (
meter.read_float_le(REG_PERIOD_AVG_P0),
meter.read_float_le(REG_PERIOD_AVG_P1),
meter.read_float_le(REG_PERIOD_AVG_P2),
)
dt_s = t_now - t_prev
t_prev = t_now
for ch in range(3):
e = avg_p[ch] * dt_s / 3600.0
total_wh[ch] += e
print(f"[{CH_NAMES[ch]}] avg_P={avg_p[ch]:+.1f} W E_total={total_wh[ch]:.3f} Wh")
mqtt_publish(CH_NAMES[ch], avg_p[ch], total_wh[ch])
Beispiel 5 — Bidirektional auf dem Master für ein BASIC-Modul
Ziel: bidirektionale Bilanzierung auf dem Master, während das Modul BASIC-Firmware hat. Der SBC reagiert über gpiozero auf die fallende DRDY-Flanke und trennt Verbrauch und Einspeisung. Hardware: Raspberry Pi + rbAmp UI1; DRDY an GPIO 15 angeschlossen (BCM-Nummerierung).
#!/usr/bin/env python3
"""Master-side bidirectional accounting via DRDY GPIO IRQ."""
import time
from threading import Event
from gpiozero import Button
from smbus2 import SMBus
from rbamp_io import RbAmpIO, REG_P0_REAL
I2C_BUS = 1
RB_ADDR = 0x50
PIN_DRDY = 15 # BCM
# Wrap the bus in a context manager so the /dev/i2c-N fd is released cleanly
# on any unhandled exception (Ctrl-C, NACK retry exhaustion, etc.).
with SMBus(I2C_BUS) as bus:
meter = RbAmpIO(bus, RB_ADDR)
meter.wait_ready()
# gpiozero treats DRDY as a "Button":
# pull_up=True -> the line idles HIGH (matches rbAmp's open-drain output)
# bounce_time=None — we want the raw falling edges, not debounced
drdy = Button(PIN_DRDY, pull_up=True, bounce_time=None)
data_ready = Event()
def on_drdy() -> None:
"""gpiozero callback — only sets the flag. All I/O happens in the main loop."""
data_ready.set()
drdy.when_pressed = on_drdy
e_consumed_wh = 0.0
e_exported_wh = 0.0
t_last = time.monotonic()
t_last_print = t_last
print("Bidirectional accumulator started")
while True:
if not data_ready.wait(timeout=1.0):
continue # no edge in the last second
data_ready.clear()
t_now = time.monotonic()
p = meter.read_float_le(REG_P0_REAL) # signed P_real
dt_s = t_now - t_last
t_last = t_now
if p > 0:
e_consumed_wh += p * dt_s / 3600.0
else:
e_exported_wh += -p * dt_s / 3600.0
# Summary print every 5 s.
if t_now - t_last_print >= 5.0:
t_last_print = t_now
print(f"P={p:+8.1f}W consumed={e_consumed_wh:.4f} Wh "
f"exported={e_exported_wh:.4f} Wh "
f"net={(e_consumed_wh - e_exported_wh):+.4f} Wh")
Notes:
threading.Eventist das naheliegende Synchronisationsmittel —set()im Callback,wait()in der Hauptschleife. Die Scheduling-Latenz unter Linux liegt weit unter dem ~100-ms-Takt des RT-Fensters, daher geht keine Flanke verloren.- Für ältere Pi-OS-Versionen ohne
gpiozeroersetzen Sie dies durchRPi.GPIO.add_event_detect(15, GPIO.FALLING, callback=on_drdy). Für Nicht-Pi-SBCs verwenden Siegpiod.LineRequest(libgpiod 2.x) — der Rest des Skripts bleibt unverändert.
Beispiel 6 — Energiebilanz des Hauses
Ziel: vollständiges Bilanz-Dashboard. Drei Module:
- rbAmp #1 am Hauptnetz (STD — bidirektional)
- rbAmp #2 am Ausgang des Solarwechselrichters (BASIC ok)
- rbAmp #3 UI3 an drei großen Lasten (Wärmepumpe, Klimaanlage, E-Auto)
Der Master verwendet broadcast_latch() für synchrone Snapshots und veröffentlicht jede Minute einen beibehaltenen Saldo an MQTT.
#!/usr/bin/env python3
"""Home energy balance via synchronous broadcast snapshot."""
import json
import time
import paho.mqtt.client as mqtt
from smbus2 import SMBus
from rbamp_io import (
RbAmpIO, broadcast_latch,
REG_PERIOD_VALID, REG_PERIOD_AVG_P0, REG_PERIOD_AVG_P1, REG_PERIOD_AVG_P2,
)
I2C_BUS = 1
ADDR_MAINS = 0x50 # bidirectional (STD)
ADDR_SOLAR = 0x51 # generation only (BASIC ok)
ADDR_LOADS = 0x52 # UI3
MQTT_HOST = "192.168.1.10"
# PERIOD_AVG_P_NEG register for the mains module — see the SKU datasheet
# of the STD product. Set to None on BASIC modules.
from typing import Optional
REG_PERIOD_AVG_P_NEG_MAINS: Optional[int] = None # Optional[int] for Py 3.9+ compat
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id="home-balance")
try:
client.connect(MQTT_HOST, 1883, keepalive=60)
except OSError as e:
print(f"MQTT broker unreachable at boot ({e}); will retry in loop_start()")
client.loop_start()
def safe_read_float(meter: RbAmpIO, reg: int) -> float:
"""Return 0.0 if the read fails (e.g. NACK from a BASIC module)."""
try:
return meter.read_float_le(reg)
except OSError:
return 0.0
totals = {
"mains_in_wh": 0.0,
"mains_out_wh": 0.0,
"solar_total_wh": 0.0,
"loads_wh": [0.0, 0.0, 0.0],
}
with SMBus(I2C_BUS) as bus:
mains = RbAmpIO(bus, ADDR_MAINS)
solar = RbAmpIO(bus, ADDR_SOLAR)
loads = RbAmpIO(bus, ADDR_LOADS)
for m in (mains, solar, loads):
m.wait_ready()
gc_tick = 0
if not broadcast_latch(bus, gc_tick):
# GC NACK → fall back to per-module sequential snapshot.
for m in (mains, solar, loads):
m.write_u8(REG_COMMAND, CMD_LATCH_PERIOD)
gc_tick += 1
t_prev = time.monotonic()
print("Home balance started")
while True:
time.sleep(60)
# Synchronous snapshot — all modules snapshot at the same instant.
if not broadcast_latch(bus, gc_tick):
for m in (mains, solar, loads):
m.write_u8(REG_COMMAND, CMD_LATCH_PERIOD)
gc_tick = (gc_tick + 1) & 0xFFFF
t_now = time.monotonic()
time.sleep(0.05)
dt_s = t_now - t_prev
t_prev = t_now
# ---- MAINS (bidirectional) ----
if mains.read_u8(REG_PERIOD_VALID) & 0x01:
p_consume = safe_read_float(mains, REG_PERIOD_AVG_P0)
p_export = (safe_read_float(mains, REG_PERIOD_AVG_P_NEG_MAINS)
if REG_PERIOD_AVG_P_NEG_MAINS is not None else 0.0)
totals["mains_in_wh"] += p_consume * dt_s / 3600.0
totals["mains_out_wh"] += p_export * dt_s / 3600.0
# ---- SOLAR ----
if solar.read_u8(REG_PERIOD_VALID) & 0x01:
p = safe_read_float(solar, REG_PERIOD_AVG_P0)
totals["solar_total_wh"] += p * dt_s / 3600.0
# ---- LOADS (UI3) ----
if loads.read_u8(REG_PERIOD_VALID) & 0x01:
for i, reg in enumerate((REG_PERIOD_AVG_P0, REG_PERIOD_AVG_P1, REG_PERIOD_AVG_P2)):
p = safe_read_float(loads, reg)
totals["loads_wh"][i] += p * dt_s / 3600.0
# Derived balance figures.
total_consumed = (totals["mains_in_wh"]
+ totals["solar_total_wh"]
- totals["mains_out_wh"])
solar_self_used = max(0.0, totals["solar_total_wh"] - totals["mains_out_wh"])
print(f"MAINS in={totals['mains_in_wh']:.2f} out={totals['mains_out_wh']:.2f}")
print(f"SOLAR gen={totals['solar_total_wh']:.2f} "
f"self-used={solar_self_used:.2f} exported={totals['mains_out_wh']:.2f}")
print(f"LOADS HP={totals['loads_wh'][0]:.2f} "
f"AC={totals['loads_wh'][1]:.2f} EV={totals['loads_wh'][2]:.2f}")
print(f"TOTAL household consumed={total_consumed:.2f} Wh")
payload = json.dumps({
"mains_in": round(totals["mains_in_wh"], 3),
"mains_out": round(totals["mains_out_wh"], 3),
"solar": round(totals["solar_total_wh"], 3),
"self_used": round(solar_self_used, 3),
"total_consumed": round(total_consumed, 3),
"hp": round(totals["loads_wh"][0], 3),
"ac": round(totals["loads_wh"][1], 3),
"ev": round(totals["loads_wh"][2], 3),
})
client.publish("home/energy/balance", payload, qos=1, retain=True)
Beispiel 7 — Erkennung von Netzereignissen
Ziel: bei jeder DRDY-Flanke die momentane Leistung P mit einem EMA vergleichen und signifikante Abweichungen in eine rotierende Logdatei schreiben. Hardware: beliebiger SBC + rbAmp + DRDY an GPIO 15. Logging: das Standardmodul logging von Python mit RotatingFileHandler — übersteht Neustarts, ohne SD-Kartentreiber.
#!/usr/bin/env python3
"""Power-event detection with rotating-file logging."""
import logging
import logging.handlers
import time
from threading import Event
from gpiozero import Button
from smbus2 import SMBus
from rbamp_io import RbAmpIO, REG_P0_REAL
I2C_BUS = 1
RB_ADDR = 0x50
PIN_DRDY = 15
EMA_ALPHA = 0.05
EVENT_THRESHOLD_W = 200.0
LOG_PATH = "/var/log/rbamp/events.log" # ensure the directory exists and is writeable
# Configure a rotating logger — 5 files × 1 MB.
handler = logging.handlers.RotatingFileHandler(
LOG_PATH, maxBytes=1_000_000, backupCount=5)
handler.setFormatter(logging.Formatter("%(asctime)s %(message)s",
"%Y-%m-%dT%H:%M:%S"))
log = logging.getLogger("rbamp.events")
log.addHandler(handler)
log.setLevel(logging.INFO)
# Wrap the bus in a context manager so the /dev/i2c-N fd is released cleanly
# on any unhandled exception.
with SMBus(I2C_BUS) as bus:
meter = RbAmpIO(bus, RB_ADDR)
meter.wait_ready()
# Seed the EMA with current power so the very first sample does not look like an event.
p_ema = meter.read_float_le(REG_P0_REAL)
drdy = Button(PIN_DRDY, pull_up=True, bounce_time=None)
data_ready = Event()
drdy.when_pressed = data_ready.set
print("Event detector started; log:", LOG_PATH)
while True:
if not data_ready.wait(timeout=1.0):
continue
data_ready.clear()
p = meter.read_float_le(REG_P0_REAL)
delta = p - p_ema
p_ema = (1 - EMA_ALPHA) * p_ema + EMA_ALPHA * p
if abs(delta) > EVENT_THRESHOLD_W:
event_type = "TURN_ON" if delta > 0 else "TURN_OFF"
line = f"{event_type} delta={delta:+.1f}W P={p:.1f}W EMA={p_ema:.1f}W"
print(line)
log.info(line) # MUST be inside the `if` —
# otherwise NameError when
# delta is below threshold.
Das Verzeichnis muss mit den richtigen Rechten existieren:
sudo mkdir -p /var/log/rbamp && sudo chown $USER /var/log/rbamp
~/.local/state/rbamp/events.logfalls Sie keine root-verwalteten Pfade wünschen.
Beispiel 8 — MQTT-Publisher mit Home-Assistant-Auto-Discovery
Ziel: sofortige HA-Integration. Der SBC veröffentlicht HA-Auto-Discovery-Konfigurationen (retained) und sendet jede Minute einen JSON-Status. Hardware: ein beliebiger SBC + ein rbAmp UI1 + MQTT-Broker.
#!/usr/bin/env python3
"""rbAmp MQTT publisher with Home Assistant Auto-discovery."""
import json
import time
import paho.mqtt.client as mqtt
from smbus2 import SMBus
from rbamp_io import (
RbAmpIO,
REG_COMMAND, REG_PERIOD_VALID, REG_PERIOD_AVG_P0,
REG_U_RMS, REG_I0_RMS, REG_PF0, REG_Q0, REG_AC_FREQ,
CMD_LATCH_PERIOD,
)
I2C_BUS = 1
RB_ADDR = 0x50
DEVICE_ID = "rbamp_main"
DEVICE_NAME = "Mains rbAmp"
MQTT_HOST = "192.168.1.10"
MQTT_USER = None # set to a string to enable basic auth
MQTT_PASS = None
DEVICE_BLOCK = {
"identifiers": [DEVICE_ID],
"name": DEVICE_NAME,
"manufacturer": "rbAmp",
"model": "rbAmp UI*",
}
def publish_discovery_sensor(client: mqtt.Client, key: str, friendly: str,
unit: str | None, dev_class: str | None,
state_class: str) -> None:
"""Publish one HA discovery config (retained)."""
cfg = {
"name": f"{DEVICE_NAME} {friendly}",
"unique_id": f"{DEVICE_ID}_{key}",
"state_topic": f"rbamp/{DEVICE_ID}/state",
"value_template": "{{ value_json." + key + " }}",
"state_class": state_class,
"device": DEVICE_BLOCK,
}
if unit: cfg["unit_of_measurement"] = unit
if dev_class: cfg["device_class"] = dev_class
client.publish(f"homeassistant/sensor/{DEVICE_ID}/{key}/config",
json.dumps(cfg), qos=1, retain=True)
def publish_discovery_all(client: mqtt.Client) -> None:
"""Publish the full HA discovery set for one rbAmp module."""
publish_discovery_sensor(client, "voltage", "Voltage", "V", "voltage", "measurement")
publish_discovery_sensor(client, "current", "Current", "A", "current", "measurement")
publish_discovery_sensor(client, "power", "Power", "W", "power", "measurement")
publish_discovery_sensor(client, "energy", "Energy", "Wh", "energy", "total_increasing")
publish_discovery_sensor(client, "frequency", "Frequency", "Hz", "frequency", "measurement")
publish_discovery_sensor(client, "power_factor", "Power Factor", None, "power_factor", "measurement")
publish_discovery_sensor(client, "apparent_power", "Apparent Power", "VA", "apparent_power", "measurement")
publish_discovery_sensor(client, "reactive_power", "Reactive Power", "var", "reactive_power", "measurement")
def on_connect(client, userdata, flags, rc, properties=None):
"""Republish discovery on every (re)connect — retained, so HA picks it up."""
print(f"MQTT connected rc={rc}")
publish_discovery_all(client)
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1,
client_id=DEVICE_ID, protocol=mqtt.MQTTv5)
if MQTT_USER:
client.username_pw_set(MQTT_USER, MQTT_PASS)
client.on_connect = on_connect
try:
client.connect(MQTT_HOST, 1883, keepalive=60)
except OSError as e:
print(f"MQTT broker unreachable at boot ({e}); will retry in loop_start()")
client.loop_start()
with SMBus(I2C_BUS) as bus:
meter = RbAmpIO(bus, RB_ADDR)
meter.wait_ready()
meter.write_u8(REG_COMMAND, CMD_LATCH_PERIOD) # primer
t_prev = time.monotonic()
total_wh = 0.0
while True:
time.sleep(60)
meter.write_u8(REG_COMMAND, CMD_LATCH_PERIOD)
t_now = time.monotonic()
time.sleep(0.05)
if (meter.read_u8(REG_PERIOD_VALID) & 0x01) == 0:
t_prev = time.monotonic()
continue
avg_p = meter.read_float_le(REG_PERIOD_AVG_P0)
dt_s = t_now - t_prev
total_wh += avg_p * dt_s / 3600.0
t_prev = t_now
# Live RT values for the state payload.
u = meter.read_float_le(REG_U_RMS)
i_ = meter.read_float_le(REG_I0_RMS)
pf = meter.read_float_le(REG_PF0)
q = meter.read_float_le(REG_Q0)
freq = meter.read_u8(REG_AC_FREQ)
payload = json.dumps({
"voltage": round(u, 1),
"current": round(i_, 3),
"power": round(avg_p, 1),
"energy": round(total_wh, 3),
"frequency": int(freq),
"power_factor": round(pf, 3),
"apparent_power": round(u * i_, 1),
"reactive_power": round(q, 1),
})
client.publish(f"rbamp/{DEVICE_ID}/state", payload, qos=0, retain=False)
print(f"Published: {payload}")
Nach der ersten Veröffentlichung legt Home Assistant automatisch ein Gerät Mains rbAmp mit acht Sensoren an, darunter eine Entität Energy, die direkt in das Energie-Dashboard passt.
Beispiel 9 — systemd-Daemon mit SQLite-Persistenz
Dieses Beispiel ersetzt den „batteriebetriebenen Tiefschlaf-Logger“ aus den Mikrocontroller-Kapiteln. Unter Linux läuft der SBC ständig, daher ist das richtige Muster ein von systemd verwalteter Daemon mit automatischem Neustart bei Fehlern und einer kleinen SQLite-Datenbank für die Persistenz über Stromzyklen hinweg.
Ziel: ein lang laufender Daemon, der jede Minute eine Periode aufnimmt, das Ergebnis in SQLite schreibt und einen Status an MQTT veröffentlicht. Der Prozess startet nach einem Neustart sauber neu und übernimmt die aufgelaufene Summe aus der Datenbank. Hardware: ein beliebiger SBC + ein rbAmp UI1.
Daemon (rbamp_daemon.py)
#!/usr/bin/env python3
"""rbAmp daemon — periodic snapshot + SQLite persistence + MQTT."""
import json
import logging
import signal
import sqlite3
import sys
import time
from contextlib import closing
import paho.mqtt.client as mqtt
from smbus2 import SMBus
from rbamp_io import (
RbAmpIO, REG_COMMAND, REG_PERIOD_VALID,
REG_PERIOD_AVG_P0, CMD_LATCH_PERIOD,
)
# ----- Configuration -----
I2C_BUS = 1
RB_ADDR = 0x50
DB_PATH = "/var/lib/rbamp/energy.db"
MQTT_HOST = "192.168.1.10"
PERIOD_S = 60
# ----- Logging -----
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
stream=sys.stdout, # systemd captures stdout into the journal
)
log = logging.getLogger("rbamp.daemon")
# ----- SQLite persistence -----
def db_init(conn: sqlite3.Connection) -> None:
"""Create the schema if it does not exist."""
conn.executescript("""
CREATE TABLE IF NOT EXISTS energy_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
total_wh REAL NOT NULL DEFAULT 0
);
INSERT OR IGNORE INTO energy_state(id, total_wh) VALUES (1, 0);
CREATE TABLE IF NOT EXISTS energy_log (
ts INTEGER NOT NULL,
dt_s REAL NOT NULL,
avg_p_w REAL NOT NULL,
e_wh REAL NOT NULL,
total_wh REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_energy_log_ts ON energy_log(ts);
""")
conn.commit()
def db_load_total(conn: sqlite3.Connection) -> float:
"""Return the accumulated total_wh persisted across restarts."""
row = conn.execute("SELECT total_wh FROM energy_state WHERE id = 1").fetchone()
return float(row[0]) if row else 0.0
def db_record(conn: sqlite3.Connection, dt_s: float, avg_p: float,
e_wh: float, total: float) -> None:
"""Append one period sample and update the running total atomically."""
with conn: # implicit BEGIN/COMMIT
conn.execute("UPDATE energy_state SET total_wh = ? WHERE id = 1", (total,))
conn.execute(
"INSERT INTO energy_log(ts, dt_s, avg_p_w, e_wh, total_wh) "
"VALUES (?, ?, ?, ?, ?)",
(int(time.time()), dt_s, avg_p, e_wh, total),
)
# ----- Signal handling for clean shutdown -----
_running = True
def _shutdown(signum, frame):
"""Handle SIGTERM (systemd stop) / SIGINT (Ctrl-C) gracefully."""
global _running
log.info("Shutdown signal %d received", signum)
_running = False
signal.signal(signal.SIGTERM, _shutdown)
signal.signal(signal.SIGINT, _shutdown)
# ----- Main -----
def main() -> int:
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id="rbamp-daemon")
try:
client.connect(MQTT_HOST, 1883, keepalive=60)
except OSError as e:
log.warning("MQTT broker unreachable at boot (%s); paho will retry", e)
client.loop_start() # paho's thread reconnects automatically
with SMBus(I2C_BUS) as bus, closing(sqlite3.connect(DB_PATH)) as conn:
db_init(conn)
total_wh = db_load_total(conn)
log.info("Resumed total_wh = %.3f Wh", total_wh)
meter = RbAmpIO(bus, RB_ADDR)
meter.wait_ready()
meter.write_u8(REG_COMMAND, CMD_LATCH_PERIOD) # primer
t_prev = time.monotonic()
while _running:
# Sleep in 1-second slices so we can respond to SIGTERM quickly.
for _ in range(PERIOD_S):
if not _running:
break
time.sleep(1)
if not _running:
break
meter.write_u8(REG_COMMAND, CMD_LATCH_PERIOD)
t_now = time.monotonic()
time.sleep(0.05)
if (meter.read_u8(REG_PERIOD_VALID) & 0x01) == 0:
log.warning("Stale snapshot — skipping")
t_prev = time.monotonic()
continue
avg_p = meter.read_float_le(REG_PERIOD_AVG_P0)
dt_s = t_now - t_prev
e_wh = avg_p * dt_s / 3600.0
total_wh += e_wh
t_prev = t_now
db_record(conn, dt_s, avg_p, e_wh, total_wh)
client.publish("rbamp/daemon/state",
json.dumps({
"dt_s": round(dt_s, 1),
"avg_p": round(avg_p, 1),
"energy_wh": round(total_wh, 3),
}),
qos=1, retain=True)
log.info("avg_P=%+.1f W E_period=%.3f Wh total=%.3f Wh",
avg_p, e_wh, total_wh)
log.info("Daemon stopped cleanly; total_wh = %.3f Wh", total_wh)
client.loop_stop()
client.disconnect()
return 0
if __name__ == "__main__":
sys.exit(main())
systemd-Unit (/etc/systemd/system/rbamp.service)
[Unit]
Description=rbAmp energy daemon
After=network-online.target time-sync.target
Wants=network-online.target time-sync.target
[Service]
Type=simple
ExecStart=/home/pi/venv-rbamp/bin/python /opt/rbamp/rbamp_daemon.py
User=pi
Group=i2c
Restart=on-failure
RestartSec=5
# Pre-create the persistence directory so the daemon never sees ENOENT.
RuntimeDirectoryMode=0755
StateDirectory=rbamp
StateDirectoryMode=0755
[Install]
WantedBy=multi-user.target
Aktivieren + starten:
sudo systemctl daemon-reload
sudo systemctl enable --now rbamp.service
journalctl -fu rbamp.service # follow the log
Der Daemon:
- Startet nach einem Absturz neu (
Restart=on-failure). - Startet nach Netzwerk und Uhrensynchronisation (
After=network-online.target time-sync.target). - Übersteht Neustarts; die SQLite-Datenbank unter
/var/lib/rbamp/energy.dbbewahrt die laufende Summe. - Reagiert auf
systemctl stop rbamp, indem esSIGTERMabfängt und einen letzten Zustandsdatensatz schreibt.
Das ist das SBC-Pendant zu „Tiefschlaf + RTC-Speicher“ — statt µA zu sparen, verlassen wir uns darauf, dass das Betriebssystem uns wach hält, und auf eine batteriegepufferte RTC, die die Zeit führt.
Beispiel 10 — Zeitabhängiger Tarif (TOU) mit Systemuhr
Ziel: Energie nach einem Zeittarif abrechnen. Der SBC verwendet die Systemuhr (bereits durch systemd-timesyncd synchronisiert) — es ist kein SNTP-Code nötig. Hardware: ein beliebiger SBC + ein rbAmp UI1.
#!/usr/bin/env python3
"""TOU tariff metering using the Linux system clock."""
import json
import time
from datetime import datetime, timezone
from zoneinfo import ZoneInfo # stdlib since Python 3.9
import paho.mqtt.client as mqtt
from smbus2 import SMBus
from rbamp_io import (
RbAmpIO, REG_COMMAND, REG_PERIOD_VALID, REG_PERIOD_AVG_P0,
CMD_LATCH_PERIOD,
)
I2C_BUS = 1
RB_ADDR = 0x50
MQTT_HOST = "192.168.1.10"
# IANA timezone name — Python's stdlib handles DST automatically.
TZ = ZoneInfo("Europe/Berlin")
PEAK_START_HOUR = 8 # inclusive
PEAK_END_HOUR = 22 # exclusive
def is_peak_hour(hour: int) -> bool:
"""Return True if `hour` (local) falls inside the peak window.
For schedules that span midnight (peak = 22..6), change to
``return hour >= PEAK_START_HOUR or hour < PEAK_END_HOUR``.
"""
return PEAK_START_HOUR <= hour < PEAK_END_HOUR
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1, client_id="rbamp-tou")
try:
client.connect(MQTT_HOST, 1883, keepalive=60)
except OSError as e:
print(f"MQTT broker unreachable at boot ({e}); will retry in loop_start()")
client.loop_start()
# Tariff buckets.
today = {"peak_wh": 0.0, "off_peak_wh": 0.0, "yday": -1}
lifetime = {"peak_wh": 0.0, "off_peak_wh": 0.0}
def accumulate(e_wh: float, now_local: datetime) -> None:
"""Add this period's energy to the right bucket and roll the day at midnight."""
yday = now_local.timetuple().tm_yday
if today["yday"] != yday:
if today["yday"] >= 0:
payload = json.dumps({
"yday": today["yday"],
"peak_wh": round(today["peak_wh"], 3),
"off_peak_wh": round(today["off_peak_wh"], 3),
"total_wh": round(today["peak_wh"] + today["off_peak_wh"], 3),
})
client.publish("rbamp/tou/day_close", payload, qos=1, retain=True)
print("Day closed:", payload)
today["peak_wh"] = 0.0
today["off_peak_wh"] = 0.0
today["yday"] = yday
if is_peak_hour(now_local.hour):
today["peak_wh"] += e_wh
lifetime["peak_wh"] += e_wh
else:
today["off_peak_wh"] += e_wh
lifetime["off_peak_wh"] += e_wh
with SMBus(I2C_BUS) as bus:
meter = RbAmpIO(bus, RB_ADDR)
meter.wait_ready()
meter.write_u8(REG_COMMAND, CMD_LATCH_PERIOD) # primer
t_prev = time.monotonic()
print(f"TOU started: peak {PEAK_START_HOUR:02d}:00..{PEAK_END_HOUR:02d}:00 local")
while True:
time.sleep(60)
meter.write_u8(REG_COMMAND, CMD_LATCH_PERIOD)
t_now = time.monotonic()
time.sleep(0.05)
if (meter.read_u8(REG_PERIOD_VALID) & 0x01) == 0:
t_prev = time.monotonic()
continue
avg_p = meter.read_float_le(REG_PERIOD_AVG_P0)
dt_s = t_now - t_prev
e_wh = avg_p * dt_s / 3600.0
t_prev = t_now
# The Linux system clock is already authoritative — no SNTP code required.
now_local = datetime.now(TZ)
accumulate(e_wh, now_local)
peak = is_peak_hour(now_local.hour)
payload = json.dumps({
"ts": now_local.isoformat(timespec="seconds"),
"tariff": "peak" if peak else "off_peak",
"avg_p": round(avg_p, 1),
"period_wh": round(e_wh, 4),
"today_peak_wh": round(today["peak_wh"], 3),
"today_off_peak_wh": round(today["off_peak_wh"], 3),
"life_peak_wh": round(lifetime["peak_wh"], 3),
"life_off_peak_wh": round(lifetime["off_peak_wh"], 3),
})
client.publish("rbamp/tou/state", payload, qos=0, retain=False)
print(payload)
Notes:
zoneinfoist die moderne Zeitzonen-API der Python-3.9+-Standardbibliothek. Auf Debian / Raspberry Pi OS bezieht sie IANA-Daten aus dem Systempakettzdata— Sommerzeitwechsel werden korrekt behandelt.- Für ältere Python-Versionen (3.8 und früher) ersetzen Sie
pytzdurch:import pytz; TZ = pytz.timezone("Europe/Berlin"). - ISO-8601-Zeitstempel mit Offset erzeugt
datetime.isoformat(timespec="seconds")— zum Beispiel2026-05-22T18:30:00+02:00. - Für bidirektionale STD-Messung rufen Sie
accumulate()zweimal auf — einmal für den Verbrauch und einmal für die Einspeisung — und veröffentlichen Sie beide Tarifblöcke, Spitzen- und Nebenzeit.
Vergleich der Beispiele
| # | Komplexität | Ausgang | MQTT | DRDY | Mehrere Module | Bidirektional | Persistenz | Anwendungsfall |
|---|---|---|---|---|---|---|---|---|
| 1 | minimal | Konsole | — | — | — | — | — | Rauchtest |
| 2 | niedrig | OLED | — | — | — | — | RAM | Zählerkasten |
| 3 | niedrig | Konsole | — | — | ja (3) | — | — | Heimüberwachung |
| 4 | mittel | — | ja | — | — | — | RAM | pro Gerät in HA |
| 5 | mittel | Konsole | — | ja | — | ja (Master) | RAM | Solar-Haushalt auf BASIC-Stufe |
| 6 | hoch | — | ja | — | ja (3) | ja | RAM + MQTT (retained) | gesamte Hausbilanz |
| 7 | mittel | Rotierende Logdatei | — | ja | — | — | Dateisystem | Ereigniserkennung |
| 8 | mittel | — | ja (+disco) | — | — | optional | RAM + MQTT | HA-Auto-Discovery |
| 9 | mittel | journald + SQLite | ja | — | — | — | SQLite | Produktiv-Daemon |
| 10 | mittel | Konsole | ja | — | — | optional | RAM + MQTT (Tagesabschluss) | TOU Spitzen-/Nebenzeit |
Bewährte Verfahren
- Führen Sie Skripte als Nicht-root-Benutzer in den Gruppen
i2cundgpioaus. Vermeiden Siesudo python ...— es verunreinigt Pfade und brichtpip --user-Installationen. - Verwenden Sie eine virtuelle Umgebung (
python3 -m venv ...), statt Pakete systemweit mitsudo pipzu installieren. - Fangen Sie
OSErrorbei I²C-Lesevorgängen immer ab — ein vorübergehender NACK oder ein kurzzeitig getrennter Slave erscheint alsOSError(EREMOTEIO). Produktionscode wiederholt den Zugriff; Testcode lässt den Fehler abstürzen, damit er deutlich sichtbar wird. - Verwenden Sie
time.monotonic()für den Master-Takt. Er wird nicht davon beeinflusst, dasssystemd-timesyncddie Wanduhr springen lässt (z. B. bei der ersten Synchronisation nach dem Start). Verwenden Sietime.time()/datetimenur für Zeitstempel. PERIOD_VALID(0x07) muss nach jedemCMD_LATCH_PERIODgeprüft werden. Dieselbe Regel gilt wie beim Mikrocontroller — Linux ändert das Protokoll des rbAmp nicht.- Warten Sie ≥ 50 ms nach einem Snapshot (
time.sleep(0.05)), bevor Sie0xDC..0xEFlesen. - Für Mehrmodul-Aufbauten liefert
broadcast_latch(bus, tick)über General Call präzise Synchronisation. Der GC-Empfang ist optional je Modul (FLEET_CONFIG.bit0, Standard AUS). Bei NACK fallen Sie auf sequenzielleCMD_LATCH_PERIOD-Aufrufe je Modul zurück. - Summen im Dateisystem sichern — JSON, SQLite, InfluxDB. Das Dateisystem ist das SBC-Pendant zu „RTC-Backup-Registern + NVM“. Günstig und zuverlässig.
- Umschließen Sie die Hauptschleife mit Signal-Handlern (
SIGTERM,SIGINT), damitsystemctl stopden Daemon sauber mit einem letzten Zustandsschreiben beendet. - Auf stdout/stderr loggen in Daemons —
journalderfasst das automatisch; Sie erhalten Rotation, Filterung undjournalctl -u rbampkostenlos.
Wie geht es weiter
Nachdem Sie diese zehn Beispiele durchgearbeitet haben:
- Für ESP32-Entwicklung im Arduino-Stil siehe arduino-examples.md.
- Für MicroPython / CircuitPython auf der Embedded-Seite siehe micropython-examples.md.
- Für natives ESP-IDF-Firmware siehe esp-idf-examples.md.
- Für STM32 HAL siehe stm32-hal-examples.md.
- Für das Raspberry Pi Pico SDK (C, nicht der Linux-Fall auf dem Pi) siehe pico-sdk-examples.md.
- Zum High-Level-Python-Paket
rbampsiehe die Tabelle der Client-Bibliotheken in der README. - Zur ESPHome-Integration (deklaratives YAML) siehe
tools/esphome-rbamp/docs/en/. - Die hier verwendete formale I²C-Registerspezifikation steht in api-reference.md.