d7b17d9cb2
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.
80 lines
2.6 KiB
Python
80 lines
2.6 KiB
Python
"""Home energy backend — private CSMS for the Anfu charger + local control of
|
|
the Tuya/SmartLife WiFi relays. One uvicorn process, one port:
|
|
|
|
ws://<host>:9000/<ChargerID> OCPP 1.6J (the JC-6620 dials in here)
|
|
http://<host>:9000/api/* REST for the web panel / curl
|
|
http://<host>:9000/docs interactive API docs
|
|
|
|
Port 9000 is load-bearing: it's hardcoded in the charger's touchscreen URL and
|
|
changing it there requires a power-cycle (wiki: troubleshooting #4).
|
|
|
|
Run: venv\\Scripts\\python -m backend.main (from the repo root)
|
|
"""
|
|
|
|
import asyncio
|
|
import logging
|
|
from pathlib import Path
|
|
|
|
import uvicorn
|
|
from fastapi import FastAPI, WebSocket
|
|
from fastapi.responses import FileResponse
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
from . import csms, routes
|
|
from .config import CONFIG
|
|
|
|
STATIC = Path(__file__).resolve().parent / "static"
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s %(levelname)s %(name)s | %(message)s",
|
|
)
|
|
log = logging.getLogger("backend")
|
|
|
|
app = FastAPI(
|
|
title="Home Energy Backend",
|
|
description="Private OCPP CSMS + WiFi relay control. The charger dials "
|
|
"ws://<host>:9000/<id>; everything else lives under /api/*.",
|
|
)
|
|
app.include_router(routes.router)
|
|
app.mount("/static", StaticFiles(directory=STATIC), name="static")
|
|
|
|
|
|
@app.get("/")
|
|
async def index_page():
|
|
return FileResponse(STATIC / "index.html")
|
|
|
|
|
|
# the service worker must be served from / so its scope covers the whole app
|
|
@app.get("/sw.js")
|
|
async def service_worker():
|
|
return FileResponse(STATIC / "sw.js", media_type="application/javascript")
|
|
|
|
|
|
# Catch-all WS route so the charger may dial any path (it uses /<ChargerID>).
|
|
# WebSocket and HTTP routes match independently, so this never shadows /api/*.
|
|
@app.websocket("/{cp_path:path}")
|
|
async def ocpp_websocket(ws: WebSocket, cp_path: str):
|
|
await csms.ocpp_socket(ws, cp_path)
|
|
|
|
|
|
async def main():
|
|
mode = "LEARN (accepting & recording new ids)" if CONFIG["learn_mode"] else "ENFORCING allowlist"
|
|
log.info(
|
|
"CSMS ws://0.0.0.0:9000/<id> | API http://0.0.0.0:9000/docs | mode: %s | "
|
|
"%d authorized id(s) | %d user(s) | %d relay(s) configured",
|
|
mode, len(CONFIG["authorized"]), len(CONFIG["users"]), len(CONFIG["relays"]),
|
|
)
|
|
if not CONFIG["users"]:
|
|
log.warning(
|
|
"NO USERS CONFIGURED — the API is OPEN (anonymous admin). "
|
|
"Create one: venv\\Scripts\\python -m backend.users add <name> --scopes admin"
|
|
)
|
|
await uvicorn.Server(
|
|
uvicorn.Config(app, host="0.0.0.0", port=9000, log_config=None)
|
|
).serve()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|