Asking for the key every time a phone changes a chart option was friction the owner doesn't want. These settings only change how data is displayed (averaging, scale, chart range, language default), so PUT /api/settings is now open. Inverter edits (name, kWp, ...) and ingest still need the key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
246 lines
11 KiB
Python
246 lines
11 KiB
Python
import time
|
|
from datetime import datetime, timezone
|
|
|
|
|
|
def reading(inv, ts, power, **kw):
|
|
return {
|
|
"inverter_id": inv,
|
|
"timestamp": datetime.fromtimestamp(ts, timezone.utc).isoformat(),
|
|
"ac_power_total_w": power,
|
|
"ac_voltage_l1_v": 230.5,
|
|
"dc_voltage_mppt1_v": 600.0,
|
|
"dc_current_mppt1_a": power / 1200,
|
|
"dc_voltage_mppt2_v": 600.0,
|
|
"dc_current_mppt2_a": power / 1200,
|
|
"daily_energy_wh": 1000 + power,
|
|
"total_energy_wh": 5_000_000,
|
|
**kw,
|
|
}
|
|
|
|
|
|
def test_rejects_missing_key(client):
|
|
r = client.post("/api/readings", json=[], headers={"X-API-Key": "nope"})
|
|
assert r.status_code == 401
|
|
|
|
|
|
def test_ingest_is_idempotent_and_keeps_unknown_fields(client):
|
|
now = int(time.time())
|
|
batch = [reading("inv1", now, 10000, p_new_param=42)]
|
|
assert client.post("/api/readings", json=batch).json() == {
|
|
"received": 1, "stored": 1, "duplicates": 0, "clamped_future": 0
|
|
}
|
|
assert client.post("/api/readings", json=batch).json()["duplicates"] == 1
|
|
|
|
latest = client.get("/api/inverters/inv1/latest").json()
|
|
assert latest["ac_power_total_w"] == 10000
|
|
assert latest["extra"] == {"p_new_param": 42}
|
|
assert latest["dc_power_total_w"] == 10000
|
|
|
|
|
|
def test_summary_flags_weak_and_silent_inverters(client):
|
|
now = int(time.time())
|
|
batch = []
|
|
for t in (now - 120, now - 60, now):
|
|
batch += [reading("inv1", t, 15000), reading("inv2", t, 14500), reading("inv3", t, 6000)]
|
|
# MPPT2 dead on inv4
|
|
batch.append(reading("inv4", t, 7500, dc_current_mppt1_a=12.5, dc_current_mppt2_a=0))
|
|
batch.append(reading("inv5", now - 3600, 15000))
|
|
batch.append(reading("inv6", now, 15000, error_code=301, status_text="Isolation fault"))
|
|
client.post("/api/readings", json=batch)
|
|
|
|
s = client.get("/api/summary").json()
|
|
by_id = {x["inverter"]["id"]: x["health"] for x in s["inverters"]}
|
|
assert s["datalogger"]["online"] is True
|
|
assert by_id["inv1"]["state"] == "ok"
|
|
assert by_id["inv3"]["state"] == "warning"
|
|
assert by_id["inv3"]["issues"][0]["code"] == "underperforming"
|
|
assert "mppt_imbalance" in [i["code"] for i in by_id["inv4"]["issues"]]
|
|
assert by_id["inv5"]["state"] == "offline" and not by_id["inv5"]["online"]
|
|
assert by_id["inv6"]["state"] == "fault"
|
|
assert s["totals"]["online_count"] == 5
|
|
assert s["totals"]["ac_power_w"] == 15000 + 14500 + 6000 + 7500 + 15000
|
|
|
|
|
|
def test_per_kwp_comparison_uses_capacity(client):
|
|
now = int(time.time())
|
|
client.post("/api/readings", json=[reading("big", now, 16000), reading("small", now, 8000)])
|
|
client.patch("/api/inverters/big", json={"capacity_kwp": 20, "name": "Roof A"})
|
|
client.patch("/api/inverters/small", json={"capacity_kwp": 10})
|
|
s = client.get("/api/summary").json()
|
|
assert s["fleet_median_w_per_kwp"] == 800
|
|
assert all(x["health"]["state"] == "ok" for x in s["inverters"])
|
|
assert s["inverters"][0]["inverter"]["name"] == "Roof A"
|
|
|
|
|
|
def test_history_power_and_daily(client):
|
|
now = int(time.time())
|
|
batch = [reading("inv1", now - i * 60, 1000 + i) for i in range(30)]
|
|
client.post("/api/readings", json=batch)
|
|
|
|
h = client.get("/api/inverters/inv1/history", params={"bucket": 600}).json()
|
|
assert h["bucket"] == 600 and 3 <= len(h["points"]) <= 4
|
|
assert "dc_power_mppt1_w" in h["points"][0]
|
|
|
|
p = client.get("/api/power").json()
|
|
assert p["inverters"] == ["inv1"] and p["points"][-1]["inv1"] > 0
|
|
|
|
d = client.get("/api/energy/daily", params={"days": 7}).json()
|
|
assert len(d["days"]) == 7
|
|
assert d["days"][-1]["total_wh"] >= 1000
|
|
|
|
d1 = client.get("/api/inverters/inv1/daily", params={"days": 3}).json()
|
|
assert d1["days"][-1]["peak_power_w"] == 1029
|
|
|
|
|
|
def test_empty_batch_marks_datalogger_alive(client):
|
|
s = client.get("/api/summary").json()
|
|
assert s["datalogger"]["online"] is False
|
|
client.post("/api/readings", json=[])
|
|
assert client.get("/api/summary").json()["datalogger"]["online"] is True
|
|
|
|
|
|
def test_fields_meta(client):
|
|
keys = [f["key"] for f in client.get("/api/meta/fields").json()]
|
|
assert "ac_power_total_w" in keys and "efficiency_pct" in keys
|
|
|
|
|
|
def onsite_payload(inv, ts, power=6882, status=8):
|
|
"""Exactly what the real on-site poller sends (2026-10-21)."""
|
|
return {
|
|
"timestamp": datetime.fromtimestamp(ts, timezone.utc).isoformat(),
|
|
"inverter_id": inv,
|
|
"ac_voltage_l1_v": 232.6, "ac_voltage_l2_v": 233.35, "ac_voltage_l3_v": 232.62,
|
|
"ac_current_l1_a": 11.75, "ac_current_l2_a": 9.16, "ac_current_l3_a": 8.95,
|
|
"ac_power_total_w": power, "grid_frequency_hz": 50.0, "temperature_c": 36,
|
|
"status_code": status, "status_text": "feeding" if status in (7, 8) else "standby/not feeding",
|
|
"p06d_raw_latched": 21450, "p052_static_v": 312.5, "p05a_static_a": 45.0,
|
|
"p063_ind0_raw": 1872,
|
|
}
|
|
|
|
|
|
def test_onsite_payload_accepted_and_ok(client):
|
|
now = int(time.time())
|
|
batch = [onsite_payload("INV1", now, 6900, status=7), onsite_payload("INV2", now), onsite_payload("INV4", now, 6800)]
|
|
r = client.post("/api/readings", json=batch)
|
|
assert r.status_code == 200
|
|
assert r.json() == {"received": 3, "stored": 3, "duplicates": 0, "clamped_future": 0}
|
|
|
|
s = client.get("/api/summary").json()
|
|
for st in s["inverters"]:
|
|
assert st["health"]["state"] == "ok", st
|
|
assert st["health"]["feeding"] is True
|
|
latest = s["inverters"][1]["latest"]
|
|
assert latest["extra"]["p06d_raw_latched"] == 21450
|
|
assert latest["dc_power_total_w"] is None and latest["efficiency_pct"] is None
|
|
# No energy counters sent: lifetime unknown, today not yet integrated
|
|
assert s["totals"]["total_energy_wh"] is None
|
|
assert s["totals"]["feeding_count"] == 3
|
|
|
|
|
|
def test_not_feeding_is_standby_and_flagged_when_peers_produce(client):
|
|
now = int(time.time())
|
|
client.post("/api/readings", json=[
|
|
onsite_payload("INV1", now, 6900), onsite_payload("INV2", now, 7000),
|
|
onsite_payload("INV4", now, 0, status=3),
|
|
])
|
|
by_id = {x["inverter"]["id"]: x["health"] for x in client.get("/api/summary").json()["inverters"]}
|
|
assert by_id["INV4"]["feeding"] is False
|
|
assert by_id["INV4"]["state"] == "warning" # 0 W while the others make ~7 kW
|
|
|
|
|
|
def test_all_idle_is_plain_standby(client):
|
|
# Everyone awake but not feeding (e.g. dusk): standby, no alarm
|
|
now = int(time.time())
|
|
client.post("/api/readings", json=[onsite_payload(i, now, 0, status=3) for i in ("INV1", "INV2", "INV4")])
|
|
states = {x["health"]["state"] for x in client.get("/api/summary").json()["inverters"]}
|
|
assert states == {"standby"}
|
|
|
|
|
|
def test_heartbeat(client):
|
|
r = client.post("/api/readings", json=[])
|
|
assert r.status_code == 200 and r.json()["received"] == 0
|
|
|
|
|
|
def test_future_timestamp_is_clamped(client):
|
|
now = int(time.time())
|
|
r = client.post("/api/readings", json=[onsite_payload("INV2", now + 3 * 3600)]).json()
|
|
assert r["clamped_future"] == 1
|
|
latest = client.get("/api/inverters/INV2/latest").json()
|
|
assert abs(latest["age_seconds"]) < 5
|
|
|
|
|
|
def test_energy_integrated_from_power_when_no_counters(client):
|
|
now = int(time.time())
|
|
# 6 kW for 30 minutes at 60 s steps -> 3 kWh
|
|
client.post("/api/readings", json=[onsite_payload("INV1", now - 1800 + i * 60, 6000) for i in range(31)])
|
|
s = client.get("/api/summary").json()
|
|
e = s["inverters"][0]["energy_today"]
|
|
if e["wh"] is not None: # skip when the window straddles local midnight
|
|
assert e["estimated"] is True
|
|
assert 2900 <= e["wh"] <= 3000
|
|
assert s["totals"]["daily_energy_estimated"] is True
|
|
|
|
|
|
def test_energy_survives_out_of_order_readings(client):
|
|
now = int(time.time())
|
|
# Latest reading arrives first, then the earlier ones (spool re-send)
|
|
client.post("/api/readings", json=[onsite_payload("INV1", now, 6000)])
|
|
client.post("/api/readings", json=[onsite_payload("INV1", now - 1800 + i * 60, 6000) for i in range(30)])
|
|
e = client.get("/api/summary").json()["inverters"][0]["energy_today"]
|
|
if e["wh"] is not None:
|
|
assert 2900 <= e["wh"] <= 3000
|
|
|
|
|
|
def test_view_settings_shared_defaults_and_auth(client):
|
|
s = client.get("/api/settings").json()
|
|
assert s["comparison_readings"] == 1 and s["power_range"] == "24h"
|
|
|
|
body = {**s, "comparison_readings": 3, "comparison_scale": "custom", "comparison_custom_kw": 25,
|
|
"power_range": "run", "power_smoothing": "light", "future_option": True}
|
|
# No API key needed: display options only
|
|
saved = client.put("/api/settings", json=body, headers={"X-API-Key": ""}).json()
|
|
assert saved["comparison_custom_kw"] == 25 and "future_option" not in saved
|
|
assert client.get("/api/settings").json()["power_range"] == "run"
|
|
|
|
assert client.put("/api/settings", json={"comparison_readings": 4}).status_code == 422
|
|
|
|
|
|
def test_recent_power_and_slow_unit_stays_online(client):
|
|
now = int(time.time())
|
|
batch = [onsite_payload("INV1", now - i * 60, 6000 + i) for i in range(7)]
|
|
# Cloud-polled unit: every 5 min, last one 8 min ago — beyond the 5 min
|
|
# default window but only ~1.5 of its own cycles
|
|
batch += [onsite_payload("INV5", now - 480 - i * 300, 5000) for i in range(6)]
|
|
client.post("/api/readings", json=batch)
|
|
|
|
by_id = {x["inverter"]["id"]: x for x in client.get("/api/summary").json()["inverters"]}
|
|
assert [p["ac_power_total_w"] for p in by_id["INV1"]["recent_power"]] == [6000, 6001, 6002, 6003, 6004]
|
|
assert by_id["INV1"]["health"]["online_window_seconds"] == 300
|
|
assert by_id["INV5"]["health"]["online"] is True
|
|
assert by_id["INV5"]["health"]["online_window_seconds"] == 750
|
|
assert len(by_id["INV5"]["recent_power"]) == 5
|
|
|
|
|
|
def test_issue_params_for_translation(client):
|
|
now = int(time.time())
|
|
client.post("/api/readings", json=[
|
|
onsite_payload("INV1", now, 7000), onsite_payload("INV2", now, 7000), onsite_payload("INV4", now, 2000),
|
|
])
|
|
inv4 = client.get("/api/summary").json()["inverters"][2]["health"]
|
|
assert inv4["issues"][0]["params"]["relative"] < 0.75
|
|
|
|
|
|
def test_power_last_production_run(client):
|
|
now = int(time.time())
|
|
# Yesterday's run, a night of silence, then this morning's run; INV5
|
|
# reports 0 W all night and must not glue the runs together
|
|
batch = [onsite_payload("INV1", now - 20 * 3600 + i * 600, 5000) for i in range(6)]
|
|
batch += [onsite_payload("INV5", now - 18 * 3600 + i * 1800, 0, status=1) for i in range(30)]
|
|
batch += [onsite_payload("INV1", now - 3 * 3600 + i * 600, 5000) for i in range(18)]
|
|
client.post("/api/readings", json=batch)
|
|
|
|
p = client.get("/api/power", params={"last_run": True}).json()
|
|
start = datetime.fromisoformat(p["from"]).timestamp()
|
|
assert abs(start - (now - 3 * 3600 - 900)) < 5
|
|
assert abs(datetime.fromisoformat(p["to"]).timestamp() - now) < 5
|