"""Database reads and writes. All timestamps in the DB are unix seconds (UTC).""" import json import sqlite3 import time from datetime import date, datetime, timedelta, timezone from zoneinfo import ZoneInfo from .config import get_settings from .fields import FIELD_KEYS, FIELDS_BY_KEY, NUMERIC_KEYS, derive from .schemas import ReadingIn BUCKETS = [60, 300, 900, 1800, 3600, 3 * 3600, 6 * 3600, 86400] MAX_POINTS = 600 def now_ts() -> int: return int(time.time()) def to_dt(ts: int | None) -> datetime | None: return datetime.fromtimestamp(ts, timezone.utc) if ts is not None else None def site_tz() -> ZoneInfo: return ZoneInfo(get_settings().site_timezone) def local_day(ts: int) -> str: return datetime.fromtimestamp(ts, site_tz()).date().isoformat() def today() -> date: return datetime.now(site_tz()).date() # ---------------------------------------------------------------- ingest def _ts_of(r: ReadingIn, received: int) -> tuple[int, bool]: """Reading time in unix seconds, and whether it had to be clamped because it lay in the future (bad clock / local time sent as UTC).""" if r.timestamp is None: return received, False t = r.timestamp if t.tzinfo is None: t = t.replace(tzinfo=timezone.utc) ts = int(t.timestamp()) if ts > received + get_settings().max_future_skew_seconds: return received, True return ts, False def _integrate(conn: sqlite3.Connection, inverter_id: str, ts: int, power: int | None) -> float | None: """Wh produced since the previous reading (trapezoid rule), or None when there's nothing to add (no power, first reading, gap too long).""" if power is None: return None prev = conn.execute( "SELECT ts, ac_power_total_w AS w FROM readings " "WHERE inverter_id = ? AND ts < ? ORDER BY ts DESC LIMIT 1", (inverter_id, ts), ).fetchone() if not prev or prev["w"] is None: return None dt = ts - prev["ts"] if dt > get_settings().energy_integration_max_gap_seconds: return None return (prev["w"] + power) / 2 * dt / 3600 def _integrated_for_day(conn: sqlite3.Connection, inverter_id: str, day: str) -> float: """Integrated Wh for one inverter and local day, from scratch.""" tz = site_tz() start = int(datetime.combine(date.fromisoformat(day), datetime.min.time(), tz).timestamp()) end = start + 2 * 86400 # covers DST days; filtered by local_day below max_gap = get_settings().energy_integration_max_gap_seconds rows = conn.execute( "SELECT ts, ac_power_total_w AS w FROM readings " "WHERE inverter_id = ? AND ts >= ? AND ts < ? ORDER BY ts", (inverter_id, start - max_gap, end), ).fetchall() total, prev = 0.0, None for r in rows: if ( prev and prev["w"] is not None and r["w"] is not None and r["ts"] - prev["ts"] <= max_gap and local_day(r["ts"]) == day ): total += (prev["w"] + r["w"]) / 2 * (r["ts"] - prev["ts"]) / 3600 prev = r return total def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, int, int]: """Store readings; returns (stored, duplicates, clamped). Re-sent readings (same inverter + timestamp) are ignored, so the poller can safely retry.""" stored = clamped = 0 received = now_ts() cols = ["inverter_id", "ts", "extra", *FIELD_KEYS] insert_sql = ( f"INSERT OR IGNORE INTO readings ({', '.join(cols)}) " f"VALUES ({', '.join('?' for _ in cols)})" ) for r in readings: ts, was_clamped = _ts_of(r, received) clamped += was_clamped values = r.model_dump(include=set(FIELD_KEYS)) extra = {**(r.model_extra or {}), **(r.extra or {})} conn.execute( "INSERT OR IGNORE INTO inverters (id, name, first_seen, last_seen) VALUES (?, ?, ?, ?)", (r.inverter_id, r.inverter_id, ts, ts), ) conn.execute( "UPDATE inverters SET last_seen = max(coalesce(last_seen, 0), ?) WHERE id = ?", (ts, r.inverter_id), ) cur = conn.execute( insert_sql, [r.inverter_id, ts, json.dumps(extra) if extra else None] + [values[k] for k in FIELD_KEYS], ) if cur.rowcount == 0: continue stored += 1 # A reading arriving after a later one (re-sent from the poller's # spool out of order) changes intervals already counted: recompute # that day instead of adding to it. out_of_order = conn.execute( "SELECT 1 FROM readings WHERE inverter_id = ? AND ts > ? LIMIT 1", (r.inverter_id, ts) ).fetchone() is not None integrated_wh = None if out_of_order else _integrate(conn, r.inverter_id, ts, values["ac_power_total_w"]) # max()/min() of two values where either may be NULL conn.execute( """ INSERT INTO daily_energy (inverter_id, day, daily_energy_wh, total_min_wh, total_max_wh, peak_power_w, integrated_wh) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (inverter_id, day) DO UPDATE SET daily_energy_wh = max(coalesce(daily_energy_wh, excluded.daily_energy_wh), coalesce(excluded.daily_energy_wh, daily_energy_wh)), total_min_wh = min(coalesce(total_min_wh, excluded.total_min_wh), coalesce(excluded.total_min_wh, total_min_wh)), total_max_wh = max(coalesce(total_max_wh, excluded.total_max_wh), coalesce(excluded.total_max_wh, total_max_wh)), peak_power_w = max(coalesce(peak_power_w, excluded.peak_power_w), coalesce(excluded.peak_power_w, peak_power_w)), integrated_wh = coalesce(integrated_wh, 0) + coalesce(excluded.integrated_wh, 0) """, ( r.inverter_id, local_day(ts), values["daily_energy_wh"], values["total_energy_wh"], values["total_energy_wh"], values["ac_power_total_w"], integrated_wh, ), ) if out_of_order: day = local_day(ts) conn.execute( "UPDATE daily_energy SET integrated_wh = ? WHERE inverter_id = ? AND day = ?", (_integrated_for_day(conn, r.inverter_id, day), r.inverter_id, day), ) return stored, len(readings) - stored, clamped def rebuild_integrated_energy(conn: sqlite3.Connection) -> None: """Recompute daily integrated energy from the stored readings.""" max_gap = get_settings().energy_integration_max_gap_seconds totals: dict[tuple[str, str], float] = {} prev: dict[str, tuple[int, int | None]] = {} for r in conn.execute( "SELECT inverter_id, ts, ac_power_total_w AS w FROM readings ORDER BY inverter_id, ts" ): p = prev.get(r["inverter_id"]) if p and p[1] is not None and r["w"] is not None and r["ts"] - p[0] <= max_gap: key = (r["inverter_id"], local_day(r["ts"])) totals[key] = totals.get(key, 0) + (p[1] + r["w"]) / 2 * (r["ts"] - p[0]) / 3600 prev[r["inverter_id"]] = (r["ts"], r["w"]) conn.execute("UPDATE daily_energy SET integrated_wh = NULL") for (inv, day), wh in totals.items(): conn.execute( "UPDATE daily_energy SET integrated_wh = ? WHERE inverter_id = ? AND day = ?", (wh, inv, day), ) def purge(conn: sqlite3.Connection, retention_days: int) -> int: cutoff = now_ts() - retention_days * 86400 return conn.execute("DELETE FROM readings WHERE ts < ?", (cutoff,)).rowcount # ---------------------------------------------------------------- inverters def inverter_dict(row: sqlite3.Row) -> dict: d = dict(row) d["name"] = d["name"] or d["id"] d["first_seen"] = to_dt(d["first_seen"]) d["last_seen"] = to_dt(d["last_seen"]) return d def list_inverters(conn: sqlite3.Connection) -> list[dict]: rows = conn.execute("SELECT * FROM inverters ORDER BY sort_order, id").fetchall() return [inverter_dict(r) for r in rows] def get_inverter(conn: sqlite3.Connection, inverter_id: str) -> dict | None: row = conn.execute("SELECT * FROM inverters WHERE id = ?", (inverter_id,)).fetchone() return inverter_dict(row) if row else None def reading_dict(row: sqlite3.Row) -> dict: d = dict(row) ts = d.pop("ts") d["timestamp"] = to_dt(ts) d["age_seconds"] = now_ts() - ts d["extra"] = json.loads(d["extra"]) if d.get("extra") else {} return derive(d) def latest(conn: sqlite3.Connection, inverter_id: str) -> dict | None: row = conn.execute( "SELECT * FROM readings WHERE inverter_id = ? ORDER BY ts DESC LIMIT 1", (inverter_id,) ).fetchone() return reading_dict(row) if row else None def latest_all(conn: sqlite3.Connection) -> dict[str, dict]: rows = conn.execute( """ SELECT r.* FROM readings r JOIN (SELECT inverter_id, max(ts) AS ts FROM readings GROUP BY inverter_id) m ON m.inverter_id = r.inverter_id AND m.ts = r.ts """ ).fetchall() return {r["inverter_id"]: reading_dict(r) for r in rows} def window_averages(conn: sqlite3.Connection, seconds: int) -> dict[str, dict]: rows = conn.execute( """ SELECT inverter_id, avg(ac_power_total_w) AS ac_power_w, avg(dc_voltage_mppt1_v * dc_current_mppt1_a) AS mppt1_w, avg(dc_voltage_mppt2_v * dc_current_mppt2_a) AS mppt2_w FROM readings WHERE ts >= ? GROUP BY inverter_id """, (now_ts() - seconds,), ).fetchall() return {r["inverter_id"]: dict(r) for r in rows} # ---------------------------------------------------------------- history def pick_bucket(start: int, end: int, requested: int | None) -> int: if requested: return max(60, requested) span = max(1, end - start) return next((b for b in BUCKETS if span / b <= MAX_POINTS), BUCKETS[-1]) def _agg(key: str) -> str: fn = "max" if FIELDS_BY_KEY[key].agg in ("max", "last") else "avg" return f"{fn}({key}) AS {key}" def history( conn: sqlite3.Connection, inverter_id: str, start: int, end: int, bucket: int, fields: list[str] | None, ) -> list[dict]: keys = [k for k in (fields or NUMERIC_KEYS) if k in NUMERIC_KEYS] # DC power is averaged per row (V*I), not as avg(V)*avg(I) sql = f""" SELECT (ts / :b) * :b AS t, {', '.join(_agg(k) for k in keys)}, avg(dc_voltage_mppt1_v * dc_current_mppt1_a) AS dc_power_mppt1_w, avg(dc_voltage_mppt2_v * dc_current_mppt2_a) AS dc_power_mppt2_w FROM readings WHERE inverter_id = :id AND ts >= :start AND ts <= :end GROUP BY t ORDER BY t """ rows = conn.execute(sql, {"b": bucket, "id": inverter_id, "start": start, "end": end}) out = [] for r in rows: d = {"t": r["t"]} for k in r.keys()[1:]: v = r[k] if v is not None and k in FIELDS_BY_KEY: v = round(v, FIELDS_BY_KEY[k].decimals + 1) elif v is not None: v = round(v) d[k] = v out.append(d) return out def fleet_power(conn: sqlite3.Connection, start: int, end: int, bucket: int) -> list[dict]: """AC power per inverter per bucket, pivoted: [{t, : W, ...}].""" rows = conn.execute( """ SELECT (ts / :b) * :b AS t, inverter_id, avg(ac_power_total_w) AS w FROM readings WHERE ts >= :start AND ts <= :end GROUP BY t, inverter_id ORDER BY t """, {"b": bucket, "start": start, "end": end}, ) points: dict[int, dict] = {} for r in rows: p = points.setdefault(r["t"], {"t": r["t"]}) p[r["inverter_id"]] = round(r["w"]) if r["w"] is not None else None return list(points.values()) # Best available energy for a day: the inverter's daily counter, else the # lifetime counter's growth, else AC power integrated over time (estimate). ENERGY_SQL = """ coalesce(daily_energy_wh, total_max_wh - total_min_wh, cast(round(integrated_wh) AS INTEGER)) AS wh, (daily_energy_wh IS NULL AND total_max_wh IS NULL AND integrated_wh IS NOT NULL) AS estimated """ def daily_energy( conn: sqlite3.Connection, first: date, last: date, inverter_id: str | None = None ) -> list[dict]: """[{day, total_wh, estimated, : Wh, ...}] for every day in range, oldest first. Days with no data have total_wh null.""" sql = f""" SELECT day, inverter_id, peak_power_w, {ENERGY_SQL} FROM daily_energy WHERE day >= ? AND day <= ? """ params: list = [first.isoformat(), last.isoformat()] if inverter_id: sql += " AND inverter_id = ?" params.append(inverter_id) by_day: dict[str, dict] = {} d = first while d <= last: by_day[d.isoformat()] = {"day": d.isoformat(), "total_wh": None, "estimated": False} d += timedelta(days=1) for r in conn.execute(sql, params): row = by_day[r["day"]] row[r["inverter_id"]] = r["wh"] if r["wh"] is not None: row["total_wh"] = (row["total_wh"] or 0) + r["wh"] row["estimated"] = row["estimated"] or bool(r["estimated"]) if inverter_id: row["peak_power_w"] = r["peak_power_w"] return list(by_day.values()) def today_energy(conn: sqlite3.Connection) -> dict[str, dict]: """{inverter_id: {"wh": int | None, "estimated": bool}} for today.""" rows = conn.execute( f"SELECT inverter_id, {ENERGY_SQL} FROM daily_energy WHERE day = ?", (today().isoformat(),), ) return {r["inverter_id"]: {"wh": r["wh"], "estimated": bool(r["estimated"])} for r in rows}