"""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) -> int: if r.timestamp is None: return now_ts() t = r.timestamp if t.tzinfo is None: t = t.replace(tzinfo=timezone.utc) return int(t.timestamp()) def ingest(conn: sqlite3.Connection, readings: list[ReadingIn]) -> tuple[int, int]: """Store readings; returns (stored, duplicates). Re-sent readings (same inverter + timestamp) are ignored, so the poller can safely retry.""" stored = 0 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 = _ts_of(r) 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 # 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) 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)) """, ( r.inverter_id, local_day(ts), values["daily_energy_wh"], values["total_energy_wh"], values["total_energy_wh"], values["ac_power_total_w"], ), ) return stored, len(readings) - stored 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()) def daily_energy( conn: sqlite3.Connection, first: date, last: date, inverter_id: str | None = None ) -> list[dict]: """[{day, total_wh, : Wh, ...}] for every day in range, oldest first. Uses the inverter's own daily counter, falling back to the lifetime counter's growth over the day when the daily counter wasn't reported.""" sql = """ SELECT day, inverter_id, peak_power_w, coalesce(daily_energy_wh, total_max_wh - total_min_wh) AS wh 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": 0} d += timedelta(days=1) for r in conn.execute(sql, params): row = by_day[r["day"]] row[r["inverter_id"]] = r["wh"] row["total_wh"] += r["wh"] or 0 if inverter_id: row["peak_power_w"] = r["peak_power_w"] return list(by_day.values()) def today_energy(conn: sqlite3.Connection) -> dict[str, int]: rows = conn.execute( "SELECT inverter_id, coalesce(daily_energy_wh, total_max_wh - total_min_wh) AS wh " "FROM daily_energy WHERE day = ?", (today().isoformat(),), ) return {r["inverter_id"]: r["wh"] or 0 for r in rows}