ESP-IDF CI / Host Tests (Unity) (push) Successful in 1m8s
CI / firmware-native (push) Successful in 2m57s
Rust Protection Tests / Cargo test (host) (push) Failing after 3m21s
ESP-IDF CI / ESP-IDF Build (v5.4) (push) Failing after 6m55s
ESP-IDF CI / Memory Budget Gate (push) Has been skipped
qa-cicd-environments / qa-kxkm-s3-build (push) Successful in 8m53s
qa-cicd-environments / qa-sim-host (push) Successful in 2m2s
qa-cicd-environments / qa-kxkm-s3-memory-budget (push) Successful in 11m17s
Context: the project archive (KXKM_Batterie_Parallelator-main) had no git history locally; a fresh repository is needed to host it on git.saillant.cc (electron/KXKM_Batterie_Parallelator). Approach: initialize a new repo on branch main, stage the archive content, and harden .gitignore before the first commit. Changes: - Import the full project tree: firmware/, firmware-idf/, firmware-rs/, iosApp/, kxkm-bmu-app/, kxkm-api/, hardware/, docs/, specs/, scripts/, models/, tests/ - Keep project dotfiles tracked despite the trailing '.*' ignore rule: .github/, .claude/, .superpowers/, .gitattributes, .markdownlint.json - Extend .gitignore: firmware/src/credentials.h (local secrets, template kept), kxkm-bmu-app/**/build/ (66 MB compiled iOS framework), .remember/ (session data) Impact: the project can now be maintained on the self-hosted Gitea forge with a clean, secret-free initial history.
194 lines
5.7 KiB
Python
194 lines
5.7 KiB
Python
"""KXKM BMU API — FastAPI service on kxkm-ai server.
|
|
|
|
Provides cloud REST access to battery state (InfluxDB), history,
|
|
and audit trail (SQLite) for the BMU smartphone app.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import Depends, FastAPI, Query
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
from .auth import require_api_key
|
|
from .config import settings
|
|
from .database import close_db, init_db, insert_audit_events, query_audit_events
|
|
from .influx import (
|
|
close_influx,
|
|
get_current_batteries,
|
|
get_devices,
|
|
get_history,
|
|
get_latest_climate,
|
|
get_latest_solar,
|
|
get_series,
|
|
init_influx,
|
|
)
|
|
from .models import (
|
|
AuditResponse,
|
|
BatteriesResponse,
|
|
ClimateState,
|
|
HistoryResponse,
|
|
SolarState,
|
|
SyncRequest,
|
|
SyncResponse,
|
|
)
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""Startup / shutdown: init InfluxDB + SQLite."""
|
|
init_influx()
|
|
await init_db()
|
|
yield
|
|
close_influx()
|
|
await close_db()
|
|
|
|
|
|
app = FastAPI(
|
|
title="KXKM BMU API",
|
|
version="1.0.0",
|
|
description="Battery Management Unit cloud API for smartphone app",
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
_origins = [o.strip() for o in settings.cors_origins.split(",") if o.strip()]
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=_origins,
|
|
allow_credentials=True,
|
|
allow_methods=["GET", "POST"],
|
|
allow_headers=["Authorization", "Content-Type"],
|
|
)
|
|
|
|
|
|
# ─── Routes ───────────────────────────────────────────────────────────
|
|
|
|
|
|
@app.post("/api/bmu/sync", response_model=SyncResponse)
|
|
async def sync(
|
|
body: SyncRequest,
|
|
_: str = Depends(require_api_key),
|
|
):
|
|
"""Receive battery history + audit events from the app."""
|
|
# Battery history points are forwarded to InfluxDB by the MQTT pipeline;
|
|
# the app sends them here as a backup when direct MQTT is unavailable.
|
|
# For now we accept and count them (write-to-influx can be added later).
|
|
accepted_history = len(body.battery_history)
|
|
|
|
accepted_audit = await insert_audit_events(body.audit_events)
|
|
|
|
return SyncResponse(
|
|
accepted_history=accepted_history,
|
|
accepted_audit=accepted_audit,
|
|
)
|
|
|
|
|
|
@app.get("/api/bmu/devices")
|
|
async def devices(_: str = Depends(require_api_key)):
|
|
"""Liste des BMU connus (valeurs du tag `bmu`)."""
|
|
return {"devices": get_devices()}
|
|
|
|
|
|
@app.get("/api/bmu/batteries", response_model=BatteriesResponse)
|
|
async def batteries(
|
|
_: str = Depends(require_api_key),
|
|
device: str | None = Query(default=None),
|
|
):
|
|
"""Get current battery state (latest points from InfluxDB)."""
|
|
bats = get_current_batteries(device)
|
|
return BatteriesResponse(batteries=bats)
|
|
|
|
|
|
@app.get("/api/bmu/history", response_model=HistoryResponse)
|
|
async def history(
|
|
_: str = Depends(require_api_key),
|
|
from_time: str = Query(alias="from", description="ISO 8601 or relative (-1h, -24h)"),
|
|
to_time: str = Query(alias="to", default="now()", description="ISO 8601 or now()"),
|
|
battery: int | None = Query(default=None, ge=0, le=15),
|
|
device: str | None = Query(default=None),
|
|
):
|
|
"""Get time-series battery history from InfluxDB."""
|
|
points = get_history(from_time, to_time, battery, device)
|
|
return HistoryResponse(
|
|
points=points,
|
|
battery=battery,
|
|
from_time=from_time,
|
|
to_time=to_time,
|
|
)
|
|
|
|
|
|
@app.get("/api/bmu/climate", response_model=ClimateState | None)
|
|
async def climate(
|
|
_: str = Depends(require_api_key),
|
|
device: str | None = Query(default=None),
|
|
):
|
|
"""Latest ambient temperature / humidity (AHT30)."""
|
|
return get_latest_climate(device)
|
|
|
|
|
|
@app.get("/api/bmu/climate/history")
|
|
async def climate_history(
|
|
_: str = Depends(require_api_key),
|
|
from_time: str = Query(alias="from", default="-24h"),
|
|
to_time: str = Query(alias="to", default="now()"),
|
|
device: str | None = Query(default=None),
|
|
):
|
|
"""Time-series temperature/humidity for charts."""
|
|
return {"points": get_series(
|
|
"climate", ["temperature_c", "humidity_pct"], from_time, to_time,
|
|
device=device)}
|
|
|
|
|
|
@app.get("/api/bmu/solar", response_model=SolarState | None)
|
|
async def solar(
|
|
_: str = Depends(require_api_key),
|
|
device: str | None = Query(default=None),
|
|
):
|
|
"""Latest solar (VE.Direct) telemetry."""
|
|
return get_latest_solar(device)
|
|
|
|
|
|
@app.get("/api/bmu/solar/history")
|
|
async def solar_history(
|
|
_: str = Depends(require_api_key),
|
|
from_time: str = Query(alias="from", default="-24h"),
|
|
to_time: str = Query(alias="to", default="now()"),
|
|
device: str | None = Query(default=None),
|
|
):
|
|
"""Time-series solar telemetry for charts."""
|
|
return {"points": get_series(
|
|
"solar", ["vpv", "ppv", "vbat", "ibat", "yield"], from_time, to_time,
|
|
device=device, device_tag="device")}
|
|
|
|
|
|
@app.get("/api/bmu/audit", response_model=AuditResponse)
|
|
async def audit(
|
|
_: str = Depends(require_api_key),
|
|
from_time: str | None = Query(alias="from", default=None),
|
|
to_time: str | None = Query(alias="to", default=None),
|
|
user: str | None = None,
|
|
action: str | None = None,
|
|
):
|
|
"""Get audit trail with optional filters."""
|
|
events, total = await query_audit_events(
|
|
from_time=from_time,
|
|
to_time=to_time,
|
|
user=user,
|
|
action=action,
|
|
)
|
|
return AuditResponse(events=events, total=total)
|
|
|
|
|
|
# ─── Entrypoint ──────────────────────────────────────────────────────
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
|
|
uvicorn.run(
|
|
"app.main:app",
|
|
host=settings.bmu_api_host,
|
|
port=settings.bmu_api_port,
|
|
reload=True,
|
|
)
|