refactor(backend): single SQLite store — config.json eliminated
backend.db (renamed from sessions.db) now holds everything: the sessions
and samples tables plus a settings table with the app-state sections
(users, allowlist, relays, chargers, learn_mode, session_secret) as JSON
blobs. All mutations go through the API/panel and take effect immediately;
there is no config file and no hand-edit-then-restart ambiguity.
- legacy config.json auto-imports into the db on first start (renamed to
config.json.migrated as a backup)
- new admin endpoints: PUT/DELETE /api/relays/{name} (how tinytuya wizard
results are registered now) and PUT /api/chargers/{cp_id} (panel labels)
- BACKEND_DB env override so tests run on an isolated temp database
- smoke test: 45 checks, real db verified untouched
This commit is contained in:
+3
-1
@@ -1,5 +1,7 @@
|
||||
# Runtime state + secrets (Tuya local keys live in config.json)
|
||||
# Runtime state + secrets (users, Tuya local keys, session secret live in backend.db)
|
||||
backend.db
|
||||
config.json
|
||||
config.json.migrated
|
||||
events.jsonl
|
||||
seen_tags.json
|
||||
sessions.db
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
{
|
||||
"learn_mode": true,
|
||||
"session_secret": "<auto-generated on first run — signs login sessions>",
|
||||
"users": {
|
||||
"admin-user": {
|
||||
"password": "<pbkdf2 hash — create users with: python -m backend.users add <name>>",
|
||||
"scopes": ["admin"],
|
||||
"id_tag": "app-admin-user"
|
||||
},
|
||||
"gun1-only-user": {
|
||||
"password": "<pbkdf2 hash>",
|
||||
"scopes": ["charger:eu092025:1", "relay:garden-lights"],
|
||||
"id_tag": "app-gun1-only-user"
|
||||
},
|
||||
"relays-only-user": {
|
||||
"password": "<pbkdf2 hash>",
|
||||
"scopes": ["relay:*"],
|
||||
"id_tag": "app-relays-only-user"
|
||||
}
|
||||
},
|
||||
"authorized": {
|
||||
"1000000000000000": {
|
||||
"name": "Card linked to a user, works everywhere",
|
||||
"kind": "card",
|
||||
"user": "admin-user"
|
||||
},
|
||||
"1000000000000001": {
|
||||
"name": "Card restricted to gun 2 of one charger",
|
||||
"kind": "card",
|
||||
"user": "gun1-only-user",
|
||||
"guns": ["eu092025:2"]
|
||||
},
|
||||
"app-remote": { "name": "Web/app remote start token", "kind": "app" }
|
||||
},
|
||||
"chargers": {
|
||||
"eu092025": {
|
||||
"label": "Anfu 60kW",
|
||||
"guns": { "1": "Gun 1 · EU (CCS)", "2": "Gun 2 · GB/T" }
|
||||
}
|
||||
},
|
||||
"relays": {
|
||||
"example-relay": {
|
||||
"id": "<tuya device id from tinytuya wizard>",
|
||||
"key": "<tuya local key from tinytuya wizard>",
|
||||
"ip": "auto",
|
||||
"version": 3.3,
|
||||
"switch": 1,
|
||||
"label": "Garden lights"
|
||||
}
|
||||
}
|
||||
}
|
||||
+39
-27
@@ -1,49 +1,61 @@
|
||||
"""Backend configuration — one JSON file, config.json, next to this module.
|
||||
"""App state sections, backed by the settings table in backend.db (store.py).
|
||||
|
||||
Holds the charger allowlist (learn_mode + authorized idTags, same shape the
|
||||
discovery phase used), the user accounts with their permission scopes, and the
|
||||
Tuya relay registry. config.json is gitignored because it contains secrets
|
||||
(password hashes, the session-signing secret, Tuya local keys);
|
||||
config.example.json documents the shape.
|
||||
CONFIG is the in-memory runtime state; save() persists it. Every mutation goes
|
||||
through the API/panel (or the backend.users CLI), takes effect immediately,
|
||||
and is durable — there is no config file to hand-edit and no restart-to-apply
|
||||
semantics. A legacy config.json (pre-2026-07-11 layout) is imported into the
|
||||
database once on startup and renamed to config.json.migrated.
|
||||
|
||||
Sections:
|
||||
learn_mode accept-and-record unknown idTags vs enforce the allowlist
|
||||
users name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag"}
|
||||
authorized idTag -> {"name", "kind": "card|app|car",
|
||||
optional "user": owner, "guns": ["eu092025:2"]}
|
||||
relays name -> {"id", "key", "ip", "version", "switch", "label"}
|
||||
chargers cp_id -> {"label", "guns": {"1": "display name"}} (UI only)
|
||||
session_secret signs login sessions; auto-generated once
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
from . import store
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
CONFIG_PATH = HERE / "config.json"
|
||||
LEGACY_CONFIG = HERE / "config.json"
|
||||
|
||||
log = logging.getLogger("config")
|
||||
|
||||
DEFAULTS = {
|
||||
"learn_mode": True,
|
||||
"users": {}, # name -> {"password": pbkdf2 hash, "scopes": [...], "id_tag": ...}
|
||||
"authorized": {}, # idTag -> {"name", "kind": "card|app|car",
|
||||
# optional "user": owner, "guns": ["eu092025:2"]}
|
||||
"relays": {}, # name -> {"id", "key", "ip", "version", "switch", "label"}
|
||||
"chargers": {}, # cp_id -> {"label", "guns": {"1": "display name", ...}} (UI only)
|
||||
"users": {},
|
||||
"authorized": {},
|
||||
"relays": {},
|
||||
"chargers": {},
|
||||
}
|
||||
|
||||
|
||||
def load() -> dict:
|
||||
if CONFIG_PATH.exists():
|
||||
cfg = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
|
||||
else:
|
||||
cfg = {}
|
||||
def _load() -> dict:
|
||||
cfg = store.load_settings()
|
||||
if not cfg and LEGACY_CONFIG.exists():
|
||||
cfg = json.loads(LEGACY_CONFIG.read_text(encoding="utf-8"))
|
||||
LEGACY_CONFIG.rename(LEGACY_CONFIG.with_suffix(".json.migrated"))
|
||||
log.warning("imported legacy config.json into %s (file kept as "
|
||||
"config.json.migrated)", store.DB_PATH.name)
|
||||
for key, default in DEFAULTS.items():
|
||||
cfg.setdefault(key, default if not isinstance(default, dict) else dict(default))
|
||||
if not cfg.get("session_secret"):
|
||||
cfg["session_secret"] = secrets.token_hex(32)
|
||||
return cfg
|
||||
|
||||
|
||||
CONFIG = load()
|
||||
|
||||
if not CONFIG.get("session_secret"):
|
||||
CONFIG["session_secret"] = secrets.token_hex(32)
|
||||
CONFIG_PATH.write_text(
|
||||
json.dumps(CONFIG, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
||||
)
|
||||
CONFIG = _load()
|
||||
|
||||
|
||||
def save() -> None:
|
||||
CONFIG_PATH.write_text(
|
||||
json.dumps(CONFIG, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
||||
)
|
||||
store.save_settings(CONFIG)
|
||||
|
||||
|
||||
save() # persist migration / generated defaults immediately
|
||||
|
||||
@@ -313,6 +313,49 @@ async def users_delete(name: str, user: dict = Depends(current_user)):
|
||||
return {"removed": name}
|
||||
|
||||
|
||||
# ---- relay & charger registry (admin; how tinytuya wizard results get in) ----
|
||||
class RelayBody(BaseModel):
|
||||
id: str # tuya device id (from tinytuya wizard)
|
||||
key: str # tuya local key (from tinytuya wizard)
|
||||
ip: str = "auto" # pin the LAN IP once known (faster than discovery)
|
||||
version: float = 3.3
|
||||
switch: int = 1
|
||||
label: Optional[str] = None
|
||||
|
||||
|
||||
@router.put("/relays/{name}")
|
||||
async def relay_put(name: str, body: RelayBody, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
entry = body.model_dump()
|
||||
entry["label"] = entry["label"] or name
|
||||
CONFIG["relays"][name] = entry
|
||||
save()
|
||||
log.info("relays: %r set by %r", name, user["name"])
|
||||
return {"relays": relays.configured()}
|
||||
|
||||
|
||||
@router.delete("/relays/{name}")
|
||||
async def relay_delete(name: str, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
if CONFIG["relays"].pop(name, None) is None:
|
||||
raise HTTPException(404, f"no relay {name!r}")
|
||||
save()
|
||||
return {"relays": relays.configured()}
|
||||
|
||||
|
||||
class ChargerBody(BaseModel):
|
||||
label: Optional[str] = None
|
||||
guns: Optional[dict[str, str]] = None # {"1": "Gun 1 · EU (CCS)"}
|
||||
|
||||
|
||||
@router.put("/chargers/{cp_id}")
|
||||
async def charger_put(cp_id: str, body: ChargerBody, user: dict = Depends(current_user)):
|
||||
need(user, "admin")
|
||||
CONFIG["chargers"][cp_id] = body.model_dump(exclude_none=True)
|
||||
save()
|
||||
return {"chargers": CONFIG["chargers"]}
|
||||
|
||||
|
||||
# ---- relays (scope: relay:<name>) ----
|
||||
@router.get("/relays")
|
||||
async def relays_list(live: bool = False, user: dict = Depends(current_user)):
|
||||
|
||||
+30
-4
@@ -1,27 +1,37 @@
|
||||
"""Charging-session store — who charged, when, and how many kWh.
|
||||
"""The one persistent store: SQLite (stdlib) in backend.db next to this module.
|
||||
|
||||
SQLite (stdlib) in sessions.db next to this module. Two tables:
|
||||
sessions — one row per transaction: cp, connector, idTag, resolved "who",
|
||||
start/end timestamps (charger-reported), meter readings, Wh, reason
|
||||
samples — per-minute MeterValues while charging (energy/power/SoC) for
|
||||
later charts
|
||||
settings — the app state sections (users, allowlist, relays, chargers,
|
||||
learn_mode, session_secret) as JSON blobs, one row per section.
|
||||
Always whole-section reads/writes, so blobs beat normalized
|
||||
tables here. Managed through config.py — see there.
|
||||
|
||||
The events.jsonl journal (journal.py) stays the raw ground truth; this is the
|
||||
queryable view. Transaction ids come from MAX(tx)+1 here, so they survive
|
||||
backend restarts (the in-memory counter used to reset to 0).
|
||||
backend restarts.
|
||||
|
||||
sqlite3 connections are cheap at household scale — one per call, no pooling.
|
||||
BACKEND_DB env var overrides the path (used by tests to stay off the real db).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
DB_PATH = HERE / "sessions.db"
|
||||
DB_PATH = Path(os.environ.get("BACKEND_DB", HERE / "backend.db"))
|
||||
|
||||
_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
tx INTEGER PRIMARY KEY,
|
||||
cp TEXT NOT NULL,
|
||||
@@ -56,6 +66,22 @@ def _db():
|
||||
return closing(con)
|
||||
|
||||
|
||||
def load_settings() -> dict:
|
||||
with _db() as con, con:
|
||||
return {
|
||||
row["key"]: json.loads(row["value"])
|
||||
for row in con.execute("SELECT key, value FROM settings")
|
||||
}
|
||||
|
||||
|
||||
def save_settings(sections: dict) -> None:
|
||||
with _db() as con, con:
|
||||
con.executemany(
|
||||
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
|
||||
[(key, json.dumps(value, ensure_ascii=False)) for key, value in sections.items()],
|
||||
)
|
||||
|
||||
|
||||
def max_tx() -> int:
|
||||
with _db() as con, con:
|
||||
row = con.execute("SELECT MAX(tx) AS m FROM sessions").fetchone()
|
||||
|
||||
Reference in New Issue
Block a user