rbAmp
PT
Loja

Projeto · · 11 min de leitura

Registo de energia num Raspberry Pi em CSV e SQLite em Python, sem nuvem

Transforme um Raspberry Pi num registador de energia autónomo: volts, amperes, watts e kWh com carimbo temporal em CSV ou SQLite, em Python simples. Sem RTC, sem nuvem.

O que vai construir

  • Uma linha CSV por intervalo — timestamp, voltage, current, power, energy — acrescentada a um ficheiro no Pi.
  • Opcionalmente, as mesmas linhas em SQLite (--sqlite energy.db), para poder fazer SELECT e criar gráficos mais tarde.
  • Carimbos temporais reais pelo relógio do sistema do Pi (sincronizado por NTP) — sem hardware de RTC.
  • Robusto a uma leitura má, e com flush para que uma linha sobreviva a um corte de energia.

Lista de materiais

Item Qtd. Notas
rbAmp BASIC SCT-UI1 1 tensão + corrente + potência ativa calculada no módulo · produto
TC SCT-013 1 classificação adequada ao seu circuito · produto
Raspberry Pi 1 qualquer modelo com o cabeçalho I²C de 40 pinos
Fios de ligação (jumper) — o barramento I²C (SDA / SCL / 5V / GND)

(Sem módulo de cartão SD, sem RTC — o Pi já tem ambos.)

Ligue e instale

O rbAmp vai nos pinos I²C do Pi (SDA GPIO2 / SCL GPIO3, VCC 5 V — porquê 5 V com um barramento de 3.3 V?), com a TC presa a um condutor. Ative o I²C (sudo raspi-config) e instale — CSV e SQLite fazem ambos parte da biblioteca padrão do Python, por isso não há dependências extra:

Bash
pip install rbamp smbus2

O CSV

Em cada intervalo acrescenta uma linha; o cabeçalho é escrito quando o ficheiro é criado pela primeira vez:

Text
timestamp,voltage_V,current_A,power_W,energy_Wh
2026-07-30T14:05:00+01:00,230.70,3.793,875.00,0.0120
2026-07-30T14:05:30+01:00,230.65,3.788,873.40,1.4700

(O carimbo temporal leva o desvio horário local do Pi, para que o ficheiro continue inequívoco um ano depois noutro anfitrião. Se o Pi estiver offline e sem sincronização NTP, os carimbos ficam em 1970-… até acertar o relógio ou ligá-lo.)

Abra numa folha de cálculo, ou — se passou --sqlite — consulte a base de dados: SELECT strftime('%H', timestamp), AVG(power_W) FROM energy GROUP BY 1;.

O script

Execute como está para CSV, ou acrescente --sqlite energy.db para também escrever uma base de dados consultável:

Python
"""
T-P4 -- Log energy to CSV (and optionally SQLite) on a Raspberry Pi.

One rbAmp module meters a circuit; every interval this script writes a
timestamped row to a CSV file, mirrors it to stdout so you can watch, and
-- if you pass `--sqlite path.db` -- also inserts the same row into an
SQLite table for easy querying (`SELECT AVG(power_W) FROM energy WHERE ...`).

Compared to the Arduino data-logger equivalent this is much simpler: the
Pi has a real filesystem and an NTP-synchronised system clock, so there
is no microSD-card module and no external RTC. Timestamps are just
`datetime.now().astimezone().isoformat(...)` -- the Pi is already telling
you the correct wall-clock time.

CSV columns:
    timestamp,voltage_V,current_A,power_W,energy_Wh

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)
                ^ rbAmp needs 5V for its analog front-end. Only the I2C
                  logic level is 3.3V (handled internally).

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

Install:
    pip install rbamp smbus2
    # `csv` and `sqlite3` are Python stdlib; no extra pip deps.

Run:
    python tp4_pi_csv_sqlite_logger.py                    # CSV only, every 30 s
    python tp4_pi_csv_sqlite_logger.py --sqlite energy.db # CSV + SQLite
    python tp4_pi_csv_sqlite_logger.py --interval 10 --ct 3

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 -- the CSV file + SQLite DB are flushed and closed cleanly.
Data is safe against power cuts: every CSV row is flushed and every SQLite
insert is committed before the loop moves on.
"""

import argparse
import csv
import os
import sqlite3
import sys
import time
from datetime import datetime

from smbus2 import SMBus

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

# ---- configuration --------------------------------------------------------
RBAMP_ADDR = 0x50
METER_CH   = 0
MY_CT      = 3         # SCT-013-030
CSV_PATH   = "energy.csv"
LOG_S      = 30.0      # one CSV row every 30 s

