rbAmp
IT
Negozio

Progetto · · 13 min di lettura

Più circuiti da un unico Raspberry Pi: un bus rbAmp multi-modulo in Python

Due o tre moduli rbAmp sul bus I²C di un Raspberry Pi, agganciati insieme con un unico broadcast: potenza per circuito e un totale coerente, in Python semplice.

Cosa costruirà

  • Per circuito tensione / corrente / potenza attiva reale da ogni modulo, letti dal Pi.
  • Una potenza attiva totale coerente — la somma dei moduli, tutti agganciati nello stesso istante, non tre letture prese in tre momenti diversi (perché conta).

  • Tutto su un unico bus I²C, un Pi, in Python semplice.

Distinta dei materiali

Voce Q.tà Note
rbAmp BASIC SCT-UI1 3 uno per circuito · prodotto
TA SCT-013 3 un modulo ciascuno, portata per circuito · prodotto
Raspberry Pi 1 qualsiasi modello con l'header I²C a 40 pin
Cavetti jumper — il bus I²C condiviso

Cablaggio del bus condiviso

Tutti i moduli stanno sugli stessi pin I²C del Pi — differiscono solo per indirizzo:

Text
Raspberry Pi          module A (0x50)   module B (0x51)   module C (0x52)
------------          ---------------   ---------------   ---------------
SDA (GPIO2) ────┬────── SDA ────┬────── SDA ────┬────── SDA
SCL (GPIO3) ────┼────── SCL ────┼────── SCL ────┼────── SCL
5V          ────┼────── VCC     ├────── VCC     ├────── VCC
GND         ────┴────── GND ────┴────── GND ────┴────── GND
                        │                │                │
                     CT on circuit A   CT on B          CT on C
  • Alimenti ogni modulo a 5 V (i pin 5 V del Pi); il bus è a logica 3.3 V (perché?). Ogni modulo ha pull-up a bordo — con due o tre moduli su un bus fino a 15 cm, li lasci attivi su ogni modulo; da quattro moduli in su, o su un bus più lungo, segua la documentazione hardware del modulo.

  • I TA si stringono attorno ai loro conduttori — non invasivi sul lato corrente. Per lavori all'interno di un quadro elettrico, si rivolga a un elettricista qualificato.

Assegni un indirizzo a ciascun modulo

I moduli escono con 0x50, quindi assegni al secondo e al terzo un indirizzo unico (0x51, 0x52) prima che condividano un bus. Sul firmware attuale è una normale operazione di produzione — nessuna modalità speciale né strumenti: prepari, armi, confermi; il modulo si riavvia al nuovo indirizzo. Lo faccia un modulo alla volta, con gli altri scollegati, così non c'è conflitto — ci pensano prepare_address_change() / commit_address_change() della libreria.

Sincronizzi, poi legga

Invece di leggere tre moduli uno dopo l'altro (ciascuno colto in un momento leggermente diverso), si invia un unico broadcast "latch ora" a tutto il bus — ogni modulo congela la sua finestra nello stesso istante. Poi si leggono gli snapshot congelati di ciascun modulo a turno. Le letture sono sequenziali, ma i valori appartengono tutti allo stesso momento, quindi sommarli è corretto. È il principio di coerenza trifase, qui in Python.

Lo script

Imposti FLEET_ADDRS e MY_CT per i suoi moduli ed esegua python tp2_multimodule_pi_monitor.py:

