"""Sends each poll cycle's readings to the Solar Monitor backend. Standard library only — nothing to pip install on the site laptop. from backend_client import BackendClient client = BackendClient(BACKEND_URL, API_KEY) ... client.send(readings) # once per poll cycle, list of dicts (may be empty) - Every reading gets a UTC `timestamp` at the moment `send()` is called, unless it already has one. - If the backend can't be reached, readings are kept in a local spool file and re-sent (oldest first) on later cycles, so an internet outage leaves no gap in the history. The backend ignores duplicates, so re-sending is safe. - Call `send([])` when no inverter answered: it still tells the backend the datalogger is alive, which is how the dashboard tells a dead inverter apart from a dead internet link. """ import json import logging import os import urllib.error import urllib.request from datetime import datetime, timezone log = logging.getLogger("backend_client") BATCH_LIMIT = 200 # backend accepts up to 200 readings per POST class BackendClient: def __init__( self, backend_url: str, api_key: str, spool_path: str = "unsent_readings.jsonl", max_spooled: int = 50_000, # ~1 week for 5 inverters at 1/min timeout: float = 15, ): self.url = backend_url.rstrip("/") + "/api/readings" self.api_key = api_key self.spool_path = spool_path self.max_spooled = max_spooled self.timeout = timeout def send(self, readings: list[dict]) -> bool: """POST this cycle's readings (plus anything spooled). Never raises. Returns True when everything was delivered.""" now = datetime.now(timezone.utc).isoformat(timespec="seconds") readings = [{"timestamp": now, **r} for r in readings] pending = self._load_spool() if pending: log.info("Re-sending %d spooled readings", len(pending)) queue = pending + readings if not queue: # Heartbeat: nothing to send, but the backend should know we're alive return self._post([]) is not None sent = 0 try: while sent < len(queue): chunk = queue[sent : sent + BATCH_LIMIT] if self._post(chunk) is None: break sent += len(chunk) finally: self._save_spool(queue[sent:]) return sent == len(queue) def _post(self, chunk: list[dict]) -> dict | None: req = urllib.request.Request( self.url, data=json.dumps(chunk).encode(), method="POST", headers={"Content-Type": "application/json", "X-API-Key": self.api_key}, ) try: with urllib.request.urlopen(req, timeout=self.timeout) as res: return json.loads(res.read() or b"{}") except urllib.error.HTTPError as e: body = e.read().decode(errors="replace")[:300] if e.code in (400, 422): # The backend rejected the data itself — retrying won't help. log.error("Backend rejected readings (%s): %s — dropping them", e.code, body) return {} log.warning("Backend error %s: %s", e.code, body) except (urllib.error.URLError, TimeoutError, OSError) as e: log.warning("Backend unreachable: %s", e) return None def _load_spool(self) -> list[dict]: if not os.path.exists(self.spool_path): return [] out = [] with open(self.spool_path, encoding="utf-8") as f: for line in f: line = line.strip() if line: try: out.append(json.loads(line)) except json.JSONDecodeError: pass return out def _save_spool(self, readings: list[dict]) -> None: if len(readings) > self.max_spooled: log.warning("Spool full — dropping %d oldest readings", len(readings) - self.max_spooled) readings = readings[-self.max_spooled :] if not readings: if os.path.exists(self.spool_path): os.remove(self.spool_path) return tmp = self.spool_path + ".tmp" with open(tmp, "w", encoding="utf-8") as f: for r in readings: f.write(json.dumps(r) + "\n") os.replace(tmp, self.spool_path)