75869364b0
Frontend rewrite (frontend/, replacing backend/static/): - Vite + TypeScript + React 19, React Router 7, zustand, TanStack Query 5 - dev: vite proxy /api -> :9000; prod: npm run build -> dist/, served by the backend with SPA fallback - pages: Control (gun bays w/ scope+readiness-gated start/stop, relays), History (who/via/gun/when/duration/kWh audit), Cards (pending review, enrolled, rejected), Users (permission checkbox matrix) - self-contained: fonts bundled, no CDN; light/dark; reduced-motion safe Backend: - learn mode removed: unknown cards are always refused and queued in pending_cards; admin approves (name + owner + gun restrictions in one step) or rejects (denied_cards, silent, un-rejectable); pending count rides /api/status as the notification signal - sessions record the auth method (card tap vs in-app button) for audit - GET /api/permissions: grantable-permission catalog driving the UI matrix - SPA static serving with path-traversal guard; 503 hint when not built Smoke test: 54 checks incl. approve/reject round-trips over a fake charge point and method audit assertions.
86 lines
3.1 KiB
Python
86 lines
3.1 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, JSONResponse
|
|
|
|
from . import csms, routes
|
|
from .config import CONFIG
|
|
|
|
# the built React app (frontend/: `npm run build` -> dist/)
|
|
DIST = Path(__file__).resolve().parent.parent / "frontend" / "dist"
|
|
|
|
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)
|
|
|
|
|
|
# SPA serving: exact files from frontend/dist, anything else falls back to
|
|
# index.html so React Router owns the URL space. Registered after the API
|
|
# router, so /api/* and /docs keep winning.
|
|
@app.get("/{full_path:path}", include_in_schema=False)
|
|
async def spa(full_path: str):
|
|
if not DIST.exists():
|
|
return JSONResponse(
|
|
{"detail": "frontend not built — run `npm run build` in frontend/ "
|
|
"(or use the Vite dev server, which proxies /api here)"},
|
|
status_code=503,
|
|
)
|
|
candidate = (DIST / full_path).resolve() if full_path else None
|
|
if candidate and candidate.is_file() and candidate.is_relative_to(DIST.resolve()):
|
|
return FileResponse(candidate)
|
|
return FileResponse(DIST / "index.html")
|
|
|
|
|
|
# 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():
|
|
log.info(
|
|
"CSMS ws://0.0.0.0:9000/<id> | API http://0.0.0.0:9000/docs | "
|
|
"%d authorized id(s) | %d pending card(s) | %d user(s) | %d relay(s) | panel %s",
|
|
len(CONFIG["authorized"]), len(CONFIG["pending_cards"]),
|
|
len(CONFIG["users"]), len(CONFIG["relays"]),
|
|
"ready" if DIST.exists() else "NOT BUILT (frontend/: npm run build)",
|
|
)
|
|
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())
|