CSV_HEADER = ["timestamp", "voltage_V", "current_A", "power_W", "energy_Wh"]
SQLITE_DDL = """
CREATE TABLE IF NOT EXISTS energy (
    timestamp TEXT NOT NULL,
    voltage_V REAL,
    current_A REAL,
    power_W   REAL,
    energy_Wh REAL
)
"""
SQLITE_INSERT = "INSERT INTO energy (timestamp, voltage_V, current_A, power_W, energy_Wh) VALUES (?, ?, ?, ?, ?)"


def ensure_ct_preset(dev, ct_code):
    """Verify-then-set CT preset (same pattern as T-P1/P2/P3)."""
    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 sample_row(dev):
    """Read one V/I/P + latch a period + roll Wh. Returns a row tuple or None
    on any RbAmpError (transient hiccup / stale snapshot). The energy tick
    silently skips on stale but V/I/P are still reported."""
    try:
        v = dev.voltage
        i = dev.current[METER_CH]
        p = dev.power[METER_CH]
    except RbAmpError:
        return None
    try:
        dev.read_period_snapshot()   # library auto-rolls the Wh accumulator
    except RbAmpStaleError:
        pass                          # keep the V/I/P row; skip the energy tick
    except RbAmpError:
        pass
    wh = dev.energy.wh(METER_CH)
    # ISO-8601 with local tz offset; Pi is NTP-synced.
    ts = datetime.now().astimezone().isoformat(timespec="seconds")
    return (ts, v, i, p, wh)


def open_csv(path):
    """Open (or create) the CSV, write the header only if new, return
    (file, writer). Line-buffered so each row hits disk immediately."""
    is_new = not os.path.exists(path) or os.path.getsize(path) == 0
    f = open(path, "a", newline="", encoding="utf-8", buffering=1)
    w = csv.writer(f)
    if is_new:
        w.writerow(CSV_HEADER)
        f.flush()
    return f, w


def open_sqlite(path):
    """Open SQLite (create tables if missing), return connection. Explicit
    commit per insert gives crash-safe single-row durability."""
    con = sqlite3.connect(path)
    con.execute(SQLITE_DDL)
    con.commit()
    return con


def run(bus, addr=RBAMP_ADDR, ct_code=MY_CT,
        csv_path=CSV_PATH, sqlite_path=None, log_s=LOG_S,
        max_iters=None, stdout=sys.stdout):
    """Core loop. `sqlite_path=None` = CSV only."""
    with RbAmp(bus, addr=addr) as dev:
        ensure_ct_preset(dev, ct_code)
        print(f"rbAmp @ 0x{dev.address:02X}  fw=0x{dev.firmware_version:02X}  "
              f"topology={dev.topology_name}  ch={dev.channels}", file=stdout)
        print(f"logging every {log_s:.1f} s -> {csv_path}"
              + (f" + sqlite:{sqlite_path}" if sqlite_path else ""),
              file=stdout)
        print("Accuracy: per clamp rating — see the BASIC page. Ctrl-C stops.\n",
              file=stdout)

        csv_file, csv_writer = open_csv(csv_path)
        con = open_sqlite(sqlite_path) if sqlite_path else None

        rows = 0
        skipped = 0
        iters = 0
        try:
            while True:
                t_start = time.monotonic()
                row = sample_row(dev)
                if row is None:
                    skipped += 1
                    print(f"[SKIP #{skipped}] read failed -- holding, no row written",
                          file=stdout)
                else:
                    ts, v, i, p, wh = row
                    csv_writer.writerow([
                        ts,
                        f"{v:.2f}", f"{i:.3f}", f"{p:.2f}", f"{wh:.4f}",
                    ])
                    csv_file.flush()              # crash-safe row
                    if con is not None:
                        con.execute(SQLITE_INSERT, (ts, v, i, p, wh))
                        con.commit()               # crash-safe row
                    rows += 1
                    print(f"row#{rows:>4d}  {ts}  U={v:6.1f}V  I={i:6.3f}A  "
                          f"P={p:7.1f}W  E={wh:9.4f}Wh", file=stdout)

                iters += 1
                if max_iters is not None and iters >= max_iters:
                    return {"rows": rows, "skipped": skipped,
                            "csv": csv_path, "sqlite": sqlite_path}

                sleep_for = log_s - (time.monotonic() - t_start)
                if sleep_for > 0:
                    time.sleep(sleep_for)
        finally:
            csv_file.close()
            if con is not None:
                con.close()


