rbAmp
ES
Tienda

Proyecto · · 11 min de lectura

Registro de energía con Raspberry Pi en CSV y SQLite en Python, sin nube

Convierta una Raspberry Pi en un registrador de energía autónomo: voltios, amperios, vatios y kWh con marca de tiempo a CSV o SQLite en Python sencillo. Sin RTC, sin nube.

Lo que va a construir

  • Una fila CSV por intervalo: timestamp, voltage, current, power, energy, añadida a un archivo en la Pi.
  • Opcionalmente las mismas filas en SQLite (--sqlite energy.db), para poder hacer SELECT y graficar después.
  • Marcas de tiempo reales desde el reloj del sistema de la Pi (sincronizado por NTP): no hace falta hardware RTC.
  • Robusto ante una lectura mala, y volcado para que una fila sobreviva a un corte de corriente.

Lista de materiales

Elemento Cant. Notas
rbAmp BASIC SCT-UI1 1 tensión + corriente + potencia real en el chip · producto
CT SCT-013 1 calibre según su circuito · producto
Raspberry Pi 1 cualquier modelo con el cabezal I²C de 40 pines
Cables de puente — el bus I²C (SDA / SCL / 5V / GND)

(Sin módulo de tarjeta SD ni RTC: la Pi ya tiene ambos.)

Conéctelo e instálelo

El rbAmp va a los pines I²C de la Pi (SDA GPIO2 / SCL GPIO3, VCC 5 V; ¿por qué 5 V con un bus de 3.3 V?), con la CT colocada alrededor de un conductor. Active I²C (sudo raspi-config) e instale: CSV y SQLite están ambos en la biblioteca estándar de Python, así que no hay dependencias extra:

Bash
pip install rbamp smbus2

El CSV

Cada intervalo añade una fila; la cabecera se escribe al crear el archivo por primera 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

(La marca de tiempo lleva el desfase horario local de la Pi, de modo que el archivo sigue sin ambigüedad un año después en otro equipo. Si su Pi está sin conexión y no sincronizada por NTP, las marcas de tiempo aparecen como 1970-… hasta que ajuste el reloj o la conecte.)

Ábralo en una hoja de cálculo o, si pasó --sqlite, consulte la base de datos: SELECT strftime('%H', timestamp), AVG(power_W) FROM energy GROUP BY 1;.

El script

Ejecútelo tal cual para CSV, o añada --sqlite energy.db para escribir también una base de datos consultable:

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 en ejecución con el backend simulado de la biblioteca rbAmp, un archivo CSV real y una base de datos SQLite real en CPython 3.12: tres escenarios: escritura en CSV y SQLite, idempotencia de añadido al reejecutar y SKIP controlado ante fallos de lectura inyectados. Cada fila se vuelca (CSV) y se confirma (SQLite) antes de que el bucle avance, de modo que un corte de corriente nunca pierde una fila escrita.)

Qué hace el script

Tres auxiliares: sample_row(), open_csv() y (opcionalmente) open_sqlite(), alimentan un bucle simple run().

sample_row(): una lectura

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))

Lee la V/I/P en vivo, fija un periodo para avanzar el total de vatios-hora, y lo sella con la hora del sistema de la Pi: ISO-8601 con el desfase horario local, sin RTC ni configuración manual del reloj porque la Pi está sincronizada por NTP. Un error de lectura transitorio devuelve None (el bucle omite esa fila); una ventana de energía obsoleta conserva la fila V/I/P pero no avanza los Wh en ese intervalo.

open_csv() / open_sqlite(): los 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

El CSV se abre en modo añadir (cabecera solo si el archivo es nuevo), con búfer por línea para que cada fila llegue al disco de inmediato. Si pasa --sqlite, también abre una base de datos SQLite y crea la tabla energy si no existe; todo ello de la biblioteca estándar de Python, así que no hay nada que instalar.

El bucle 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

Cada --interval segundos toma una muestra y, si la lectura fue correcta, escribe una fila CSV (y una fila SQLite si está activado), volcando y confirmando antes de dormir, de modo que un corte de corriente nunca pierde una fila escrita. Un bloque finally cierra limpiamente el archivo y la base de datos con Ctrl-C. Ese volcado y confirmación por fila es toda la garantía de durabilidad.

Uso de los datos

Abra el CSV en cualquier hoja de cálculo: represente la potencia a lo largo del día, sume la energía por hora, detecte los ciclos del frigorífico. O, con la opción SQLite, ejecute SQL directamente sobre él: medias horarias, totales diarios, todo. Como la columna de energía son vatios-hora reales integrados en el host, los totales cuadran con lo que cabría esperar en la factura. ¿Lo quiere graficado en directo? Introdúzcalo en Home Assistant; pero para un registro totalmente sin conexión, estos archivos son suyos.

Resumen de la serie Python

Ahora dispone del conjunto completo de herramientas autónomo de la Pi; no se necesita red:

  • Léalo: un módulo en el terminal.
  • Escálelo: varios circuitos en un bus, de forma coherente.
  • Actúe: dispare un relé GPIO por sobrecorriente.
  • Regístrelo: esta construcción, a CSV / SQLite.

Lea a continuación