Python
"""
T-P2 — Multi-module Raspberry Pi bus (per-circuit + coherent whole-panel total).

Three rbAmp UI1 modules share the Pi's one I2C bus, each measuring its own
circuit's mains. The v1.3+ General-Call broadcast latches all three period
accumulators on the same instant so the summed Wh total is honest -- every
module integrates the same wall-clock window, no per-module drift.

Wiring (Raspberry Pi, hardware I2C, three modules in parallel on the same bus):
    Every rbAmp:  SDA -> GPIO2  (Pi pin 3)
                  SCL -> GPIO3  (Pi pin 5)
                  GND -> any GND pin
                  VCC -> 5V     (Pi pin 2 or 4)
                       ^ rbAmp needs 5V for its analog front-end. Only the
                         I2C logic level is 3.3V (handled internally).
    Optional external 4.7 kOhm pull-ups on SDA and SCL to 3.3V. The Pi has
    on-board 1.8 kOhm pull-ups which are usually enough for two or three
    modules on a short bus; add external pull-ups if you see NACKs on longer
    runs or with more devices.

Unique addresses: modules ship at 0x50. To make three of them coexist on
one bus, provision the extras once with the address-change flow
(`prepare_address_change` -> `commit_address_change`). That is a separate
one-time step; this tutorial assumes the three addresses are already
0x50 / 0x51 / 0x52.

Enable I2C once on the Pi (same as T-P1):
    sudo raspi-config    # Interface Options -> I2C -> Enable

The stock 100 kHz Broadcom I2C kernel driver is clean; no
`dtparam=i2c_arm_baudrate` override needed.

Install:
    pip install rbamp smbus2

Run:
    python tp2_multimodule_pi_monitor.py
    # or with a custom fleet:
    #   python tp2_multimodule_pi_monitor.py --addr 0x50 --addr 0x51 --addr 0x52

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,
    RbAmpFleet,
    RbAmpError,
    RbAmpStaleError,
    RbAmpSensorClass,
)

# ---- configuration --------------------------------------------------------
FLEET_ADDRS = [0x50, 0x51, 0x52]   # provisioned addresses of the 3 modules
MY_CT       = 3                    # SCT-013-030 for every module (edit per-mod if needed)

LIVE_S      = 1.0    # refresh per-module live V/I/P each second
ENERGY_S    = 30.0   # broadcast a GC latch + roll total Wh every 30 s
GC_GROUP    = 0      # 0 = all-call (every GC-enabled module latches)


def ensure_ct_preset(dev, ct_code):
    """Verify-then-set: rewrite CT preset only if it actually differs. See T-P1."""
    try:
        applied = dev.read_ct_model_ch(0)
    except RbAmpError:
        applied = -1
    if applied == ct_code:
        return False
    dev.set_sensor_class(RbAmpSensorClass.SCT_013)
    dev.set_ct_model_ch(0, ct_code)
    return True


def enrol_fleet(bus, addrs, ct_code):
    """Bring up N modules at explicit addresses (no bus scan). Any module that
    fails begin() is reported and skipped -- the fleet keeps the rest."""
    fleet = RbAmpFleet(bus)
    for a in addrs:
        try:
            dev = RbAmp(bus, addr=a)
            dev.begin()
        except RbAmpError as e:
            print(f"[0x{a:02X}] enrol FAILED: {type(e).__name__} -- {e}")
            continue
        rewrote = ensure_ct_preset(dev, ct_code)
        note = "CT rewritten" if rewrote else "CT already set"
        print(f"[0x{a:02X}] enrolled  fw=0x{dev.firmware_version:02X}  "
              f"topology={dev.topology_name}  ch={dev.channels}  ({note})")
        fleet.add(dev)
    return fleet


def print_live(fleet):
    """One live row: per-module V / I / P plus a fleet total P line."""
    total_p = 0.0
    parts = []
    for m in fleet:
        try:
            v = m.voltage
            i = m.current[0]
            p = m.power[0]
        except RbAmpError:
            parts.append(f"[0x{m.address:02X}]  --- V   --- A   ---- W")
            continue
        total_p += p
        parts.append(f"[0x{m.address:02X}] {v:6.1f}V {i:5.2f}A {p:6.0f}W")
    total_wh = fleet.total_energy_wh()
    print("  ".join(parts) + f"  |  totP={total_p:7.0f}W  totE={total_wh:9.4f}Wh")


def roll_gc_energy(fleet):
    """One GC-synchronised period window across the whole fleet.

      1. gc_latch() broadcasts the 5-byte GC frame `A5 27 group tick_lo tick_hi`
         at I2C general-call address 0x00. Every GC-enabled module with a
         matching group latches its period accumulator on the same clock edge.
      2. Sleep the settle window (inside gc_latch).
      3. check_sync() reads REG_GC_TICK per module; any stale/NACK -> missed.
      4. Per in-sync module, read_period_snapshot(settle_ms=0, skip_latch=True)
         reads the already-latched values -- no per-module latch, no settle.
    """
    tick = fleet.gc_latch(group=GC_GROUP)          # auto-increments internal counter
    sync = fleet.check_sync(expected_tick=tick)

    missed = [s for s in sync if not s.in_sync]
    if missed:
        for s in missed:
            print(f"  * [0x{s.addr:02X}] MISSED gc tick "
                  f"(got=0x{s.gc_tick:04X} expected=0x{tick:04X} reachable={s.reachable})")

    for m, s in zip(fleet, sync):
        if not s.in_sync:
            continue
        try:
            snap = m.read_period_snapshot(settle_ms=0, skip_latch=True)
        except RbAmpStaleError:
            print(f"  * [0x{m.address:02X}] period STALE (in_sync but slave says stale)")
            continue
        except RbAmpError as e:
            print(f"  * [0x{m.address:02X}] period skipped: {type(e).__name__} -- {e}")
            continue
        print(f"  * [0x{m.address:02X}] avg_P={snap.avg_p[0]:6.1f}W  "
              f"dt={snap.master_dt_ms:5d}ms  E={m.energy.wh(0):8.4f}Wh")

    print(f"  * tick=0x{tick:04X}  in_sync={sum(1 for s in sync if s.in_sync)}/{len(sync)}  "
          f"fleet totE={fleet.total_energy_wh():.4f}Wh")


def run(bus, addrs=None, ct_code=MY_CT,
        live_s=LIVE_S, energy_s=ENERGY_S, max_iters=None):
    if addrs is None:
        addrs = FLEET_ADDRS
    fleet = enrol_fleet(bus, addrs, ct_code)
    if len(fleet) == 0:
        print("no modules enrolled -- check wiring and addresses; exiting")
        return
    enabled = fleet.enable_gc_all(group=GC_GROUP)
    print(f"GC latch enabled on {enabled}/{len(fleet)} module(s), group={GC_GROUP}")
    print("Accuracy: per clamp rating — see the BASIC page. Ctrl-C to stop.\n")

    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
            print_live(fleet)
        if now >= next_energy_t:
            next_energy_t = now + energy_s
            roll_gc_energy(fleet)

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

        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="Multi-module Raspberry Pi rbAmp bus with fleet GC-latch energy sync."
    )
    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), action="append",
                    default=None,
                    help="rbAmp address (repeatable; default: 0x50 0x51 0x52)")
    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)")
    args = ap.parse_args()

    addrs = args.addr if args.addr else FLEET_ADDRS

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


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

(Verificato in esecuzione con il backend mock della libreria Python rbAmp su CPython 3.12 — rbamp 1.3.0 + smbus2 0.6.1. Usa il latch broadcast RbAmpFleet della v1.3+, non il latch sequenziale per modulo. check_sync() segnala qualsiasi modulo che ha mancato il broadcast, così un modulo cablato male o non provisionato è evidente.)

Cosa vedrà

Righe live al secondo con un totale progressivo, e una riga di energia sincronizzata ogni 30 s:

Text
[0x50] enrolled  fw=0x04  topology=SINGLE  ch=1  (CT already set)
[0x51] enrolled  fw=0x04  topology=SINGLE  ch=1  (CT already set)
[0x52] enrolled  fw=0x04  topology=SINGLE  ch=1  (CT already set)
GC latch enabled on 3/3 module(s), group=0

[0x50]  230.5V  3.52A    812W  [0x51]  230.5V  1.93A    445W  [0x52]  230.5V  5.37A   1237W  |  totP=   2494W  totE=   0.0000Wh
  * [0x50] avg_P= 795.8W  dt= 3253ms  E=  0.7191Wh
  * [0x51] avg_P= 436.1W  dt= 3203ms  E=  0.3880Wh
  * [0x52] avg_P=1212.3W  dt= 3152ms  E=  1.0614Wh
  * tick=0x0001  in_sync=3/3  fleet totE=2.1685Wh

Cosa fa lo script

RbAmpFleet si occupa della contabilità del fleet; tre funzioni mandano avanti tutto — enrol_fleet() all'avvio, poi print_live() e roll_gc_energy() sulle rispettive cadenze.

enrol_fleet() — avvia i moduli

Python
fleet = RbAmpFleet(bus)
for a in [0x50, 0x51, 0x52]:
    dev = RbAmp(bus, addr=a); dev.begin()
    ensure_ct_preset(dev, MY_CT)
    fleet.add(dev)

Avvia ogni modulo al suo indirizzo esplicito (nessuna scansione del bus, così vede gli indirizzi nel tutorial), verifica e poi imposta il suo preset TA (nessuna scrittura inutile in flash), e lo aggiunge al fleet. Un modulo che non riesce in begin() viene segnalato e saltato — il fleet mantiene il resto, quindi un collegamento difettoso non compromette l'intera esecuzione.

Python
for m in fleet:
    v = m.voltage; i = m.current[0]; p = m.power[0]
    total_p += p

Percorre il fleet e legge per ogni modulo V / I / P in tempo reale per la visualizzazione, sommando la potenza dei singoli moduli in un totale live dell'intero quadro. Queste letture live non devono essere sincronizzate — servono per il display.

roll_gc_energy() — la parte coerente

Python
tick = fleet.gc_latch(group=0)                 # ONE broadcast latches every module together
sync = fleet.check_sync(expected_tick=tick)    # did each accept the tick?
for m, s in zip(fleet, sync):
    if not s.in_sync:                          # dropped / GC-disabled / wrong group
        continue
    snap = m.read_period_snapshot(settle_ms=0, skip_latch=True)   # read the frozen window

È per questo che il totale è affidabile. gc_latch() trasmette un frame General-Call all'indirizzo 0x00 — ogni modulo abilitato congela la sua finestra di periodo nello stesso istante. check_sync() legge poi il REG_GC_TICK di ciascun modulo e segnala quelli che hanno mancato il broadcast (stampa una riga MISSED gc tick e salta quel modulo per la finestra — quelli sani continuano a scorrere). Poi read_period_snapshot(skip_latch=True) legge ogni finestra già congelata senza rifare il latch, e fleet.total_energy_wh() somma il fleet. Poiché ogni modulo ha fatto il latch insieme, i Wh sommati sono coerenti — non tre letture prese in tre momenti diversi. Quella riga di salute check_sync è esattamente ciò che strumenterebbe in un'installazione reale.

Lo personalizzi

  • Più circuiti — aggiunga moduli sul bus, assegni a ciascuno un indirizzo; entrano nel fleet. Tenga conto delle regole di carico del bus / pull-up man mano che il numero cresce.

  • Registri il quadro — una riga per modulo per intervallo su CSV o SQLite (la build del logger).

  • Lo serva — esponga il singolo circuito + il totale come endpoint Flask o lo pubblichi via MQTT — in locale, senza cloud.
  • Azioni per circuito — far scattare un relè per modulo oltre il proprio limite (la build relè).
  • Fleet indipendenti — group_id diversi permettono a gruppi non correlati di agganciarsi con la propria cadenza, tutti sullo stesso bus.

Cosa segue

  • Agisca — faccia scattare un relè GPIO quando un circuito supera un limite di corrente.
  • Registri — energia periodica per circuito su CSV o SQLite.
  • Preferisce Home Assistant? Lo stesso bus multi-modulo è l'intero quadro su un ESP32 con ESPHome.

Leggi anche