Files
julian d7b17d9cb2 feat(backend): production backend — CSMS, multi-user auth, relays, session store, web panel
One FastAPI process on port 9000 (the charger's hardcoded URL), replacing
discovering/station.py for production:

- csms.py: OCPP 1.6J handlers ported from the proven discovery code; the
  decide() gate now supports per-gun RFID restriction ("connectors": [2])
  enforced at StartTransaction
- users.py: username/password auth (PBKDF2), stateless HMAC sessions
  (cookie + bearer, 30 days), fnmatch permission scopes
  (charger:<cp>:<gun>, relay:<name>, admin) and a user CLI
- relays.py: local tinytuya control of the SmartLife/Tuya WiFi relays
  (no cloud; needs one-time id/local-key extraction via tinytuya wizard)
- store.py: SQLite consumption tracking — who charged, when, how many kWh,
  per-minute energy/power/SoC samples; tx ids survive restarts
- routes.py: /api/* with per-scope checks, allowlist/user CRUD, runtime
  learn-mode flip, session history with visibility rules
- static/: self-contained vanilla-JS PWA — login, per-gun start/stop gated
  by scope + gun readiness, relay toggles, history, admin tab

config.json (password hashes, session secret, Tuya keys) and sessions.db
are gitignored; config.example.json documents the shape. Covered by a
37-check smoke test incl. a fake charge point over the real WS route.
2026-07-11 18:58:09 +02:00

104 lines
3.3 KiB
Python

"""Local control of the Tuya/SmartLife WiFi relays — no Tuya cloud in the loop.
The relays pair via the SmartLife app (BLE-assisted onboarding) but once on
WiFi they speak Tuya's local protocol on TCP 6668, which tinytuya drives
directly. Each relay needs its device id + LOCAL KEY in config.json under
"relays" — extracted once with `tinytuya wizard` (see the wiki: wifi-relays).
tinytuya is synchronous/blocking, so every call runs in a worker thread via
asyncio.to_thread to keep the OCPP socket responsive.
"""
import asyncio
import logging
try:
import tinytuya
except ImportError: # backend still runs (charger-only) without it
tinytuya = None
from .config import CONFIG
log = logging.getLogger("relays")
class RelayError(RuntimeError):
pass
def configured() -> dict:
"""The relay registry without secrets — safe to return over the API."""
return {
name: {"label": cfg.get("label", name), "ip": cfg.get("ip", "auto")}
for name, cfg in CONFIG["relays"].items()
}
def _device(name: str):
if tinytuya is None:
raise RelayError("tinytuya is not installed (pip install tinytuya)")
cfg = CONFIG["relays"].get(name)
if cfg is None:
raise RelayError(f"unknown relay {name!r}; configured: {list(CONFIG['relays'])}")
ip = cfg.get("ip", "auto")
# "Auto" makes tinytuya find the device via its UDP broadcast (slower);
# pin the IP in config.json (with a DHCP reservation) once known.
dev = tinytuya.OutletDevice(
cfg["id"], ip if ip and ip != "auto" else "Auto", cfg["key"]
)
dev.set_version(float(cfg.get("version", 3.3)))
dev.set_socketTimeout(5)
return dev, str(cfg.get("switch", 1))
def _check(name: str, result) -> dict:
if not isinstance(result, dict) or "dps" not in result:
raise RelayError(f"relay {name!r} did not answer: {result!r}")
return result["dps"]
def _status_sync(name: str) -> dict:
dev, sw = _device(name)
dps = _check(name, dev.status())
return {"relay": name, "on": bool(dps.get(sw)), "dps": dps}
def _switch_sync(name: str, on: bool) -> dict:
dev, sw = _device(name)
result = dev.set_status(on, int(sw))
# some firmwares reply with the new dps, some with an empty ack — verify
if not (isinstance(result, dict) and "dps" in result):
result = dev.status()
dps = _check(name, result)
actual = bool(dps.get(sw, on))
if actual != on:
raise RelayError(f"relay {name!r} did not switch (wanted {on}, reads {actual})")
return {"relay": name, "on": actual}
async def status(name: str) -> dict:
return await asyncio.to_thread(_status_sync, name)
async def switch(name: str, on: bool) -> dict:
return await asyncio.to_thread(_switch_sync, name, on)
async def toggle(name: str) -> dict:
current = await status(name)
return await switch(name, not current["on"])
async def status_all() -> dict:
"""Poll every configured relay concurrently; errors become per-relay strings."""
names = list(CONFIG["relays"])
results = await asyncio.gather(*(status(n) for n in names), return_exceptions=True)
out = {}
for name, res in zip(names, results):
if isinstance(res, BaseException):
out[name] = {"relay": name, "error": str(res)}
else:
out[name] = res
out[name]["label"] = CONFIG["relays"][name].get("label", name)
return out