rbAmp
IT
Negozio

Progetto · · 11 min di lettura

Monitor di energia Raspberry Pi in Python: watt live, senza cloud

Legga la potenza di rete reale su un Raspberry Pi in poche righe di Python: volt, ampere, watt e kWh da un modulo rbAmp via I²C, stampati in tempo reale. Nessun cloud.

Cosa costruirà

  • Tensione, corrente, potenza attiva reale e fattore di potenza live stampati nel terminale, circa una volta al secondo.
  • Un totale energia (Wh) in corso, integrato sul Pi nel tempo dell'orologio.
  • Tutto sul bus I²C del Pi — quattro fili — in CPython semplice.
  • Nessun servizio Wi-Fi, nessun cloud, nessun HA. Solo uno script da eseguire.

Distinta dei materiali

Voce Q.tà Note
rbAmp BASIC SCT-UI1 1 tensione + corrente + potenza reale a bordo · prodotto
Trasformatore di corrente SCT-013 1 portata da adattare al suo circuito · prodotto
Raspberry Pi 1 qualsiasi modello con l'header I²C a 40 pin
Cavetti jumper — il bus I²C (SDA / SCL / 5V / GND)

Abiliti I²C e installi la libreria

Sul Pi, attivi una volta l'interfaccia I²C — sudo raspi-config → Interface Options → I2C → abilita (oppure aggiunga dtparam=i2c_arm=on a /boot/firmware/config.txt e riavvii). Poi installi il pacchetto:

Bash
pip install rbamp smbus2

(Il driver I²C del kernel del Pi gira a 100 kHz per impostazione predefinita e va bene con il modulo — qui non serve nessun workaround a 50 kHz; vale solo per il driver ESP-IDF su ESP32.)

Lo cablili

Il modulo rbAmp va sui pin I²C del Pi:

Text
Raspberry Pi header          rbAmp (0x50)
-------------------          ------------
pin 3  SDA (GPIO2) ────────── SDA
pin 5  SCL (GPIO3) ────────── SCL
pin 2  5V          ────────── VCC        (rbAmp wants 5 V)
pin 6  GND         ────────── GND
                              │
                              └── SCT-013 clamped around ONE mains conductor (arrow → load)
  • Il bus I²C del Pi è a logica 3.3 V, e il modulo rbAmp ha pull-up a bordo — quindi nessun pull-up extra per un singolo modulo. Alimenti il modulo a 5 V (i pin 5 V del Pi); le linee del bus restano a riposo a 3.3 V. (Perché alimentazione a 5 V con bus a 3.3 V?)

  • I TA SCT-013 si stringono attorno a un conduttore isolato — per il lato corrente non taglia né spella mai il filo sotto tensione. Il lato di tensione CA si collega alla rete. Per lavori all'interno di un quadro elettrico, si rivolga a un elettricista qualificato.

Lo script

Salvi, imposti MY_CT (oppure passi --ct) per adattarlo al suo TA, ed esegua python tp1_standalone_pi_monitor.py:

Python
"""
T-P1 — Standalone Raspberry Pi energy monitor (no network, no HA).

One rbAmp UI1 module on the Raspberry Pi hardware I2C bus. Prints live
mains Voltage / Current / Power / Power Factor to the terminal every
second, and every 30 s latches a period snapshot to roll a host-side
Energy (Wh) total. Nothing is invented on-device: Wh is integrated on
the host from average power x wall-clock dt, which is what makes the
total honest.

Wiring (Raspberry Pi, hardware I2C):
    rbAmp SDA -> GPIO2  (Pi pin 3)
    rbAmp SCL -> GPIO3  (Pi pin 5)
    rbAmp GND -> any GND pin
    rbAmp VCC -> 5V     (Pi pin 2 or 4; 4.5-5.5 V -- below 4.5 V the ADC loses accuracy)

Enable I2C once on the Pi:
    sudo raspi-config    # Interface Options -> I2C -> Enable
                         # (equivalent to `dtparam=i2c_arm=on`)

The stock Raspberry Pi Broadcom I2C driver runs at 100 kHz and is
clean with rbAmp straight out of the box -- no `dtparam=i2c_arm_baudrate`
override is needed. (The 50 kHz workaround only applies to the ESP-IDF
i2c_master driver on ESP32.)

Install:
    pip install rbamp smbus2

Run:
    python tp1_standalone_pi_monitor.py
    # or with a non-default bus / address / CT model:
    #   python tp1_standalone_pi_monitor.py --bus 1 --addr 0x50 --ct 3

Set MY_CT below (or pass --ct) to match YOUR clamp before first run.
The value persists to the module's flash, so this script only re-writes
it when it actually differs -- no flash wear on every power-up.

Accuracy: per clamp rating — the class and the sensor's own tolerance are both in the accuracy table on the BASIC page.
Ctrl-C to stop.
"""

import argparse
import time

from smbus2 import SMBus