def main():
    ap = argparse.ArgumentParser(
        description="Log rbAmp energy to CSV (and optionally SQLite) on a Raspberry Pi."
    )
    ap.add_argument("--bus",      type=int, default=1)
    ap.add_argument("--addr",     type=lambda s: int(s, 0), default=RBAMP_ADDR)
    ap.add_argument("--ct",       type=int, default=MY_CT)
    ap.add_argument("--csv",      type=str, default=CSV_PATH)
    ap.add_argument("--sqlite",   type=str, default=None,
                    help="Optional path to an SQLite DB file (adds `energy` table).")
    ap.add_argument("--interval", type=float, default=LOG_S,
                    help="Seconds between rows (default 30).")
    args = ap.parse_args()

    with SMBus(args.bus) as bus:
        run(bus, addr=args.addr, ct_code=args.ct,
            csv_path=args.csv, sqlite_path=args.sqlite, log_s=args.interval)


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

(Verificado em execução contra o backend simulado da biblioteca rbAmp + um CSV real no sistema de ficheiros e uma BD SQLite real em CPython 3.12 — três cenários: escrita CSV+SQLite, idempotência de anexação numa nova execução e SKIP controlado em falhas de leitura injetadas. Cada linha é escrita (CSV) e confirmada (SQLite) antes de o ciclo avançar, por isso um corte de energia nunca perde uma linha escrita.)

O que o script faz

Três funções auxiliares — sample_row(), open_csv() e (opcionalmente) open_sqlite() — alimentam um ciclo run() simples.

sample_row() — uma leitura

Python
v = dev.voltage; i = dev.current[0]; p = dev.power[0]   # RbAmpError here -> return None (skip the row)
dev.read_period_snapshot()                              # roll the Wh accumulator (stale -> keep V/I/P, skip tick)
ts = datetime.now().astimezone().isoformat(timespec="seconds")
return (ts, v, i, p, dev.energy.wh(0))

Lê a V/I/P em tempo real, faz latch de um período para avançar o total de watt-hora, e carimba-o com a hora do sistema do Pi — ISO-8601 com o desvio horário local, sem RTC e sem configuração manual do relógio porque o Pi está sincronizado por NTP. Um erro de leitura transitório devolve None (o ciclo salta essa linha); uma janela de energia obsoleta mantém a linha V/I/P mas não avança os Wh nesse intervalo.

open_csv() / open_sqlite() — os destinos

Python
f = open(path, "a", newline="", encoding="utf-8", buffering=1)   # line-buffered -> each row hits disk
if is_new: writer.writerow(CSV_HEADER)                           # header written once
con.execute("CREATE TABLE IF NOT EXISTS energy (...)")           # SQLite, only if --sqlite given

O CSV abre em modo de acrescentar (cabeçalho apenas se o ficheiro for novo), com buffer de linha para que cada linha fique em disco imediatamente. Passe --sqlite e também abre uma BD SQLite e cria a tabela energy se não existir — ambas da biblioteca padrão do Python, por isso não há nada extra para instalar.

O ciclo run()

Python
row = sample_row(dev)
if row is None:  skipped += 1                       # bad read -> log a SKIP, no row
else:
    csv_writer.writerow([...]); csv_file.flush()    # crash-safe CSV row
    if con: con.execute(INSERT, row); con.commit()  # crash-safe SQLite row

A cada intervalo de --interval segundos recolhe uma amostra e — se a leitura foi boa — escreve uma linha CSV (e uma linha SQLite, se ativo), com flush e commit antes de entrar em espera, para que um corte de energia nunca perca uma linha escrita. Um bloco finally fecha o ficheiro e a BD de forma limpa com Ctrl-C. Esse flush/commit por linha é toda a história da durabilidade.

Usar os dados

Abra o CSV em qualquer folha de cálculo — trace a potência ao longo do dia, some a energia por hora, identifique o frigorífico a ciclar. Ou, com a opção SQLite, execute SQL diretamente sobre ele — médias horárias, totais diários, tudo. Como a coluna de energia são watt-hora reais integrados no anfitrião, os totais batem certo com o que esperaria na fatura. Quer vê-lo em gráfico em tempo real? Coloque-o no Home Assistant — mas para um registo totalmente offline, estes ficheiros são seus.

A série Python, resumo

Tem agora o kit completo autónomo para Pi — sem necessidade de rede:

  • Leia-o — um módulo no terminal.
  • Escale-o — vários circuitos num barramento, coerentemente.
  • Atue sobre ela — dispare um relé GPIO por sobrecorrente.
  • Registe — esta construção, em CSV / SQLite.

Leia a seguir