from rbamp import (
    RbAmp,
    RbAmpError,
    RbAmpStaleError,
    RbAmpSensorClass,
)

# ---- configuration --------------------------------------------------------
# CT model code (matches your clamp; persists to module flash):
#   1 = SCT-013-005 (5 A)     4 = SCT-013-050 (50 A)
#   2 = SCT-013-010 (10 A)    6 = SCT-013-020 (20 A)
#   3 = SCT-013-030 (30 A)
MY_CT = 3

LIVE_S   = 1.0    # refresh V/I/P/PF each second
ENERGY_S = 30.0   # latch a period + roll Wh every 30 s


def ensure_ct_preset(dev, ct_code):
    """Verify-then-set: only rewrite the CT preset if the module isn't
    already on it. set_sensor_class / set_ct_model_ch both persist to
    flash, so this avoids a needless flash write every power-up.
    """
    try:
        applied = dev.read_ct_model_ch(0)
    except RbAmpError:
        applied = -1
    if applied == ct_code:
        print(f"CT model already SCT_013 code={ct_code}; skipping flash write")
        return False
    print(f"configuring CT model SCT_013 code={ct_code} (persists to flash)...")
    dev.set_sensor_class(RbAmpSensorClass.SCT_013)
    dev.set_ct_model_ch(0, ct_code)
    return True


def read_live(dev, last, counters):
    """Read one live sample. A single transient hiccup keeps the previous
    plausible reading so the terminal keeps ticking (mirrors the Arduino
    T-A1 NaN-guard)."""
    try:
        v  = dev.voltage
        i  = dev.current[0]
        p  = dev.power[0]
        pf = dev.power_factor[0]
    except RbAmpError as e:
        counters["bad"] += 1
        print(f"read skipped: {type(e).__name__} -- {e}")
        return
    last["V"], last["I"], last["P"], last["PF"] = v, i, p, pf
    counters["ok"] += 1
    print(
        f"U={v:6.1f}V  I={i:6.3f}A  P={p:7.1f}W  PF={pf:+.2f}  "
        f"E={dev.energy.wh(0):8.4f}Wh  "
        f"[ok={counters['ok']} bad={counters['bad']}]"
    )


def roll_energy(dev):
    """Latch a metering period; the library rolls Wh from avg power x master
    dt on a successful valid snapshot. A stale / not-ready period is reported
    and skipped so the loop keeps running on the last live values."""
    try:
        snap = dev.read_period_snapshot()
    except RbAmpStaleError:
        print("  * period STALE (skipped)")
        return
    except RbAmpError as e:
        print(f"  * period skipped: {type(e).__name__} -- {e}")
        return
    print(
        f"  * period ok: avg_P0={snap.avg_p[0]:6.2f}W  "
        f"dt={snap.master_dt_ms:5d}ms  ->  E={dev.energy.wh(0):.4f}Wh"
    )


def run(bus, addr=0x50, ct_code=MY_CT,
        live_s=LIVE_S, energy_s=ENERGY_S, max_iters=None):
    """Core loop; broken out so a test harness can swap in a mock bus."""
    with RbAmp(bus, addr) as dev:
        print(
            f"rbAmp @ 0x{dev.address:02X}  fw=0x{dev.firmware_version:02X}  "
            f"topology={dev.topology_name}  channels={dev.channels}  "
            f"voltage_hw={'yes' if dev.has_voltage_hw else 'no'}"
        )
        ensure_ct_preset(dev, ct_code)
        print("Accuracy: per clamp rating — see the BASIC page. Ctrl-C to stop.\n")

        last = {"V": 0.0, "I": 0.0, "P": 0.0, "PF": 0.0}
        counters = {"ok": 0, "bad": 0}

        next_live_t   = time.monotonic()
        next_energy_t = next_live_t + energy_s
        iters = 0

        while True:
            now = time.monotonic()
            if now >= next_live_t:
                next_live_t = now + live_s
                read_live(dev, last, counters)
            if now >= next_energy_t:
                next_energy_t = now + energy_s
                roll_energy(dev)

            iters += 1
            if max_iters is not None and iters >= max_iters:
                return counters

            sleep_for = min(next_live_t, next_energy_t) - time.monotonic()
            if sleep_for > 0:
                time.sleep(sleep_for)


def main():
    ap = argparse.ArgumentParser(
        description="Standalone Raspberry Pi energy monitor for a single rbAmp UI1 module."
    )
    ap.add_argument("--bus",  type=int, default=1,
                    help="I2C bus number (Raspberry Pi default: 1)")
    ap.add_argument("--addr", type=lambda s: int(s, 0), default=0x50,
                    help="rbAmp I2C address (default: 0x50)")
    ap.add_argument("--ct",   type=int, default=MY_CT,
                    help="CT model code: 1=SCT-013-005, 2=-010, 3=-030, "
                         "4=-050, 6=-020 (default: 3 = 30 A)")
    args = ap.parse_args()

    with SMBus(args.bus) as bus:
        run(bus, addr=args.addr, ct_code=args.ct)


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\nstopped.")

(Verificato in esecuzione con il backend di test della libreria Python rbAmp su CPython 3.12 — rbamp 1.3.0 + smbus2 0.6.1. set_ct_model_ch() persiste nella flash, quindi lo script riscrive il preset TA solo quando differisce davvero — nessun consumo della flash a ogni esecuzione. Il nucleo run() è isolato così è facile da testare o riutilizzare.)

Cosa fa lo script

L'intera libreria Python rbAmp sta in un paio di blocchi with e una manciata di letture.

I context manager

Python
with SMBus(1) as bus:
    with RbAmp(bus, 0x50) as dev:
        ...

SMBus(1) apre il bus I²C del Pi; RbAmp(bus, 0x50) collega la libreria al modulo sull'indirizzo 0x50. Entrambi sono context manager, quindi il bus e il dispositivo vengono chiusi automaticamente all'uscita del blocco (o con Ctrl-C) — la versione pythonica di "apri il bus, interroga il modulo".

Le letture live

Python
v  = dev.voltage
i  = dev.current[0]
p  = dev.power[0]
pf = dev.power_factor[0]

Queste proprietà restituiscono le misure reali del modulo: dev.power[0] è la potenza attiva reale in watt — la media di tensione istantanea × corrente, non corrente × una tensione presunta. (La forma a metodo dev.read_power(0) è esattamente equivalente — usi quella che si legge meglio.) Una lettura transitoria può generare RbAmpError; lo script la intercetta e mantiene i valori buoni precedenti invece di bloccarsi.

Energia — lo snapshot del periodo

Python
snap = dev.read_period_snapshot()   # atomic LATCH: close the window, read avg power
print(dev.energy.wh(0))             # host-integrated watt-hours, honest over wall-clock time

read_period_snapshot() invia al modulo un LATCH atomico — "chiudi la finestra di misura ora" — e la libreria aggiorna lato host il totale in wattora da average_power × elapsed_time. Il Pi possiede l'intervallo di integrazione, quindi non c'è alcun contatore on-device che possa derivare; dev.energy.wh(0) è un totale in corso onesto. Una finestra non aggiornata genera RbAmpStaleError, che lo script semplicemente salta.

Cosa vedrà

Nel terminale, una lettura live che segue il carico — accenda una lampada o un bollitore e guardi i watt salire:

Text
rbAmp @ 0x50  fw=0x04  topology=SINGLE  channels=1  voltage_hw=yes
CT model already SCT_013 code=3; skipping flash write
Accuracy: per clamp rating — see the BASIC page. Ctrl-C to stop.

U= 231.2V  I= 4.874A  P= 1123.5W  PF=+1.00  E=  0.0000Wh  [ok=1 bad=0]
U= 231.2V  I= 4.874A  P= 1123.5W  PF=+1.00  E=  0.0000Wh  [ok=2 bad=0]
  * period ok: avg_P0=1119.40W  dt=   50ms  ->  E=0.0622Wh
U= 231.2V  I= 4.874A  P= 1123.5W  PF=+1.00  E=  0.0622Wh  [ok=3 bad=0]

Quanto è accurato?

Con un TA SCT-013, la classe e la tolleranza propria del TA sono pubblicate per portata nella tabella di precisione SCT-013. Il modulo misura la potenza attiva reale con compensazione di fase per canale — quindi i carichi reattivi e a basso fattore di potenza si leggono onestamente. Il perché dietro i numeri: come funziona davvero la misura di energia con TA.

Lo personalizzi

  • Lo registri su file o SQLite — il Pi ha un vero filesystem; aggiunga ogni lettura a un CSV o a un database (è la build del logger).

  • Lo serva — il Pi è in rete: esponga le letture come un piccolo endpoint Flask, o le pubblichi via MQTT al suo broker — senza alcun cloud.

  • Un riepilogo via cron — esegua lo script con un timer e si invii via e-mail il totale giornaliero in kWh.

  • Aggiunga un display — un piccolo OLED I²C sullo stesso bus per una lettura senza schermo.
  • Più circuiti — metta più moduli sul bus e li totalizzi (è la build multi-modulo).

Niente di tutto questo tocca la misura — sono ciò che fa con i numeri che le letture già forniscono.

Cosa segue

Questo singolo modulo nel terminale è la base. Da qui la serie Python si sviluppa:

  • Misuri più circuiti — più moduli rbAmp su un bus, letti e totalizzati dal Pi.
  • Agisca — faccia scattare un relè GPIO quando un circuito supera un limite di corrente.
  • Registri — energia periodica su CSV o SQLite.

(Preferisce un microcontrollore invece di un Pi? Lo stesso modulo gira su Arduino o in Home Assistant via ESPHome.)


Leggi anche