Compare commits

..
195 Commits
Author SHA1 Message Date
tliu93 018f13d73d M8-R15: fix HA discovery identities and thermal totals
frontend / frontend (push) Successful in 47s
pytest / test (push) Successful in 4m1s
docker-image / build-and-push (push) Successful in 1m38s
2026-08-28 01:20:52 +02:00
tliu93 8180082f90 M8-R14: preserve zero DSMR sample interval
docker-image / build-and-push (push) Successful in 1m35s
frontend / frontend (push) Successful in 47s
pytest / test (push) Successful in 4m15s
2026-08-27 21:29:45 +02:00
tliu93 b472f91f19 M8-R13: simplify prices and meter controls
frontend / frontend (push) Successful in 53s
pytest / test (push) Successful in 4m34s
docker-image / build-and-push (push) Successful in 1m49s
2026-08-27 20:01:41 +02:00
tliu93 c9ce05d95a M8-R12: align and format thermal cost UI 2026-08-27 19:18:03 +02:00
tliu93 33ca3da593 M8-R11: make business timezone deterministic
frontend / frontend (push) Successful in 46s
pytest / test (push) Successful in 3m56s
2026-08-27 12:16:52 +02:00
tliu93 d5623b9fcb M8-R10: document meter lifecycle recovery runbook
frontend / frontend (push) Successful in 47s
pytest / test (push) Failing after 3m55s
2026-08-24 18:37:46 +02:00
tliu93 b1b6a309cb M8-R09: add meter close unbind and transfer workflows 2026-08-24 18:37:46 +02:00
tliu93 8dc3f71aaf M8-R08: add atomic meter close and binding transfer 2026-08-24 18:37:46 +02:00
tliu93 2be4f78f8a M8-R07B: align roadmap with direct serial Compose configuration 2026-08-24 06:45:31 +02:00
tliu93 1a958cb102 M8-R07A: remove obsolete WarmteLink overlay references 2026-08-24 06:45:31 +02:00
tliu93 c851bad829 M8-R07: integrate WarmteLink device access into Compose 2026-08-24 06:45:31 +02:00
tliu93 09abe05f66 M8-R06: refresh Tibber prices after startup and configuration 2026-08-24 06:45:31 +02:00
tliu93 0924e8df52 M8-R05: recover WarmteLink ingestion and discovery automatically 2026-08-24 06:45:31 +02:00
tliu93 72ac7e7300 M8-R04: interpret WarmteLink timestamps as Amsterdam wall time 2026-08-24 06:45:31 +02:00
tliu93 18083822ea M8-R04A: fix fake discovery receive clock 2026-08-24 06:45:31 +02:00
tliu93 3beeb5a461 M8-R03B: keep meter swap recompute in caller transaction 2026-08-24 06:45:31 +02:00
tliu93 631b14e2ec M8-R03: hand off channel binding during meter swap 2026-08-24 06:45:31 +02:00
tliu93 231c340ea6 M8-R03A: stabilize thermal recompute time-range tests 2026-08-24 06:45:30 +02:00
tliu93 c24b6684cc M8-R02A: reconcile DSMR runtime after source CRUD 2026-08-24 06:45:30 +02:00
tliu93 d9e82038dc M8-R02: report DSMR MQTT source health 2026-08-24 06:45:30 +02:00
tliu93 e59c192097 M8-R01: add configurable MQTT client identity 2026-08-24 00:44:28 +02:00
tliu93 2a47dab272 M8-R01A: align lifespan DSMR reconcile mock contract 2026-08-24 00:35:24 +02:00
tliu93 9db7f63274 M8-R00: align tariff expose tests with source bindings 2026-08-24 00:15:48 +02:00
tliu93 ebf96de4f1 M8-T20: document and validate WarmteLink deployment 2026-08-23 21:28:26 +02:00
tliu93 5b9d60e80a M8-T19: add scope-aware energy contract and cost UI 2026-08-23 21:22:06 +02:00
tliu93 963e43e3e4 M8-T18: add source and multi-commodity meter UI 2026-08-23 21:22:06 +02:00
tliu93 39c11ae606 M8-T17: add Home Assistant thermal entities 2026-08-23 21:22:06 +02:00
tliu93 3eec701448 M8-T16: add thermal meter cost APIs 2026-08-23 21:22:06 +02:00
tliu93 489e5b596a M8-T15: add thermal meter cost engine 2026-08-23 21:22:06 +02:00
tliu93 567ddb9779 M8-T14: add generic meter cost periods 2026-08-23 21:22:06 +02:00
tliu93 0fb51d338c M8-T13: add district heating pricing profile 2026-08-23 21:22:06 +02:00
tliu93 b812d5ac46 M8-T12: scope energy contracts 2026-08-23 21:22:06 +02:00
tliu93 a9458394f2 M8-T11: add WarmteLink discovery and history API 2026-08-23 21:22:06 +02:00
tliu93 4884a19e3d M8-T10: add WarmteLink serial worker manager 2026-08-23 21:22:06 +02:00
tliu93 afe653bafa M8-T09: add WarmteLink ingest state machine 2026-08-23 21:22:06 +02:00
tliu93 25a08c47a4 M8-T08: add WarmteLink reading schema 2026-08-23 21:22:05 +02:00
tliu93 ffc693e995 M8-T07: extract reusable P1 parser 2026-08-23 21:22:05 +02:00
tliu93 5855fff451 M8-T06: add meter source management API 2026-08-23 21:22:05 +02:00
tliu93 1ea2f659e0 M8-T05: bind electricity costs to source bindings 2026-08-23 21:22:05 +02:00
tliu93 2e125dbd53 M8-T04: reconcile DSMR ingest from meter sources 2026-08-23 21:22:05 +02:00
tliu93 28486a83c7 M8-T03: adopt DSMR history into meter sources 2026-08-23 21:22:05 +02:00
tliu93 a78401c2ef M8-T02: add source profiles and binding services 2026-08-23 21:22:05 +02:00
tliu93 009856a50d M8-T01: add meter source identity schema 2026-08-23 21:22:05 +02:00
tliu93 43c2ddce1a M8: clarify Alembic schema migration plan 2026-08-22 22:02:14 +02:00
tliu93 d7f04aee8c M8: finalize WarmteLink implementation plan
pytest / test (push) Successful in 2m22s
frontend / frontend (push) Successful in 29s
2026-08-22 21:23:19 +02:00
tliu93 8dbb59a3b7 PRE-M8-T03: finalize WarmteLink hardware validation
frontend / frontend (push) Successful in 30s
pytest / test (push) Successful in 2m23s
2026-08-22 19:29:54 +02:00
tliu93 2992bbb0ef PRE-M8-T02: add read-only WarmteLink serial probe 2026-08-22 18:06:15 +02:00
tliu93 22faeb45bb PRE-M8-T01: add WarmteLink P1 telegram parser 2026-08-22 17:47:30 +02:00
tliu93 c37dfacfc7 PRE-M8: record WarmteLink findings and implementation plan 2026-08-22 17:23:41 +02:00
tliu93 16b050d821 PRE-M8: add staged WarmteLink bring-up reference
frontend / frontend (push) Successful in 29s
pytest / test (push) Successful in 2m23s
2026-08-20 12:11:05 +02:00
tliu93 d3d914b117 PRE-M8: add WarmteLink P1 planning placeholders
frontend / frontend (push) Successful in 27s
pytest / test (push) Successful in 2m20s
2026-08-18 17:20:31 +02:00
tliu93 fc4af857e3 AGENTS: make repository guidance harness-neutral
frontend / frontend (push) Successful in 46s
pytest / test (push) Successful in 2m33s
2026-08-18 13:28:23 +02:00
tliu93 0958d9a2e9 fix(energy): report real kWh in the cost Summary instead of mislabelled money
docker-image / build-and-push (push) Successful in 1m37s
frontend / frontend (push) Successful in 10m24s
pytest / test (push) Successful in 11m57s
The Summary cards labelled `metered_import` / `metered_export` as "(kWh)", but
both fields are monetary totals (Σ import_cost / Σ export_revenue).  Today's
page therefore showed "Import 1.339 kWh" when the meter had actually imported
4.188 kWh — the 1.339 was EUR.  Cross-checked against the DSMR cumulative
registers and Home Assistant: our energy figures were correct all along, only
the label was wrong.

summarize() now also aggregates the metered energy, reusing the already-fetched
non-degraded rows so no extra query is issued:

  metered_import_kwh = Σ (d1_kwh + d2_kwh)
  metered_export_kwh = Σ (r1_kwh + r2_kwh)

The Import/Export cards show kWh as the headline figure and keep the monetary
equivalent as a sub-line, so the split between energy cost and standing
charges/credits behind total_payable stays visible.

The `_kwh` suffix is now the only thing separating energy from money in this
payload, so the docstrings on both summarize() and SummaryResponse call that
out explicitly.

app/integrations/expose.py reads only the money keys, so the HA outbound
sensors are unaffected by the additive fields.
2026-08-06 22:20:56 +02:00
tliu93 b405aea88b docs: require frontend codegen alongside the OpenAPI export in the gates
frontend / frontend (push) Successful in 9m59s
pytest / test (push) Successful in 11m51s
docker-image / build-and-push (push) Successful in 12m49s
The local gate list only covered `scripts/export_openapi.py` + a clean
`openapi/` diff, but `frontend/src/api/schema.d.ts` is generated from that JSON
and CI re-runs `npm run codegen` with `git diff --exit-code`. d07a083 changed a
route docstring, refreshed openapi.json, and skipped codegen — local green,
remote red on a one-line comment diff. Spell out both steps and note that route
docstrings feed the OpenAPI description too.

Also add AGENTS.md as a symlink to CLAUDE.md so other agent tooling picks up
the same contract.
2026-07-27 19:03:03 +02:00
tliu93 bfc7aa3031 chore(frontend): regenerate API schema after sell_fee docstring change
frontend / frontend (push) Successful in 9m59s
pytest / test (push) Successful in 12m27s
d07a083 changed the /api/energy/prices docstring (sell now deducts sell_fee)
and refreshed openapi/openapi.json, but frontend/src/api/schema.d.ts was not
regenerated, so CI's "check codegen is in sync" step failed. Comment-only diff.
2026-07-27 18:29:54 +02:00
tliu93 2f63b9630c fix(prices): keep hover marker on the hovered slot past midnight
The price chart keyed its X axis on formatLocalTime() "HH:mm" labels, which
repeat across a today+tomorrow range. Recharts resolves axis tooltips by value
(combineTooltipPayload -> findEntryInArray), so hovering a slot after midnight
matched today's identically labelled point: the tooltip showed today's prices
and the active dot jumped back to today's position instead of following the
cursor.

Key the axis on the ISO instant instead (buildChartRows, sorted by slot start)
and format down to HH:mm in the tick formatter; the tooltip label now carries
the date so today and tomorrow are distinguishable.

Also mark the price slot currently in effect by default: findActiveSlotIndex()
locates the slot containing now, rendered as a ReferenceDot on the buy and sell
lines plus a caption, re-evaluated every 30s.

Regression test drives a real mousemove over a sized chart in jsdom and asserts
the resolved slot and active-dot position.
2026-07-27 18:29:08 +02:00
tliu93 d07a083e03 fix(tibber): deduct verkoopvergoeding (sell_fee) from feed-in sell price
frontend / frontend (push) Failing after 5m49s
pytest / test (push) Successful in 20m30s
docker-image / build-and-push (push) Successful in 13m26s
Tibber's API `total` already includes the buy-side inkoopvergoeding
(verified from production data: total = spot×1.21 + energy_tax 0.11085 +
inkoopvergoeding 0.0248). Under net metering Tibber pays back
`total − verkoopvergoeding` per returned kWh (NL: EUR 0.28 -> 0.2552), so the
two EUR 0.0248 fees do NOT cancel — the feed-in price sits 0.0248 below buy.

Model the verkoopvergoeding as a first-class, always-subtracted contract
field `energy.sell_fee` (default 0.0248) instead of folding it into
`sell_adjust`. New sell formula:

    sell = total − energy_tax − sell_fee − sell_adjust

`sell_adjust` now carries only the net-metering energy-tax refund
(= −energy_tax). Applied in both the billing strategy and the /prices
endpoint; recorded in the pricing snapshot. Frontend renders the field
automatically (dynamic profile form). Docs (references, m6) corrected to
drop the wrong "fees cancel" premise.
2026-07-20 13:50:13 +02:00
tliu93 b65f700d56 fix(tibber): fetch forward-looking today+tomorrow via priceInfo(QUARTER_HOURLY)
pytest / test (push) Successful in 20m2s
frontend / frontend (push) Failing after 6m5s
docker-image / build-and-push (push) Successful in 13m27s
priceInfoRange is a historical cursor connection whose range ends at "now": it
never returns upcoming slots. With it, the DB only ever held prices up to the
last hourly refresh, which caused two problems:

  1. The price chart could only show history up to now, never a forward curve.
  2. Worse, per-slot billing was subtly wrong. _tibber_strategy looks up the
     price via `starts_at <= t0` (nearest slot at or before the period). Because
     a period's exact 15-min slot was not fetched until the next hourly refresh
     (~1h later), intra-hour periods were billed with the PREVIOUS quarter's
     price and then locked in by the immutability guard — never corrected.

Switch to priceInfo(resolution: QUARTER_HOURLY) { today tomorrow }, which is
forward-looking AND quarter-hourly: today is always the full local day (96
slots) and tomorrow fills in once Tibber publishes day-ahead prices (picked up
by the next hourly refresh). Every 15-min slot's exact price is now in the DB
before the slot closes, so each period finds its own slot (accurate billing)
and the live current-price entity stays fresh.

Verified against the live Tibber API: fetch_price_range returns 192 points
(96 today + 96 tomorrow), spanning local today 00:00 → tomorrow 23:45, with
future slots present (previously 0).
2026-07-18 20:20:33 +02:00
tliu93 f4cea3874b test(energy-cost): pin local_now in future-window summarize test
frontend / frontend (push) Failing after 6m38s
pytest / test (push) Successful in 20m16s
docker-image / build-and-push (push) Successful in 13m32s
test_future_window_counts_0_days relied on the real wall-clock date and assumed
7/1→8/1 2026 was entirely in the future; once that range started elapsing the
window counted fixed-fee days and the assertion failed. Pin local_now to
June 25 2026 (as the sibling window tests already do) so the case stays
deterministic.
2026-07-17 18:49:26 +02:00
tliu93 134f0abb5f fix(tibber): fetch newest price slots via priceInfoRange last:192
priceInfoRange is a Relay-style cursor connection over the subscription's
entire price history. With no cursor, first:96 returned the OLDEST 96 slots,
anchored at the subscription start date — a fixed window that never advanced.
For a contract added mid-period this meant refresh_prices kept re-upserting the
same day-one slots forever, so GET /api/energy/prices found nothing in the
today+tomorrow window and the UI showed "No Tibber price points available".

Use last:192 to return the newest 192 quarter-hourly slots (2 days), which ends
at the latest published slot and advances daily, fully covering the prices
endpoint's today+tomorrow window.
2026-07-17 18:49:26 +02:00
tliu93 3e04b15656 feat(modbus): add DDSU666 profile and select read function code per profile
frontend / frontend (push) Successful in 2m21s
pytest / test (push) Successful in 9m50s
docker-image / build-and-push (push) Successful in 4m24s
- Add CHINT DDSU666 profile (ddsu666.yaml): FC03 holding registers, voltage/
  current/active power (kW)/reactive power (kvar)/PF/frequency, import+export
  active energy. Word/byte order left at big-endian as a documented best guess
  (manual has no float example) — to be confirmed on-device.
- Add DDSU666-Modbus-Protocol.md reference extracted from the official manual,
  plus the source PDF (parity with the SDM120 reference).
- Generalize driver.read_blocks to dispatch FC03 (holding) or FC04 (input)
  based on a function_code argument (default 4, SDM120 behaviour unchanged);
  the code is validated before any connection is attempted.
- Wire profile.function_code through the CLI read command, the background
  poller, and the device /test endpoint — previously the profile field was
  declared but never honoured (read path was hardcoded to FC04).
- Tests: default -> FC04, function_code=3 -> FC03 holding, invalid FC rejected
  before connecting.
2026-06-30 17:16:25 +02:00
tliu93 f2e8f6a8e7 docs(roadmap): queue Authentication next-steps — sliding session renewal + long-lived token targets (location/poo ingestion)
frontend / frontend (push) Successful in 2m16s
pytest / test (push) Successful in 10m40s
2026-06-27 22:16:02 +02:00
tliu93 90a03e7fd6 FUE-T09: grace-shift *_today daily reset past local midnight + dedicated 00:00:10 publish
docker-image / build-and-push (push) Successful in 4m29s
frontend / frontend (push) Successful in 2m17s
pytest / test (push) Successful in 11m2s
2026-06-26 12:21:51 +02:00
tliu93 d3fc90b320 FUE-T08: defer daily fixed-fee/heffingskorting settlement to local 01:05 in summarize() 2026-06-26 11:44:34 +02:00
tliu93 d4acfc438a FUE-T07: use meter label directly as energy-cost HA device name (drop 'Energy Cost' prefix)
frontend / frontend (push) Successful in 2m14s
pytest / test (push) Successful in 10m49s
2026-06-25 21:28:13 +02:00
tliu93 c26160b10b FUE-T06: trigger HA discovery republish after meter declare/update
frontend / frontend (push) Successful in 2m11s
pytest / test (push) Successful in 10m36s
2026-06-25 20:54:42 +02:00
tliu93 efbe36d7c0 FUE-T05: anchor energy-cost HA device identity to active meter (uuid id, label name, empty when none) 2026-06-25 20:43:07 +02:00
tliu93 f663981cdb FUE-T04: add Meter.uuid (stable HA identity anchor) + backfill migration 2026-06-25 20:20:01 +02:00
tliu93 da05fd2f09 FUE-T03: correct meters POST docstring (no recomputed_periods field) and inaccurate test comments
frontend / frontend (push) Successful in 2m11s
pytest / test (push) Successful in 8m51s
2026-06-25 18:36:46 +02:00
tliu93 188168b16a FUE-T02: fix EditMeterForm timestamp parsing to use shared parseBackendTimestamp (handles offset form) 2026-06-25 18:33:42 +02:00
tliu93 f1e7ce3133 FUE-T01: count billing window start day in full for fixed-fee/credit accrual (symmetric with end day) 2026-06-25 18:33:42 +02:00
tliu93 e3d0d17cac M7-T07: finalize M7 docs (roadmap entry, design index, status done, meter-epochs module doc)
frontend / frontend (push) Successful in 2m10s
pytest / test (push) Successful in 8m34s
2026-06-25 17:01:54 +02:00
tliu93 33f5de0591 M7-T06: add meter management UI (timeline, declare swap, edit) to Energy view 2026-06-25 17:01:54 +02:00
tliu93 839faaf95b M7-T05: add meter CRUD API + retroactive recompute + OpenAPI regen 2026-06-25 17:01:54 +02:00
tliu93 82bb329500 M7-T04: anchor cumulative cost entities to active meter start (per-meter reset) 2026-06-25 17:01:54 +02:00
tliu93 17057ed41e M7-T03: make billing engine meter-aware (no cross-meter delta, delta sanity guard, period.meter_id) 2026-06-25 17:01:54 +02:00
tliu93 227b146c2c M7-T02: add meter service layer (declare/swap/close/edit, meter_at, mutual exclusion) 2026-06-25 17:01:54 +02:00
tliu93 32a20785ee M7-T01: add meter table + model + energy_cost_period.meter_id + backfill migration 2026-06-25 14:48:39 +02:00
tliu93 2544514f52 M7: add meter-epochs / meter-swap-archival milestone design doc
frontend / frontend (push) Successful in 2m6s
pytest / test (push) Successful in 7m51s
Design for explicit meter lifecycle (epochs) so the register-difference
billing engine never computes a delta across a meter swap (2G->4G or house
move). Meter-centric (no Home entity); per-meter cumulative reset; retroactive
declaration with recompute; delta sanity guard as backstop. 7 atomic task cards.
2026-06-25 14:23:25 +02:00
tliu93 96e85fb48e FU11: anchor cumulative cost at recording start; add daily-reset cost entities; prefill add-version form
pytest / test (push) Successful in 7m32s
frontend / frontend (push) Successful in 2m6s
- MQTT import_cost_total / export_revenue_total now anchor fixed-fee / tax-credit
  accrual at max(contract start, first recorded period), so standing charges for
  untracked pre-recording days are no longer folded into the running total.
- Add energy.import_cost_today / energy.export_revenue_today (monetary,
  total_increasing) that reset at server-local midnight, for per-day cost
  aggregation in Home Assistant alongside the running totals.
- ContractForm add-version mode prefills the contract's open version values, so
  only the fields that actually change need editing.
2026-06-25 12:45:24 +02:00
tliu93 b71009620a compose add tz 2026-06-25 11:48:45 +02:00
tliu93 8b91146c29 FU10: localize energy time math to server tz; accrue fixed/credit per elapsed local day
frontend / frontend (push) Successful in 2m5s
pytest / test (push) Successful in 7m34s
- Store UTC, compute day boundaries in server local timezone (new app/services/timezone.py).
- summarize: fixed fee / tax credit accrue only for elapsed whole local days,
  integrated across contract versions — no future-day inflation, no version-switch collapse.
- MQTT import_cost_total / export_revenue_total getters delegate to summarize (no inline
  apportionment), anchored at the active contract's earliest version effective_from so the
  total sensors stay monotonic and never jump backward.
- effective_from: naive datetimes interpreted as server-local wall-clock, then stored UTC.
- frontend ContractForm sends local-midnight naive datetime (was UTC midnight).
- get_costs_summary default window uses server-local "today".
2026-06-25 11:13:30 +02:00
tliu93 682e06d256 modbus: add explicit cascade delete (device + readings + toggles + HA cleanup)
frontend / frontend (push) Successful in 2m4s
pytest / test (push) Successful in 7m32s
A disabled device with historical readings still cannot be deleted by default
(409 guard stays, to prevent accidental data loss). A new explicit opt-in lets
the user remove it for real:

- DELETE /api/modbus/devices/{uuid}?cascade=true removes the device's readings
  and exposed_entity_toggle rows, then the device, in one transaction (FK order:
  readings before device). Best-effort clears the HA discovery configs first
  (MQTT not connected -> no-op, never blocks the delete). Default (no cascade)
  unchanged. Returns 200 with deletion counts.
- Frontend: a 'Force Delete (all data)' button appears only after the 409, with
  a red irreversible warning; cascade is sent only on that explicit action.
- Also corrected a stale comment: FK RESTRICT IS enforced at runtime now.
2026-06-24 17:38:52 +02:00
tliu93 d7f0731d1c ha_discovery: publish state/availability under home_automation prefix
Follow the standard MQTT Discovery split: discovery config stays under the HA
discovery prefix (homeassistant/.../config, required), but the actual state and
availability are published under our own prefix (default home_automation/). The
config payload's state_topic/availability fields point at the new prefix so HA
reads state from there.

- new config ha_state_topic_prefix (default home_automation).
- build_discovery_payload + all publish_* split discovery_prefix (config topic)
  from state_prefix (state/availability). energy-cost still omits availability;
  modbus availability structure unchanged. Tests updated.
2026-06-24 16:21:15 +02:00
tliu93 9bc46f8d2d expose: buy/sell_price_now follow the live dual-tariff slot
Subscribe the separate DSMR tariff topic (dsmr/meter-stats/electricity_tariff,
1=dal/off-peak, 2=normal/peak), keep the latest slot in memory, and make the
manual-contract buy/sell_price_now sensors show the matching tariff's price
(tariff 1 -> dal, 2/unknown -> normal). Tibber (single 15-min price) unchanged.
Billing is untouched (register-split already handles tariffs correctly).

- new config dsmr_tariff_topic; subscribe managed by apply_dsmr_subscription
  (restart-free on config save). In-memory tariff is lock-guarded.
- import_cost_total / export_revenue_total cumulative getters unchanged.
2026-06-24 15:39:21 +02:00
tliu93 6f8cb05eab expose: fold standing fee into import cost, tax credit into export revenue
So HA can show the full payable: net = import - export = Total Payable, with
both entities staying monotonic-positive (no negative-value/reset pitfalls).

- import_cost_total = SUM(import_cost) + days*(network_fee+management_fee)/30
- export_revenue_total = SUM(export_revenue) + days*heffingskorting/365
  (days = calendar days since the active version's effective_from, incl. today)
- state_class total_increasing -> total (monetary-compatible; values still only
  increase). device_class/key/names: key unchanged, names clarified.
- buy/sell_price_now and DeviceInfo untouched. Decimal money math. Tests added.
2026-06-24 14:26:32 +02:00
tliu93 effe434637 frontend: show Energy/DSMR/meter times in local timezone, 24h
Backend serializes SQLite-read (naive) UTC datetimes without a Z, so the browser
was parsing them as local time -> the UI effectively showed UTC values.

- New src/utils/datetime.ts: treats a tz-less timestamp as UTC, then formats in
  the browser's local timezone with hour12:false (no AM/PM).
- Applied to Energy tabs (contracts/prices/costs/DSMR), per-device readings &
  trends, and the meter readings table on the Records page.
- CostView Today/This month now use local day boundaries (queries stay UTC ISO).
- Untouched: location/poo (raw Zulu strings), the map, and query-window params.
- Tests are timezone-independent (verified under TZ=America/Los_Angeles).
2026-06-24 13:22:07 +02:00
tliu93 9d3e28a529 Billing fix: don't bill periods from stale/out-of-range DSMR readings
Root cause (found in the live DB): register_at() returned the latest reading
for any boundary beyond the DSMR data range (a future instant or a long gap),
so future periods got start==end -> delta 0 and were written as degraded=False
'ok' rows with cost 0. recompute_range() over a future end then filled the whole
month with such fake rows, which then occupied the slots so the per-minute tick
(immutability guard skips non-degraded rows) never recomputed the real data.

- register_at: ignore a reading older than one period (15min) before the
  boundary -> returns None -> period is marked degraded instead of a fake 0.
- recompute_range: only process closed periods (t1 <= now); never future ones.
- Tests cover staleness window, out-of-range -> degraded, recompute skips
  future, and a regression that normal closed periods are unaffected.
2026-06-24 12:44:05 +02:00
tliu93 7e61b0a938 HA Discovery fix: energy-cost sensors are always-available
The energy-cost device has only sensors (no online/offline heartbeat), but the
discovery config still declared an availability topic that nothing ever publishes
'online' to — so Home Assistant marked every energy-cost entity 'unavailable'
even though the state topic was being published (visible in MQTT Explorer).

- DeviceInfo gains provides_availability (default True, keeps Modbus behavior).
- _energy_cost_provider sets provides_availability=False.
- build_discovery_payload only emits availability/availability_mode for devices
  that publish a heartbeat; HA treats the rest as always-available.
- Test asserts energy-cost configs omit availability.
2026-06-24 11:54:49 +02:00
tliu93 e8521351d7 frontend: add DSMR data panel to Energy page
- New 'DSMR' tab showing the latest parsed telegram (GET /api/energy/dsmr/latest)
  as a key/value table — the source-of-truth view so you can see ingest is
  landing data without reading the DB.
- Auto-refresh toggle (~10s); loading/error/empty states (empty explains the
  likely cause); null phase values shown as a dash.
- useDsmrLatest extended with optional auto-refresh. Tests added.
2026-06-24 11:02:42 +02:00
tliu93 8d4f496ff4 DSMR hardening: restart-free config + decouple from telegram id
Config hot-reload (no restart):
- MqttManager.unsubscribe(); apply_dsmr_subscription(settings) re-applies the
  DSMR subscription (subscribe/unsubscribe/topic-change, fresh snapshot so the
  sample interval also takes effect).
- Called from lifespan AND PUT /api/config, so toggling DSMR ingest in the UI
  takes effect immediately without restarting the app.

Decouple ingest from the DSMR telegram id (overflows / resets to zero):
- Migration 20260624_12: drop UNIQUE(source_id), make recorded_at UNIQUE.
- Idempotency now keys on recorded_at (telegram timestamp); the table's own
  autoincrement PK is the stable identity. source_id kept only as a reference.
- Regression test: colliding telegram ids no longer drop new data.
2026-06-24 11:02:32 +02:00
tliu93 78f3cc4776 M6-T11: document M6 (energy pricing + DSMR + Tibber) across README/roadmap/arch
- README: M6 section + feature list + new tables/config items.
- roadmap: M6 row (graduated) + detail section; M6 in milestone index.
- architecture-overview: M6 models/services/integrations/routes/jobs/config.
- design/README: index m6, drop stale '三个里程碑' wording.
- OpenAPI already in sync (no diff).
2026-06-23 23:52:07 +02:00
tliu93 96e88861d4 M6-T10: frontend contract management + price/cost views + Tibber test
- EnergyPage: Mantine Tabs (Devices kept intact + Contracts/Prices/Costs).
- ContractManager/ContractForm: list/activate/add-version + version history;
  form fields rendered dynamically from /api/energy/profiles structure.
- TibberPrices + CostView: Recharts price curve, cost trend/detail/summary,
  recompute; window-bounded, currency/units from API, empty/error/loading states.
- ConfigPage: tri-state Tibber test button (token never shown).
- hooks.ts: typed energy hooks; schema.d.ts regenerated via codegen.
2026-06-23 23:32:39 +02:00
tliu93 57f2459f60 M6-T09: add Energy data API (prices/costs/summary/dsmr-latest/recompute/tibber-test)
- routes/api/energy.py + schemas/energy.py: GET prices (tibber points or manual
  tariff, buy/sell consistent with the pricing strategies), GET costs (time
  window + limit, ascending), GET costs/summary (summarize passthrough), GET
  dsmr/latest, POST costs/recompute (idempotent, <=366d guard, CSRF), POST
  tibber/test (three-state, token never echoed, CSRF).
- main.py registers router; OpenAPI re-exported; tests for all endpoints.
2026-06-23 23:05:45 +02:00
tliu93 c61fc2d4ba M6-T08: add energy_cost expose provider + post-billing state publish
- expose.py: _energy_cost_provider yields buy/sell_price_now + import_cost_total
  /export_revenue_total (total_increasing, monetary), value_getters read from
  energy_cost_period; 2-element identifiers so the existing HA Discovery builder
  (which indexes identifiers[1]) works. Other providers/mechanism untouched.
- main.py: energy-cost job calls publish_states after computing periods (no-op
  when MQTT/Discovery off). Tests added.
Note: energy-cost sensors lack an availability heartbeat (ha_discovery mechanism
limitation, out of scope here).
2026-06-23 22:44:41 +02:00
tliu93 d35ac7d752 M6-T07: add metering billing engine + period job + summary + recompute
- app/services/energy_cost.py: register_at (register values at a UTC boundary),
  compute_period (register deltas x active-version strategy, snapshot price +
  contract_version_id, immutable unless overwrite), compute_closed_periods
  (bounded lookback), recompute_range (explicit overwrite), summarize
  (sum net + standing fees month/30 - heffingskorting year/365).
- Missing tibber price -> skip; missing reading -> degraded (zeroed amounts,
  null version), consistently on both create and recompute paths.
- main.py: 1-minute energy-cost job (existing jobs/MQTT untouched). Tests added.
2026-06-23 22:26:56 +02:00
tliu93 ef48032adb M6-T06: extend MqttManager with subscribe + DSMR ingest
- mqtt.py: subscription registry, on_message dispatch (swallows handler
  errors), re-subscribe on (re)connect; publish/connect/disconnect/reconnect
  unchanged.
- app/services/dsmr_ingest.py: handle_message stores the full telegram frame
  (no allowlist; gas/phases/null preserved), 10s downsample by timestamp.second,
  source_id idempotency (select + IntegrityError rollback). Net-thread safe.
- main.py registers the DSMR subscription only when dsmr_ingest_enabled.
2026-06-23 21:52:57 +02:00
tliu93 7e266a21eb M6-T05: add Tibber GraphQL client + price refresh service + schedule
- app/integrations/tibber/client.py: fetch_price_range/fetch_current_price
  (priceInfoRange QUARTER_HOURLY, startsAt->UTC, no fixed node count assumption),
  TibberError/TibberAuthError; token never logged or put in exception text.
- app/services/tibber_prices.py: refresh_prices upserts by starts_at (idempotent),
  no-op unless an active kind=tibber contract + token exist.
- main.py: hourly tibber-refresh job (existing jobs/MQTT untouched). Tests added.
2026-06-23 21:35:29 +02:00
tliu93 4284bd40a7 M6-T04: add EnergyContract CRUD + versions + profile validation API
- app/services/contracts.py: create_contract, add_version (append-only,
  auto-closes prior version), activate_contract (mutex), and
  active_contract_version_at (half-open [from, to)) for the billing engine.
- app/schemas/energy_contract.py + routes/api/energy_contracts.py: 6 endpoints
  (GET/POST contracts, GET/PATCH contracts/{id}, POST .../versions, GET profiles).
  Values validated against pricing profiles (422 on mismatch); no DELETE.
- main.py registers router; OpenAPI re-exported; tests for CRUD/version/activate.
2026-06-23 21:19:25 +02:00
tliu93 bedea196c3 M6-T03: add pricing profile framework + strategy registry
- app/integrations/pricing: profiles.py (pydantic ManualProfile/TibberProfile,
  load_profile/list_profiles/validate_values), manual.yaml + tibber.yaml
  (structure-only, no price values), strategies.py (register/get_strategy,
  manual dual-tariff + tibber strategies, all Decimal).
- tibber strategy matches nearest tibber_price with starts_at <= t0.
- tests for profiles + strategies (hand-checked dual-tariff & tibber math).
2026-06-23 20:58:34 +02:00
tliu93 df54f5518b M6-T02: add DSMR + Tibber flat config fields
- Settings: dsmr_ingest_enabled, dsmr_mqtt_topic, dsmr_sample_interval_s,
  tibber_api_token (secret), tibber_home_id (all opt-in / off by default).
- CONFIG_FIELDS DSMR + Tibber sections; _settings_payload extended.
- .env.example examples; test_api_config coverage (sections, secret, 422).
2026-06-23 20:43:46 +02:00
tliu93 18fe18281b M6-T01: add 5 energy tables, models, and migration
- app/models/energy.py: DsmrReading, EnergyContract, EnergyContractVersion,
  TibberPrice, EnergyCostPeriod (per design §3.5; JSON blobs, RESTRICT FKs).
- alembic_app migration 20260623_11_energy_tables (head), env.py imports.
- app_db_adopt APP_BASELINE_REVISION bumped to new head.
- tests/test_energy_models.py + expose_catalog test fixups for new head.
2026-06-23 20:33:35 +02:00
tliu93 355c8eb8b8 fix: add paho-mqtt and pymodbus to dev-requirements lock (CI install was missing M5 deps)
pytest / test (push) Successful in 5m13s
frontend / frontend (push) Successful in 1m48s
2026-06-23 20:06:13 +02:00
tliu93 1ffdaebbbd M6: add Tibber API + NL energy pricing + DSMR reference doc
frontend / frontend (push) Successful in 1m54s
pytest / test (push) Failing after 32s
2026-06-23 19:56:02 +02:00
tliu93 c64693b8e5 M6: add design doc — generic pricing layer (manual/tibber) + DSMR cost engine 2026-06-23 19:53:26 +02:00
tliu93 c89d083942 M5: add read-only per-meter readings tabs to Records page; English-only UI strings 2026-06-22 22:16:55 +02:00
tliu93 6090b98ab0 M5: enable SQLite foreign_keys pragma for DB-level FK enforcement 2026-06-22 20:45:47 +02:00
tliu93 489cd7df3d M5: default Modbus polling to off (opt-in) to avoid unnecessary DB writes 2026-06-22 20:28:12 +02:00
tliu93 35cdc7f22a M5: use DB-merged runtime settings for MQTT/discovery; add MQTT test button; move Expose panel into config accordion 2026-06-22 20:11:54 +02:00
tliu93 75d685f04d M5: roll Energy chart window for live auto-refresh (English label); render boolean config fields as switches 2026-06-22 19:40:18 +02:00
tliu93 935e68846c M5: Energy view — per-metric decimal formatting and chart auto-refresh toggle 2026-06-22 19:18:29 +02:00
tliu93 4767a7af60 M5-T13: document Modbus/Energy/MQTT, mark M5 done, finalize OpenAPI 2026-06-22 16:10:11 +02:00
tliu93 45d87f36f7 M5-T12: add expose toggle API and Home Assistant Expose settings panel 2026-06-22 15:50:49 +02:00
tliu93 35b95f5c88 M5-T11: add HA discovery and state publishing wired to polling 2026-06-22 15:32:43 +02:00
tliu93 9d05f5ea62 M5-T10: add paho MQTT client with lifespan connect/reconnect and mqtt/test endpoint 2026-06-22 15:06:30 +02:00
tliu93 360cddc05b M5-T09: add exposed_entities table and ExposableEntity provider framework 2026-06-22 14:50:40 +02:00
tliu93 14b846549e M5-T08: add MQTT, HA Discovery, and Modbus polling config fields 2026-06-22 14:27:21 +02:00
tliu93 68165f0e01 M5-T07: add latest-reading cards and Recharts trend charts; readings return most-recent rows 2026-06-22 14:17:59 +02:00
tliu93 2dc469274a M5-T06: add Energy device management UI and sidebar entry 2026-06-22 13:52:33 +02:00
tliu93 702a1cec00 M5-T05: add Modbus JSON API (device CRUD, readings, metrics, test) 2026-06-22 13:37:48 +02:00
tliu93 49d15d8ffe M5-T04: add Modbus poll service and APScheduler polling job 2026-06-22 13:24:11 +02:00
tliu93 c89cea4953 M5-T03: add Modbus TCP driver, YAML profile framework, sdm120, modbus_cli 2026-06-22 13:03:50 +02:00
tliu93 d9c82e39fb M5-T02: add modbus_device and modbus_reading tables and models 2026-06-22 12:45:50 +02:00
tliu93 eac7860b51 M5-T01B: render ConfigPage sections as Mantine Accordion 2026-06-22 12:34:04 +02:00
tliu93 da7d0f9d62 M5-T01: refactor AppLayout from top bar to sidebar navigation 2026-06-22 12:26:52 +02:00
tliu93 e49a6ad963 M5(design): generic modbus_device + JSON readings; YAML profiles; Accordion config; manual CLI/MQTT testing
frontend / frontend (push) Successful in 1m26s
pytest / test (push) Successful in 3m52s
Rework the M5 design doc data model and add manual-testing surface:

- Two-layer model: rename energy_meters/energy_readings -> generic
  modbus_device + modbus_reading; readings become a JSON payload blob
  instead of a wide fixed-column table (aggregation via SQLite
  json_extract, generated-column index as a future lever).
- Protocol knowledge moves to read-only YAML profiles (data+functions,
  no OOP inheritance); deployment/config (friendly_name, unit_id, host)
  stays on the device row; multiple devices share one profile.
- UUID = stable internal identity, also anchors HA discovery unique_id
  (Z2M rename model); device metadata for HA derived from the profile.
- Naming scheme C: modbus_* / /api/modbus/devices at the data+API layer,
  'Energy' as the first domain view in the frontend.
- New task M5-T01B: ConfigPage Accordion sectioning (avoids a second
  in-page side nav conflicting with the T01 app sidebar).
- Manual testing: read-only modbus_cli 'probe' subcommand (FC03/04 only,
  no register writes); mqtt/test now publishes a test message viewable
  in MQTT Explorer; no MQTT CLI (manual verification via UI + HA).
2026-06-22 11:55:39 +02:00
tliu93 d70b985eb0 fix(ci): recompile dev-requirements.txt to include pyotp (pytest CI install)
pytest / test (push) Successful in 3m51s
frontend / frontend (push) Successful in 1m26s
2026-06-22 11:08:06 +02:00
tliu93 e3c47b2762 docs(CLAUDE): switch to direct-on-main workflow for this single-user repo
frontend / frontend (push) Successful in 1m35s
pytest / test (push) Failing after 31s
2026-06-22 10:37:34 +02:00
tliu93 dbf17f3592 docs(CLAUDE): pin default sub-agent models (Implementer/Fixer=Sonnet, Reviewer=Opus) with manual-override clause 2026-06-22 09:50:46 +02:00
tliu93 ae75e4582d M4-T09: document login hardening, finalize OpenAPI and roadmap 2026-06-21 23:01:50 +02:00
tliu93 ee1264b66b M4-T08: add two-step login and TOTP settings panel (qrcode.react) 2026-06-21 22:42:41 +02:00
tliu93 51da8c5716 M4-T07: add admin_cli disable-totp and reissue-totp escape commands 2026-06-21 22:27:07 +02:00
tliu93 81bd32f613 M4-T06: add TOTP second factor to login (totp_code + recovery codes) 2026-06-21 22:08:55 +02:00
tliu93 ee3031013e M4-T05: add TOTP service and setup/enable/disable/status API 2026-06-21 21:55:17 +02:00
tliu93 5026967cee M4-T04: add AuthUser TOTP columns and auth_recovery_code table 2026-06-21 21:38:22 +02:00
tliu93 5481fbc99c M4-T03: add admin_cli escape hatch (reset-password, unlock, list-admin) 2026-06-21 21:28:41 +02:00
tliu93 e480a84a44 M4-T02: add exponential login back-off service and wire into login endpoint 2026-06-21 21:20:28 +02:00
tliu93 64d3882c16 M4-T01: add auth_login_throttle table + LoginThrottle model 2026-06-21 21:03:20 +02:00
tliu93 6b67b8e0f8 modify compose dev port 2026-06-21 20:49:24 +02:00
tliu93 0cb94d85ec docs(design): plan M4 login-hardening (first) + M5 IoT/energy
- Add docs/references/SDM120-Modbus-Protocol.md extracted from the SDM120 PDF
- M4 login hardening: brute-force exponential backoff, CLI escape hatch
  (reset-password/unlock/disable-totp), optional TOTP 2FA
- M5 IoT/energy: Modbus-TCP SDM120 polling + energy tables, MQTT/HA
  Discovery expose framework, frontend sidebar + energy view
- Add manual acceptance walkthroughs (M4 lock/unlock; M5 energy_cli read)
- Index both milestones in docs/design/README.md
2026-06-21 20:46:12 +02:00
tliu93 9da88db221 docs(roadmap): graduate next-phase work out of Future Ideas
frontend / frontend (push) Successful in 1m18s
pytest / test (push) Successful in 1m32s
Promote four now-decided directions from Future Ideas into a new
"下一阶段:已确定要做" section (roadmap altitude, not yet broken into task cards):
TOTP second factor for the public dashboard, frontend optimization (scope TBD),
MQTT / IoT integration, and a settings-page long-lived API token (PAT-style,
related to but distinct from M3's mobile OAuth). Future Ideas is now an empty,
purpose-stated bucket for not-yet-decided ideas.
2026-06-13 17:38:50 +02:00
tliu93 1a3aaea933 fix(docker): pin frontend-build to $BUILDPLATFORM to avoid QEMU V8 crash
frontend / frontend (push) Successful in 1m19s
pytest / test (push) Successful in 1m31s
docker-image / build-and-push (push) Successful in 3m55s
Multi-arch image builds (linux/amd64,linux/arm64) emulate the foreign arch via
QEMU. The unpinned `FROM node:22-slim` frontend-build stage was built per
target arch, so Node ran under emulation and V8's baseline JIT crashed (SIGTRAP
/ exit 133 on `npm ci`) on the CI runner's QEMU.

Pin the stage to --platform=$BUILDPLATFORM so the static, arch-independent SPA
dist/ is built once on the native build host and COPYd into each arch's runtime
stage. Node never runs emulated; both arch images are still produced.
2026-06-13 17:21:05 +02:00
tliu93 bf7fd71a21 Merge pull request 'Feature/m2 frontend v2' (#8) from feature/m2-frontend-v2 into main
pytest / test (push) Successful in 1m29s
frontend / frontend (push) Successful in 1m15s
docker-image / build-and-push (push) Failing after 59s
Reviewed-on: #8
2026-06-13 17:00:19 +02:00
tliu93 962ba26c7c docs(roadmap): add Future Ideas — TOTP 2FA for the public dashboard
frontend / frontend (push) Successful in 1m15s
pytest / test (push) Successful in 1m30s
frontend / frontend (pull_request) Successful in 1m16s
pytest / test (pull_request) Successful in 1m30s
Record TOTP (RFC 6238) as a deferred hardening idea for the now public-facing
Web dashboard: second factor on the single-admin login, with CLI-only password
reset and a CLI TOTP reset/recovery path that works even if the recovery codes
are lost (no lock-out dead end). Not M2.5, not scheduled — parked under a new
Future Ideas section.
2026-06-13 15:29:20 +02:00
tliu93 da236643f2 M2: frontend walkthrough fixes + explicit dev compose stack
frontend / frontend (push) Successful in 2m0s
pytest / test (push) Successful in 1m32s
Post-M2 self-walkthrough polish, batched into one commit.

Map / heat:
- fix heat-layer white-screen crash after login (add layer to map before
  setLatLngs; an off-map leaflet.heat layer has a null _map and throws)
- normalize each heat layer to the densest pixel cell visible in the CURRENT
  viewport (maxZoom:0 so intensity factor f=1) and recompute on moveend/zoomend,
  so sparse poo data reaches red and stays normalized at any zoom level
- dark CARTO basemap tiles when the color scheme is dark

UI:
- dark-mode toggle in the top-right, beside the settings gear
- switch top-right nav (records / theme / settings / logout) to Feather icons
  with hover tooltips
- home: Grafana-style quick time-range presets + back/forward shift buttons,
  placed between the From/To pickers and Apply; fix Select/tooltip z-index
  (Leaflet stacking) and the shift-button height alignment

API client:
- stop flooding GET /api/session with 401s: the session probe and the login
  endpoint own their 401s (no global redirect), which fixes the logout hang and
  the spinning login page

Compose:
- rename docker-compose.override.yml -> docker-compose.dev.yml as an explicit,
  non-auto-layered dev stack (8001, -dev container names, prod-copy ./data DB);
  update tests/test_deployment.py (read dev.yml, tolerate the !override tag) and
  the README "Docker Compose" section

Tests:
- pixel-grid peak counter, time-range presets, heat-layer ordering regression,
  and 401-redirect regression
2026-06-13 15:20:50 +02:00
tliu93 bd09523e94 M2-T13: docs wrap-up + retire frontend constraints + dependency cleanup
- README: add 前端 v2 (React SPA) section (dev/build/codegen/hosting/gates),
  update directory listing, drop stale Jinja descriptions
- architecture-overview: retire '不引入前后端分离' constraint; reflect SPA + JSON API
- roadmap: mark M2 done
- remove orphaned jinja2 dependency (recompile requirements*.txt; no other churn)
- delete empty tests/test_auth.py stub; drop dead _extract_csrf_token in test_api_data
- verified image still builds and app imports with the slimmer deps
2026-06-13 15:20:50 +02:00
tliu93 53f1245d83 docs(m2): mark M2-T12 done 2026-06-13 15:20:50 +02:00
tliu93 51f712f602 M2-T12: multi-stage Dockerfile (node build -> python runtime) + frontend CI
- Dockerfile: node:22-slim stage runs npm ci + npm run build; python runtime
  stage COPY --from copies dist to /app/frontend/dist (matches SPA_DIST_DIR);
  runtime image has no node
- .dockerignore: exclude frontend/node_modules and frontend/dist from context
- .github/workflows/frontend.yml: npm ci + codegen-sync + lint/typecheck/test/build
- tests/test_deployment.py: skip COPY --from sources in the context-existence
  check; assert the multi-stage frontend build wiring
- verified with a real docker build (image serves SPA, no node at runtime)
2026-06-13 15:20:50 +02:00
tliu93 f8b1e5fc71 docs(m2): mark M2-T11 done 2026-06-13 15:20:50 +02:00
tliu93 a9830c42d8 M2-T11: serve React SPA from FastAPI and remove Jinja pages
- app/main.py serves the SPA build (SPA_DIST_DIR, default frontend/dist):
  mounts /assets and a GET catch-all returning index.html for client routes;
  catch-all 404s on /api/*, never swallows /docs, /openapi.json, /static, assets,
  ingestion/ticktick/status; skips SPA serving when dist absent (backend-only CI)
- delete app/api/routes/pages.py, app/api/routes/auth.py, app/templates/
  (all replaced by /api/* + SPA; auth service layer kept)
- remove/replace Jinja page tests (JSON coverage already in test_api_*);
  add tests/test_spa_hosting.py for the fallback contract
- regenerate openapi/ (Jinja paths gone) and frontend schema.d.ts
2026-06-13 15:20:50 +02:00
tliu93 8aa7316b26 docs(m2): mark M2-T09 done 2026-06-13 15:20:50 +02:00
tliu93 32d93bba2a M2-T09: build data visualization UI (heatmap map as home page)
- self-contained RecordsMap (only module importing leaflet/react-leaflet/
  leaflet.heat/leaflet.markercluster); OSM tiles, swappable behind clean props
- heatmap layers for location + poo (primary); time-range selector fetches
  only the window (locations server-filtered; poo client-filtered)
- toggleable scatter layer with marker clustering; point-select reuses T10's
  edit/delete modals + hooks; query-key prefixes refresh map on mutation
- pure map logic isolated + unit-tested; leaflet mocked in component tests
- responsive layout; typed client only
2026-06-13 15:20:50 +02:00
tliu93 0d988a9b28 docs(m2): mark M2-T10 done 2026-06-13 15:20:50 +02:00
tliu93 ef7ea6b971 M2-T10: build records management UI (paginated lists + single-record CRUD)
- reusable src/records/ module: useUpdate/useDelete Poo+Location hooks
  (encodeURIComponent PK, prefix-based query invalidation), EditPooModal,
  EditLocationModal, ConfirmDeleteModal — exported for the map (T09) to reuse
- RecordsPage (/records): paginated poo + location tables (page size 100),
  edit + delete-with-confirm, refresh on success
- query keys ['poo']/['locations'] so map and list invalidations cross-cut
- typed client only; vitest tests
2026-06-13 15:20:50 +02:00
tliu93 6cc6382515 docs(m2): mark M2-T08 done 2026-06-13 15:20:50 +02:00
tliu93 ef2bd3c9c5 M2-T08: build config UI (replaces Jinja config page)
- GET /api/config renders sections; secret fields shown as empty password inputs
- save handles full-field submission semantics: always send non-secret values,
  send secret only when user typed a new value (blank secret keeps old)
- SMTP test button reflects tri-state (success / config-error 400 / failed 502)
  by reading ApiError.body.result
- typed client only; responsive Mantine layout; vitest tests
2026-06-13 15:20:50 +02:00
tliu93 cc2c02a2e2 docs(m2): mark M2-T07 done 2026-06-13 15:20:50 +02:00
tliu93 b2e26f0b17 M2-T07: build auth UI (login, session bootstrap, forced password change, logout)
- real Mantine login form -> POST /api/auth/login; 401 inline error; redirect when already authed
- ProtectedRoute: loading state, preserves intended destination, gates force_password_change
- ChangePasswordPage forced-change gate -> POST /api/auth/password
- logout control in AppLayout nav -> POST /api/auth/logout
- typed client only; vitest tests for the login flow
2026-06-13 15:20:50 +02:00
tliu93 8975acc48b docs(m2): mark M2-T06 done 2026-06-13 15:20:50 +02:00
tliu93 6cfeb2b865 M2-T06: scaffold React SPA frontend with typed OpenAPI client
- Vite + React 18 + TypeScript + Mantine + TanStack Query + react-router-dom
- typed client: openapi-typescript -> src/api/schema.d.ts (committed), openapi-fetch
- fetch wrapper middleware: cookies, X-CSRF-Token on writes, 401 -> /login,
  non-401 errors carry parsed JSON body
- SessionProvider/useSession (GET /api/session), ProtectedRoute skeleton
- app shell (Mantine + router) with placeholder login/home/config pages + gear nav
- dev proxy to FastAPI; vitest smoke test; frontend README
- npm scripts: dev/build/preview/lint/typecheck/test/codegen
2026-06-13 15:20:50 +02:00
tliu93 dba9e28540 docs(m2): mark M2-T05 done 2026-06-13 15:20:50 +02:00
tliu93 2bc5d6ea9a M2-T05: add SMTP test action API (POST /api/config/smtp/test)
- reuses send_smtp_test_email; tri-state result success(200)/config-error(400)/failed(502)
- session + CSRF protected; never echoes SMTP secrets
- SmtpTestResponse schema; regenerate openapi/
- extend tests/test_api_config.py (3 states + 401 + missing-CSRF 403)
2026-06-13 15:20:50 +02:00
tliu93 3ec663e138 docs(m2): mark M2-T04 done 2026-06-12 23:35:56 +02:00
tliu93 048414c5cb M2-T04: add single-row record CRUD API (patch/delete)
- PATCH/DELETE /api/locations/{person}/{datetime} and /api/poo/{timestamp}
- update only non-PK fields (PK immutable); 404 on missing PK
- delete scoped to exact full PK with rowcount guard (0->404, 1->ok);
  no batch/truncate/drop path
- session + CSRF protected; bare ingestion endpoints untouched
- service helpers in app/services/location.py and poo.py; regenerate openapi/
- tests/test_api_record_crud.py
2026-06-12 23:33:08 +02:00
tliu93 9ce3f2a0b8 docs(m2): mark M2-T03 done 2026-06-12 23:27:02 +02:00
tliu93 0fba7cfe11 M2-T03: add read-only data JSON API
- GET /api/locations (inclusive time window start/end, pagination, cap 5000)
- GET /api/poo (pagination, cap 1000, newest first)
- GET /api/public-ip (current state + recent history, cap 1000)
- all session-protected, read-only, bounded (no full-table export)
- typed response schemas; register router; regenerate openapi/
- tests/test_api_data.py
2026-06-12 23:24:17 +02:00
tliu93 d8303eaa3d docs(m2): mark M2-T02 done 2026-06-12 23:18:43 +02:00
tliu93 8da1f13e60 M2-T02: add session/auth JSON API for the SPA
- GET /api/session (user + csrf_token, 401 when unauthenticated)
- POST /api/auth/login (sets HttpOnly session cookie; 401 on bad creds; no CSRF)
- POST /api/auth/logout (session+CSRF; revokes session, clears cookie; 204)
- POST /api/auth/password (session+CSRF; reuses change_password; 400 on failure; 204)
- reuses app/services/auth.py and shared require_session/require_csrf deps
- register router in app/main.py; regenerate openapi/
- tests/test_api_session.py
2026-06-12 23:15:56 +02:00
tliu93 de77019ce3 docs(m2): mark M2-T01 done 2026-06-12 23:11:38 +02:00
tliu93 c2b1b7b751 M2-T01: add config JSON API (GET/PUT /api/config)
- new app/api/routes/api/ package with shared require_session (401) and
  require_csrf (presence-only X-CSRF-Token, 403) dependencies
- GET /api/config returns masked config sections; PUT /api/config reuses
  save_config_updates (blank secret keeps old; invalid -> 422, no write)
- session-protected; PUT also CSRF-protected
- register router in app/main.py; regenerate openapi/
- tests/test_api_config.py
2026-06-12 23:08:14 +02:00
tliu93 3628ac51e5 chore(m2): green the ruff baseline before M2 orchestration
- ignore E402 in scripts/*.py (deliberate sys.path bootstrap before app imports)
- drop unused pathlib.Path import in tests/test_auth.py

Establishes a clean ruff gate so each M2 task can be verified green at its boundary.
2026-06-12 22:56:21 +02:00
tliu93 1756192270 docs: record future-ideas backlog and refine CLAUDE.md workflow rules
pytest / test (push) Successful in 46s
- Add docs/future-ideas.md: unscheduled backlog (more data sources/types,
  long-term storage, Home Assistant data persistence, MQTT client, near-term PWA).
- CLAUDE.md: codify M1 lessons — reviewer blind-review discipline,
  build-context integrity checks when deleting/moving files,
  fixup-vs-standalone-commit boundary, and a pre-release walkthrough
  (run app + docker build + manual smoke) before tagging.
2026-06-12 22:50:47 +02:00
tliu93 66ec9979cc docs(m2): lock M2 frontend design decisions
pytest / test (push) Failing after 11m46s
Record the decisions reached in planning into docs/design/m2-frontend-v2.md:
component library = Mantine; map = Leaflet (react-leaflet + leaflet.heat +
markercluster, isolated behind a component seam for a future MapLibre swap);
OpenAPI typed client committed + CI-checked; CSRF simplified to SameSite=Lax +
a custom write header (no per-session token); heatmap-first map as the home
view with a required time-range picker and an auxiliary paginated list;
record CRUD edits non-PK fields and deletes single rows (no UI create); bare
ingestion endpoints stay until M3; trips optional. Wireframes intentionally
skipped for this milestone.
2026-06-12 22:40:57 +02:00
tliu93 c1a5d7a425 fix(docker): stop COPYing removed alembic_location/alembic_poo into the image
pytest / test (push) Successful in 50s
docker-image / build-and-push (push) Successful in 3m52s
M1-T04 deleted the alembic_location / alembic_poo chains and their .ini files,
but the Dockerfile still COPYed those four paths, so the release image build
failed at 'COPY alembic_poo.ini ./' (path not found). Drop the four stale COPY
lines (only alembic_app remains). Add test_dockerfile_copy_sources_exist, which
asserts every Dockerfile COPY source exists in the build context, so this class
of breakage fails pytest instead of only surfacing in the image CI.

Verified with a real local 'docker build' (succeeds) and pytest (98 passed).
2026-06-12 20:48:34 +02:00
tliu93 1e0b235cef Merge pull request 'Feature/m1 db consolidation' (#7) from feature/m1-db-consolidation into main
pytest / test (push) Has been cancelled
docker-image / build-and-push (push) Has been cancelled
Reviewed-on: #7
2026-06-12 20:33:34 +02:00
tliu93 a337b06c94 M1-rework: rename leftover pk_cols param in reconciliation test stubs
pytest / test (push) Successful in 48s
pytest / test (pull_request) Failing after 10m49s
Round-2 audit nit (review-notes/M1-full-review-2.md): two _always_fail
monkeypatch stubs still named their (ignored) third positional parameter
pk_cols after _reconcile switched to a full columns list. Rename to columns
for consistency. Test-only, no behavior change.

pytest 97 passed; ruff clean.
2026-06-12 19:11:13 +02:00
tliu93 1cbe6c46d2 M1-rework: harden legacy-migration reconciliation to full-row equality
Audit finding (review-notes/M1-full-review-1.md, FINDING 1): _reconcile only
checked primary-key presence, so a source row skipped by INSERT OR IGNORE due
to a value difference against a pre-existing same-PK target row would
false-pass. Compare ALL columns with SQLite's NULL-safe IS operator instead,
so reconciliation is a true full-row guarantee (idempotent re-runs still pass
because the rows match column-for-column). Add tests for the value-mismatch
abort and for idempotency under full-row reconciliation. Remove the now-unused
pk_cols parameter.

pytest 97 passed; ruff clean (pre-existing only); data-safety grep still empty.
2026-06-12 19:05:56 +02:00
tliu93 2f634006d2 M1-T07: align docs to single-DB reality and re-export OpenAPI
Rewrite README (single app.db + one alembic_app chain, legacy data moved
once via scripts.migrate_legacy_data, accurate test list) and remove the
Grafana Provisioning section. Update architecture-overview to the unified
data layer (one Base, app-DB engine with WAL) and retire the
alembic_location / alembic_poo sections. Mark M1 done in the roadmap.
Re-export openapi/, which catches the spec up to the already-existing
/config/smtp/test and /public-ip/check endpoints (purely additive; M1's
DB-session dependency swap produced no schema change).

pytest 95 passed; ruff clean (pre-existing only); OpenAPI export idempotent.
2026-06-12 17:13:28 +02:00
tliu93 dc624bb7e5 M1-T06: remove Grafana from compose and delete provisioning
Drop the grafana service and the homeautomation_grafana_storage volume
declaration from docker-compose.yml (migration and app services unchanged),
and delete the grafana/ provisioning + dashboards directory. Visualization
moves to the M2 React frontend; the named volume's actual data is retired
manually as an ops step, never by automation.

docker compose config -q passes; pytest 95 passed; ruff clean.
2026-06-12 17:02:49 +02:00
tliu93 af8c602988 M1-T05: drop location/poo database config from Settings and tests
Remove the dead location_database_url / poo_database_url fields and the
location_sqlite_path / poo_sqlite_path computed properties from Settings;
drop them from the config-page payload and from .env.example. Update the
test hardcodes (test_config, test_public_ip, test_smtp) and reduce the
conftest test_database_urls fixture to the single app DB. The one-time
migration script keeps reading legacy URLs from env/CLI, independent of
Settings.

pytest 95 passed; ruff clean (pre-existing only).
2026-06-12 16:57:54 +02:00
tliu93 0d898e09f2 M1-T04: converge startup chain onto the single app DB
run_all_migrations() now adopts/initializes only the app DB and returns
{'app': ...}. app/main.py drops the location/poo readiness checks
(ensure_location_db_ready / ensure_poo_db_ready) and their imports;
ensure_runtime_dirs only provisions the app DB path; lifespan still
fail-closes on a missing/unmanaged app DB. Delete the retired
location/poo adopt scripts and the alembic_location / alembic_poo
chains. Update tests to single-DB expectations and drop the obsolete
location/poo adoption + readiness tests.

pytest 95 passed; ruff clean (pre-existing only); a fresh app DB
initialized via scripts.run_migrations contains location + poo_records.
2026-06-12 16:50:05 +02:00
tliu93 3d3c2bcc57 M1-T03: unify data layer, models, deps and routes onto single app DB
Collapse the three data layers into one. app/db.py now exposes a single
Base, a cached engine bound to app_database_url with SQLite WAL enabled, and
get_engine/get_session_local/reset_db_caches/get_db_session. Delete
app/auth_db.py, app/poo_db.py and app/models/base.py. All models (auth,
config, public_ip, location, poo) inherit the one Base and register on a
single metadata. Dependencies converge to a single get_db; all routes use it.

Also update the alembic env.py files (app/location/poo) and tests that
imported the removed modules so the suite stays green, and drop the obsolete
test_legacy_style_location_db test whose flow (app reading a separate location
DB) no longer exists. Location/poo Alembic chains, adopt scripts and adoption
tests remain for M1-T04; config fields remain for M1-T05.

pytest 109 passed; ruff clean (pre-existing only); WAL verified; single
Base.metadata holds all seven tables.
2026-06-12 16:35:07 +02:00
tliu93 bc8dd062d5 M1-T02: add idempotent legacy data migration script
scripts/migrate_legacy_data.py copies rows from the legacy locationRecorder.db
/ pooRecorder.db into the unified app DB's location / poo_records tables using
ATTACH + INSERT OR IGNORE (idempotent via PK-conflict skip; explicit columns,
never SELECT *). After copy it reconciles every source row against the target
and raises / exits non-zero on any shortfall. Missing legacy files are a safe
no-op (skipped); --dry-run writes nothing. Not part of the Alembic chain; run
manually once at cut-over. Never deletes or overwrites any file.

Validated end-to-end on copies of the real production DBs: dry-run reported
75103 location + 874 poo rows and wrote nothing; the real run copied all rows
with reconciliation passing; a second run copied 0 (idempotent).
2026-06-12 16:13:55 +02:00
tliu93 427a491380 M1-T01: add app-chain revision creating location + poo_records tables
Add alembic_app revision 20260611_06_merge_location_poo_tables that builds
empty location and poo_records tables (REAL float columns, matching the
production schema and the adopt scripts' EXPECTED_*_TABLE_INFO constants).
Update APP_BASELINE_REVISION to the new head. Schema-only; data migration
is handled separately by scripts/migrate_legacy_data.py (M1-T02).
2026-06-12 16:02:46 +02:00
tliu93 b359bbe3bf docs: add next-phase roadmap, milestone design docs, and CLAUDE.md
pytest / test (push) Successful in 54s
- roadmap.md: M1 (DB consolidation) -> M2 (React SPA) -> M3 (token/mobile)
- docs/design/: agent-pipeline design docs with atomic tasks for M1-M3
- CLAUDE.md: workflow, doc map, commit conventions, review-notes briefing flow
- .gitignore: ignore local review-notes/
2026-06-12 15:37:17 +02:00
tliu93 636bb2b80b Merge pull request 'add get public and storage feature' (#6) from feature/public_ip into main
docker-image / build-and-push (push) Successful in 3m59s
pytest / test (push) Successful in 53s
Reviewed-on: #6
2026-04-29 13:16:58 +02:00
tliu93 eda49489e0 update reademe and docs
pytest / test (push) Successful in 56s
pytest / test (pull_request) Successful in 59s
2026-04-29 13:07:59 +02:00
tliu93 779e160b95 add ip change notification and refine sender display
pytest / test (push) Successful in 57s
pytest / test (pull_request) Successful in 54s
2026-04-29 13:03:12 +02:00
tliu93 3ea3498e58 add smtp module and testing 2026-04-29 12:11:10 +02:00
tliu93 5a420bd37b add get public and storage feature 2026-04-29 11:45:49 +02:00
tliu93 a24e402d47 add grafana provisioning
pytest / test (push) Successful in 46s
2026-04-23 00:12:51 +02:00
tliu93 8565534b73 Merge pull request 'fix ci test' (#5) from feature/add_separate_migration_container into main
pytest / test (push) Successful in 45s
docker-image / build-and-push (push) Successful in 3m40s
Reviewed-on: #5
2026-04-22 13:35:40 +02:00
tliu93 4acdd2dc60 fix ci test
pytest / test (push) Successful in 45s
pytest / test (pull_request) Successful in 44s
2026-04-22 13:31:26 +02:00
tliu93 c9af7530e5 Merge pull request 'change adoption to separate step' (#4) from feature/add_separate_migration_container into main
pytest / test (push) Failing after 44s
docker-image / build-and-push (push) Successful in 3m40s
Reviewed-on: #4
2026-04-22 13:28:30 +02:00
tliu93 a76d6bfb71 change adoption to separate step
pytest / test (push) Failing after 46s
pytest / test (pull_request) Failing after 45s
2026-04-22 13:28:00 +02:00
310 changed files with 105695 additions and 2744 deletions
+3
View File
@@ -8,3 +8,6 @@ data
openapi
src
# Frontend host build artifacts — built inside the node stage, not needed from context
frontend/node_modules
frontend/dist
+43 -2
View File
@@ -4,13 +4,17 @@ APP_NAME=Home Automation Backend (Python)
APP_ENV=production
APP_HOSTNAME=home-automation.example.com
APP_DATABASE_URL=sqlite:////app/data/app.db
LOCATION_DATABASE_URL=sqlite:////app/data/locationRecorder.db
POO_DATABASE_URL=sqlite:////app/data/pooRecorder.db
AUTH_BOOTSTRAP_USERNAME=admin
AUTH_BOOTSTRAP_PASSWORD=change-me
# Required by Docker Compose for the WarmteLink serial device. Set these only in
# your local .env; use a stable /dev/serial/by-id path and its numeric host GID.
# WARMTELINK_DEVICE_PATH=/dev/serial/by-id/<stable-by-id-name>
# WARMTELINK_SERIAL_GID=<host-serial-gid>
# Optional: runtime overrides.
# Leave these commented out to use the application's built-in defaults.
# TZ=Europe/Amsterdam
# APP_DEBUG=
# AUTH_SESSION_COOKIE_NAME=
# AUTH_SESSION_TTL_HOURS=
@@ -30,3 +34,40 @@ TICKTICK_CLIENT_ID=
TICKTICK_CLIENT_SECRET=
TICKTICK_TOKEN=
HOME_ASSISTANT_ACTION_TASK_PROJECT_ID=
# Optional: Modbus polling (global kill-switch; default false — opt-in).
# MODBUS_POLLING_ENABLED=false
# Optional: MQTT broker connection.
# Leave MQTT_ENABLED=false (or unset) when MQTT is not needed.
MQTT_ENABLED=false
MQTT_BROKER_HOST=
MQTT_BROKER_PORT=1883
MQTT_USERNAME=
MQTT_PASSWORD=
MQTT_TLS_ENABLED=false
# MQTT_CLIENT_ID must be a non-empty ASCII slug; use a distinct value per deployment.
MQTT_CLIENT_ID=home-automation
# Optional: Home Assistant MQTT Discovery.
# Requires MQTT_ENABLED=true and a running MQTT broker.
# HA_DISCOVERY_PREFIX is the config topic prefix (must be "homeassistant" for HA auto-discovery).
# HA_STATE_TOPIC_PREFIX is the prefix for state/availability topics (separate from discovery).
HA_DISCOVERY_ENABLED=false
HA_DISCOVERY_PREFIX=homeassistant
HA_STATE_TOPIC_PREFIX=home_automation
# Optional: DSMR smart-meter ingest via MQTT (M6; default off — opt-in).
# Set DSMR_INGEST_ENABLED=true to subscribe to the DSMR MQTT topic and
# store 10-second downsampled telegram frames in dsmr_reading.
# DSMR_INGEST_ENABLED=false
# DSMR_MQTT_TOPIC=dsmr/json
# DSMR_SAMPLE_INTERVAL_S=10
# DSMR tariff topic: publishes "1" (dal/off-peak) or "2" (normal/peak).
# Empty string disables tariff-aware pricing (buy/sell_price_now always show normal rate).
# DSMR_TARIFF_TOPIC=dsmr/meter-stats/electricity_tariff
# Optional: Tibber dynamic pricing credentials (M6).
# Only used when an active energy contract with kind=tibber is configured.
# TIBBER_API_TOKEN=
# TIBBER_HOME_ID=
+49
View File
@@ -0,0 +1,49 @@
name: frontend
on:
push:
branches:
- "**"
pull_request:
workflow_dispatch:
jobs:
frontend:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
working-directory: frontend
run: npm ci
- name: Check codegen is in sync
working-directory: frontend
run: |
npm run codegen
git diff --exit-code src/api/schema.d.ts
- name: Lint
working-directory: frontend
run: npm run lint
- name: Type-check
working-directory: frontend
run: npm run typecheck
- name: Test
working-directory: frontend
run: npm run test
- name: Build
working-directory: frontend
run: npm run build
+1
View File
@@ -5,3 +5,4 @@
__pycache__/
*.pyc
data/
review-notes/
+208
View File
@@ -0,0 +1,208 @@
# AGENTS.md — Home Automation Backend
本文件是本仓库 coding agent 指引的 **single source of truth**`CLAUDE.md` 通过符号链接指向本文件。它定义本项目的**工作流程、文档位置、commit 规范**。支持对应项目指引的 agent 在动手前应完整读取本文件。
## 项目速览
- 个人用 home-automation 应用:**FastAPI + React SPA + SQLite + SQLAlchemy + Alembic**,前后端同源托管。
- 单 admin 鉴权(Argon2 + server-side session cookie),runtime config 落 `app_config` 表。
- 模块:public IPv4 monitor、SMTP 通知、location / poo recorder、Home Assistant in/out、TickTick OAuth、Modbus / DSMR 能耗采集、MQTT / HA Discovery、动态电价与电费计算。
- 已发布 `v1.5.1`。M1、M2、M4-M7 已完成;M3 token / 移动端仍为远期方向。
- **当前现实**:已收敛为单一 `app.db`、一套 DeclarativeBase 和一条 Alembic 链;只有历史数据迁移 runbook 会读取旧 location / poo 数据库。
- 明确不做:Notion 模块。
## 文档地图与「开工前必读」
文档都在 `docs/`
| 路径 | 作用 |
| --- | --- |
| `docs/roadmap.md` | 全局规划与里程碑总览 |
| `docs/design/README.md` | **协作契约**:任务卡格式、原子任务定义、校验闸门、数据安全红线 |
| `docs/design/m1-db-consolidation.md` | M1 原子任务(含真实代码现状盘点 + 人工 runbook) |
| `docs/design/m2-frontend-v2.md` | M2 原子任务 + API 契约 + 前端校验闸门 |
| `docs/design/m3-token-mobile.md` | M3(远期,暂缓) |
| `docs/design/m4-login-hardening.md` | M4 登录加固(已完成) |
| `docs/design/m5-iot-energy.md` | M5 IoT / 能耗采集(已完成) |
| `docs/design/m6-tibber-dynamic-energy.md` | M6 动态电价、DSMR 与电费计算(已完成) |
| `docs/design/m7-meter-epochs-archival.md` | M7 电表生命周期 / 换表归档(已完成) |
| `docs/*.md`auth / public-ip-monitor / location-recorder …) | 各模块说明,按需读 |
**开工时读取顺序**
1. `docs/design/README.md`(每轮都读,它是流程与验收的共同契约)。
2. 本轮对应的 milestone 文档(如 `docs/design/m1-db-consolidation.md`),定位要做的任务卡。
3. 任务卡 `Files` 列出的源文件 + 该模块的 `docs/*.md`(按需)。
4. `docs/roadmap.md` 仅在需要全局视角时读。
## 工作流程
### 实现模式(由用户的提示词决定)
- **默认逐步**:给一个 milestone 文档,按其中原子任务**一步一步**实现。
- **(a) 只实现一步**:用户说"只实现一步 / 这一个任务"时,**只做那一个任务卡**,跑完校验闸门后停下,等用户确认,不要顺手往下做。
- **(b) 完成整个 milestone**:仅当用户在提示词里**显式要求启用 sub-agent**时,才起 implementer / reviewer / fixer sub-agent(按下方**『默认能力档位』**选择模型,用户人工指定则覆盖),按任务依赖顺序跑完整条链。
- **Sub-agent 纪律**:只在用户显式要求时才 spawn sub-agent;单步/小改动在主线内联完成。当前 harness 支持独立 sub-agent 时,使用其原生机制按下方**『默认能力档位』**派发;不支持时不得假装已创建 sub-agent,应明确说明限制,并仅在用户允许 fallback 时由主 agent 继续。
### 默认能力档位(实现模式 sub-agent;可被人工指定覆盖)
起 implementer / reviewer / fixer sub-agent 时,**默认**按下列能力档位选择当前 harness 支持的模型,无需用户每次人工指定:
| 角色 | 通用模型要求 | 推理档位 | Harness 示例(非强制) |
| --- | --- | --- | --- |
| **Implementer** | 平衡型代码实现模型 | `medium` 或等效档位 | Claude CodeSonnetCodex/OpenAIGPT-5.6 Terra (`gpt-5.6-terra`) |
| **Fixer**(返工) | 平衡型代码实现模型 | `medium` 或等效档位 | Claude CodeSonnetCodex/OpenAIGPT-5.6 Terra (`gpt-5.6-terra`) |
| **Reviewer** | 当前 harness 支持的最强通用推理 / 代码模型 | `extra-high` / `xhigh` 或等效档位 | Claude CodeOpusCodex/OpenAIGPT-5.6 Sol (`gpt-5.6-sol`) |
- **示例非强制**:示例模型只表示当前推荐映射,不构成跨 harness 的硬性模型 ID;当前 harness 不支持时,选择最符合「通用模型要求」的可用模型。
- **选择优先级**:用户显式指定 > 当前 harness 的原生角色配置 > 上表的 harness 示例 > 按通用模型要求自动选择。
- **推理档位说明**:若 harness 提供独立的 reasoning-effort 设置,按上表设置;若不提供,在 spawn prompt 中明确 implementer/fixer 按平衡深度思考,reviewer 按对抗性外部审计强度复核。
### 角色(Orchestrator → Implementer → Reviewer → Fixer
- 我(主线)= **Orchestrator**:挑依赖已满足的下一个任务、派发、转述结果、维护任务 `Status`
- **Implementer**(平衡型代码实现模型,medium 或等效档位):一次一个任务,严格按任务卡,不扩范围。
- **Reviewer**(最强通用推理 / 代码模型,extra-high / xhigh 或等效档位):实现完成后起 Reviewer sub-agent,按任务卡 `Acceptance criteria` + `Reviewer checklist` 复核、**独立重跑校验闸门**,驱动返工直到本轮 PASS。
- **Fixer**(平衡型代码实现模型,medium 或等效档位):按 reviewer 的编号返工清单返工;**每轮返工起一个干净的 Fixer**(与首次实现的 Implementer 分开冷启动),先读对应 `review-notes/<task>-review-<n>.md` 再改。
#### Reviewer 盲审纪律(M1 教训)
M1 里 review **从未触发过一次 rework**,根因是 orchestrator 把自己的结论 / 辩护喂给了 reviewer,造成 context bleed、review 沦为橡皮图章。所以:
- reviewer 必须**使用全新、独立的 sub-agent / thread 冷启动,并最小化喂料**——spawn prompt 只给:① 任务卡(`Acceptance criteria` + `Reviewer checklist`)、② 对应的 `review-notes/<task>-impl|rework-<n>.md` 路径、③ 要审的 diff / commit 范围。
- **不要**在 prompt 里塞 orchestrator 自己的判断、"我觉得没问题"、对实现选择的辩护,或上一轮 reviewer 的倾向性结论。让它**独立得出结论、独立重跑校验闸门**。
- 事后另起的整库**独立盲审**(如对抗复审)同理:使用全新独立的 agent / thread、最小上下文,把它当"**外部审计**"而非"确认自己没错"。
### 校验闸门(每个任务结束都要全绿)
根目录、激活 `.venv` 后:
```bash
pytest # 权威闸门(CI 跑的就是它)
ruff check . # line-length=100
python scripts/export_openapi.py && git diff --exit-code openapi/ # 改了路由/schema 才需要,且产物须入库
```
前端任务(M2)在 `frontend/` 下另跑 `npm run lint && npm run typecheck && npm run test && npm run build`(详见 m2 文档 §8)。
**不过闸门就不算完成**,不得跳过、不得留红给下一轮。
**Repo-meta 例外**:纯文档、agent 指引、符号链接等不影响可执行代码、构建与 API 契约的变更,可在用户明确同意时跳过代码闸门。仍须完成针对性校验(如链接目标、文件类型、diff 与 Git 状态),并在结果中明确记录未运行哪些闸门。
#### API 契约同步:`openapi/` 与 `schema.d.ts` 是**两步**v1.4.0 后教训)
**只跑 `export_openapi.py` 不够。** 前端的 `frontend/src/api/schema.d.ts` 是由 `openapi/openapi.json` 二次生成的,CI`.github/workflows/frontend.yml`*Check codegen is in sync*)会重跑 codegen 并 `git diff --exit-code src/api/schema.d.ts`。漏了第二步 → 本地闸门全绿、远端 CI 红。真出过:`d07a083` 改了 `/api/energy/prices` 的 docstring 并同步了 `openapi.json`,但没重跑 codegen,只差一行注释就把 CI 挂了。
所以**只要动了路由 / Pydantic schema / 路由 docstring**docstring 也会进 OpenAPI description!),两步都要跑,两个产物都要入库:
```bash
# 1) 后端契约
python scripts/export_openapi.py && git diff --exit-code openapi/
# 2) 前端类型(在 frontend/ 下)
npm run codegen && git diff --exit-code src/api/schema.d.ts
```
- 判据:`git diff --exit-code openapi/` 有输出 → **必然**还要跑一次 `npm run codegen`
- 反过来也成立:`schema.d.ts` 不要手改,它是生成物。
- Reviewer 审"动了路由 / schema / 路由 docstring"类任务时,把**这两个产物是否都已重新生成并入库**当作 acceptance 的一部分。
### 构建上下文完整性(M1 Dockerfile 教训)
`docker build` **不在 pytest/ruff 闸门里**——M1 删了 `alembic_location/poo` 后忘了同步 `Dockerfile``COPY`,单元闸门全绿却把坏掉的镜像构建一路漏到 release tag。所以:
- 任务**删除 / 移动 / 重命名文件或目录**时,必须 grep 构建清单是否还在引用它们:`Dockerfile`(尤其 `COPY` 源)、`docker/``*.ini`、CI workflow、`requirements*.txt` 等。
- 已有回归测试 `tests/test_deployment.py::test_dockerfile_copy_sources_exist` 守"Dockerfile `COPY` 源必须存在于构建上下文";新增 / 改动 `COPY` 时确保它仍覆盖得到。
- Reviewer 审"删 / 移文件"类任务时,**必须顺带核对构建清单引用**,把它当 acceptance 的一部分。
## 每轮简报(`review-notes/`
由 milestone 任务卡驱动的每轮实现、返工或 review,都要在 `review-notes/` 下产出**中文简报**。该目录**已在 `.gitignore` 忽略**,纯本地、不入库——它是 agent 之间和与人之间的交接载体,不是仓库产物。纯讨论、只读分析与不进入正式任务链的 repo-meta 变更无需产出简报,除非用户明确要求。
- **实现 / 返工简报**:每轮实现完成后(无论首次实现还是返工),写一份。文件名建议 `<task-id>-impl-<n>.md` / `<task-id>-rework-<n>.md`(如 `M1-T03-impl-1.md``M1-T03-rework-1.md`)。至少包含:
1. **本轮修改的具体内容**(改了哪些文件、做了什么、为什么)。
2. **自动化测试结果**`pytest` / `ruff` / 前端闸门的实际输出或结论,通过/失败逐项写清)。
3. **若需人工 walkthrough**:写明具体步骤(怎么启动、点哪里、预期看到什么);若无需人工验证,明确写"无需人工 walkthrough"。
- **review 简报**:每轮 review 后写一份,文件名建议 `<task-id>-review-<n>.md`(如 `M1-T03-review-1.md`)。至少包含:评审结论(`PASS` 或带编号的返工清单)、对照任务卡 `Acceptance criteria` + `Reviewer checklist` 的逐条核对、reviewer 独立重跑校验闸门的结果。
**用途**:① reviewer 审核时参考对应的实现简报;② implementer 返工时参考对应的 review 简报;③ 人类(用户)通读这些简报确认有无问题。简报之间用文件名里的 `<task-id>` 与轮次 `<n>` 对应起来。
### Orchestrator 派发契约(让简报真正被读到)
**关键**:sub-agent 冷启动、不继承主线上下文,**不会因为本文件提到简报就自动去读**对应文件。简报能流转,靠的是 orchestrator(主线)在**每次 spawn 时把路径显式写进 prompt**,而不是被动约定。所以派发时必须做到:
- **显式告诉它「先读哪个简报」**:
- 派 implementer 做**首次实现** → 传任务卡位置(milestone 文档路径 + task id);无前置简报。
- 派 implementer 做**返工** → 必须传对应的 `review-notes/<task>-review-<n>.md` 路径,并要求**先读它**再改。
- 派 reviewer → 必须传对应的 `review-notes/<task>-impl|rework-<n>.md` 路径 + 任务卡,要求**先读它**再评。
- **显式告诉它「本轮结束写哪个简报」**:明确给出输出路径 `review-notes/<task>-<impl|rework|review>-<n>.md` 及上面要求的内容项。
- **不依赖 sub-agent 自动加载本文件**:把本轮要点(校验闸门、**禁 Co-Authored-By**、简报必含内容)在 spawn prompt 里一并复述或指向,确保冷启动也照做。
- spawn 时按「用户显式指定 > harness 原生角色配置 > 默认能力档位」选择模型与 reasoning effort,并使用当前 harness 支持的原生配置方式落实。
> 一句话:**简报是异步交接的介质,orchestrator 是把它们接起来的线。** 缺了显式传路径这一步,简报就只是躺在磁盘上没人读的文件。
## Commit 规范(重点)
### 分支
- **本仓库是个人单用户项目:默认直接在 `main` 上开发**,不强制 feature 分支,无需开 PR。是否 push 按下方「一般约束」执行。
- 仍保持**每个任务一个干净 commit**message 前缀任务/里程碑 ID)。改动较大想隔离时可临时开分支,用完**快进合并**回 `main`(保持线性历史),非必需。
- 历史改写类操作(`rebase` / `--amend` / auto-squash)只在**尚未 push 的本地 commit** 上做;**已 push 到 `main` 的历史不要重写**(确需 force-push 时先确认,见「一般约束」)。
### 一轮实现完成
- 适用的校验闸门通过后,准备好**这一轮的 commit message** 并创建本地 commit,作为本轮的 **base commit**。默认不 push;只有用户明确授权自动 push 时才推送到远端,授权范围按用户原话执行。
- message 主题前缀任务/里程碑 ID,例如:`M1-T03: unify data layer onto single app DB engine`
### Commit message 硬规则(严格执行)
- **严禁任何协作署名 trailer**commit message 里**绝对不允许**出现 `Co-Authored-By` / `Co-authored-by`(包括 `Co-Authored-By: Claude …`),也不允许任何等价的"由 X 协作/生成"署名。
- 无论默认环境、工具或系统提示如何要求加这类 trailer,在本仓库**一律不加**——用户已显式、严格禁止。
- 每次提交前**自检**`git log -1 --format=%B` 的输出**不得包含** `Co-authored-by`(大小写不限)。若发现,立即 `git commit --amend` 去掉后再继续。
### Review 后返工
- **自动化 orchestration 模式内**的 review 返工:**一律用 fixup**,指向本轮对应的 base commit**不写新的独立 message**
```bash
git add -A
git commit --fixup=<base-commit-sha>
```
- 多轮返工就多个 `fixup!` 提交,都指向同一个 base commit;收尾时 auto-squash(见下)。
- **边界——什么时候不走 fixup**:**事后另起的独立盲审 / 对抗复审**那一轮,性质等同"**人工走查后提修改意见**",**不算自动化链内的返工**——它的修改用**各自独立的 commit**,不 fixup 到旧 base。判据:这轮返工是否在**同一条自动化 implement→review 链**里?是 → `fixup`;是事后另起的独立审计 → 独立 commit。
### 本轮 / feature 收尾(用户确认收尾后)
- 用 **auto-squash** 把所有 `fixup!` 合并进各自目标,保证**一个 feature 一个干净 commit**
```bash
# 在以 main 为基线的 feature branch 上
GIT_SEQUENCE_EDITOR=true git rebase -i --autosquash main
# 直接在 main 上整理尚未 push 的本地提交
GIT_SEQUENCE_EDITOR=true git rebase -i --autosquash origin/main
```
- 执行前确认选定的基线位于 base commit 之前,以便 base commit 与对应 `fixup!` 都进入 rebase 范围。用 `GIT_SEQUENCE_EDITOR=true` 让它**非交互**执行(不弹编辑器,自动接受 autosquash 排好的 todo)。
- autosquash **改写历史**:仅在 push / 开 PR **之前**做。若该分支已 push,需要 force-push——属对外操作,**先取得用户确认再做**。
### 一般约束
- **个人单用户仓库:默认直接在 `main` 上开发并创建本地 commit**。默认不 push;只有用户明确授权自动 push 时才推送到远端。
- 始终需要**单独、明确授权**的操作:**force-push / 改写已推送历史**,以及**打 tag**(会触发镜像 CI / 对外发布;且打 tag 前须按下方「发版前置走查」真跑一次 `docker build`)。
## 发版前置走查(打 tag 前必做)
单元闸门绿 ≠ 真的能跑、能构建、能用。M1 出过"绿了但 docker 构建坏了"的事故,所以**打版本 tag(触发镜像 CI)之前**,除了 `pytest` / `ruff` 全绿,还要:
- **真起 app**:迁移(`python -m scripts.run_migrations`)→ `uvicorn app.main:app ...`,确认能正常启动、关键路由不 500。
- **真跑镜像构建**:本地 `docker build`(多阶段就跑完整条),确认构建通过、`COPY` 源都在。
- **关键功能人工瞄一眼**:尤其前端 / 可视化类(M2 的热力图、首页地图)——自动闸门判断不了"渲染对不对、UX 顺不顺",这部分**靠看跑起来的 app,不靠读代码**。
- 上述任一不过 → **不打 tag**。tag 一旦 push 会触发 docker 镜像 CI / 对外发布,属对外操作,**先确认**。
## 数据安全红线(不可违反)
- 任何脚本 / migration **都不得删除或覆盖用户数据文件**(旧 `.db`、备份、volume)。删除只能是人工、事后、保留归档的独立步骤(见 `docs/design/m1-db-consolidation.md` §6 runbook)。
- 涉及历史数据的迁移**先在备份副本上演练**;迁移脚本必须幂等且搬完对账行数。
- Review 时只要发现"删文件 / drop 有数据的表 / truncate"出现在自动化任务里,直接判返工。
## 常用命令
```bash
# 环境
python -m venv .venv && source .venv/bin/activate && pip install -r dev-requirements.txt
# 迁移(初始化/适配 DB
python -m scripts.run_migrations
# 起服务
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
# 测试 / lint / OpenAPI 导出
pytest
ruff check .
python scripts/export_openapi.py
```
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+21 -4
View File
@@ -1,3 +1,20 @@
# Stage 1: build the React SPA.
# Pin to the native build host ($BUILDPLATFORM) so the Node/V8 build never runs
# under QEMU during multi-arch builds — emulated Node crashes V8's baseline JIT
# (SIGTRAP / exit 133 on `npm ci`). The dist/ output is static JS/CSS, i.e.
# architecture-independent, so building it once and COPYing it into each
# target-arch runtime stage is both correct and avoids the emulator entirely.
FROM --platform=$BUILDPLATFORM node:22-slim AS frontend-build
WORKDIR /frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
RUN npm run build
# Stage 2: python runtime (no node)
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
@@ -11,15 +28,15 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
COPY alembic_app ./alembic_app
COPY alembic_app.ini ./
COPY alembic_location ./alembic_location
COPY alembic_location.ini ./
COPY alembic_poo ./alembic_poo
COPY alembic_poo.ini ./
COPY scripts ./scripts
COPY docker ./docker
COPY README.md ./
RUN mkdir -p /app/data
# Copy the built SPA dist from the frontend-build stage
COPY --from=frontend-build /frontend/dist ./frontend/dist
EXPOSE 8000
ENTRYPOINT ["/app/docker/entrypoint.sh"]
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+415 -60
View File
@@ -4,14 +4,25 @@
当前系统已经包含:
- FastAPI Web 应用与服务端模板页面
- SQLite + SQLAlchemy + Alembic 的库结构
- username/password + server-side session 鉴权
- FastAPI Web 应用React SPA 前端 + JSON API
- SQLite + SQLAlchemy + Alembic 的库结构
- username/password + server-side session 鉴权(含登录加固,见下文)
- runtime config 页面与 app DB 持久化
- public IPv4 monitor、历史持久化与定时检查
- SMTP 配置、测试发信与 public IPv4 changed 邮件通知
- location recorder
- poo recorder
- Home Assistant inbound / outbound integration
- Home Assistant inbound / outbound integrationREST 通道)
- TickTick OAuth 与 action task 集成
- **Modbus 设备采集**:通过 YAML profile(首个:SDM120 电表)按设备周期轮询 Modbus-TCP 网关,解码工程量并落通用读数表(`modbus_device` + `modbus_reading`
- **MQTT + Home Assistant Discovery**:以可勾选方式把 Modbus 设备/工程量注册为 HA device/entity(含 binary_sensor online),state 周期发布;配置变更可重连重发
- **前端侧边栏 + Energy 视图**:侧边导航替换顶栏;Energy 页管理 Modbus 设备、展示最新读数与 Recharts 走势图;Config 页 Accordion 分区展开;Expose 设置勾选 HA 可暴露实体
- **DSMR 实时电表接入**:订阅 DSMR Reader 的 `dsmr/json`(每秒一帧)、整帧 JSON blob 按 10 秒降采样落库(`dsmr_reading`
- **通用电价合同层**YAML profile 定合同结构(manual 固定/双费率 / tibber 动态电价);`EnergyContract`+`EnergyContractVersion` 存 UI 可填的数值,改价加新版本旧版本保留;price strategy 按 kind 出价
- **实时买卖电费计算**:每 15 分钟按寄存器差值(`_1`=dal/低、`_2`=normal/高)× 买/卖价算计量电费,快照不可变;日/月/年汇总加固定费减 heffingskorting
- **反哺 Home Assistant Energy**:当前买/卖价 + 累计买电支出/卖电收入(`total_increasing`)发成 HA 实体,可直接挂 HA Energy 仪表盘
- **多数据源 Meter 与 WarmteLink**DSMR MQTT 与只读 WarmteLink P1 serial source 统一为 Source → Channel → Binding → MeterWarmteLink 提供 heating `GJ` 与 hot-water `m³` 的 Decimal history、质量与重连
- **热力合同与成本**electricity / thermal scope 可各有一个 active 合同;热力按 15 分钟账本计算 variable、fixed 与 all-in 成本,并可按需暴露给 HA
- pytest 测试与 OpenAPI 导出脚本
- Docker / Compose 部署入口
@@ -21,43 +32,46 @@
## 当前配置现实
当前系统仍然是三个独立的 SQLite 数据库文件,而不是单一数据库
当前系统使用单一 SQLite 数据库文件`app.db`),所有数据表都在其中
- `app` 级共享数据使用自己的 DB 文件
- `location` 模块使用自己的 DB 文件
- `poo` 模块使用自己的 DB 文件
- auth(单个 admin 用户、server-side session
- runtime config 持久化(`app_config` 表)
- public IPv4 当前状态与变化历史
- location 记录(`location` 表)
- poo 记录(`poo_records` 表)
- Modbus 设备定义(`modbus_device` 表)
- Modbus 通用读数(`modbus_reading` 表,JSON payload
- HA 实体暴露开关(`exposed_entity_toggle` 表)
- DSMR 电表实时读数(`dsmr_reading` 表,整帧 JSON blob10s 降采样)
- 电价合同(`energy_contract` 表)与版本(`energy_contract_version` 表,values JSON
- Tibber 15 分钟电价缓存(`tibber_price` 表,不可变)
- 每 15 分钟计量电费(`energy_cost_period` 表,快照价,不可变)
- meter source、channel 与 binding`meter_source``meter_source_channel``meter_source_binding`
- WarmteLink scalar 历史(`warmtelink_reading`)与热力 15 分钟成本账本(`meter_cost_period`
当前阶段明确不借这次重构把这些 DB 合并。配置层已经显式反映这一点
配置层只保留一个数据库环境变量
- `APP_DATABASE_URL`
- `LOCATION_DATABASE_URL`
- `POO_DATABASE_URL`
目前 auth、`location``poo` 都已经接到各自独立的数据库文件。
`app.db` 不会在应用启动时自动创建,需要先运行:
其中 `app` 级共享 DB 当前主要用于:
```bash
python -m scripts.run_migrations
```
- 单个 admin 用户
- server-side session
- runtime config 持久化
这部分现在也使用 Alembic 管理:
- `app db` 不会在应用启动时自动创建
- 需要先运行 `python scripts/app_db_adopt.py`
- 这个脚本会创建新 DB 并建好 schema
该命令会通过 Alembic 将 `app.db` 初始化或升级到最新 head(包括 Modbus、DSMR、Source/Channel/Binding、WarmteLink、electricity/thermal 合同与成本账本)。
## 当前目录
主要目录如下:
- `app/`: FastAPI 应用代码
- `alembic_app/`: App DB 的 Alembic migration 环境
- `alembic_location/`: Location DB 的 Alembic migration 环境
- `alembic_poo/`: Poo DB 的 Alembic migration 环境
- `app/`: FastAPI 应用代码(包含 JSON API、业务服务、数据模型)
- `frontend/`: React SPA 前端(Vite + React + TypeScript + Mantine
- `alembic_app/`: App DB 的唯一 Alembic migration 环境(管理所有 app 表,包括 Modbus、DSMR、Meter source、WarmteLink、合同与成本账本)
- `tests/`: pytest 测试
- `docs/`: 当前系统说明文档
- `scripts/`: 辅助脚本,例如 OpenAPI 导出
- `openapi/`: OpenAPI schema 静态产物(`openapi.json` / `openapi.yaml`),纳入版本控制
## 依赖管理
@@ -107,9 +121,7 @@ cp .env.example .env
3. 初始化数据库
```bash
python scripts/app_db_adopt.py
python scripts/location_db_adopt.py
python scripts/poo_db_adopt.py
python -m scripts.run_migrations
```
4. 启动服务
@@ -120,30 +132,81 @@ uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
启动后可访问:
- 应用首页:`http://localhost:8000/`
- 应用首页React SPA`http://localhost:8000/`
- 健康检查:`http://localhost:8000/status`
- Swagger UI`http://localhost:8000/docs`
- ReDoc`http://localhost:8000/redoc`
## 前端 v2React SPA
M2 用 React SPA 取代了原有 Jinja 服务端模板,由 FastAPI 同源托管(同一容器、同一 origin)。
### 技术栈
- **Vite + React + TypeScript + Mantine**(组件库)
- **TanStack Query**(数据请求/缓存)
- **Leaflet / react-leaflet**(地图与热力图)
- **Recharts**Energy 视图走势图,M5 引入)
- **openapi-typescript + openapi-fetch**(类型化 API client,由 `openapi/openapi.json` 生成)
### 本地开发(前端)
前端开发服务器会把 `/api``/location``/poo``/public-ip``/homeassistant``/ticktick``/status` 等路径代理到后端 FastAPI`:8000`)。
```bash
cd frontend
npm install
npm run dev # 启动 Vite dev server(默认 :5173),代理后端
```
### 构建
```bash
cd frontend
npm run build # 产出 frontend/dist
```
FastAPI 启动时若 `frontend/dist/index.html` 存在,则自动挂载该目录,并对非 `/api` 路径做 SPA fallback(返回 `index.html`)。该路径可通过环境变量 `SPA_DIST_DIR` 覆盖(默认值为 `frontend/dist`,与多阶段 Dockerfile 中 `COPY``/app/frontend/dist` 一致)。
### 类型化 API Client
前端 API client 由后端 OpenAPI schema 自动生成:
```bash
cd frontend
npm run codegen # 从 ../openapi/openapi.json 生成 src/api/schema.d.ts
```
生成物(`src/api/schema.d.ts`)已提交入库,CI 会校验它与 `openapi/openapi.json` 保持同步。
### 前端校验闸门
```bash
cd frontend
npm run lint # ESLint
npm run typecheck # TypeScript 类型检查
npm run test # Vitest 单元测试
npm run build # 构建,确认产出 dist
```
## 数据库与 Alembic
当前默认使用 SQLite,并区分三个数据库文件:
当前使用单一 SQLite 数据库文件:
- App DB`sqlite:///./data/app.db`
- Location DB`sqlite:///./data/locationRecorder.db`
- Poo DB`sqlite:///./data/pooRecorder.db`
- 数据目录:`./data/`
初始化 migration 环境后,可继续添加模型并生成迁移
所有模型(auth / config / public_ip / location / poo / modbus / expose)共用同一个 `Base`,均通过单一 Alembic 链管理
当前 `app``location` `poo` 都已经有各自独立的 Alembic 链路。
- Alembic 环境:`alembic_app.ini` + `alembic_app/`
- 统一 migration job`python -m scripts.run_migrations`
- App DB 接管 / 初始化:`python scripts/app_db_adopt.py`
- App Alembic 环境:`alembic_app.ini` + `alembic_app/`
- Location Alembic 环境:`alembic_location.ini` + `alembic_location/`
- Poo Alembic 环境:`alembic_poo.ini` + `alembic_poo/`
- App DB 初始化:`python scripts/app_db_adopt.py`
- Location DB 接管 / 初始化:`python scripts/location_db_adopt.py`
- Poo DB 接管 / 初始化:`python scripts/poo_db_adopt.py`
历史 location / poo 数据(旧版本遗留的独立 DB 文件)已通过以下脚本一次性迁移至 `app.db`(幂等,不删除旧文件):
```bash
python -m scripts.migrate_legacy_data
```
## 基础鉴权
@@ -151,9 +214,9 @@ uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
- 认证模型:`username/password`
- 会话模型:server-side session + cookie
- 当前主要受保护页面:`/config`
- 当前公开页面:`/login`
- 当前公开 API现有业务 API 暂未在这一轮统一收口到 auth 下
- 当前受保护入口:React SPA`/` 等客户端路由)调用 `/api/*` JSON 端点
- 当前公开页面:`/login`SPA 登录页)
- 当前公开 API裸 ingestion 端点(`/location/record``/poo/record` 等设备调用端点)暂未收口到 session 保护(M3 再做)
安全实现的当前边界:
@@ -161,7 +224,7 @@ uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
- session cookie 使用 `HttpOnly`
- `Secure` 默认随 `APP_ENV` 切换:非 development 时默认开启
- `SameSite=Lax`
- 登录表单和登出表单都有基础 CSRF 防护
- 写请求(POST/PUT/PATCH/DELETE)需携带 `X-CSRF-Token` headerSameSite=Lax + 自定义 header 纵深防御,无需 per-session token 值比对)
首次启动时,如果 `APP_DATABASE_URL` 对应的 auth DB 里还没有用户,应用会使用:
@@ -175,12 +238,203 @@ uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
首次登录后会被要求立即修改密码。这个 bootstrap 只用于首个用户落库,不是后续的完整配置管理方案。
当前前端主要有两条页面路径
React SPA 主要页面路由(客户端路由,均由 FastAPI fallback 到 `index.html`
- `/login`
- `/config`
- `/login`:登录页
- `/`:首页(地图热力图主视图)
- `/config`:配置页(取代原 Jinja `/config`
- `/records`:记录管理列表页
无论是本地 `host:port` 还是反向代理后的域名访问,登录成功后都使用相对路径跳转到 `/config`
无论是本地 `host:port` 还是反向代理后的域名访问,登录成功后进入 SPA 首页(`/`
## M4 登录加固
M4 在基础鉴权之上叠加了三层防御,详细说明见 [`docs/auth.md`](./docs/auth.md)。
### 防爆破 / 指数退避
登录失败超过 3 次后进入指数退避(`wait = min(900s, 1s × 2^(failures-3))`),期间请求返回 `429 Too Many Requests`(含 `Retry-After` 响应头);成功登录后自动清零。退避按 **client IP****username** 双键取较大值,不会因此永久锁定账号(只是延迟,不是封号)。
- 全局开关:`AUTH_LOGIN_THROTTLE_ENABLED`CONFIG_FIELDS,默认 `true`
- 反代后需要 `AUTH_TRUST_FORWARDED_FOR=true` 才会读 `X-Forwarded-For``.env` 部署级配置,默认 `false`
### CLI 逃生通道
拿到服务器 CLI 权限时,可以在**不依赖任何已存凭据**(无需密码、恢复码)的情况下重置密码、解锁退避、关停 TOTP:
```bash
# 重置密码(不加 --password 则交互式输入,不回显)
python -m scripts.admin_cli reset-password admin
# 解锁退避(被 429 挡住时使用)
python -m scripts.admin_cli unlock --all # 清所有退避行
python -m scripts.admin_cli unlock --ip 1.2.3.4 # 按 IP 清
python -m scripts.admin_cli unlock --username admin # 按 username 清
# TOTP 相关(需要先启用,见下文)
python -m scripts.admin_cli disable-totp admin # 关停 TOTP(零凭据,逃生口)
python -m scripts.admin_cli reissue-totp admin # 重新发放 TOTP secret(打印新 URI
# 查看用户列表
python -m scripts.admin_cli list-admin
```
在 Docker 容器内执行时:
```bash
docker compose exec app python -m scripts.admin_cli <command>
```
### 可选 TOTP 二次验证
admin 可在 React SPA 设置页(`/config`)自选启用 RFC 6238 TOTP
1. 设置页点「启用 TOTP」→ 后端生成 `otpauth://` URI,前端渲染二维码(`qrcode.react`
2. 用 Authenticator App(如 Google Authenticator、Authy)扫码
3. 输入当前 6 位动态码确认 → TOTP 启用
4. 妥善保存一次性展示的 10 个恢复码(格式 `xxxx-xxxx`
启用后,登录需要两步:密码 → 6 位动态码(或恢复码,一次性)。不启用则维持纯密码登录,行为不变。
恢复码丢失时,可用 CLI 逃生:`python -m scripts.admin_cli disable-totp admin`,随后即可纯密码登录。
TOTP issuer 标签(显示在 Authenticator 里)通过 `AUTH_TOTP_ISSUER` 环境变量配置(`.env` 部署级),默认回退 `app_name`
## M5 Modbus 设备采集 / Energy / MQTT + HA Discovery
M5 给后端接入家庭 IoT 生态,新增通用 Modbus 采集链路(首个领域:能耗)、MQTT + Home Assistant Discovery 发布,以及前端侧边栏与 Energy 视图。
### 依赖
后端新增:
- `pymodbus`Modbus-TCP 客户端(轮询电表等 slave 设备)
- `paho-mqtt`MQTT 客户端(HA Discovery 与 state 发布)
- `pyyaml`YAML profile 加载(设备协议声明式描述)
前端新增:
- `recharts`Energy 视图走势图
### Modbus 设备采集
采集链路采用两层分离:**YAML profile**(协议知识,随代码走)+ **`modbus_device` 数据库行**(部署/可配置信息)+ **`modbus_reading` 通用读数表**JSON payload 遥测)。
- **profile**(如 `sdm120.yaml`)描述:读哪些寄存器(FC04 块读)、每个量的 key/unit/device_class/ha_component。纯协议知识,不含 unit_id / friendly_name 等部署项。
- **`modbus_device` 行**friendly_name、网关 host/port、Modbus slave `unit_id`(电表 Meter ID,设备面板可改故落 DB)、选用哪个 profile、采样周期、是否启用。
- **`modbus_reading` 行**device_id FK、recorded_at、payloadJSON,如 `{"voltage": 230.2, "current": 1.3, ...}`)。
- 多设备可共享同一 profile(如两块 SDM120 共用 `sdm120` profile,各自独立 unit_id 和 friendly_name)。
- APScheduler 后台 job 周期轮询所有 `enabled` 设备,更新 `last_poll_at` / `last_poll_ok`。全局开关 `MODBUS_POLLING_ENABLED`CONFIG_FIELDS)。
**手工命令行试读**(不依赖 DB,最快验证网关连通性):
```bash
# 按 profile 解码读一次(验证整套解码链路)
python -m scripts.modbus_cli read --host <网关IP> --port 502 --unit 1 --profile sdm120
# 手工指定请求内容(first-contact 验证,不依赖 profile
python -m scripts.modbus_cli probe --host <网关IP> --port 502 --unit 1 --fc 4 --address 0x0000 --count 2 --decode float32
```
CLI 工具为受控手工验证而设(设备需接市电),仅暴露读功能码(FC03/04),无写寄存器子命令。
### MQTT + Home Assistant Discovery
后端作为 MQTT 发布方,把 Modbus 设备/工程量以 HA Discovery 协议自动注册为 device/entity
- 每个 Modbus 设备 = 一个 HA device`unique_id` 锚定于设备 `uuid`,不随改名变)
- 各工程量 = sensor entitydevice_class/unit 取自 YAML profile);另有 binary_sensor `online`(取 `last_poll_ok`
- 每次轮询成功后推 state topic;连接成功或勾选变更时重发 retained discovery config
- `POST /api/config/mqtt/test`:试连 broker 并发布一条测试消息(可用 MQTT Explorer 验证链路)
**Config 页配置流程**
1.`/config` 的「MQTT」section 填写 broker host/port/username/password,启用 `MQTT_ENABLED`
2. 点「发送测试消息」确认 broker 链路通
3. 启用 `HA_DISCOVERY_ENABLED`
4. 在「Home Assistant Expose」面板勾选要暴露的实体,点「重新发布 discovery」
5. 在 Home Assistant 确认对应 device/entity 出现
### API 端点(M5 新增)
| 端点 | 用途 |
| --- | --- |
| `GET /api/modbus/devices` | 列出 Modbus 设备 |
| `POST /api/modbus/devices` | 新建设备 |
| `GET /api/modbus/devices/{uuid}` | 单个设备 |
| `PATCH /api/modbus/devices/{uuid}` | 修改设备(含 enable/disable|
| `DELETE /api/modbus/devices/{uuid}` | 删除设备;有读数时 409 |
| `GET /api/modbus/devices/{uuid}/metrics` | 该设备 profile 的量目录(key/unit/device_class|
| `GET /api/modbus/devices/{uuid}/latest` | 最新一条读数 payload |
| `GET /api/modbus/devices/{uuid}/readings` | 时间范围读数(start/end/limit),供走势图 |
| `POST /api/modbus/devices/{uuid}/test` | 即时试读(不落库) |
| `GET /api/modbus/profiles` | 列出可用 profile 名 + 描述 |
| `GET /api/expose` | 可暴露实体目录 + 勾选状态 + MQTT/Discovery 状态 |
| `PUT /api/expose` | 设置逐 key 暴露开关 |
| `POST /api/expose/republish` | 手动重发 discovery |
| `POST /api/config/mqtt/test` | 试连 broker 并发布测试消息 |
### 前端视图(M5 新增)
- **侧边栏**:把顶栏改为侧边导航(Home / Records / Energy / Config + 主题切换 + 注销),当前路由高亮,移动端可折叠。
- **`/energy`Energy 视图)**:设备 CRUD(新建/编辑/删除,删除有二次确认;有读数时引导改用禁用);最新读数卡片(字段标签/单位取自 profile metrics);时间序列走势图(Recharts,支持电压/电流/功率/电能,带时间范围选择)。
- **Config 页 Accordion**:各大 config section 可独立折叠/展开;「Home Assistant Expose」面板按设备分组勾选可暴露实体、显示 MQTT/Discovery 连接状态、「重新发布 discovery」按钮。
- SPA 路由新增 `/energy`
## M6 DSMR 接入 / 电价合同 / 实时电费计算 / HA Energy 反哺
M6 在 M5 IoT 基建之上接入 DSMR 实时智能电表数据,建立通用电价合同层,按每 15 分钟算出实际买卖电费并反哺 HA Energy。
### 依赖
M6 **不新增任何 Python 依赖**,复用 M5 已有的 `httpx`Tibber GraphQL)、`paho-mqtt`DSMR 订阅)、`pyyaml`pricing profile 加载)、`apscheduler`(抓价 job、计费 job)。
### DSMR 实时电表接入
订阅 DSMR Reader 的 `dsmr/json` topic(每秒一帧完整 telegram),整帧存为 JSON blob、按 `dsmr_sample_interval_s`(默认 10 秒)降采样落 `dsmr_reading``source_id` 幂等去重)。`dsmr_ingest_enabled`(默认 falseopt-in)。
### 电价合同层
- **YAML profile 定结构**(仓库内,不放数值):`manual.yaml`(固定/双费率:buy_normal/dal、sell_normal/dal、energy_tax、ode、固定费、heffingskorting);`tibber.yaml`(动态:source=tibber_apienergy_tax、sell_adjust
- **`EnergyContract` + `EnergyContractVersion`**(UI 填数值):改价 = 加新版本行(带 `effective_from`),旧版本保留(审计链);一次只有一个 active 合同
- **price strategy**`manual` 用双费率常数(`buy = energy_buy_档 + energy_tax``sell = sell_档`);`tibber``tibber_price.total` 作买价(已含税,demo 确认 `total=energy+tax`),`total energy_tax sell_adjust` 作卖价(卖价残差 `sell_adjust` 默认 0,待真实账单核定)
### 每 15 分钟计量电费(不可变)
APScheduler 1 分钟 tick,取每个闭合 15 分钟窗口的 DSMR 寄存器差值(`delivered_1/2``returned_1/2``_1`=dal/低,`_2`=normal/高,NL 惯例)× 当时合同版本的 strategy 出价,upsert `energy_cost_period`(快照当时价 + `contract_version_id`)。缺价/缺数据时标 `degraded``POST /api/energy/costs/recompute` 显式重算。
日/月/年汇总 = Σnet + 固定费(network_fee + management_fee 按月→天 × 天数)- heffingskorting(按年→天 × 天数),读时计算、不落表。能源税 `energy_tax` 参考值约 0.1108 EUR/kWh2026 第一档含 VAT,待真实账单核定;该值由 UI 填入合同版本,YAML profile 仅声明字段 unit,代码无写死默认数值)。
### Tibber 动态电价
`app/integrations/tibber/client.py` httpx POST GraphQL`priceInfoRange(QUARTER_HOURLY, first=96)`),解析 `startsAt`/`total`/`energy`/`tax`/`level`,按 `starts_at` upsert `tibber_price`(幂等)。启动 + 每小时抓取今明两天 15 分钟价、幂等 upserthourly trigger,确保每日刷新且可补重试);仅当 active 合同 kind=tibber 且 `tibber_api_token` 存在时运行。`POST /api/energy/tibber/test` 试连三态(success 带当前价 / config-error / failed)。
### 反哺 Home Assistant Energy
`_energy_cost_provider` 向 expose 框架注册 4 个实体:`buy_price_now``sell_price_now`(€/kWh sensor)、`import_cost_total``export_revenue_total``total_increasing` monetary,可直接挂 HA Energy 仪表盘)。默认未勾选,在 Expose 面板启用。
### API 端点(M6 新增)
| 端点 | 用途 |
| --- | --- |
| `GET /api/energy/contracts` | 列出合同 + active 标记 |
| `POST /api/energy/contracts` | 新建合同(kind + 首版本值,按 profile 校验)|
| `GET /api/energy/contracts/{id}` | 单个合同 + 版本历史 |
| `PATCH /api/energy/contracts/{id}` | 改名 / 激活 |
| `POST /api/energy/contracts/{id}/versions` | 加新版本(改价,带生效日期)|
| `GET /api/energy/profiles` | 列出 pricing profile 结构(前端按它渲染表单)|
| `GET /api/energy/prices` | 区间价格点(曲线)|
| `GET /api/energy/costs` | 区间 `energy_cost_period`(走势/明细)|
| `GET /api/energy/costs/summary` | 区间汇总(计量电费 + 固定费 − 抵扣)|
| `POST /api/energy/costs/recompute` | 幂等重算 |
| `GET /api/energy/dsmr/latest` | 最新 `dsmr_reading` |
| `POST /api/energy/tibber/test` | 试连 Tibber + 拉当前价,三态 |
DSMR/Tibber 标量配置复用现有 `GET/PUT /api/config`(新增 `dsmr_ingest_enabled``dsmr_mqtt_topic``dsmr_sample_interval_s``tibber_api_token`secret)、`tibber_home_id`)。
### 前端视图(M6 新增,并入 Energy 视图)
- **Contracts Tab**:合同列表 + 新建/编辑(表单按 `/api/energy/profiles` 结构渲染,不 hardcode 字段)+ 激活 + 改价加版本 + 版本历史只读。
- **Prices Tab**15 分钟价格曲线(tibber 动态或 manual 档位),复用 Recharts。
- **Costs Tab**:费用走势/明细 + 汇总卡片(含固定费/抵扣)。
- **Config 页 Tibber 测试**:三态(success/config-error/failed)。
## Config 持久化
@@ -195,11 +449,89 @@ uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
这意味着:
- location / poo / app DB 地址仍然属于 bootstrap 范畴
- app DB 地址`APP_DATABASE_URL`仍然属于 bootstrap 范畴
- 运行时可编辑配置主要通过 `app_config` 表持久化
- token / secret 这类运行时必须可取回的配置,目前允许明文存储在 config 表中
- 登录密码仍然单独使用 Argon2 哈希,不走 config 表明文存储
当前已经接入 config 页面的运行时配置包括:
- 基础系统配置
- auth cookie 相关配置
- SMTP 基础配置
- TickTick OAuth 配置
- Home Assistant 配置
- MQTT broker 配置(`MQTT_ENABLED``MQTT_BROKER_HOST/PORT/USERNAME/PASSWORD``MQTT_TLS_ENABLED`
- Home Assistant Discovery 配置(`HA_DISCOVERY_ENABLED``HA_DISCOVERY_PREFIX`
- Modbus 采集配置(`MODBUS_POLLING_ENABLED`
- DSMR 接入配置(`DSMR_INGEST_ENABLED``DSMR_MQTT_TOPIC``DSMR_SAMPLE_INTERVAL_S`
- Tibber 凭据(`TIBBER_API_TOKEN`secret)、`TIBBER_HOME_ID`
其中 SMTP password 与其他 secret 字段一致:
- 页面不明文回显
- 留空提交时保留旧值
- 用于测试发信与自动通知时不会写入响应
## Public IPv4 Monitor
当前系统已经提供最小可用的 public IPv4 monitor
- 使用单一 provider 检查当前公网 IPv4
- 将状态与变化历史持久化到 app DB
- 提供受保护的手动检查入口:`GET /public-ip/check`
- 启动时注册 APScheduler job,默认每 4 小时检查一次
当前 app DB 中与此功能相关的新表:
- `public_ip_state`
- `public_ip_history`
状态语义如下:
- `first_seen`:首次发现当前公网 IPv4
- `unchanged`:与上次状态一致
- `changed`:公网 IPv4 发生变化
- `error`:provider 请求失败或返回无效值
## SMTP 与邮件通知
当前系统已经提供最小可用的 SMTP 能力:
- SMTP 配置可在 React SPA `/config` 页面填写并保存到 `app_config`(通过 `PUT /api/config`
- 可通过 config 页面发送测试邮件(`POST /api/config/smtp/test`
- 邮件 `From` 头支持显示名,例如 `Home Automation <sender@example.com>`
当前 SMTP 配置项包括:
- `SMTP_ENABLED`
- `SMTP_HOST`
- `SMTP_PORT`
- `SMTP_USERNAME`
- `SMTP_PASSWORD`
- `SMTP_FROM_NAME`
- `SMTP_FROM_ADDRESS`
- `SMTP_TO_ADDRESS`
- `SMTP_USE_STARTTLS`
当前 public IPv4 monitor 已与 SMTP sender 接通,但只处理一个很小的通知场景:
- 当 public IPv4 check 结果为 `changed` 时,自动发送一封英文纯文本邮件
以下情况不会发邮件:
- `first_seen`
- `unchanged`
- `error`
当前通知邮件内容固定,不提供模板系统,正文会包含:
- previous IP
- current IP
- detected time
手动测试时,如果需要再次模拟一次 IP 变化,可以临时修改 `public_ip_state.current_ipv4` 为一个保留测试地址,然后再次调用 `GET /public-ip/check`
## OpenAPI
可使用下面的脚本重新导出当前 API 定义:
@@ -219,18 +551,34 @@ python scripts/export_openapi.py
当前 Compose 分成两层:
- `docker-compose.yml`:默认使用 registry image,适合部署 / 生产拉取
- `docker-compose.override.yml`仅为本地开发追加 `build: .`
- `docker-compose.yml`:默认使用 registry image,适合部署 / 生产拉取(暴露 8881
- `docker-compose.dev.yml`:本地开发显式叠加层——追加 `build: .`、独立 project /
容器名(`-dev` 后缀)、暴露 8001,并把 DB 指向挂载的 `./data` 副本,可与生产栈在同一台机器上并存
本地开发启动方式:
WarmteLink serial access is configured directly by both Compose combinations. Before starting either
one, set these host-specific values in your uncommitted local `.env` (use a stable `/dev/serial/by-id/...`
path, never a transient `/dev/ttyUSB*` name):
```bash
docker compose up -d --build
```dotenv
WARMTELINK_DEVICE_PATH=/dev/serial/by-id/<stable-by-id-name>
WARMTELINK_SERIAL_GID=<host-serial-gid>
```
上面的命令会自动叠加 `docker-compose.override.yml`,因此本地仍然会按当前工作目录重新 build。
Only `app` receives the device as `/dev/warmtelink:rw` and the serial group; `migration` does not.
The app remains non-root, non-privileged, and has no added capabilities. One physical serial port may
have only one owner: stop the app before running the Pre-M8 P1 probe. Never remove `./data`, databases,
or volumes while changing this configuration.
如果要按生产方式直接从 registry 拉取并启动,显式只使用基础 compose 文件
本地开发启动方式(显式叠加 dev 层)
```bash
docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d --build
```
dev 层刻意不沿用 `docker-compose.override.yml` 这种会被 `docker compose up` 自动叠加的文件名,
因此默认的 `docker compose up` 只用生产基础文件,不会把开发端口 / 配置误带到生产。
如果要按生产方式直接从 registry 拉取并启动,使用基础 compose 文件:
```bash
docker compose -f docker-compose.yml pull
@@ -287,9 +635,16 @@ pytest
当前测试包含:
- app 基本启动测试
- `/status` endpoint 测试
- 登录 / session 基础流程测试
- app 启动与 `/status` 检查
- 登录 / session / 鉴权流程
- runtime config 读写
- public IPv4 monitor
- SMTP 配置与测试发信
- location / poo recorder 端点
- Home Assistant inbound 集成
- TickTick OAuth
- 部署与迁移(`run_migrations`
- legacy 数据迁移脚本(`migrate_legacy_data`
## OpenAPI 导出
+17 -3
View File
@@ -3,10 +3,24 @@ from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from app.auth_db import AuthBase
from app.config import get_settings
from app.db import Base
from app.models.config import AppConfigEntry # noqa: F401
from app.models.auth import AuthSession, AuthUser # noqa: F401
from app.models.auth import AuthSession, AuthUser, RecoveryCode # noqa: F401
from app.models.auth_throttle import LoginThrottle # noqa: F401
from app.models.public_ip import PublicIPHistory, PublicIPState # noqa: F401
from app.models.location import Location # noqa: F401
from app.models.poo import PooRecord # noqa: F401
from app.models.modbus import ModbusDevice, ModbusReading # noqa: F401
from app.models.expose import ExposedEntityToggle # noqa: F401
from app.models.energy import ( # noqa: F401
DsmrReading,
EnergyContract,
EnergyContractVersion,
TibberPrice,
EnergyCostPeriod,
)
from app.models.meter_source import MeterSource, MeterSourceBinding, MeterSourceChannel # noqa: F401
config = context.config
@@ -18,7 +32,7 @@ configured_url = config.get_main_option("sqlalchemy.url")
if not configured_url or configured_url == "sqlite:///./data/app.db":
config.set_main_option("sqlalchemy.url", settings.app_database_url)
target_metadata = AuthBase.metadata
target_metadata = Base.metadata
def run_migrations_offline() -> None:
@@ -0,0 +1,55 @@
"""public ip monitor tables
Revision ID: 20260429_05_public_ip_monitor
Revises: 20260420_04_app_config_table
Create Date: 2026-04-29 00:00:01.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "20260429_05_public_ip_monitor"
down_revision: Union[str, None] = "20260420_04_app_config_table"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"public_ip_history",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("ipv4", sa.String(length=45), nullable=False),
sa.Column("observed_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("change_type", sa.String(length=32), nullable=False),
sa.Column("provider", sa.String(length=64), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
"ix_public_ip_history_observed_at",
"public_ip_history",
["observed_at"],
unique=False,
)
op.create_table(
"public_ip_state",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("current_ipv4", sa.String(length=45), nullable=False),
sa.Column("previous_ipv4", sa.String(length=45), nullable=True),
sa.Column("first_seen_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("last_checked_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("last_changed_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_check_status", sa.String(length=32), nullable=False),
sa.Column("last_check_error", sa.String(length=255), nullable=True),
sa.Column("last_provider", sa.String(length=64), nullable=True),
sa.PrimaryKeyConstraint("id"),
)
def downgrade() -> None:
op.drop_table("public_ip_state")
op.drop_index("ix_public_ip_history_observed_at", table_name="public_ip_history")
op.drop_table("public_ip_history")
@@ -0,0 +1,43 @@
"""merge location and poo_records tables into app chain
Revision ID: 20260611_06_merge_location_poo_tables
Revises: 20260429_05_public_ip_monitor
Create Date: 2026-06-11 00:00:01.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "20260611_06_merge_location_poo_tables"
down_revision: Union[str, None] = "20260429_05_public_ip_monitor"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"location",
sa.Column("person", sa.Text(), nullable=False),
sa.Column("datetime", sa.Text(), nullable=False),
sa.Column("latitude", sa.REAL(), nullable=False),
sa.Column("longitude", sa.REAL(), nullable=False),
sa.Column("altitude", sa.REAL(), nullable=True),
sa.PrimaryKeyConstraint("person", "datetime"),
)
op.create_table(
"poo_records",
sa.Column("timestamp", sa.Text(), nullable=False),
sa.Column("status", sa.Text(), nullable=False),
sa.Column("latitude", sa.REAL(), nullable=False),
sa.Column("longitude", sa.REAL(), nullable=False),
sa.PrimaryKeyConstraint("timestamp"),
)
def downgrade() -> None:
op.drop_table("poo_records")
op.drop_table("location")
@@ -0,0 +1,43 @@
"""add auth_login_throttle table for exponential back-off throttling
Revision ID: 20260621_07_auth_login_throttle
Revises: 20260611_06_merge_location_poo_tables
Create Date: 2026-06-21 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "20260621_07_auth_login_throttle"
down_revision: Union[str, None] = "20260611_06_merge_location_poo_tables"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"auth_login_throttle",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("key", sa.String(length=255), nullable=False),
sa.Column("scope", sa.String(length=16), nullable=False),
sa.Column("failures", sa.Integer(), nullable=False),
sa.Column("first_failed_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("last_failed_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("next_allowed_at", sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("scope", "key", name="uq_auth_login_throttle_scope_key"),
)
op.create_index(
"ix_auth_login_throttle_scope_key",
"auth_login_throttle",
["scope", "key"],
unique=False,
)
def downgrade() -> None:
op.drop_index("ix_auth_login_throttle_scope_key", table_name="auth_login_throttle")
op.drop_table("auth_login_throttle")
+61
View File
@@ -0,0 +1,61 @@
"""add TOTP fields to auth_users and create auth_recovery_code table
Revision ID: 20260621_08_totp
Revises: 20260621_07_auth_login_throttle
Create Date: 2026-06-21 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260621_08_totp"
down_revision: Union[str, None] = "20260621_07_auth_login_throttle"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# Add totp_secret (nullable) to auth_users — existing rows get NULL, which is correct.
op.add_column("auth_users", sa.Column("totp_secret", sa.String(length=64), nullable=True))
# Add totp_enabled (NOT NULL) with server_default="0" so existing rows default to false.
op.add_column(
"auth_users",
sa.Column(
"totp_enabled",
sa.Boolean(),
nullable=False,
server_default="0",
),
)
# Create auth_recovery_code table for one-time TOTP recovery codes.
op.create_table(
"auth_recovery_code",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("user_id", sa.Integer(), nullable=False),
sa.Column("code_hash", sa.String(length=255), nullable=False),
sa.Column("used_at", sa.DateTime(timezone=True), nullable=True),
sa.ForeignKeyConstraint(["user_id"], ["auth_users.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(
op.f("ix_auth_recovery_code_user_id"),
"auth_recovery_code",
["user_id"],
unique=False,
)
def downgrade() -> None:
# Drop auth_recovery_code table first (has FK to auth_users).
op.drop_index(op.f("ix_auth_recovery_code_user_id"), table_name="auth_recovery_code")
op.drop_table("auth_recovery_code")
# Drop the two TOTP columns from auth_users.
# Use batch_alter_table for SQLite compatibility (alembic's portable column-drop path).
with op.batch_alter_table("auth_users") as batch_op:
batch_op.drop_column("totp_enabled")
batch_op.drop_column("totp_secret")
@@ -0,0 +1,81 @@
"""add modbus_device and modbus_reading tables
Revision ID: 20260622_09_modbus_tables
Revises: 20260621_08_totp
Create Date: 2026-06-22 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260622_09_modbus_tables"
down_revision: Union[str, None] = "20260621_08_totp"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# modbus_device — deployment/configurable metadata for each polled device.
op.create_table(
"modbus_device",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("uuid", sa.String(length=36), nullable=False),
sa.Column("friendly_name", sa.String(length=255), nullable=False),
sa.Column("transport", sa.String(length=16), nullable=False),
sa.Column("host", sa.String(length=255), nullable=False),
sa.Column("port", sa.Integer(), nullable=False),
sa.Column("unit_id", sa.Integer(), nullable=False),
sa.Column("profile", sa.String(length=64), nullable=False),
sa.Column("poll_interval_s", sa.Integer(), nullable=False),
sa.Column("enabled", sa.Boolean(), nullable=False),
sa.Column("last_poll_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_poll_ok", sa.Boolean(), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("uuid", name="uq_modbus_device_uuid"),
)
# modbus_reading — generic telemetry, one row per device per poll cycle.
op.create_table(
"modbus_reading",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("device_id", sa.Integer(), nullable=False),
sa.Column("recorded_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("payload", sa.JSON(), nullable=False),
sa.ForeignKeyConstraint(
["device_id"],
["modbus_device.id"],
ondelete="RESTRICT",
),
sa.PrimaryKeyConstraint("id"),
)
# Individual index on recorded_at (from the ORM-level index=True).
op.create_index(
"ix_modbus_reading_recorded_at",
"modbus_reading",
["recorded_at"],
unique=False,
)
# Composite index for efficient time-range queries per device.
op.create_index(
"ix_modbus_reading_device_recorded",
"modbus_reading",
["device_id", "recorded_at"],
unique=False,
)
def downgrade() -> None:
# Drop the reading table first (it has a FK referencing modbus_device).
op.drop_index("ix_modbus_reading_device_recorded", table_name="modbus_reading")
op.drop_index("ix_modbus_reading_recorded_at", table_name="modbus_reading")
op.drop_table("modbus_reading")
# Drop the device table.
op.drop_table("modbus_device")
@@ -0,0 +1,44 @@
"""add exposed_entity_toggle table
Revision ID: 20260622_10_exposed_entities
Revises: 20260622_09_modbus_tables
Create Date: 2026-06-22 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260622_10_exposed_entities"
down_revision: Union[str, None] = "20260622_09_modbus_tables"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# exposed_entity_toggle — per-entity on/off switch for MQTT / HA Discovery.
op.create_table(
"exposed_entity_toggle",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("key", sa.String(length=255), nullable=False),
sa.Column("enabled", sa.Boolean(), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("key", name="uq_exposed_entity_toggle_key"),
)
# Index on key for fast single-key lookups (toggle by key).
op.create_index(
"ix_exposed_entity_toggle_key",
"exposed_entity_toggle",
["key"],
unique=True,
)
def downgrade() -> None:
# Drop index then table — only removes what this revision created.
op.drop_index("ix_exposed_entity_toggle_key", table_name="exposed_entity_toggle")
op.drop_table("exposed_entity_toggle")
@@ -0,0 +1,132 @@
"""add energy pricing and DSMR metering tables
Revision ID: 20260623_11_energy_tables
Revises: 20260622_10_exposed_entities
Create Date: 2026-06-23 00:00:00.000000
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260623_11_energy_tables"
down_revision: Union[str, None] = "20260622_10_exposed_entities"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# dsmr_reading — raw DSMR telegram blobs (10-second down-sampled).
# No device table: single P1 smart meter; a ``source`` column can be added later
# if a second meter is introduced.
op.create_table(
"dsmr_reading",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("recorded_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("source_id", sa.Integer(), nullable=True),
sa.Column("payload", sa.JSON(), nullable=False),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("source_id", name="uq_dsmr_reading_source_id"),
)
op.create_index(
"ix_dsmr_reading_recorded_at",
"dsmr_reading",
["recorded_at"],
unique=False,
)
# energy_contract — contract head (manual or tibber, one active at a time).
op.create_table(
"energy_contract",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("kind", sa.String(length=32), nullable=False),
sa.Column("active", sa.Boolean(), nullable=False),
sa.Column("currency", sa.String(length=8), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
# energy_contract_version — versioned pricing values; append-only for auditability.
# Must be created after energy_contract because of the FK dependency.
op.create_table(
"energy_contract_version",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("contract_id", sa.Integer(), nullable=False),
sa.Column("effective_from", sa.DateTime(timezone=True), nullable=False),
sa.Column("effective_to", sa.DateTime(timezone=True), nullable=True),
sa.Column("values", sa.JSON(), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(
["contract_id"],
["energy_contract.id"],
ondelete="RESTRICT",
),
sa.PrimaryKeyConstraint("id"),
)
# tibber_price — cached Tibber 15-minute spot prices (immutable once fetched).
op.create_table(
"tibber_price",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("starts_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("resolution", sa.String(length=32), nullable=False),
sa.Column("energy", sa.Float(), nullable=False),
sa.Column("tax", sa.Float(), nullable=False),
sa.Column("total", sa.Float(), nullable=False),
sa.Column("level", sa.String(length=32), nullable=True),
sa.Column("currency", sa.String(length=8), nullable=False),
sa.Column("fetched_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("starts_at", name="uq_tibber_price_starts_at"),
)
# energy_cost_period — computed 15-minute billing periods (immutable snapshot).
# Must be created after energy_contract_version because of the FK dependency.
op.create_table(
"energy_cost_period",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("period_start", sa.DateTime(timezone=True), nullable=False),
sa.Column("d1_kwh", sa.Float(), nullable=False),
sa.Column("d2_kwh", sa.Float(), nullable=False),
sa.Column("r1_kwh", sa.Float(), nullable=False),
sa.Column("r2_kwh", sa.Float(), nullable=False),
sa.Column("import_cost", sa.Float(), nullable=False),
sa.Column("export_revenue", sa.Float(), nullable=False),
sa.Column("net_cost", sa.Float(), nullable=False),
sa.Column("currency", sa.String(length=8), nullable=False),
sa.Column("pricing", sa.JSON(), nullable=False),
sa.Column("contract_version_id", sa.Integer(), nullable=True),
sa.Column("degraded", sa.Boolean(), nullable=False),
sa.Column("computed_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(
["contract_version_id"],
["energy_contract_version.id"],
ondelete="RESTRICT",
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("period_start", name="uq_energy_cost_period_period_start"),
)
def downgrade() -> None:
# Drop tables in reverse dependency order: tables with FKs first.
# energy_cost_period has a FK to energy_contract_version — drop it first.
op.drop_table("energy_cost_period")
# tibber_price has no FK dependencies on our new tables.
op.drop_table("tibber_price")
# energy_contract_version has a FK to energy_contract — drop it before energy_contract.
op.drop_table("energy_contract_version")
# energy_contract has no FK dependencies on our new tables.
op.drop_table("energy_contract")
# dsmr_reading has no FK dependencies.
op.drop_index("ix_dsmr_reading_recorded_at", table_name="dsmr_reading")
op.drop_table("dsmr_reading")
@@ -0,0 +1,58 @@
"""decouple dsmr_reading from the telegram id
The DSMR Reader's own ``id`` field is auto-incrementing but is known to overflow
and require a manual reset to zero (a long-standing DSMR firmware quirk). If we
keep a UNIQUE constraint on ``source_id`` (the telegram id) and use it for
idempotency, an overflow/reset would make legitimately-new telegrams collide with
old ids and be silently dropped as "duplicates" — data loss.
This migration removes that coupling:
- Drops the UNIQUE constraint on ``source_id`` (the column is kept as a plain,
nullable reference value; it is no longer relied upon for uniqueness/dedup).
- Makes ``recorded_at`` (the telegram timestamp) UNIQUE instead — a single P1
meter emits one telegram per timestamp, so this is a robust, telegram-id-
independent idempotency key. The table's own autoincrement ``id`` PK remains
the stable internal identity.
Revision ID: 20260624_12_dsmr_decouple_telegram_id
Revises: 20260623_11_energy_tables
Create Date: 2026-06-24 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
revision: str = "20260624_12_dsmr_decouple_telegram_id"
down_revision: Union[str, None] = "20260623_11_energy_tables"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# SQLite cannot ALTER away a constraint in place, so recreate the table via
# Alembic's batch mode. The table is recreated and rows are copied; existing
# data (if any) is preserved. recorded_at must be unique for this to succeed
# — a single meter never emits two telegrams at the exact same timestamp.
with op.batch_alter_table("dsmr_reading", schema=None) as batch_op:
# Old non-unique index on recorded_at is replaced by the unique constraint.
batch_op.drop_index("ix_dsmr_reading_recorded_at")
# Telegram id is no longer a uniqueness/idempotency key.
batch_op.drop_constraint("uq_dsmr_reading_source_id", type_="unique")
# Timestamp becomes the telegram-id-independent dedup key.
batch_op.create_unique_constraint(
"uq_dsmr_reading_recorded_at", ["recorded_at"]
)
def downgrade() -> None:
with op.batch_alter_table("dsmr_reading", schema=None) as batch_op:
batch_op.drop_constraint("uq_dsmr_reading_recorded_at", type_="unique")
batch_op.create_unique_constraint(
"uq_dsmr_reading_source_id", ["source_id"]
)
batch_op.create_index(
"ix_dsmr_reading_recorded_at", ["recorded_at"], unique=False
)
@@ -0,0 +1,238 @@
"""add meter table and energy_cost_period.meter_id
Introduces the ``meter`` table (one row per physical meter installation epoch)
and a nullable FK column ``energy_cost_period.meter_id`` that attributes each
billing period to a specific physical meter.
**Backfill logic (§3.7 of the M7 design doc)**:
If the database already contains any ``dsmr_reading`` or
``energy_cost_period`` rows, one initial ``meter`` row is created:
label = "Initial meter"
commodity = "electricity"
started_at = earliest dsmr_reading.recorded_at
(or, if none, earliest energy_cost_period.period_start,
or, if still none, the migration timestamp)
ended_at = NULL (still active)
reason = "initial"
All existing ``energy_cost_period`` rows are then back-filled with that
initial meter's id.
**Idempotency**: the backfill is guarded with a check for any existing
``meter`` row whose ``reason = 'initial'`` and ``commodity = 'electricity'``
and ``ended_at IS NULL``, so repeating the upgrade does not create duplicate
meters or overwrite already-filled meter_id values.
**Audit (on-non-degraded periods only)**: after backfilling, the number of
non-degraded ``energy_cost_period`` rows with ``meter_id IS NULL`` must be
zero; if it is not, the migration raises a ``RuntimeError`` and rolls back.
**Data safety**: this migration is additive only — no existing rows are
deleted or overwritten; it only creates a new table, adds a nullable column,
and back-fills that column.
Revision ID: 20260625_13_meter_table
Revises: 20260624_12_dsmr_decouple_telegram_id
Create Date: 2026-06-25 00:00:00.000000
"""
from datetime import datetime, timezone
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260625_13_meter_table"
down_revision: Union[str, None] = "20260624_12_dsmr_decouple_telegram_id"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
# ------------------------------------------------------------------ #
# 1. Create the meter table. #
# ------------------------------------------------------------------ #
op.create_table(
"meter",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("label", sa.String(length=255), nullable=False),
sa.Column("commodity", sa.String(length=32), nullable=False),
sa.Column("started_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("ended_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("reason", sa.String(length=64), nullable=False),
sa.Column("note", sa.String(length=1024), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
# ------------------------------------------------------------------ #
# 2. Add meter_id column to energy_cost_period (nullable FK). #
# ------------------------------------------------------------------ #
with op.batch_alter_table("energy_cost_period", schema=None) as batch_op:
batch_op.add_column(
sa.Column("meter_id", sa.Integer(), nullable=True)
)
batch_op.create_foreign_key(
"fk_energy_cost_period_meter_id",
"meter",
["meter_id"],
["id"],
ondelete="RESTRICT",
)
# ------------------------------------------------------------------ #
# 3. Backfill initial meter (idempotent). #
# ------------------------------------------------------------------ #
conn = op.get_bind()
# Check if there is already an initial meter (idempotency guard).
existing_initial = conn.execute(
sa.text(
"SELECT id FROM meter "
"WHERE reason = 'initial' AND commodity = 'electricity' AND ended_at IS NULL "
"LIMIT 1"
)
).fetchone()
if existing_initial is not None:
# Already backfilled — nothing to do.
return
# Determine whether there is any historical data to create a meter for.
has_readings = conn.execute(
sa.text("SELECT 1 FROM dsmr_reading LIMIT 1")
).fetchone()
has_periods = conn.execute(
sa.text("SELECT 1 FROM energy_cost_period LIMIT 1")
).fetchone()
if not has_readings and not has_periods:
# Empty database: no historical data, so no initial meter is needed.
# meter_id will remain NULL on any future rows until T02 service layer
# starts populating it.
return
# Determine started_at: earliest dsmr_reading.recorded_at, falling back to
# earliest energy_cost_period.period_start, and finally to now().
earliest_reading_row = conn.execute(
sa.text("SELECT MIN(recorded_at) AS ts FROM dsmr_reading")
).fetchone()
earliest_period_row = conn.execute(
sa.text("SELECT MIN(period_start) AS ts FROM energy_cost_period")
).fetchone()
started_at_value: datetime | None = None
if earliest_reading_row and earliest_reading_row[0] is not None:
# SQLite returns ISO strings for datetime columns; parse to datetime.
raw = earliest_reading_row[0]
started_at_value = _parse_sqlite_datetime(raw)
if started_at_value is None and earliest_period_row and earliest_period_row[0] is not None:
raw = earliest_period_row[0]
started_at_value = _parse_sqlite_datetime(raw)
if started_at_value is None:
started_at_value = datetime.now(tz=timezone.utc)
now_utc = datetime.now(tz=timezone.utc)
# Insert the initial meter row.
conn.execute(
sa.text(
"INSERT INTO meter (label, commodity, started_at, ended_at, reason, note, created_at) "
"VALUES (:label, :commodity, :started_at, NULL, :reason, NULL, :created_at)"
),
{
"label": "Initial meter",
"commodity": "electricity",
"started_at": _iso(started_at_value),
"reason": "initial",
"created_at": _iso(now_utc),
},
)
# Retrieve the newly created meter id.
meter_row = conn.execute(
sa.text(
"SELECT id FROM meter "
"WHERE reason = 'initial' AND commodity = 'electricity' AND ended_at IS NULL "
"LIMIT 1"
)
).fetchone()
assert meter_row is not None, "Initial meter row not found after insert"
meter_id: int = meter_row[0]
# Back-fill all existing energy_cost_period rows that have meter_id IS NULL.
conn.execute(
sa.text(
"UPDATE energy_cost_period SET meter_id = :mid WHERE meter_id IS NULL"
),
{"mid": meter_id},
)
# ------------------------------------------------------------------ #
# 4. Audit: verify all non-degraded periods have a meter_id. #
# ------------------------------------------------------------------ #
unmatched_row = conn.execute(
sa.text(
"SELECT COUNT(*) FROM energy_cost_period "
"WHERE meter_id IS NULL AND degraded = 0"
)
).fetchone()
unmatched_count: int = unmatched_row[0] if unmatched_row else 0
if unmatched_count != 0:
raise RuntimeError(
f"Meter backfill audit failed: {unmatched_count} non-degraded "
"energy_cost_period row(s) still have meter_id IS NULL after backfill. "
"Migration aborted to protect data integrity."
)
def downgrade() -> None:
# Remove the FK column from energy_cost_period first (references meter).
with op.batch_alter_table("energy_cost_period", schema=None) as batch_op:
batch_op.drop_constraint("fk_energy_cost_period_meter_id", type_="foreignkey")
batch_op.drop_column("meter_id")
# Drop the meter table.
op.drop_table("meter")
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _parse_sqlite_datetime(value: str | datetime) -> datetime:
"""Parse a SQLite datetime value into an aware UTC datetime.
SQLite stores datetimes as ISO 8601 strings. SQLAlchemy may return them
as plain strings or as naive datetimes (no tzinfo) depending on the driver
and column declaration. This helper normalises both forms to an aware UTC
``datetime``.
"""
if isinstance(value, datetime):
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value
# String form — strip trailing Z or +00:00 variants, then attach UTC.
s = str(value).strip()
for suffix in ("+00:00", "Z", " UTC"):
if s.endswith(suffix):
s = s[: -len(suffix)]
# SQLite uses space as the T separator in some formats.
s = s.replace(" ", "T")
try:
dt = datetime.fromisoformat(s)
except ValueError:
# Fallback: strip subseconds if present to handle unusual formats.
dt = datetime.strptime(s[:19], "%Y-%m-%dT%H:%M:%S")
return dt.replace(tzinfo=timezone.utc)
def _iso(dt: datetime) -> str:
"""Serialise a datetime to an ISO 8601 string for SQLite storage."""
if dt.tzinfo is not None:
dt = dt.astimezone(timezone.utc).replace(tzinfo=None)
return dt.strftime("%Y-%m-%dT%H:%M:%S")
@@ -0,0 +1,104 @@
"""add uuid column to meter table
Adds a stable ``uuid`` (UUID v4 string) column to the ``meter`` table so that
each meter epoch has a durable identity anchor suitable for use as an HA
Discovery ``unique_id``.
**Migration strategy (SQLite-safe)**:
SQLite does not support adding a NOT NULL + UNIQUE column to a non-empty table
in a single ``ALTER TABLE ADD COLUMN`` statement (adding a NOT NULL column
without a default value is rejected if the table already has rows). The
safe approach used here is:
1. Add ``uuid`` as a **nullable** column (SQLite allows this).
2. **Back-fill** every existing ``meter`` row with a distinct ``str(uuid4())``
value. Each row gets its *own* random UUID — not a shared value — so the
subsequent UNIQUE constraint is satisfied.
3. Use ``batch_alter_table`` (which re-creates the table under the hood in
SQLite) to alter the column to ``NOT NULL`` and add a UNIQUE constraint.
**Idempotency**: only rows where ``uuid IS NULL`` are back-filled; rows that
already have a uuid (e.g. from a repeated upgrade after a partial failure) are
left untouched.
**Audit**: after back-fill, the count of rows with ``uuid IS NULL`` must be
exactly zero; if not, the migration raises ``RuntimeError`` and rolls back.
**Data safety**: this migration is additive only — no existing rows are deleted
or overwritten; it only adds a new column and fills it in.
Revision ID: 20260625_14_meter_uuid
Revises: 20260625_13_meter_table
Create Date: 2026-06-25 00:00:00.000000
"""
import uuid as _uuid
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260625_14_meter_uuid"
down_revision: Union[str, None] = "20260625_13_meter_table"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
conn = op.get_bind()
# ------------------------------------------------------------------ #
# 1. Add uuid as a nullable column. #
# ------------------------------------------------------------------ #
with op.batch_alter_table("meter", schema=None) as batch_op:
batch_op.add_column(
sa.Column("uuid", sa.String(length=36), nullable=True)
)
# ------------------------------------------------------------------ #
# 2. Back-fill: assign a distinct UUID to every row that has #
# uuid IS NULL. Each row gets its own random value so that the #
# subsequent UNIQUE constraint is satisfied. #
# ------------------------------------------------------------------ #
rows = conn.execute(sa.text("SELECT id FROM meter WHERE uuid IS NULL")).fetchall()
for (meter_id,) in rows:
new_uuid = str(_uuid.uuid4())
conn.execute(
sa.text("UPDATE meter SET uuid = :uuid WHERE id = :mid"),
{"uuid": new_uuid, "mid": meter_id},
)
# ------------------------------------------------------------------ #
# 3. Audit: verify no rows remain with uuid IS NULL. #
# ------------------------------------------------------------------ #
null_count_row = conn.execute(
sa.text("SELECT COUNT(*) FROM meter WHERE uuid IS NULL")
).fetchone()
null_count: int = null_count_row[0] if null_count_row else 0
if null_count != 0:
raise RuntimeError(
f"meter.uuid back-fill audit failed: {null_count} meter row(s) still have "
"uuid IS NULL after back-fill. Migration aborted to protect data integrity."
)
# ------------------------------------------------------------------ #
# 4. Alter column to NOT NULL + UNIQUE (requires batch on SQLite). #
# batch_alter_table re-creates the table, so the UNIQUE constraint #
# and NOT NULL are applied atomically. #
# ------------------------------------------------------------------ #
with op.batch_alter_table("meter", schema=None) as batch_op:
batch_op.alter_column(
"uuid",
existing_type=sa.String(length=36),
nullable=False,
)
batch_op.create_unique_constraint("uq_meter_uuid", ["uuid"])
def downgrade() -> None:
# Drop the UNIQUE constraint and the uuid column (batch on SQLite).
with op.batch_alter_table("meter", schema=None) as batch_op:
batch_op.drop_constraint("uq_meter_uuid", type_="unique")
batch_op.drop_column("uuid")
@@ -0,0 +1,107 @@
"""add protocol-agnostic meter source, channel, and binding tables
Revision ID: 20260822_15_meter_sources
Revises: 20260625_14_meter_uuid
Create Date: 2026-08-22 00:00:00.000000
This revision is additive on upgrade. It deliberately does not backfill
existing DSMR data; that adoption is a later, separately audited migration.
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260822_15_meter_sources"
down_revision: Union[str, None] = "20260625_14_meter_uuid"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"meter_source",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("uuid", sa.String(length=36), nullable=False),
sa.Column("name", sa.String(length=255), nullable=False),
sa.Column("kind", sa.String(length=64), nullable=False),
sa.Column("enabled", sa.Boolean(), nullable=False),
sa.Column("config", sa.JSON(), nullable=False),
sa.Column("status", sa.String(length=32), nullable=False),
sa.Column("last_seen_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("last_error", sa.String(length=1024), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("uuid", name="uq_meter_source_uuid"),
)
op.create_index("ix_meter_source_kind_enabled", "meter_source", ["kind", "enabled"])
op.create_table(
"meter_source_channel",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("uuid", sa.String(length=36), nullable=False),
sa.Column("source_id", sa.Integer(), nullable=False),
sa.Column("channel_key", sa.String(length=128), nullable=False),
sa.Column("label", sa.String(length=255), nullable=False),
sa.Column("suggested_commodity", sa.String(length=32), nullable=True),
sa.Column("unit", sa.String(length=32), nullable=False),
sa.Column("device_type", sa.String(length=64), nullable=True),
sa.Column("fingerprint", sa.String(length=64), nullable=True),
sa.Column("latest_value", sa.Numeric(precision=20, scale=6), nullable=True),
sa.Column("latest_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("latest_quality", sa.String(length=32), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(["source_id"], ["meter_source.id"], ondelete="RESTRICT"),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("uuid", name="uq_meter_source_channel_uuid"),
sa.UniqueConstraint("source_id", "channel_key", name="uq_meter_source_channel_source_key"),
)
op.create_index("ix_meter_source_channel_source_id", "meter_source_channel", ["source_id"])
op.create_table(
"meter_source_binding",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("uuid", sa.String(length=36), nullable=False),
sa.Column("meter_id", sa.Integer(), nullable=False),
sa.Column("channel_id", sa.Integer(), nullable=False),
sa.Column("started_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("ended_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(["meter_id"], ["meter.id"], ondelete="RESTRICT"),
sa.ForeignKeyConstraint(
["channel_id"], ["meter_source_channel.id"], ondelete="RESTRICT"
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("uuid", name="uq_meter_source_binding_uuid"),
)
op.create_index("ix_meter_source_binding_meter_id", "meter_source_binding", ["meter_id"])
op.create_index("ix_meter_source_binding_channel_id", "meter_source_binding", ["channel_id"])
with op.batch_alter_table("energy_cost_period", schema=None) as batch_op:
batch_op.add_column(sa.Column("source_binding_id", sa.Integer(), nullable=True))
batch_op.create_foreign_key(
"fk_energy_cost_period_source_binding_id",
"meter_source_binding",
["source_binding_id"],
["id"],
ondelete="RESTRICT",
)
def downgrade() -> None:
with op.batch_alter_table("energy_cost_period", schema=None) as batch_op:
batch_op.drop_constraint("fk_energy_cost_period_source_binding_id", type_="foreignkey")
batch_op.drop_column("source_binding_id")
op.drop_index("ix_meter_source_binding_channel_id", table_name="meter_source_binding")
op.drop_index("ix_meter_source_binding_meter_id", table_name="meter_source_binding")
op.drop_table("meter_source_binding")
op.drop_index("ix_meter_source_channel_source_id", table_name="meter_source_channel")
op.drop_table("meter_source_channel")
op.drop_index("ix_meter_source_kind_enabled", table_name="meter_source")
op.drop_table("meter_source")
@@ -0,0 +1,269 @@
"""adopt historical DSMR rows into the source and binding model
Revision ID: 20260822_16_dsmr_source_adoption
Revises: 20260822_15_meter_sources
Create Date: 2026-08-22 00:00:00.000000
The upgrade is deliberately data-preserving: it creates one migration-owned
DSMR source/channel, moves the telegram identifier to ``telegram_id``, and
audits every reading and cost row before committing. Old ``app_config`` rows,
payload JSON, and cost snapshots are never deleted or rewritten.
"""
from __future__ import annotations
import uuid
from datetime import datetime, timezone
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260822_16_dsmr_source_adoption"
down_revision: Union[str, None] = "20260822_15_meter_sources"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def _as_bool(value: str | None) -> bool:
return value is not None and value.strip().lower() in {"1", "true", "yes", "on"}
def _iso_now() -> str:
return datetime.now(tz=timezone.utc).replace(tzinfo=None).isoformat(sep=" ")
def _config(connection: sa.Connection) -> dict[str, object]:
rows = connection.execute(sa.text("SELECT key, value FROM app_config")).all()
values = {str(key): str(value) for key, value in rows}
# An unconfigured historical DSMR installation needs a disabled identity,
# not guessed connection details. Preserve every legacy value we model
# when any legacy DSMR/MQTT configuration was explicitly present.
legacy_keys = {
"MQTT_BROKER_HOST", "MQTT_BROKER_PORT", "MQTT_USERNAME", "MQTT_PASSWORD",
"MQTT_TLS_ENABLED", "DSMR_MQTT_TOPIC", "DSMR_TARIFF_TOPIC", "DSMR_SAMPLE_INTERVAL_S",
}
if not legacy_keys & values.keys():
return {}
return {
"broker_host": values.get("MQTT_BROKER_HOST", ""),
"broker_port": int(values.get("MQTT_BROKER_PORT", "1883")),
"username": values.get("MQTT_USERNAME", ""),
"password": values.get("MQTT_PASSWORD", ""),
"tls_enabled": _as_bool(values.get("MQTT_TLS_ENABLED")),
"topic": values.get("DSMR_MQTT_TOPIC", "dsmr/json"),
"tariff_topic": values.get("DSMR_TARIFF_TOPIC", "dsmr/meter-stats/electricity_tariff"),
"sample_interval_s": int(values.get("DSMR_SAMPLE_INTERVAL_S", "10")),
}
def _count(connection: sa.Connection, table: str) -> int:
return int(connection.execute(sa.text(f"SELECT COUNT(*) FROM {table}")).scalar_one())
def upgrade() -> None:
connection = op.get_bind()
readings_before = _count(connection, "dsmr_reading")
costs_before = _count(connection, "energy_cost_period")
sources_before = _count(connection, "meter_source")
channels_before = _count(connection, "meter_source_channel")
bindings_before = _count(connection, "meter_source_binding")
now = _iso_now()
# A source exists even without historical configuration/readings. It stays
# disabled unless the old explicit DSMR switch was enabled, so no broker or
# topic is guessed at runtime.
config = _config(connection)
source_result = connection.execute(
sa.text(
"INSERT INTO meter_source "
"(uuid, name, kind, enabled, config, status, last_seen_at, last_error, created_at, updated_at) "
"VALUES (:uuid, :name, 'dsmr_mqtt', :enabled, :config, 'unknown', NULL, NULL, :now, :now)"
),
{
"uuid": str(uuid.uuid4()),
"name": "Migrated DSMR source",
"enabled": _as_bool(
connection.execute(
sa.text("SELECT value FROM app_config WHERE key = 'DSMR_INGEST_ENABLED'")
).scalar_one_or_none()
),
"config": __import__("json").dumps(config),
"now": now,
},
)
source_id = source_result.lastrowid
if source_id is None:
raise RuntimeError("DSMR source adoption failed to create a source")
channel_result = connection.execute(
sa.text(
"INSERT INTO meter_source_channel "
"(uuid, source_id, channel_key, label, suggested_commodity, unit, device_type, fingerprint, "
"latest_value, latest_at, latest_quality, created_at, updated_at) "
"VALUES (:uuid, :source_id, 'electricity-total', 'DSMR electricity total', 'electricity', "
"'kWh', NULL, NULL, NULL, NULL, NULL, :now, :now)"
),
{"uuid": str(uuid.uuid4()), "source_id": source_id, "now": now},
)
channel_id = channel_result.lastrowid
if channel_id is None:
raise RuntimeError("DSMR source adoption failed to create an electricity channel")
if _count(connection, "meter_source") != sources_before + 1:
raise RuntimeError("DSMR source adoption source row-count audit failed")
if _count(connection, "meter_source_channel") != channels_before + 1:
raise RuntimeError("DSMR source adoption channel row-count audit failed")
# Rename/add while nullable, back-fill all rows, then make the FK non-null
# and replace the legacy timestamp-only uniqueness in a SQLite batch rebuild.
with op.batch_alter_table("dsmr_reading", schema=None) as batch_op:
batch_op.alter_column("source_id", new_column_name="telegram_id")
batch_op.add_column(sa.Column("meter_source_id", sa.Integer(), nullable=True))
connection.execute(
sa.text("UPDATE dsmr_reading SET meter_source_id = :source_id WHERE meter_source_id IS NULL"),
{"source_id": source_id},
)
with op.batch_alter_table("dsmr_reading", schema=None) as batch_op:
batch_op.drop_constraint("uq_dsmr_reading_recorded_at", type_="unique")
batch_op.alter_column("meter_source_id", existing_type=sa.Integer(), nullable=False)
batch_op.create_foreign_key(
"fk_dsmr_reading_meter_source_id", "meter_source", ["meter_source_id"], ["id"],
ondelete="RESTRICT",
)
batch_op.create_unique_constraint(
"uq_dsmr_reading_source_recorded_at", ["meter_source_id", "recorded_at"]
)
batch_op.create_index("ix_dsmr_reading_meter_source_id", ["meter_source_id"])
adopted_readings = int(
connection.execute(
sa.text("SELECT COUNT(*) FROM dsmr_reading WHERE meter_source_id = :source_id"),
{"source_id": source_id},
).scalar_one()
)
if adopted_readings != readings_before:
raise RuntimeError("DSMR source adoption reading source audit failed")
# Bind each electricity meter only where it overlaps the actual DSMR data.
data_window = connection.execute(
sa.text("SELECT MIN(recorded_at), MAX(recorded_at) FROM dsmr_reading")
).one()
expected_binding_count = 0
if data_window[0] is not None:
meters = connection.execute(
sa.text(
"SELECT id, started_at, ended_at FROM meter WHERE commodity = 'electricity' "
"ORDER BY started_at, id"
)
).all()
for meter_id, started_at, ended_at in meters:
# Intersect [meter start, meter end) with the inclusive historical
# samples. A closed boundary at the final sample remains valid for
# the preceding interval; an empty intersection gets no fake binding.
if started_at > data_window[1] or (ended_at is not None and ended_at <= data_window[0]):
continue
expected_binding_count += 1
binding_start = max(started_at, data_window[0])
binding_end = ended_at
connection.execute(
sa.text(
"INSERT INTO meter_source_binding "
"(uuid, meter_id, channel_id, started_at, ended_at, created_at, updated_at) "
"VALUES (:uuid, :meter_id, :channel_id, :started_at, :ended_at, :now, :now)"
),
{
"uuid": str(uuid.uuid4()), "meter_id": meter_id, "channel_id": channel_id,
"started_at": binding_start, "ended_at": binding_end, "now": now,
},
)
# A cost period may be linked only if exactly one binding covers both its
# start and end. Historical boundary/unknown rows remain auditable but are
# explicitly degraded instead of being silently attributed to a current meter.
periods = connection.execute(
sa.text("SELECT id, meter_id, period_start, degraded FROM energy_cost_period")
).all()
resolvable_normal_periods: dict[int, int] = {}
unresolved_period_ids: set[int] = set()
for period_id, meter_id, period_start, degraded_before in periods:
candidates = []
if meter_id is not None:
candidates = connection.execute(
sa.text(
"SELECT id FROM meter_source_binding "
"WHERE meter_id = :meter_id AND started_at <= :start "
"AND (ended_at IS NULL OR julianday(ended_at) > julianday(:start, '+15 minutes'))"
),
{"meter_id": meter_id, "start": period_start},
).all()
if len(candidates) == 1:
if not degraded_before:
resolvable_normal_periods[period_id] = candidates[0][0]
connection.execute(
sa.text("UPDATE energy_cost_period SET source_binding_id = :binding_id WHERE id = :id"),
{"binding_id": candidates[0][0], "id": period_id},
)
else:
unresolved_period_ids.add(period_id)
connection.execute(
sa.text(
"UPDATE energy_cost_period SET degraded = 1, source_binding_id = NULL WHERE id = :id"
),
{"id": period_id},
)
readings_after = _count(connection, "dsmr_reading")
costs_after = _count(connection, "energy_cost_period")
if readings_after != readings_before or costs_after != costs_before:
raise RuntimeError("DSMR source adoption row-count audit failed")
if _count(connection, "meter_source_binding") != bindings_before + expected_binding_count:
raise RuntimeError("DSMR source adoption binding row-count audit failed")
if int(
connection.execute(
sa.text("SELECT COUNT(*) FROM meter_source_binding WHERE channel_id = :channel_id"),
{"channel_id": channel_id},
).scalar_one()
) != expected_binding_count:
raise RuntimeError("DSMR source adoption binding channel audit failed")
for period_id, binding_id in resolvable_normal_periods.items():
bound, degraded = connection.execute(
sa.text("SELECT source_binding_id, degraded FROM energy_cost_period WHERE id = :id"),
{"id": period_id},
).one()
if bound != binding_id or degraded:
raise RuntimeError("DSMR source adoption resolvable cost audit failed")
if unresolved_period_ids:
unresolved_count = int(
connection.execute(
sa.text(
"SELECT COUNT(*) FROM energy_cost_period "
"WHERE id IN :period_ids AND (degraded != 1 OR source_binding_id IS NOT NULL)"
).bindparams(sa.bindparam("period_ids", expanding=True)),
{"period_ids": list(unresolved_period_ids)},
).scalar_one()
)
if unresolved_count:
raise RuntimeError("DSMR source adoption unresolved cost audit failed")
orphan_rows = connection.execute(sa.text("PRAGMA foreign_key_check")).all()
if orphan_rows:
raise RuntimeError("DSMR source adoption foreign-key audit failed")
normal_unbound = int(
connection.execute(
sa.text("SELECT COUNT(*) FROM energy_cost_period WHERE degraded = 0 AND source_binding_id IS NULL")
).scalar_one()
)
if normal_unbound:
raise RuntimeError(f"DSMR source adoption left {normal_unbound} normal cost period(s) unbound")
if _count(connection, "meter_source") < 1:
raise RuntimeError("DSMR source adoption source audit failed")
def downgrade() -> None:
# Schema-only downgrade for isolated test databases. It intentionally does
# not delete migration-created source/channel/binding rows.
with op.batch_alter_table("dsmr_reading", schema=None) as batch_op:
batch_op.drop_index("ix_dsmr_reading_meter_source_id")
batch_op.drop_constraint("uq_dsmr_reading_source_recorded_at", type_="unique")
batch_op.drop_constraint("fk_dsmr_reading_meter_source_id", type_="foreignkey")
batch_op.drop_column("meter_source_id")
batch_op.alter_column("telegram_id", new_column_name="source_id")
batch_op.create_unique_constraint("uq_dsmr_reading_recorded_at", ["recorded_at"])
@@ -0,0 +1,52 @@
"""add normalized WarmteLink scalar reading history
Revision ID: 20260822_17_warmtelink_readings
Revises: 20260822_16_dsmr_source_adoption
Create Date: 2026-08-22 00:00:00.000000
The upgrade is additive: existing business rows are neither changed nor
removed. The downgrade is schema-only and is exercised only on isolated test
databases.
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260822_17_warmtelink_readings"
down_revision: Union[str, None] = "20260822_16_dsmr_source_adoption"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"warmtelink_reading",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("channel_id", sa.Integer(), nullable=False),
sa.Column("recorded_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("received_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("value", sa.Numeric(precision=15, scale=3), nullable=False),
sa.Column("unit", sa.String(length=32), nullable=False),
sa.Column("quality", sa.String(length=32), nullable=False),
sa.Column("equipment_fingerprint", sa.String(length=64), nullable=False),
sa.CheckConstraint(
"quality IN ('valid', 'invalid', 'unverifiable')",
name="ck_warmtelink_reading_quality",
),
sa.ForeignKeyConstraint(
["channel_id"], ["meter_source_channel.id"], ondelete="RESTRICT"
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint(
"channel_id", "recorded_at", name="uq_warmtelink_reading_channel_recorded_at"
),
)
op.create_index("ix_warmtelink_reading_recorded_at", "warmtelink_reading", ["recorded_at"])
def downgrade() -> None:
op.drop_index("ix_warmtelink_reading_recorded_at", table_name="warmtelink_reading")
op.drop_table("warmtelink_reading")
@@ -0,0 +1,107 @@
"""add a billing scope to energy contracts
Revision ID: 20260822_18_contract_scopes
Revises: 20260822_17_warmtelink_readings
Create Date: 2026-08-22 00:00:00.000000
The upgrade preserves every existing contract, version and cost row. Existing
contracts predate scopes and therefore deterministically belong to electricity.
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260822_18_contract_scopes"
down_revision: Union[str, None] = "20260822_17_warmtelink_readings"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def _count(connection: sa.Connection, table: str) -> int:
return int(connection.execute(sa.text(f"SELECT COUNT(*) FROM {table}")).scalar_one())
def _orphan_count(connection: sa.Connection) -> int:
version_orphans = connection.execute(
sa.text(
"SELECT COUNT(*) FROM energy_contract_version v "
"LEFT JOIN energy_contract c ON c.id = v.contract_id WHERE c.id IS NULL"
)
).scalar_one()
cost_orphans = connection.execute(
sa.text(
"SELECT COUNT(*) FROM energy_cost_period p "
"LEFT JOIN energy_contract_version v ON v.id = p.contract_version_id "
"WHERE p.contract_version_id IS NOT NULL AND v.id IS NULL"
)
).scalar_one()
return int(version_orphans) + int(cost_orphans)
def _audit_scope_upgrade(connection: sa.Connection, before: dict[str, int], orphan_before: int) -> None:
after = {table: _count(connection, table) for table in before}
if after != before:
raise RuntimeError("contract scope migration row-count audit failed")
if _orphan_count(connection) != orphan_before:
raise RuntimeError("contract scope migration FK audit failed")
invalid_scope_count = connection.execute(
sa.text("SELECT COUNT(*) FROM energy_contract WHERE scope IS NULL OR scope != 'electricity'")
).scalar_one()
if invalid_scope_count:
raise RuntimeError("contract scope migration backfill audit failed")
# Kept on Alembic's Config attributes rather than an environment switch so
# isolated migration tests can deterministically exercise the rollback
# boundary without changing production behavior.
failure_injector = op.get_context().config.attributes.get("m8_t12_post_ddl_audit_failure")
if callable(failure_injector):
failure_injector()
def _apply_scope_schema() -> None:
# SQLite batch mode reconstructs the table. The server default gives every
# historical row its deterministic value during reconstruction.
with op.batch_alter_table("energy_contract", schema=None) as batch_op:
batch_op.add_column(
sa.Column("scope", sa.String(length=32), nullable=False, server_default="electricity")
)
batch_op.create_index("ix_energy_contract_scope", ["scope"])
def upgrade() -> None:
connection = op.get_bind()
before = {
table: _count(connection, table)
for table in ("energy_contract", "energy_contract_version", "energy_cost_period")
}
orphan_before = _orphan_count(connection)
if connection.dialect.name != "sqlite":
_apply_scope_schema()
_audit_scope_upgrade(connection, before, orphan_before)
return
# Alembic marks SQLite batch DDL as non-transactional. SQLite itself can
# nevertheless atomically roll back CREATE/COPY/DROP/RENAME when an
# explicit transaction owns the complete batch operation. Keep the audit
# inside that boundary so a failed audit cannot strand a revision-17 DB
# with a revision-18 table shape.
connection.exec_driver_sql("BEGIN IMMEDIATE")
try:
_apply_scope_schema()
_audit_scope_upgrade(connection, before, orphan_before)
except BaseException:
connection.exec_driver_sql("ROLLBACK")
raise
else:
connection.exec_driver_sql("COMMIT")
def downgrade() -> None:
# Schema reversibility is only exercised against isolated temporary test DBs.
with op.batch_alter_table("energy_contract", schema=None) as batch_op:
batch_op.drop_index("ix_energy_contract_scope")
batch_op.drop_column("scope")
@@ -0,0 +1,95 @@
"""add generic commodity-scoped meter cost periods
Revision ID: 20260822_19_meter_cost_periods
Revises: 20260822_18_contract_scopes
Create Date: 2026-08-22 00:00:00.000000
This additive migration creates a separate audit ledger for non-electricity
meter costs. It deliberately does not alter, migrate, or delete rows from the
existing electricity-only energy_cost_period table.
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "20260822_19_meter_cost_periods"
down_revision: Union[str, None] = "20260822_18_contract_scopes"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
class ExactDecimal(sa.TypeDecorator):
"""Use SQLite text storage while retaining Numeric semantics elsewhere."""
impl = sa.Numeric
cache_ok = True
def __init__(self, precision: int, scale: int) -> None:
self.precision = precision
self.scale = scale
super().__init__(precision=precision, scale=scale)
def load_dialect_impl(self, dialect):
if dialect.name == "sqlite":
return dialect.type_descriptor(sa.String(self.precision + 2))
return dialect.type_descriptor(sa.Numeric(self.precision, self.scale, asdecimal=True))
def upgrade() -> None:
op.create_table(
"meter_cost_period",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("commodity", sa.String(length=32), nullable=False),
sa.Column("period_start", sa.DateTime(timezone=True), nullable=False),
sa.Column("period_end", sa.DateTime(timezone=True), nullable=False),
sa.Column("meter_id", sa.Integer(), nullable=True),
sa.Column("source_binding_id", sa.Integer(), nullable=True),
sa.Column("contract_version_id", sa.Integer(), nullable=True),
# SQLite NUMERIC coercion binds Decimal values as binary floats. Store
# fixed-width decimal text there, while retaining Numeric semantics on
# other supported dialects.
sa.Column("quantity", ExactDecimal(15, 6), nullable=False),
sa.Column("cost", ExactDecimal(15, 9), nullable=False),
sa.Column("currency", sa.String(length=8), nullable=False),
sa.Column("cost_breakdown", sa.JSON(), nullable=False),
sa.Column("pricing_snapshot", sa.JSON(), nullable=False),
sa.Column("quality", sa.String(length=32), nullable=False),
sa.Column("degraded", sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column("degraded_reason", sa.String(length=255), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
sa.ForeignKeyConstraint(["meter_id"], ["meter.id"], ondelete="RESTRICT"),
sa.ForeignKeyConstraint(
["source_binding_id"], ["meter_source_binding.id"], ondelete="RESTRICT"
),
sa.ForeignKeyConstraint(
["contract_version_id"], ["energy_contract_version.id"], ondelete="RESTRICT"
),
sa.CheckConstraint(
"degraded OR (meter_id IS NOT NULL AND source_binding_id IS NOT NULL "
"AND contract_version_id IS NOT NULL)",
name="ck_meter_cost_period_normal_audit_links",
),
sa.CheckConstraint("period_end > period_start", name="ck_meter_cost_period_positive_interval"),
sa.CheckConstraint(
"NOT degraded OR (degraded_reason IS NOT NULL AND length(trim(degraded_reason)) > 0)",
name="ck_meter_cost_period_degraded_reason",
),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("commodity", "period_start", name="uq_meter_cost_period_commodity_start"),
)
op.create_index(
"ix_meter_cost_period_commodity_start", "meter_cost_period", ["commodity", "period_start"]
)
op.create_index(
"ix_meter_cost_period_source_binding_id", "meter_cost_period", ["source_binding_id"]
)
def downgrade() -> None:
op.drop_index("ix_meter_cost_period_source_binding_id", table_name="meter_cost_period")
op.drop_index("ix_meter_cost_period_commodity_start", table_name="meter_cost_period")
op.drop_table("meter_cost_period")
-37
View File
@@ -1,37 +0,0 @@
[alembic]
script_location = alembic_location
prepend_sys_path = .
path_separator = os
sqlalchemy.url = sqlite:///./data/locationRecorder.db
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
-2
View File
@@ -1,2 +0,0 @@
This directory contains the Alembic migration environment for the Python rewrite skeleton.
-48
View File
@@ -1,48 +0,0 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from app.config import get_settings
from app.models import Location # noqa: F401
from app.models.base import Base
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
settings = get_settings()
configured_url = config.get_main_option("sqlalchemy.url")
if not configured_url or configured_url == "sqlite:///./data/locationRecorder.db":
config.set_main_option("sqlalchemy.url", settings.location_database_url)
target_metadata = Base.metadata
def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url, target_metadata=target_metadata, literal_binds=True)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
-26
View File
@@ -1,26 +0,0 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}
-1
View File
@@ -1 +0,0 @@
@@ -1,33 +0,0 @@
"""location baseline
Revision ID: 20260419_01_location_baseline
Revises:
Create Date: 2026-04-19 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "20260419_01_location_baseline"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"location",
sa.Column("person", sa.Text(), nullable=False),
sa.Column("datetime", sa.Text(), nullable=False),
sa.Column("latitude", sa.Float(), nullable=False),
sa.Column("longitude", sa.Float(), nullable=False),
sa.Column("altitude", sa.Float(), nullable=True),
sa.PrimaryKeyConstraint("person", "datetime"),
)
def downgrade() -> None:
op.drop_table("location")
-37
View File
@@ -1,37 +0,0 @@
[alembic]
script_location = alembic_poo
prepend_sys_path = .
path_separator = os
sqlalchemy.url = sqlite:///./data/pooRecorder.db
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers = console
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
-48
View File
@@ -1,48 +0,0 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
from app.config import get_settings
from app.models.poo import PooRecord # noqa: F401
from app.poo_db import PooBase
config = context.config
if config.config_file_name is not None:
fileConfig(config.config_file_name)
settings = get_settings()
configured_url = config.get_main_option("sqlalchemy.url")
if not configured_url or configured_url == "sqlite:///./data/pooRecorder.db":
config.set_main_option("sqlalchemy.url", settings.poo_database_url)
target_metadata = PooBase.metadata
def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url, target_metadata=target_metadata, literal_binds=True)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
@@ -1,32 +0,0 @@
"""poo baseline
Revision ID: 20260420_01_poo_baseline
Revises:
Create Date: 2026-04-20 00:00:00.000000
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
revision: str = "20260420_01_poo_baseline"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.create_table(
"poo_records",
sa.Column("timestamp", sa.Text(), nullable=False),
sa.Column("status", sa.Text(), nullable=False),
sa.Column("latitude", sa.Float(), nullable=False),
sa.Column("longitude", sa.Float(), nullable=False),
sa.PrimaryKeyConstraint("timestamp"),
)
def downgrade() -> None:
op.drop_table("poo_records")
View File
+324
View File
@@ -0,0 +1,324 @@
from __future__ import annotations
import logging
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from app.api.routes.api.deps import require_csrf, require_session
from app.config import Settings, get_settings
from app.dependencies import get_app_settings, get_db
from app.integrations.mqtt import MQTT_SETTINGS_KEYS, mqtt_manager, mqtt_test_client_id
from app.schemas.config import (
ConfigField,
ConfigResponse,
ConfigSection,
ConfigUpdateRequest,
ConfigUpdateResponse,
MqttTestResponse,
SmtpTestResponse,
)
from app.services.auth import AuthenticatedSession
from app.services.config_page import ConfigSaveError, build_config_sections, save_config_updates
from app.services.email import EmailConfigurationError, EmailDeliveryError, send_smtp_test_email
from app.services.tibber_prices import active_tibber_contract_exists, trigger_tibber_refresh
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["api-config"])
def _sections_from_raw(sections_raw: list[dict]) -> list[ConfigSection]:
result = []
for section in sections_raw:
fields = [ConfigField(**f) for f in section["fields"]]
result.append(ConfigSection(name=section["name"], fields=fields))
return result
@router.get("/config", response_model=ConfigResponse)
def get_config(
db: Session = Depends(get_db),
settings: Settings = Depends(get_app_settings),
_auth: AuthenticatedSession = Depends(require_session),
) -> ConfigResponse:
"""Return all configuration sections. Secret field values are masked (empty string)."""
sections_raw = build_config_sections(db, settings)
return ConfigResponse(sections=_sections_from_raw(sections_raw))
@router.put("/config", response_model=ConfigUpdateResponse)
def put_config(
body: ConfigUpdateRequest,
db: Session = Depends(get_db),
settings: Settings = Depends(get_app_settings),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> ConfigUpdateResponse:
"""
Save configuration updates.
- Blank secret value keeps the existing stored value (no change).
- Invalid values return 422 and nothing is written to the database.
- If MQTT-related settings changed, the MQTT client reconnects automatically.
"""
# Detect whether any MQTT-related key is being submitted (non-secret change
# or non-blank secret change) so we know to reconnect after saving.
mqtt_keys_submitted = any(k.lower() in MQTT_SETTINGS_KEYS for k in body.updates)
tibber_values_before = (
settings.tibber_api_token,
settings.tibber_home_id,
)
try:
save_config_updates(db, body.updates, settings)
except ConfigSaveError as exc:
logger.warning("Rejected config update via API: %s", exc)
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="invalid config submission",
) from exc
# Re-read settings after save (save_config_updates clears the settings cache).
# Use build_runtime_settings so the reconnect picks up DB-stored values, not
# just the bootstrap env (otherwise a broker configured via the UI is ignored).
from app.services.config_page import build_runtime_settings
refreshed_settings = build_runtime_settings(db, get_settings())
# Reconnect MQTT client if any MQTT setting was updated.
if mqtt_keys_submitted:
logger.info("MQTT settings changed — triggering reconnect.")
mqtt_manager.reconnect(refreshed_settings)
# Re-apply the DSMR subscription so enabling/disabling DSMR ingest (or changing
# its topic / sample interval) takes effect immediately, without an app restart.
# Done after any MQTT reconnect so it operates on the current client.
from app.services.dsmr_ingest import apply_dsmr_subscription
apply_dsmr_subscription(refreshed_settings)
tibber_values_changed = tibber_values_before != (
refreshed_settings.tibber_api_token,
refreshed_settings.tibber_home_id,
)
if tibber_values_changed and active_tibber_contract_exists(db):
trigger_tibber_refresh()
sections_raw = build_config_sections(db, refreshed_settings)
return ConfigUpdateResponse(sections=_sections_from_raw(sections_raw))
@router.post(
"/config/smtp/test",
responses={
200: {"model": SmtpTestResponse},
400: {"model": SmtpTestResponse},
502: {"model": SmtpTestResponse},
},
)
def post_smtp_test(
settings: Settings = Depends(get_app_settings),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> JSONResponse:
"""
Send a test SMTP email using the current runtime settings.
Returns a structured result indicating success or the category of failure.
Three possible outcomes:
- 200 { "result": "success", "message": ... }
- 400 { "result": "config-error", "message": ... } (EmailConfigurationError)
- 502 { "result": "failed", "message": ... } (EmailDeliveryError)
SMTP credentials are never echoed in the response.
"""
try:
send_smtp_test_email(settings)
except EmailConfigurationError as exc:
logger.warning("SMTP test rejected due to configuration: %s", exc)
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={"result": "config-error", "message": str(exc)},
)
except EmailDeliveryError as exc:
logger.warning("SMTP test delivery failed: %s", exc)
return JSONResponse(
status_code=status.HTTP_502_BAD_GATEWAY,
content={"result": "failed", "message": str(exc)},
)
return JSONResponse(
status_code=status.HTTP_200_OK,
content={"result": "success", "message": "Test email sent successfully."},
)
# ---------------------------------------------------------------------------
# POST /api/config/mqtt/test — M5-T10
# ---------------------------------------------------------------------------
class _MqttConfigurationError(ValueError):
"""Raised when MQTT settings are incomplete or disabled."""
class _MqttConnectionError(RuntimeError):
"""Raised when MQTT broker connection or publish fails."""
@router.post(
"/config/mqtt/test",
responses={
200: {"model": MqttTestResponse},
400: {"model": MqttTestResponse},
502: {"model": MqttTestResponse},
},
)
def post_mqtt_test(
settings: Settings = Depends(get_app_settings),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> JSONResponse:
"""
Test MQTT broker connectivity by attempting to connect and publishing a
test message to ``<ha_discovery_prefix>/home-automation/test``.
The message is visible in MQTT Explorer (or any subscriber) so users can
confirm the full broker publish path is working.
Three possible outcomes:
- 200 { "result": "success", "message": ... }
- 400 { "result": "config-error", "message": ... } (not configured)
- 502 { "result": "failed", "message": ... } (connection/publish error)
MQTT credentials are never echoed in the response.
"""
try:
_run_mqtt_test(settings)
except _MqttConfigurationError as exc:
logger.warning("MQTT test rejected due to configuration: %s", exc)
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content={"result": "config-error", "message": str(exc)},
)
except _MqttConnectionError as exc:
logger.warning("MQTT test connection/publish failed: %s", exc)
return JSONResponse(
status_code=status.HTTP_502_BAD_GATEWAY,
content={"result": "failed", "message": str(exc)},
)
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"result": "success",
"message": (
f"Test message published to "
f"{settings.ha_discovery_prefix}/home-automation/test."
),
},
)
def _run_mqtt_test(settings: Settings) -> None:
"""Attempt a transient MQTT connection and publish a test message.
Raises
------
_MqttConfigurationError
When MQTT is not enabled or broker host is not configured.
_MqttConnectionError
When the broker is unreachable or the publish fails.
"""
import socket
import paho.mqtt.client as mqtt
if not settings.mqtt_broker_host:
raise _MqttConfigurationError("MQTT broker host is not configured.")
test_topic = f"{settings.ha_discovery_prefix}/home-automation/test"
test_payload = '{"source": "home-automation", "event": "mqtt_test"}'
connected_event = __import__("threading").Event()
published_event = __import__("threading").Event()
connect_error: list[str] = []
client = mqtt.Client(
callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
client_id=mqtt_test_client_id(settings.mqtt_client_id),
)
def _on_connect(
_client: mqtt.Client,
_userdata: object,
_flags: mqtt.ConnectFlags,
reason_code: mqtt.ReasonCode,
_properties: mqtt.Properties | None,
) -> None:
if reason_code.is_failure:
connect_error.append(f"Broker refused connection: {reason_code}")
connected_event.set()
def _on_publish(
_client: mqtt.Client,
_userdata: object,
_mid: int,
_reason_code: mqtt.ReasonCode,
_properties: mqtt.Properties | None,
) -> None:
published_event.set()
client.on_connect = _on_connect
client.on_publish = _on_publish
if settings.mqtt_tls_enabled:
try:
client.tls_set()
except Exception as exc:
raise _MqttConnectionError(f"TLS setup failed: {exc}") from exc
if settings.mqtt_username:
client.username_pw_set(
username=settings.mqtt_username,
password=settings.mqtt_password or None,
)
client.loop_start()
try:
try:
client.connect(
host=settings.mqtt_broker_host,
port=settings.mqtt_broker_port,
keepalive=10,
)
except (OSError, socket.error) as exc:
# Sanitise: ensure password never leaks into the error message.
msg = _sanitize_mqtt_error(str(exc), settings.mqtt_password)
raise _MqttConnectionError(f"Cannot reach broker: {msg}") from exc
# Wait up to 5 s for connection acknowledgement.
if not connected_event.wait(timeout=5):
raise _MqttConnectionError("Broker connection timed out (5 s).")
if connect_error:
raise _MqttConnectionError(connect_error[0])
# Publish test message.
client.publish(test_topic, payload=test_payload, qos=1, retain=False)
# Wait up to 5 s for the publish ACK (QoS 1).
if not published_event.wait(timeout=5):
raise _MqttConnectionError("Publish timed out (5 s) — broker reachable but no ACK.")
finally:
try:
client.disconnect()
except Exception:
pass
client.loop_stop()
def _sanitize_mqtt_error(message: str, password: str | None) -> str:
"""Replace *password* in *message* with ``[redacted]``."""
if password:
return message.replace(password, "[redacted]")
return message
+275
View File
@@ -0,0 +1,275 @@
from __future__ import annotations
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
from sqlalchemy import desc, select
from sqlalchemy.orm import Session
from app.api.routes.api.deps import require_csrf, require_session
from app.dependencies import get_db
from app.models.location import Location
from app.models.poo import PooRecord
from app.models.public_ip import PublicIPHistory, PublicIPState
from app.schemas.data import (
LocationRecord,
LocationUpdateRequest,
LocationsResponse,
PooRecord as PooRecordSchema,
PooResponse,
PooUpdateRequest,
PublicIPHistorySchema,
PublicIPResponse,
PublicIPStateSchema,
)
from app.services.auth import AuthenticatedSession
from app.services.location import delete_location, update_location
from app.services.poo import delete_poo_record, update_poo_record
router = APIRouter(prefix="/api", tags=["api-data"])
@router.get("/locations", response_model=LocationsResponse)
def get_locations(
limit: int = Query(default=1000, ge=1, le=5000),
offset: int = Query(default=0, ge=0),
start: str | None = Query(default=None),
end: str | None = Query(default=None),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> LocationsResponse:
"""
Return location records with optional time-window filtering and pagination.
- ``start`` / ``end`` are ISO8601 strings; filtering is **inclusive** on both bounds.
- Results are ordered by ``datetime`` ascending.
- ``limit`` is capped at 5000 to prevent full-table exports.
"""
stmt = select(Location)
if start is not None:
stmt = stmt.where(Location.datetime >= start)
if end is not None:
stmt = stmt.where(Location.datetime <= end)
stmt = stmt.order_by(Location.datetime).offset(offset).limit(limit)
rows = db.execute(stmt).scalars().all()
items = [
LocationRecord(
person=row.person,
datetime=row.datetime,
latitude=row.latitude,
longitude=row.longitude,
altitude=row.altitude,
)
for row in rows
]
return LocationsResponse(items=items, limit=limit, offset=offset)
@router.get("/poo", response_model=PooResponse)
def get_poo(
limit: int = Query(default=100, ge=1, le=1000),
offset: int = Query(default=0, ge=0),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> PooResponse:
"""
Return poo records ordered by timestamp descending (most recent first).
``limit`` is capped at 1000 to prevent full-table exports.
"""
stmt = (
select(PooRecord)
.order_by(desc(PooRecord.timestamp))
.offset(offset)
.limit(limit)
)
rows = db.execute(stmt).scalars().all()
items = [
PooRecordSchema(
timestamp=row.timestamp,
status=row.status,
latitude=row.latitude,
longitude=row.longitude,
)
for row in rows
]
return PooResponse(items=items, limit=limit, offset=offset)
@router.get("/public-ip", response_model=PublicIPResponse)
def get_public_ip(
limit: int = Query(default=100, ge=1, le=1000),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> PublicIPResponse:
"""
Return the current public IP state and recent history.
- ``state`` is ``null`` if no IP check has been performed yet.
- ``history`` is ordered by ``observed_at`` descending (most recent first).
- ``limit`` applies to the history list and is capped at 1000.
"""
state_row = db.execute(
select(PublicIPState).where(PublicIPState.id == 1).limit(1)
).scalar_one_or_none()
history_rows = db.execute(
select(PublicIPHistory).order_by(desc(PublicIPHistory.observed_at)).limit(limit)
).scalars().all()
state = PublicIPStateSchema.model_validate(state_row) if state_row is not None else None
history = [PublicIPHistorySchema.model_validate(row) for row in history_rows]
return PublicIPResponse(state=state, history=history)
# ---------------------------------------------------------------------------
# PATCH /api/locations/{person}/{datetime}
# ---------------------------------------------------------------------------
@router.patch("/locations/{person}/{datetime}", response_model=LocationRecord)
def patch_location(
person: str,
datetime: str,
body: LocationUpdateRequest = Body(default=LocationUpdateRequest()),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> LocationRecord:
"""
Update the non-PK fields of a single location record.
- ``person`` and ``datetime`` identify the row (composite PK) and are immutable.
- Only ``latitude``, ``longitude``, and ``altitude`` may be updated.
- Omitted body fields are left unchanged.
- Returns **404** if the PK does not exist.
"""
row = update_location(
db,
person,
datetime,
latitude=body.latitude,
longitude=body.longitude,
altitude=body.altitude,
)
if row is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="location record not found",
)
return LocationRecord(
person=row.person,
datetime=row.datetime,
latitude=row.latitude,
longitude=row.longitude,
altitude=row.altitude,
)
# ---------------------------------------------------------------------------
# DELETE /api/locations/{person}/{datetime}
# ---------------------------------------------------------------------------
@router.delete(
"/locations/{person}/{datetime}",
status_code=status.HTTP_204_NO_CONTENT,
response_model=None,
)
def delete_location_record(
person: str,
datetime: str,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> None:
"""
Delete the single location record identified by its composite PK.
- Exactly one row is deleted; **404** if the PK does not exist.
- No batch delete / truncate path is available.
"""
deleted = delete_location(db, person, datetime)
if not deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="location record not found",
)
# ---------------------------------------------------------------------------
# PATCH /api/poo/{timestamp}
# ---------------------------------------------------------------------------
@router.patch("/poo/{timestamp}", response_model=PooRecordSchema)
def patch_poo(
timestamp: str,
body: PooUpdateRequest = Body(default=PooUpdateRequest()),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> PooRecordSchema:
"""
Update the non-PK fields of a single poo record.
- ``timestamp`` is the PK and is immutable.
- Only ``status``, ``latitude``, and ``longitude`` may be updated.
- Omitted body fields are left unchanged.
- Returns **404** if the PK does not exist.
"""
row = update_poo_record(
db,
timestamp,
status=body.status,
latitude=body.latitude,
longitude=body.longitude,
)
if row is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="poo record not found",
)
return PooRecordSchema(
timestamp=row.timestamp,
status=row.status,
latitude=row.latitude,
longitude=row.longitude,
)
# ---------------------------------------------------------------------------
# DELETE /api/poo/{timestamp}
# ---------------------------------------------------------------------------
@router.delete(
"/poo/{timestamp}",
status_code=status.HTTP_204_NO_CONTENT,
response_model=None,
)
def delete_poo(
timestamp: str,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> None:
"""
Delete the single poo record identified by its PK.
- Exactly one row is deleted; **404** if the PK does not exist.
- No batch delete / truncate path is available.
"""
deleted = delete_poo_record(db, timestamp)
if not deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="poo record not found",
)
+28
View File
@@ -0,0 +1,28 @@
from __future__ import annotations
from fastapi import Depends, Header, HTTPException, status
from app.dependencies import get_current_auth_session
from app.services.auth import AuthenticatedSession
def require_session(
auth: AuthenticatedSession | None = Depends(get_current_auth_session),
) -> AuthenticatedSession:
if auth is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="authentication required",
)
return auth
def require_csrf(
_auth: AuthenticatedSession = Depends(require_session),
x_csrf_token: str | None = Header(default=None, alias="X-CSRF-Token"),
) -> None:
if not x_csrf_token:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="missing CSRF token",
)
+607
View File
@@ -0,0 +1,607 @@
"""Energy data API: prices, costs, summary, DSMR, recompute, Tibber test (M6-T09).
All endpoints are under /api/energy, require an authenticated session, and
write endpoints (POST) additionally require a non-empty X-CSRF-Token header.
Route prefix note
-----------------
This router shares the ``/api/energy`` prefix with ``energy_contracts.py``
(which handles contract CRUD at /contracts/* and /profiles). The sub-paths
used here (/prices, /costs, /costs/summary, /costs/recompute, /dsmr/latest,
/tibber/test) are disjoint from the contract router's paths, so there is no
conflict.
Tibber token security
---------------------
``POST /api/energy/tibber/test`` calls the Tibber API but **never** echoes the
token in the response body or in log messages. Three-state logic mirrors the
MQTT test endpoint (M5-T10, app/api/routes/api/config.py::post_mqtt_test):
200 { result: "success", message: ..., price: {...} }
400 { result: "config-error", message: ... }
502 { result: "failed", message: ... }
Recompute safety
----------------
``POST /api/energy/costs/recompute`` is idempotent: it calls
``energy_cost.recompute_range`` which upserts existing rows without deleting
anything. The endpoint enforces a maximum time-window of 366 days to avoid
unbounded recomputation triggered by erroneous client requests.
Prices endpoint behaviour
-------------------------
``GET /api/energy/prices`` queries the ``tibber_price`` table for tibber
contracts, or derives the effective fixed-tariff prices for manual contracts
using the same formula as the billing engine (_manual_strategy in strategies.py):
buy_dal = energy.buy.dal + energy.energy_tax + energy.ode
buy_normal = energy.buy.normal + energy.energy_tax + energy.ode
sell_dal = energy.sell.dal (no tax added to sell price)
sell_normal = energy.sell.normal
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime, timedelta
from typing import Any, Literal
from fastapi import APIRouter, Depends, Query, status
from fastapi.responses import JSONResponse
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.api.routes.api.deps import require_csrf, require_session
from app.dependencies import get_app_settings, get_db
from app.config import Settings
from app.integrations.tibber.client import (
TibberAuthError,
TibberError,
fetch_current_price,
)
from app.models.energy import DsmrReading, EnergyCostPeriod, TibberPrice
from app.schemas.energy import (
CostPeriodSchema,
CostsResponse,
DsmrLatestResponse,
ManualTariffSchema,
PricePointSchema,
PricesResponse,
RecomputeResponse,
SummaryResponse,
TibberTestPriceSchema,
TibberTestResponse,
)
from app.services.auth import AuthenticatedSession
from app.services.contracts import active_contract_version_at
from app.services.energy_cost import recompute_range, summarize
from app.services.timezone import local_midnight_utc, local_now
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/energy", tags=["api-energy"])
# Maximum number of cost periods returned per request (mirrors modbus readings cap).
_COSTS_LIMIT_MAX = 5000
# Maximum allowed time-window for recompute to prevent unbounded computation.
_RECOMPUTE_MAX_DAYS = 366
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
def _as_utc(dt: datetime) -> datetime:
"""Attach UTC tzinfo to a naive datetime (SQLite read-back workaround)."""
if dt.tzinfo is None:
return dt.replace(tzinfo=UTC)
return dt
def _manual_tariff_from_values(values: dict[str, Any]) -> ManualTariffSchema:
"""Derive the effective fixed tariff from a manual contract version's values dict.
Mirrors the _manual_strategy formula (strategies.py):
buy_dal = energy.buy.dal + energy.energy_tax + energy.ode
buy_normal = energy.buy.normal + energy.energy_tax + energy.ode
sell_dal = energy.sell.dal (no tax added)
sell_normal = energy.sell.normal
"""
from decimal import Decimal
def _d(v: Any) -> Decimal:
return Decimal(str(v or 0))
energy = values.get("energy", {})
buy = energy.get("buy", {})
sell = energy.get("sell", {})
energy_tax = _d(energy.get("energy_tax", 0))
ode = _d(energy.get("ode", 0))
buy_dal = _d(buy.get("dal", 0)) + energy_tax + ode
buy_normal = _d(buy.get("normal", 0)) + energy_tax + ode
sell_dal = _d(sell.get("dal", 0))
sell_normal = _d(sell.get("normal", 0))
return ManualTariffSchema(
buy_dal=float(buy_dal),
buy_normal=float(buy_normal),
sell_dal=float(sell_dal),
sell_normal=float(sell_normal),
)
def _electricity_prices_response(response: PricesResponse) -> JSONResponse:
"""Preserve the exact pre-scope electricity response body."""
return JSONResponse(
content=response.model_dump(
mode="json", include={"kind", "currency", "points", "tariff"}
)
)
# ---------------------------------------------------------------------------
# GET /api/energy/prices
# ---------------------------------------------------------------------------
@router.get("/prices", response_model=PricesResponse, response_model_exclude_none=True)
def get_prices(
scope: Literal["electricity", "thermal"] = Query("electricity"),
start: datetime | None = Query(
default=None,
description="Inclusive start of the time window (ISO 8601). "
"Defaults to the start of today UTC when omitted.",
),
end: datetime | None = Query(
default=None,
description="Inclusive end of the time window (ISO 8601). "
"Defaults to the end of tomorrow UTC when omitted.",
),
limit: int = Query(
default=500,
ge=1,
le=_COSTS_LIMIT_MAX,
description="Maximum number of Tibber price points to return.",
),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> PricesResponse:
"""Return the price curve for the active contract.
**Tibber contracts** (kind="tibber"):
Fetches ``tibber_price`` rows within ``[start, end]``, ordered ascending
by ``starts_at``. At most ``limit`` rows are returned (most recent first
within the window, then reversed to ascending order — identical to the
modbus readings pattern).
Response ``points`` carries per-slot:
- ``buy = total`` (Tibber all-inclusive price)
- ``sell = total energy_tax sell_fee sell_adjust`` (from active version values)
- ``level`` (Tibber price level, may be null)
``tariff`` is null.
**Manual contracts** (kind="manual"):
``points`` is empty. ``tariff`` carries the four effective prices
derived using the billing engine formula:
- ``buy_dal = energy.buy.dal + energy_tax + ode``
- ``buy_normal = energy.buy.normal + energy_tax + ode``
- ``sell_dal = energy.sell.dal``
- ``sell_normal = energy.sell.normal``
**No active contract**: returns kind=null, currency="EUR", points=[], tariff=null (200).
"""
now = datetime.now(UTC)
if scope == "thermal":
version = active_contract_version_at(db, now, scope="thermal")
if version is None:
return PricesResponse(kind=None, currency="EUR", points=[], tariff=None)
return PricesResponse(
kind="district_heating", currency=version.contract.currency,
contract_version_id=version.id, effective_from=_as_utc(version.effective_from),
effective_to=_as_utc(version.effective_to) if version.effective_to else None,
values=version.values, points=[], tariff=None,
)
# Default window: today + tomorrow.
if start is None:
start = now.replace(hour=0, minute=0, second=0, microsecond=0)
if end is None:
end = (start + timedelta(days=2)).replace(hour=0, minute=0, second=0, microsecond=0)
start_utc = _as_utc(start)
end_utc = _as_utc(end)
# Resolve the active contract version at the start of the window.
version = active_contract_version_at(db, start_utc)
if version is None:
return _electricity_prices_response(PricesResponse(
kind=None,
currency="EUR",
points=[],
tariff=None,
))
contract = version.contract
currency = contract.currency
if contract.kind == "tibber":
# Fetch tibber_price rows in the window.
stmt = (
select(TibberPrice)
.where(
TibberPrice.starts_at >= start_utc,
TibberPrice.starts_at <= end_utc,
)
.order_by(TibberPrice.starts_at.desc())
.limit(limit)
)
rows = list(reversed(db.execute(stmt).scalars().all()))
# Derive sell price per-point using version values
# (energy_tax + sell_fee + sell_adjust).
from decimal import Decimal
def _d(v: Any) -> Decimal:
return Decimal(str(v or 0))
energy = version.values.get("energy", {}) if version.values else {}
energy_tax = _d(energy.get("energy_tax", 0))
sell_fee = _d(energy.get("sell_fee", 0))
sell_adjust = _d(energy.get("sell_adjust", 0))
points = []
for row in rows:
total = _d(row.total)
sell = float(total - energy_tax - sell_fee - sell_adjust)
points.append(
PricePointSchema(
starts_at=_as_utc(row.starts_at),
buy=row.total,
sell=sell,
level=row.level,
)
)
return _electricity_prices_response(PricesResponse(
kind="tibber",
currency=currency,
points=points,
tariff=None,
))
elif contract.kind == "manual":
tariff = _manual_tariff_from_values(version.values or {})
return _electricity_prices_response(PricesResponse(
kind="manual",
currency=currency,
points=[],
tariff=tariff,
))
else:
# Unknown kind — return empty response gracefully.
return _electricity_prices_response(PricesResponse(
kind=contract.kind,
currency=currency,
points=[],
tariff=None,
))
# ---------------------------------------------------------------------------
# GET /api/energy/costs
# ---------------------------------------------------------------------------
@router.get("/costs", response_model=CostsResponse)
def get_costs(
start: datetime | None = Query(
default=None,
description="Inclusive lower bound for period_start (ISO 8601).",
),
end: datetime | None = Query(
default=None,
description="Inclusive upper bound for period_start (ISO 8601).",
),
limit: int = Query(
default=500,
ge=1,
le=_COSTS_LIMIT_MAX,
description=f"Maximum number of cost periods to return (default 500, max {_COSTS_LIMIT_MAX}).",
),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> CostsResponse:
"""Return energy_cost_period rows within a time window.
Rows are ordered by ``period_start`` ascending. When the window contains
more rows than ``limit``, the **most recent** N rows are returned (DESC LIMIT),
then reversed to ascending order — identical to the modbus readings pattern.
Query parameters:
- ``start``: inclusive lower bound on ``period_start`` (ISO 8601 datetime).
- ``end``: inclusive upper bound on ``period_start`` (ISO 8601 datetime).
- ``limit``: max rows to return (default 500, max {_COSTS_LIMIT_MAX}).
"""
stmt = (
select(EnergyCostPeriod)
.order_by(EnergyCostPeriod.period_start.desc())
.limit(limit)
)
if start is not None:
stmt = stmt.where(EnergyCostPeriod.period_start >= _as_utc(start))
if end is not None:
stmt = stmt.where(EnergyCostPeriod.period_start <= _as_utc(end))
rows = list(reversed(db.execute(stmt).scalars().all()))
items = [CostPeriodSchema.model_validate(r) for r in rows]
return CostsResponse(items=items, total=len(items))
# ---------------------------------------------------------------------------
# GET /api/energy/costs/summary
# ---------------------------------------------------------------------------
@router.get("/costs/summary", response_model=SummaryResponse)
def get_costs_summary(
start: datetime | None = Query(
default=None,
description=(
"Inclusive start of the summary interval (ISO 8601). "
"Defaults to the start of the current UTC day."
),
),
end: datetime | None = Query(
default=None,
description=(
"Exclusive end of the summary interval (ISO 8601). "
"Defaults to the start of the next UTC day (i.e. today's full data)."
),
),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> SummaryResponse:
"""Aggregate billing for a time interval.
Calls ``energy_cost.summarize(session, start, end)`` which computes:
total_payable = Σ(net_cost) + fixed_costs credits
where ``fixed_costs`` is (network_fee + management_fee) apportioned to the
interval length in days (÷30 per month), and ``credits`` is heffingskorting
apportioned similarly (÷365 per year).
Both ``fixed_costs`` and ``credits`` are derived from the **currently active
contract version at ``end``**. When no active contract exists they are 0.
"""
if start is None or end is None:
# Default to the server's local today: [local_midnight, next_local_midnight).
# This ensures "today" aligns with the local calendar day (NL time) rather
# than UTC midnight.
local_today = local_now().date()
if start is None:
start = local_midnight_utc(local_today)
if end is None:
end = local_midnight_utc(local_today + timedelta(days=1))
result = summarize(db, _as_utc(start), _as_utc(end))
return SummaryResponse(**result)
# ---------------------------------------------------------------------------
# GET /api/energy/dsmr/latest
# ---------------------------------------------------------------------------
@router.get("/dsmr/latest", response_model=DsmrLatestResponse)
def get_dsmr_latest(
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> DsmrLatestResponse:
"""Return the most recent dsmr_reading row.
Returns ``{"found": false, "recorded_at": null, "payload": null}`` (200, not
404) when no rows exist yet, so the front-end can distinguish "no data" from
a server error.
"""
row = db.execute(
select(DsmrReading)
.order_by(DsmrReading.recorded_at.desc())
.limit(1)
).scalar_one_or_none()
if row is None:
return DsmrLatestResponse(found=False)
return DsmrLatestResponse(
found=True,
recorded_at=_as_utc(row.recorded_at),
payload=row.payload,
)
# ---------------------------------------------------------------------------
# POST /api/energy/costs/recompute
# ---------------------------------------------------------------------------
@router.post(
"/costs/recompute",
responses={
200: {"model": RecomputeResponse},
422: {"description": "Validation error (missing window or range too large)"},
},
)
def post_recompute(
start: datetime = Query(
...,
description="Inclusive start of the recompute window (ISO 8601). Required.",
),
end: datetime = Query(
...,
description="Exclusive end of the recompute window (ISO 8601). Required.",
),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> RecomputeResponse:
"""Idempotently recompute billing records in a time window.
Calls ``energy_cost.recompute_range(session, start, end)`` which overwrites
existing rows (including successful ones) for every UTC quarter-hour boundary
in ``[start, end)``.
**Idempotency**: repeated calls with the same window produce the same
outcome. No rows are deleted; only upserted.
**Window constraint**: the maximum allowed range is {_RECOMPUTE_MAX_DAYS} days.
Requests exceeding this return 422.
Returns the number of periods for which a billing record was written.
Periods skipped due to missing contract or missing Tibber price are not counted.
"""
start_utc = _as_utc(start)
end_utc = _as_utc(end)
if end_utc <= start_utc:
from fastapi import HTTPException
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="'end' must be strictly after 'start'.",
)
span_days = (end_utc - start_utc).total_seconds() / 86400
if span_days > _RECOMPUTE_MAX_DAYS:
from fastapi import HTTPException
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=(
f"Time window is {span_days:.1f} days which exceeds the maximum of "
f"{_RECOMPUTE_MAX_DAYS} days. Use a smaller window."
),
)
n = recompute_range(db, start_utc, end_utc)
logger.info(
"POST /api/energy/costs/recompute [%s, %s): wrote %d period(s).",
start_utc.isoformat(),
end_utc.isoformat(),
n,
)
return RecomputeResponse(recomputed=n)
# ---------------------------------------------------------------------------
# POST /api/energy/tibber/test
# ---------------------------------------------------------------------------
@router.post(
"/tibber/test",
responses={
200: {"model": TibberTestResponse},
400: {"model": TibberTestResponse},
502: {"model": TibberTestResponse},
},
)
def post_tibber_test(
settings: Settings = Depends(get_app_settings),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> JSONResponse:
"""Test Tibber API connectivity by fetching the current price point.
Three possible outcomes:
- **200** ``{ result: "success", message: ..., price: {...} }``
The Tibber API responded with a valid current price. ``price`` contains
starts_at, total, energy, tax, currency, and level.
- **400** ``{ result: "config-error", message: ... }``
The Tibber API token is empty or not configured.
- **502** ``{ result: "failed", message: ... }``
The API call failed (authentication rejected, network error, timeout,
unexpected response, etc.).
The API token is **never** included in the response body or logged.
"""
token = settings.tibber_api_token
home_id = settings.tibber_home_id or None # treat empty string as None
if not token:
logger.info("POST /api/energy/tibber/test: no token configured.")
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content=TibberTestResponse(
result="config-error",
message=(
"Tibber API token is not configured. "
"Set TIBBER_API_TOKEN in the Config page."
),
price=None,
).model_dump(mode="json"),
)
try:
price_point = fetch_current_price(token, home_id)
except TibberAuthError:
logger.warning("POST /api/energy/tibber/test: authentication failed.")
return JSONResponse(
status_code=status.HTTP_502_BAD_GATEWAY,
content=TibberTestResponse(
result="failed",
message=(
"Tibber API authentication failed. "
"Check that your API token is correct."
),
price=None,
).model_dump(mode="json"),
)
except TibberError as exc:
logger.warning("POST /api/energy/tibber/test: API call failed — %s", exc)
return JSONResponse(
status_code=status.HTTP_502_BAD_GATEWAY,
content=TibberTestResponse(
result="failed",
message=f"Tibber API call failed: {exc}",
price=None,
).model_dump(mode="json"),
)
price_schema = TibberTestPriceSchema(
starts_at=price_point.starts_at,
total=price_point.total,
energy=price_point.energy,
tax=price_point.tax,
currency=price_point.currency,
level=price_point.level,
)
logger.info(
"POST /api/energy/tibber/test: success (starts_at=%s, total=%s %s).",
price_point.starts_at.isoformat(),
price_point.total,
price_point.currency,
)
return JSONResponse(
status_code=status.HTTP_200_OK,
content=TibberTestResponse(
result="success",
message=(
f"Tibber API connected. Current price: "
f"{price_point.total} {price_point.currency}/kWh "
f"(starts {price_point.starts_at.isoformat()})."
),
price=price_schema,
).model_dump(mode="json"),
)
+345
View File
@@ -0,0 +1,345 @@
"""EnergyContract CRUD, versioning, and pricing-profile API (M6-T04).
All endpoints are under /api/energy, require an authenticated session, and
write endpoints (POST/PATCH) additionally require a non-empty X-CSRF-Token
header.
There is deliberately no DELETE endpoint for contracts: the FK RESTRICT
constraint on energy_contract_version.contract_id and
energy_cost_period.contract_version_id prevents accidental deletion of
contracts that have billing history. Users should instead deactivate a
contract (PATCH active=false) to stop it from being used.
Route ordering note
-------------------
GET /api/energy/profiles and GET /api/energy/contracts/{id} are on separate
path prefixes (/energy/profiles vs /energy/contracts/{id}) so there is no
ambiguity even without extra ordering gymnastics.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api.routes.api.deps import require_csrf, require_session
from app.dependencies import get_db
from app.integrations.pricing.profiles import (
ProfileNotFoundError,
ProfileValidationError,
list_profiles,
)
from app.schemas.energy_contract import (
ContractCreate,
ContractDetailResponse,
ContractListResponse,
ContractPatch,
ContractResponse,
ContractVersionResponse,
ProfilesResponse,
VersionCreate,
)
from app.services.auth import AuthenticatedSession
from app.services import timezone as _tz_mod
from app.services.contracts import (
CONTRACT_KIND_SCOPES,
ContractVersionError,
ContractScopeError,
activate_contract,
add_version,
create_contract,
deactivate_contract,
get_contract_or_none,
list_contracts,
)
from app.services.tibber_prices import trigger_tibber_refresh
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/energy", tags=["api-energy-contracts"])
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _get_contract_or_404(db: Session, contract_id: int):
"""Return the contract with the given id or raise 404."""
contract = get_contract_or_none(db, contract_id)
if contract is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Energy contract {contract_id!r} not found.",
)
return contract
def _contract_detail(db: Session, contract) -> ContractDetailResponse:
"""Build a ContractDetailResponse for *contract*, loading versions."""
# Eager-load versions ordered by effective_from for consistent display.
from sqlalchemy import select
from app.models.energy import EnergyContractVersion
versions = list(
db.execute(
select(EnergyContractVersion)
.where(EnergyContractVersion.contract_id == contract.id)
.order_by(EnergyContractVersion.effective_from)
)
.scalars()
.all()
)
version_schemas = [ContractVersionResponse.model_validate(v) for v in versions]
return ContractDetailResponse(
id=contract.id,
name=contract.name,
kind=contract.kind,
scope=contract.scope,
active=contract.active,
currency=contract.currency,
created_at=contract.created_at,
updated_at=contract.updated_at,
versions=version_schemas,
)
def _raise_422_for_profile_error(exc: Exception) -> Any:
"""Convert a ProfileValidationError or ProfileNotFoundError into HTTP 422."""
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=str(exc),
)
def _localize_effective_from(dt: datetime | None) -> datetime:
"""Resolve *dt* to an aware UTC datetime for storage.
Rules (Principle A):
- If *dt* is None → use ``datetime.now(UTC)`` (unchanged from before).
- If *dt* is timezone-aware → convert to UTC as-is.
- If *dt* is timezone-naive → interpret as server local wall-clock time,
localize with ``local_tz()``, then convert to UTC.
This means a front-end that sends ``"2026-06-25T00:00:00"`` (no Z) has it
interpreted as local midnight (e.g. CEST = UTC+2 → stored as 2026-06-24T22:00:00Z),
not as UTC midnight.
"""
if dt is None:
return datetime.now(UTC)
if dt.tzinfo is not None:
# Already aware: convert to UTC.
return dt.astimezone(UTC)
# Naive: assume server local wall-clock.
tz = _tz_mod.local_tz()
local_dt = dt.replace(tzinfo=tz)
return local_dt.astimezone(UTC)
# ---------------------------------------------------------------------------
# GET /api/energy/profiles
# ---------------------------------------------------------------------------
@router.get("/profiles", response_model=ProfilesResponse)
def get_profiles(
_auth: AuthenticatedSession = Depends(require_session),
) -> ProfilesResponse:
"""List all available pricing profile structures.
Returns the full profile structure for each supported contract kind
(``manual`` and ``tibber``). The front-end uses this to dynamically
render the correct fields and labels for the contract creation/editing form.
"""
return ProfilesResponse(profiles=list_profiles())
# ---------------------------------------------------------------------------
# GET /api/energy/contracts
# ---------------------------------------------------------------------------
@router.get("/contracts", response_model=ContractListResponse)
def list_energy_contracts(
scope: str = "electricity",
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> ContractListResponse:
"""List all energy contracts with their active status.
Scope defaults to ``electricity`` for old clients. Returns a flat list (no embedded version history); use
GET /api/energy/contracts/{id} to fetch the full version history for a
specific contract.
"""
if scope not in set(CONTRACT_KIND_SCOPES.values()):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Unknown energy contract scope: {scope!r}",
)
contracts = list_contracts(db, scope=scope)
items = [ContractResponse.model_validate(c) for c in contracts]
return ContractListResponse(items=items, total=len(items))
# ---------------------------------------------------------------------------
# POST /api/energy/contracts
# ---------------------------------------------------------------------------
@router.post(
"/contracts",
response_model=ContractDetailResponse,
status_code=status.HTTP_201_CREATED,
)
def create_energy_contract(
body: ContractCreate,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> ContractDetailResponse:
"""Create a new energy contract with an initial pricing version.
The ``values`` dict is validated against the YAML profile for the given
``kind``; non-conforming values result in 422 Unprocessable Entity.
The new contract is created with ``active=False``; use
PATCH /api/energy/contracts/{id} with ``active=true`` to activate it.
"""
effective_from = _localize_effective_from(body.effective_from)
try:
contract = create_contract(
db,
name=body.name,
kind=body.kind,
currency=body.currency,
scope=body.scope,
values=body.values,
effective_from=effective_from,
)
except (ProfileNotFoundError, ProfileValidationError, ContractScopeError) as exc:
_raise_422_for_profile_error(exc)
db.commit()
db.refresh(contract)
logger.info("Created energy contract id=%d name=%r kind=%s", contract.id, contract.name, contract.kind)
return _contract_detail(db, contract)
# ---------------------------------------------------------------------------
# GET /api/energy/contracts/{id}
# ---------------------------------------------------------------------------
@router.get("/contracts/{contract_id}", response_model=ContractDetailResponse)
def get_energy_contract(
contract_id: int,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> ContractDetailResponse:
"""Return a single energy contract with its full version history.
Versions are ordered by ``effective_from`` ascending so the caller can
easily inspect the pricing timeline.
"""
contract = _get_contract_or_404(db, contract_id)
return _contract_detail(db, contract)
# ---------------------------------------------------------------------------
# PATCH /api/energy/contracts/{id}
# ---------------------------------------------------------------------------
@router.patch("/contracts/{contract_id}", response_model=ContractDetailResponse)
def patch_energy_contract(
contract_id: int,
body: ContractPatch,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> ContractDetailResponse:
"""Partially update a contract: rename or change activation status.
- ``name``: updates the human-readable label.
- ``active=true``: activates this contract (same-scope contracts are deactivated).
- ``active=false``: deactivates this contract (no effect on others).
At most one contract may be active per scope; the service layer enforces
scope-local mutual exclusion.
"""
contract = _get_contract_or_404(db, contract_id)
was_active = contract.active
if body.name is not None:
contract.name = body.name
contract.updated_at = datetime.now(UTC)
if body.active is True:
activate_contract(db, contract)
elif body.active is False:
deactivate_contract(db, contract)
db.commit()
db.refresh(contract)
if body.active is True and not was_active and contract.kind == "tibber":
trigger_tibber_refresh()
return _contract_detail(db, contract)
# ---------------------------------------------------------------------------
# POST /api/energy/contracts/{id}/versions
# ---------------------------------------------------------------------------
@router.post(
"/contracts/{contract_id}/versions",
response_model=ContractDetailResponse,
status_code=status.HTTP_201_CREATED,
)
def add_contract_version(
contract_id: int,
body: VersionCreate,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> ContractDetailResponse:
"""Add a new pricing version to an existing contract.
This is how price changes are recorded: the current open version is
automatically closed (its ``effective_to`` is set to ``body.effective_from``)
and a new version is created starting at ``body.effective_from``.
The ``values`` dict must conform to the contract's pricing profile.
Non-conforming values return 422. If ``effective_from`` is not strictly
after the previous version's ``effective_from``, 422 is returned without
writing any rows.
Historical versions are never modified; this endpoint is append-only.
"""
contract = _get_contract_or_404(db, contract_id)
effective_from = _localize_effective_from(body.effective_from)
try:
add_version(
db,
contract,
effective_from=effective_from,
values=body.values,
)
except ContractVersionError as exc:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=str(exc),
)
except (ProfileNotFoundError, ProfileValidationError) as exc:
_raise_422_for_profile_error(exc)
db.commit()
db.refresh(contract)
return _contract_detail(db, contract)
+221
View File
@@ -0,0 +1,221 @@
"""Expose API routes (M5-T12).
Three endpoints:
GET /api/expose — Return catalog of exposable entities, per-key
toggle state, and MQTT/Discovery connection status.
PUT /api/expose — Set per-key toggle state (map key → bool);
triggers a HA Discovery re-publish on success.
POST /api/expose/republish — Manually trigger a full HA Discovery re-publish.
Auth model:
- GET: session required (no CSRF — read-only).
- PUT, POST: session + CSRF required.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api.routes.api.deps import require_csrf, require_session
from app.config import get_settings
from app.dependencies import get_db
from app.services.config_page import build_runtime_settings
from app.integrations.expose import CatalogEntry, build_catalog
from app.integrations.mqtt import mqtt_manager
from app.models.expose import ExposedEntityToggle
from app.schemas.expose import (
CatalogEntrySchema,
DeviceInfoSchema,
ExposeResponse,
ExposeUpdateRequest,
ExposeUpdateResponse,
ExposableEntitySchema,
MqttStatusSchema,
RepublishResponse,
)
from app.services.auth import AuthenticatedSession
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["api-expose"])
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
def _get_mqtt_status(db: Session) -> MqttStatusSchema:
"""Build MQTT/Discovery status from live runtime state (DB-merged settings)."""
settings = build_runtime_settings(db, get_settings())
return MqttStatusSchema(
mqtt_configured=mqtt_manager.is_configured(settings),
mqtt_connected=mqtt_manager.is_connected,
discovery_enabled=bool(settings.ha_discovery_enabled),
)
def _entry_to_schema(entry: CatalogEntry) -> CatalogEntrySchema:
"""Convert a CatalogEntry to its Pydantic schema form.
Excludes ``value_getter`` because it is a non-serialisable callable.
"""
entity = entry.entity
return CatalogEntrySchema(
entity=ExposableEntitySchema(
key=entity.key,
component=entity.component,
device=DeviceInfoSchema(
identifiers=list(entity.device.identifiers),
name=entity.device.name,
),
device_class=entity.device_class,
unit=entity.unit,
name=entity.name,
state_class=entity.state_class,
),
enabled=entry.enabled,
)
def _build_response_data(
session: Session,
) -> tuple[list[CatalogEntrySchema], MqttStatusSchema]:
"""Return (catalog_entries, mqtt_status) for building GET / PUT responses."""
catalog = build_catalog(session)
catalog_schema = [_entry_to_schema(e) for e in catalog]
mqtt_status = _get_mqtt_status(session)
return catalog_schema, mqtt_status
# ---------------------------------------------------------------------------
# GET /api/expose
# ---------------------------------------------------------------------------
@router.get("/expose", response_model=ExposeResponse)
def get_expose(
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> ExposeResponse:
"""Return the full exposable-entity catalog with toggle states and MQTT status.
The catalog is computed dynamically from registered providers (e.g. the
Modbus provider enumerates all enabled devices and their metric entities).
Toggle states come from the ``exposed_entity_toggle`` table; entities with
no row default to ``enabled=False``.
"""
catalog_schema, mqtt_status = _build_response_data(db)
return ExposeResponse(catalog=catalog_schema, mqtt_status=mqtt_status)
# ---------------------------------------------------------------------------
# PUT /api/expose
# ---------------------------------------------------------------------------
@router.put("/expose", response_model=ExposeUpdateResponse)
def put_expose(
body: ExposeUpdateRequest,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> ExposeUpdateResponse:
"""Set per-entity toggle state.
Accepts a map of ``{key: bool}`` and upserts rows in the
``exposed_entity_toggle`` table. Only keys present in ``body.toggles``
are touched; other entities' toggles are left unchanged.
After writing the toggles, triggers a HA Discovery re-publish so any
changes (enabled ↔ disabled) are reflected in Home Assistant immediately.
"""
now = datetime.now(UTC)
for key, enabled in body.toggles.items():
existing = (
db.query(ExposedEntityToggle)
.filter(ExposedEntityToggle.key == key)
.first()
)
if existing is not None:
existing.enabled = enabled
existing.updated_at = now
else:
db.add(
ExposedEntityToggle(
key=key,
enabled=enabled,
updated_at=now,
)
)
db.commit()
# Trigger discovery re-publish after toggle change.
_trigger_republish(db)
catalog_schema, mqtt_status = _build_response_data(db)
return ExposeUpdateResponse(catalog=catalog_schema, mqtt_status=mqtt_status)
# ---------------------------------------------------------------------------
# POST /api/expose/republish
# ---------------------------------------------------------------------------
@router.post("/expose/republish", response_model=RepublishResponse)
def post_expose_republish(
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> RepublishResponse:
"""Manually trigger a full HA Discovery re-publish.
Calls ``publish_discovery(session)`` from the HA discovery service (M5-T11).
Returns a status indicating whether the publish was attempted (or skipped
because MQTT / discovery is not enabled / connected).
"""
settings = build_runtime_settings(db, get_settings())
if not (settings.mqtt_enabled and settings.ha_discovery_enabled and mqtt_manager.is_connected):
return RepublishResponse(
ok=False,
message="MQTT / HA Discovery not enabled or broker not connected.",
)
try:
_trigger_republish(db)
return RepublishResponse(
ok=True,
message="HA Discovery re-published successfully.",
)
except Exception as exc:
logger.exception("post_expose_republish: unexpected error during publish")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Discovery re-publish failed.",
) from exc
# ---------------------------------------------------------------------------
# Internal: trigger discovery re-publish
# ---------------------------------------------------------------------------
def _trigger_republish(session: Session) -> None:
"""Call publish_discovery from the HA discovery service.
No-op if MQTT / discovery is not enabled or broker is not connected
(publish_discovery guards internally). All errors are swallowed to avoid
breaking the API response.
"""
try:
from app.services.ha_discovery import publish_discovery
publish_discovery(session)
except Exception:
logger.exception("_trigger_republish: publish_discovery raised an error")
+150
View File
@@ -0,0 +1,150 @@
"""Authenticated API for the thermal 15-minute cost ledger."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from decimal import Decimal
from typing import Literal
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from app.api.routes.api.deps import require_csrf, require_session
from app.dependencies import get_db
from app.models.energy import MeterCostPeriod
from app.schemas.meter_cost import (
MeterCostPeriodSchema,
MeterCostRecomputeResponse,
MeterCostsResponse,
ThermalCostSummaryResponse,
)
from app.services.auth import AuthenticatedSession
from app.services.meter_cost import recompute_range, summarize
from app.services.timezone import local_midnight_utc, local_now
router = APIRouter(prefix="/api/energy/meter-costs", tags=["api-energy"])
_LIMIT_MAX = 5000
_RECOMPUTE_MAX_DAYS = 31
_QUARTER = timedelta(minutes=15)
def _utc(value: datetime) -> datetime:
return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
def _decimal_strings(value: object) -> object:
if isinstance(value, dict):
return {str(key): _decimal_strings(item) for key, item in value.items()}
if isinstance(value, Decimal):
return format(value, "f")
return str(value) if isinstance(value, (int, float)) else value
def _row_schema(row: MeterCostPeriod) -> MeterCostPeriodSchema:
return MeterCostPeriodSchema(
commodity=row.commodity,
period_start=_utc(row.period_start), period_end=_utc(row.period_end),
meter_id=row.meter_id, source_binding_id=row.source_binding_id,
contract_version_id=row.contract_version_id, quantity=format(row.quantity, "f"),
cost=format(row.cost, "f"), currency=row.currency,
cost_breakdown=_decimal_strings(row.cost_breakdown),
pricing_snapshot=_decimal_strings(row.pricing_snapshot), quality=row.quality,
degraded=row.degraded, degraded_reason=row.degraded_reason,
)
@router.get("", response_model=MeterCostsResponse)
def get_meter_costs(
scope: Literal["thermal"] = Query("thermal"),
commodity: Literal["heating", "hot_water"] | None = None,
start: datetime | None = None,
end: datetime | None = None,
limit: int = Query(500, ge=1, le=_LIMIT_MAX),
offset: int = Query(0, ge=0),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> MeterCostsResponse:
"""List thermal rows in a half-open time window with stable pagination."""
del scope
if start is not None and end is not None and _utc(end) <= _utc(start):
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "'end' must be after 'start'.")
clauses = []
if commodity is not None:
clauses.append(MeterCostPeriod.commodity == commodity)
if start is not None:
clauses.append(MeterCostPeriod.period_start >= _utc(start))
if end is not None:
clauses.append(MeterCostPeriod.period_start < _utc(end))
total = db.scalar(select(func.count()).select_from(MeterCostPeriod).where(*clauses)) or 0
rows = db.execute(
select(MeterCostPeriod).where(*clauses).order_by(MeterCostPeriod.period_start, MeterCostPeriod.id)
.offset(offset).limit(limit)
).scalars().all()
return MeterCostsResponse(items=[_row_schema(row) for row in rows], total=total)
@router.get("/summary", response_model=ThermalCostSummaryResponse)
def get_meter_cost_summary(
scope: Literal["thermal"] = Query("thermal"),
start: datetime | None = None,
end: datetime | None = None,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> ThermalCostSummaryResponse:
"""Summarize thermal variable and once-per-contract daily fixed costs."""
del scope
if start is None or end is None:
today = local_now().date()
start = start or local_midnight_utc(today)
end = end or local_midnight_utc(today + timedelta(days=1))
start, end = _utc(start), _utc(end)
if end <= start:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "'end' must be after 'start'.")
result = summarize(db, start, end)
breakdown = result["breakdown"]
fixed_breakdown = result["fixed_breakdown"]
fixed = result["fixed_cost"]
return ThermalCostSummaryResponse(
currency=result["currency"], heating=format(breakdown["heating"], "f"),
hot_water_heating=format(breakdown["hot_water_heating"], "f"),
hot_water=format(breakdown["hot_water"], "f"), hot_water_tax=format(breakdown["hot_water_tax"], "f"),
variable_subtotal=format(result["variable_cost"], "f"),
fixed_breakdown={key: format(value, "f") for key, value in fixed_breakdown.items()},
fixed_subtotal=format(fixed, "f"),
all_in=format(result["total_cost"], "f"), period_count=result["period_count"],
degraded_count=result["degraded_count"],
)
@router.post("/recompute", response_model=MeterCostRecomputeResponse)
def post_meter_cost_recompute(
scope: Literal["thermal"] = Query("thermal"),
start: datetime = Query(...), end: datetime = Query(...),
db: Session = Depends(get_db), _auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> MeterCostRecomputeResponse:
"""Atomically overwrite closed, UTC-quarter thermal rows in a bounded window."""
del scope
start, end = _utc(start), _utc(end)
if end <= start or end - start > timedelta(days=_RECOMPUTE_MAX_DAYS):
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "invalid or overlarge recompute window")
if start.minute % 15 or start.second or start.microsecond or end.minute % 15 or end.second or end.microsecond:
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "start and end must align to UTC quarters")
if end > datetime.now(UTC):
raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, "recompute window must be closed")
try:
processed = recompute_range(db, start, end, commit=False)
# Ensure pending upserts participate in this transaction before the
# counts are read; a flush/query failure must still roll everything back.
db.flush()
rows = db.execute(select(MeterCostPeriod.degraded).where(
MeterCostPeriod.period_start >= start, MeterCostPeriod.period_start < end
)).scalars().all()
degraded = sum(bool(value) for value in rows)
db.commit()
except Exception:
db.rollback()
raise
return MeterCostRecomputeResponse(processed=processed, normal=len(rows) - degraded, degraded=degraded)
+414
View File
@@ -0,0 +1,414 @@
"""Authenticated HTTP contract for meter sources, channels, and bindings."""
from __future__ import annotations
from datetime import UTC, datetime
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.api.routes.api.deps import require_csrf, require_session
from app.config import get_settings
from app.dependencies import get_db
from app.integrations.meter_sources import SourceProfileError, list_source_profiles, sanitize_source_config
from app.models.energy import DsmrReading, Meter
from app.models.meter_source import MeterSource, MeterSourceBinding, MeterSourceChannel, WarmteLinkReading
from app.schemas.meter_source import (
BindingCreate, BindingListResponse, BindingPatch, BindingResponse, ChannelBindingSummaryResponse,
BindingTransferRequest, BindingTransferResponse,
ChannelReadingResponse,
ChannelReadingsResponse, CommoditiesResponse, CommodityResponse, DiscoverResponse,
DiscoverChannelResponse,
MeterSourceChannelListResponse, MeterSourceChannelResponse, MeterSourceCreate,
MeterSourceListResponse, MeterSourcePatch, MeterSourceResponse, SourceConfigFieldResponse,
SourceProfileResponse, SourceProfilesResponse,
)
from app.services.auth import AuthenticatedSession
from app.services.config_page import build_runtime_settings
from app.services.dsmr_ingest import apply_dsmr_subscription
from app.services.meter_sources import (
BindingNotFoundError, ChannelNotFoundError, MeterNotFoundError,
MeterSourceError, SourceDeleteRestrictedError, SourceNotFoundError, create_binding,
create_source, delete_source, list_bindings, list_sources, transfer_binding, update_binding, update_source,
)
from app.services.energy_cost import recompute_range as electricity_recompute_range
from app.services import timezone as _tz_mod
from app.services.warmtelink_worker import warmtelink_worker_manager
router = APIRouter(prefix="/api/energy", tags=["api-energy-meter-sources"])
def _reconcile_runtimes_after_commit(db: Session) -> None:
"""Best-effort runtime convergence after a durable source CRUD commit."""
try:
warmtelink_worker_manager.reconcile()
except Exception:
# The manager records individual source failures itself. Do not turn a
# successful durable create/update/delete into a misleading HTTP 500.
pass
try:
apply_dsmr_subscription(build_runtime_settings(db, get_settings()))
except Exception:
# DSMR owns independent source clients. Its failure must neither undo
# durable CRUD nor prevent the WarmteLink manager from converging.
pass
finally:
# DSMR health callbacks use short independent sessions. Make a CRUD
# response observe any durable status change they just committed.
db.expire_all()
def _as_utc(value: datetime) -> datetime:
if value.tzinfo is None:
return value.replace(tzinfo=_tz_mod.local_tz()).astimezone(UTC)
return value.astimezone(UTC)
def _source_or_404(db: Session, uuid: str) -> MeterSource:
source = db.execute(select(MeterSource).where(MeterSource.uuid == uuid)).scalar_one_or_none()
if source is None:
raise HTTPException(status_code=404, detail="Meter source not found.")
return source
def _channel_or_404(db: Session, source: MeterSource, uuid: str) -> MeterSourceChannel:
channel = db.execute(
select(MeterSourceChannel).where(
MeterSourceChannel.uuid == uuid, MeterSourceChannel.source_id == source.id
)
).scalar_one_or_none()
if channel is None:
raise HTTPException(status_code=404, detail="Meter source channel not found.")
return channel
def _source_response(source: MeterSource) -> MeterSourceResponse:
return MeterSourceResponse(
uuid=source.uuid, name=source.name, kind=source.kind, enabled=source.enabled,
config=sanitize_source_config(source.kind, source.config), status=source.status,
last_seen_at=source.last_seen_at, last_error=source.last_error,
created_at=source.created_at, updated_at=source.updated_at,
)
def binding_response(binding: MeterSourceBinding) -> BindingResponse:
return BindingResponse(
uuid=binding.uuid, meter_id=binding.meter_id, source_channel_uuid=binding.channel.uuid,
source_uuid=binding.channel.source.uuid, started_at=binding.started_at, ended_at=binding.ended_at,
created_at=binding.created_at, updated_at=binding.updated_at,
)
def _binding_error(exc: MeterSourceError) -> HTTPException:
if isinstance(exc, (SourceNotFoundError, ChannelNotFoundError, MeterNotFoundError, BindingNotFoundError)):
return HTTPException(status_code=404, detail=str(exc))
return HTTPException(status_code=422, detail=str(exc))
def _recompute_binding_commodity(db: Session, commodity: str, start: datetime) -> None:
end = datetime.now(UTC)
if start >= end:
return
if commodity == "electricity":
electricity_recompute_range(db, start, end, commit=False, strict=True)
else:
from app.services.meter_cost import recompute_range
recompute_range(db, start, end, commit=False)
def _republish_after_commit(db: Session) -> None:
try:
from app.services.ha_discovery import publish_discovery
publish_discovery(db)
except Exception:
pass
@router.get("/source-profiles", response_model=SourceProfilesResponse)
def source_profiles(_auth: AuthenticatedSession = Depends(require_session)) -> SourceProfilesResponse:
"""Return profile metadata; default secrets are never populated with stored values."""
profiles = []
for profile in list_source_profiles():
fields = [
SourceConfigFieldResponse(name=f.name, value_type=f.value_type.__name__, default=f.default,
required=f.required, secret=f.secret)
for f in profile.fields
]
profiles.append(SourceProfileResponse(
kind=profile.kind, fields=fields,
defaults={f.name: f.default for f in profile.fields if not f.required},
capabilities=sorted(profile.capabilities), allowed_units=sorted(profile.allowed_units),
))
return SourceProfilesResponse(items=profiles)
@router.get("/commodities", response_model=CommoditiesResponse)
def commodities(_auth: AuthenticatedSession = Depends(require_session)) -> CommoditiesResponse:
return CommoditiesResponse(items=[
CommodityResponse(key="electricity", unit="kWh", capabilities=["meter", "binding", "cost"]),
CommodityResponse(key="heating", unit="GJ", capabilities=["meter", "binding"]),
CommodityResponse(key="hot_water", unit="", capabilities=["meter", "binding"]),
])
@router.get("/sources", response_model=MeterSourceListResponse)
def get_sources(db: Session = Depends(get_db), _auth: AuthenticatedSession = Depends(require_session)) -> MeterSourceListResponse:
items = [_source_response(source) for source in list_sources(db)]
return MeterSourceListResponse(items=items, total=len(items))
@router.post("/sources", response_model=MeterSourceResponse, status_code=status.HTTP_201_CREATED)
def post_source(body: MeterSourceCreate, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session), _csrf: None = Depends(require_csrf)) -> MeterSourceResponse:
try:
source = create_source(db, name=body.name, kind=body.kind, config=body.config, enabled=body.enabled)
db.commit()
_reconcile_runtimes_after_commit(db)
return _source_response(_source_or_404(db, source.uuid))
except (SourceProfileError, MeterSourceError) as exc:
db.rollback()
raise HTTPException(status_code=422, detail=str(exc)) from exc
@router.get("/sources/{source_uuid}", response_model=MeterSourceResponse)
def get_source_detail(source_uuid: str, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session)) -> MeterSourceResponse:
return _source_response(_source_or_404(db, source_uuid))
@router.patch("/sources/{source_uuid}", response_model=MeterSourceResponse)
def patch_source(source_uuid: str, body: MeterSourcePatch, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session), _csrf: None = Depends(require_csrf)) -> MeterSourceResponse:
source = _source_or_404(db, source_uuid)
try:
updated = update_source(db, source.id, name=body.name, enabled=body.enabled, config_patch=body.config)
db.commit()
_reconcile_runtimes_after_commit(db)
return _source_response(_source_or_404(db, updated.uuid))
except (SourceProfileError, MeterSourceError) as exc:
db.rollback()
raise _binding_error(exc) from exc
@router.delete(
"/sources/{source_uuid}", status_code=status.HTTP_204_NO_CONTENT, response_model=None
)
def remove_source(source_uuid: str, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session), _csrf: None = Depends(require_csrf)) -> None:
source = _source_or_404(db, source_uuid)
# DSMR readings are not a relationship on MeterSource to avoid loading a large history.
if db.execute(select(DsmrReading.id).where(DsmrReading.meter_source_id == source.id).limit(1)).scalar() is not None:
raise HTTPException(status_code=409, detail="Meter source has dependent readings.")
try:
delete_source(db, source.id)
db.commit()
_reconcile_runtimes_after_commit(db)
return Response(status_code=status.HTTP_204_NO_CONTENT)
except SourceDeleteRestrictedError as exc:
db.rollback()
raise HTTPException(status_code=409, detail=str(exc)) from exc
@router.post("/sources/{source_uuid}/discover", response_model=DiscoverResponse)
def discover_source(source_uuid: str, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session), _csrf: None = Depends(require_csrf)) -> DiscoverResponse:
source = _source_or_404(db, source_uuid)
if source.kind == "warmtelink_serial":
if not source.enabled:
return DiscoverResponse(
requested=False, supported=True, status="error",
detail="The WarmteLink source is disabled.", channels=_discover_channels(db, source),
)
# This merely schedules lifecycle convergence. It never opens a serial
# descriptor or waits for a frame in the request thread; the one managed
# worker remains the sole owner of serial I/O and can keep reconnecting.
request = warmtelink_worker_manager.request_discovery(source.id)
if request.completed.is_set():
# A worker may have accepted a frame during the bounded wait.
# Refresh only durable accepted metadata, never candidates/raw data.
db.expire_all()
source = _source_or_404(db, source_uuid)
return DiscoverResponse(
requested=request.status != "error", supported=True, status=request.status,
request_id=request.request_id or None, detail=request.detail,
channels=_discover_channels(db, source),
)
return DiscoverResponse(requested=False, supported=True, status="managed_by_runtime",
detail="This source is discovered by its runtime subscription; no connection was opened.")
@router.get("/sources/{source_uuid}/channels", response_model=MeterSourceChannelListResponse)
def source_channels(source_uuid: str, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session)) -> MeterSourceChannelListResponse:
source = _source_or_404(db, source_uuid)
channels = db.execute(select(MeterSourceChannel).where(MeterSourceChannel.source_id == source.id)).scalars().all()
items = []
for channel in channels:
bindings = list_bindings(db, channel_id=channel.id)
meter_ids = [binding.meter_id for binding in bindings]
items.append(MeterSourceChannelResponse(
uuid=channel.uuid, label=channel.label, suggested_commodity=channel.suggested_commodity,
unit=channel.unit, device_type=channel.device_type, latest_value=channel.latest_value,
latest_at=channel.latest_at, latest_quality=channel.latest_quality, binding_count=len(bindings),
bound_meter_ids=meter_ids,
binding_summary=ChannelBindingSummaryResponse(count=len(bindings), meter_ids=meter_ids),
))
return MeterSourceChannelListResponse(items=items, total=len(items), source_status=source.status)
@router.get("/sources/{source_uuid}/channels/{channel_uuid}/readings", response_model=ChannelReadingsResponse)
def channel_readings(source_uuid: str, channel_uuid: str, limit: int = Query(default=100, ge=1, le=1000),
from_: datetime | None = Query(default=None, alias="from"),
to: datetime | None = Query(default=None), db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session)) -> ChannelReadingsResponse:
source = _source_or_404(db, source_uuid)
channel = _channel_or_404(db, source, channel_uuid)
if from_ is not None and to is not None and _as_utc(from_) >= _as_utc(to):
raise HTTPException(status_code=422, detail="'from' must be earlier than 'to'.")
if source.kind == "warmtelink_serial":
statement = select(WarmteLinkReading).where(WarmteLinkReading.channel_id == channel.id)
model = WarmteLinkReading
else:
# DSMR remains a source-level protocol history. Its channel is the
# public electricity identity, while payload/telegram diagnostics stay
# private to ingestion and the legacy latest endpoint.
statement = select(DsmrReading).where(DsmrReading.meter_source_id == source.id)
model = DsmrReading
if from_ is not None:
statement = statement.where(model.recorded_at >= _as_utc(from_))
if to is not None:
statement = statement.where(model.recorded_at < _as_utc(to))
rows = list(db.execute(statement.order_by(model.recorded_at.asc()).limit(limit)).scalars())
return ChannelReadingsResponse(
items=[ChannelReadingResponse(
recorded_at=row.recorded_at,
value=getattr(row, "value", None), quality=getattr(row, "quality", None),
) for row in rows],
total=len(rows),
)
def _discover_channels(db: Session, source: MeterSource) -> list[DiscoverChannelResponse]:
"""Return only public, accepted channel metadata for discover responses."""
return [
DiscoverChannelResponse(
uuid=channel.uuid, label=channel.label, unit=channel.unit,
latest_value=channel.latest_value, latest_at=channel.latest_at,
latest_quality=channel.latest_quality,
)
for channel in db.execute(
select(MeterSourceChannel).where(MeterSourceChannel.source_id == source.id)
).scalars()
]
@router.get("/meters/{meter_id}/bindings", response_model=BindingListResponse)
def meter_bindings(meter_id: int, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session)) -> BindingListResponse:
if db.get(Meter, meter_id) is None:
raise HTTPException(status_code=404, detail="Meter not found.")
items = [binding_response(binding) for binding in list_bindings(db, meter_id=meter_id)]
return BindingListResponse(items=items, total=len(items))
@router.post("/meters/{meter_id}/bindings", response_model=BindingResponse, status_code=status.HTTP_201_CREATED)
def post_meter_binding(meter_id: int, body: BindingCreate, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session), _csrf: None = Depends(require_csrf)) -> BindingResponse:
channel = db.execute(select(MeterSourceChannel).where(MeterSourceChannel.uuid == body.source_channel_uuid)).scalar_one_or_none()
if channel is None:
raise HTTPException(status_code=404, detail="Meter source channel not found.")
try:
binding = create_binding(db, meter_id=meter_id, channel_id=channel.id, started_at=_as_utc(body.started_at),
ended_at=_as_utc(body.ended_at) if body.ended_at else None)
meter = db.get(Meter, meter_id)
db.flush()
_recompute_binding_commodity(db, meter.commodity, _as_utc(body.started_at))
db.commit()
db.refresh(binding)
_republish_after_commit(db)
return binding_response(binding)
except MeterSourceError as exc:
db.rollback()
raise _binding_error(exc) from exc
except Exception:
db.rollback()
raise
@router.patch("/bindings/{binding_uuid}", response_model=BindingResponse)
def patch_binding(binding_uuid: str, body: BindingPatch, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session), _csrf: None = Depends(require_csrf)) -> BindingResponse:
binding = db.execute(select(MeterSourceBinding).where(MeterSourceBinding.uuid == binding_uuid)).scalar_one_or_none()
if binding is None:
raise HTTPException(status_code=404, detail="Meter source binding not found.")
try:
# ``ended_at`` has three meaningful states in the service layer: omitted
# keeps the existing boundary, null reopens the interval, and a datetime
# changes the exclusive end. Do not collapse omitted into null here.
changes: dict[str, datetime | None] = {}
if "started_at" in body.model_fields_set:
changes["started_at"] = _as_utc(body.started_at) if body.started_at is not None else None
if "ended_at" in body.model_fields_set:
changes["ended_at"] = _as_utc(body.ended_at) if body.ended_at is not None else None
old_started_at = _as_utc(binding.started_at)
old_ended_at = _as_utc(binding.ended_at) if binding.ended_at is not None else None
updated = update_binding(db, binding.id, **changes)
meter = db.get(Meter, updated.meter_id)
if "started_at" in changes:
earliest = min(old_started_at, _as_utc(updated.started_at))
elif "ended_at" in changes:
new_ended_at = _as_utc(updated.ended_at) if updated.ended_at is not None else None
changed_ends = [value for value in (old_ended_at, new_ended_at) if value is not None]
earliest = min(changed_ends) if changed_ends else old_started_at
else:
earliest = old_started_at
db.flush()
_recompute_binding_commodity(db, meter.commodity, earliest)
db.commit()
db.refresh(updated)
_republish_after_commit(db)
return binding_response(updated)
except MeterSourceError as exc:
db.rollback()
raise _binding_error(exc) from exc
except Exception:
db.rollback()
raise
@router.post("/meters/{meter_id}/bindings/transfer", response_model=BindingTransferResponse)
def post_binding_transfer(
meter_id: int, body: BindingTransferRequest, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session), _csrf: None = Depends(require_csrf),
) -> BindingTransferResponse:
source = db.execute(select(MeterSourceBinding).where(
MeterSourceBinding.uuid == body.from_binding_uuid
)).scalar_one_or_none()
channel = db.execute(select(MeterSourceChannel).where(
MeterSourceChannel.uuid == body.to_source_channel_uuid
)).scalar_one_or_none()
if source is None or channel is None:
raise HTTPException(status_code=404, detail="Meter source binding or channel not found.")
effective_at = _as_utc(body.effective_at)
try:
closed, created = transfer_binding(db, target_meter_id=meter_id, from_binding_id=source.id,
to_channel_id=channel.id, effective_at=effective_at)
meter = db.get(Meter, meter_id)
if closed.meter_id == meter.id:
earliest = effective_at
else:
earliest = min(_as_utc(closed.ended_at), effective_at)
db.flush()
_recompute_binding_commodity(db, meter.commodity, earliest)
db.commit()
db.refresh(closed)
db.refresh(created)
except MeterSourceError as exc:
db.rollback()
raise _binding_error(exc) from exc
except Exception:
db.rollback()
raise
_republish_after_commit(db)
return BindingTransferResponse(closed_binding=binding_response(closed), created_binding=binding_response(created))
+449
View File
@@ -0,0 +1,449 @@
"""Meter CRUD, swap declaration, and retroactive recompute API (M7-T05).
All endpoints are under /api/energy/meters, require an authenticated session,
and write endpoints (POST/PATCH) additionally require a non-empty X-CSRF-Token
header.
Route semantics
---------------
GET /api/energy/meters — list all meter epochs (ascending started_at)
POST /api/energy/meters — declare a meter swap / initial meter epoch
PATCH /api/energy/meters/{id} — edit label / note, or correct started_at (retroactive)
Retroactive recompute
---------------------
Whenever a write operation changes a meter's ``started_at`` (new declaration
or PATCH correction), the affected billing window is re-judged via
``recompute_range``:
- **POST** (new meter, possibly retroactive):
window = [new_meter.started_at, now)
Rationale: the new meter's ``started_at`` closes the previous meter at that
point; all periods from that boundary forward may have a different meter
attribution. Using ``now`` as the upper bound is safe because
``recompute_range`` only processes closed quarters and the operation is
idempotent.
- **PATCH started_at** (retroactive correction):
window = [min(old_started_at, new_started_at), now)
Rationale: shifting the boundary in either direction affects all periods
between the old and new boundary (and potentially beyond if re-attribution
cascades). Using the minimum of the two timestamps guarantees the entire
affected range is covered; using ``now`` as the upper bound is safe and
idempotent.
``started_at`` localisation (Principle A, FU10 convention)
----------------------------------------------------------
If the client sends a timezone-naive ``started_at`` value, it is interpreted as
the **server's local wall-clock time** and converted to UTC before storage.
Timezone-aware values are converted to UTC as-is. This is identical to the
``_localize_effective_from`` convention used in ``energy_contracts.py``.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy import select
from app.api.routes.api.deps import require_csrf, require_session
from app.dependencies import get_db
from app.models.energy import Meter
from app.models.meter_source import MeterSourceChannel
from app.schemas.meter import (
MeterCloseRequest,
MeterDeclareRequest,
MeterBindingSummary,
MeterListResponse,
MeterPatchRequest,
MeterResponse,
)
from app.services.meter_sources import (
ChannelNotFoundError,
MeterSourceError,
create_binding,
create_binding_for_meter_swap,
close_open_bindings_for_meter,
)
from app.services import timezone as _tz_mod
from app.services.auth import AuthenticatedSession
from app.services.energy_cost import recompute_range
from app.services.meters import (
MeterIntervalError,
MeterOverlapError,
declare_meter,
close_meter,
list_meters,
update_meter,
)
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/energy", tags=["api-energy-meters"])
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _trigger_discovery_republish(session: Session) -> None:
"""Call publish_discovery after a meter write operation (best-effort).
No-op if MQTT / discovery is not enabled or the broker is not connected
(publish_discovery guards internally). All errors are swallowed so that a
discovery failure never breaks the API response.
Must be called **after** db.commit() so that publish_discovery sees the
final committed state of the meter table when it rebuilds the catalog.
"""
try:
from app.services.ha_discovery import publish_discovery
publish_discovery(session)
except Exception:
logger.exception("_trigger_discovery_republish: publish_discovery raised an error")
def _get_meter_or_404(db: Session, meter_id: int) -> Meter:
"""Return the meter with the given id or raise 404."""
meter: Optional[Meter] = db.get(Meter, meter_id)
if meter is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Meter {meter_id!r} not found.",
)
return meter
def _localize_started_at(dt: datetime) -> datetime:
"""Resolve *dt* to an aware UTC datetime for storage.
Follows the same Principle-A convention as ``_localize_effective_from``
in ``energy_contracts.py`` (FU10):
- Timezone-aware → convert to UTC as-is.
- Timezone-naive → interpret as server local wall-clock time, localize
with ``local_tz()``, then convert to UTC.
A front-end sending ``"2026-06-25T00:00:00"`` (no Z) has it interpreted
as local midnight (e.g. CEST = UTC+2 → stored as 2026-06-24T22:00:00Z),
not as UTC midnight.
"""
if dt.tzinfo is not None:
return dt.astimezone(UTC)
tz = _tz_mod.local_tz()
local_dt = dt.replace(tzinfo=tz)
return local_dt.astimezone(UTC)
def _trigger_recompute(db: Session, start: datetime, label: str) -> int:
"""Trigger recompute_range from *start* to now (UTC).
This is the standard "retroactive window" call: everything from the
affected boundary up to the current moment needs re-attribution.
Using ``now`` as the upper bound is safe because ``recompute_range``
only touches closed quarter-hour periods and the operation is idempotent.
"""
end = datetime.now(UTC)
if start >= end:
# started_at is in the future — nothing to recompute.
logger.info("%s: started_at (%s) is in the future, skipping recompute.", label, start)
return 0
n = recompute_range(db, start, end, commit=False, strict=True)
logger.info(
"%s: recomputed %d period(s) in window [%s, %s).",
label,
n,
start.isoformat(),
end.isoformat(),
)
return n
def _recompute_commodity(db: Session, commodity: str, start: datetime, label: str) -> int:
if commodity == "electricity":
return _trigger_recompute(db, start, label)
from app.services.meter_cost import recompute_range as thermal_recompute_range
end = datetime.now(UTC)
if start >= end:
return 0
return thermal_recompute_range(db, start, end, commit=False)
def _meter_response(meter: Meter) -> MeterResponse:
"""Serialize meter plus binding summaries without exposing source config."""
response = MeterResponse.model_validate(meter)
response.bindings = [
MeterBindingSummary(
uuid=binding.uuid,
source_channel_uuid=binding.channel.uuid,
source_uuid=binding.channel.source.uuid,
started_at=binding.started_at,
ended_at=binding.ended_at,
)
for binding in meter.source_bindings
]
return response
# ---------------------------------------------------------------------------
# GET /api/energy/meters
# ---------------------------------------------------------------------------
@router.get("/meters", response_model=MeterListResponse)
def list_energy_meters(
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> MeterListResponse:
"""List all meter epochs in ascending ``started_at`` order.
Returns the full historical sequence of meter installations across all
commodities. The active meter (``ended_at=null``) appears last because it
has the latest ``started_at``.
"""
meters = list_meters(db)
items = [_meter_response(m) for m in meters]
return MeterListResponse(items=items, total=len(items))
# ---------------------------------------------------------------------------
# POST /api/energy/meters
# ---------------------------------------------------------------------------
@router.post(
"/meters",
response_model=MeterResponse,
status_code=status.HTTP_201_CREATED,
)
def declare_energy_meter(
body: MeterDeclareRequest,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> MeterResponse:
"""Declare a new meter epoch (swap, home move, or initial declaration).
Closes the current active meter for the given commodity at ``started_at``
and opens a new active meter. If no active meter exists, the new meter is
simply created without closing anything.
**Validation**: ``started_at`` must be **≥** the current active meter's
own ``started_at`` (no chronological backdate below the active epoch's
start). Equal timestamps are allowed (replaces the current meter at the
same logical moment). Violation → 422.
**Retroactive recompute**: if ``started_at`` is in the past, billing
records from that point forward are re-judged via ``recompute_range`` to
reflect the new meter attribution. The recompute is transparent — the
response body is the created meter (``MeterResponse``) only and does **not**
include a recompute count; callers should re-fetch costs if they need the
updated totals.
"""
started_at_utc = _localize_started_at(body.started_at)
try:
old_meter = db.execute(
select(Meter).where(Meter.commodity == body.commodity, Meter.ended_at.is_(None))
).scalar_one_or_none()
new_meter = declare_meter(
db,
label=body.label,
started_at=started_at_utc,
reason=body.reason.value,
commodity=body.commodity,
note=body.note,
)
db.flush() # assign PK before an optional binding and recompute
# A closed predecessor must never retain an open interval. For a
# meter swap with no selected channel we can safely hand off exactly
# one compatible open channel; ambiguity is fail-closed.
auto_channel = None
if body.source_channel_uuid is None and old_meter is not None and body.reason.value == "meter_swap":
candidates = [b for b in old_meter.source_bindings if b.ended_at is None and b.channel.unit == {"electricity": "kWh", "heating": "GJ", "hot_water": ""}.get(body.commodity)]
if len(candidates) > 1:
raise MeterSourceError("Meter swap has ambiguous open bindings; select a channel explicitly.")
if len(candidates) == 1:
auto_channel = candidates[0].channel
if body.source_channel_uuid is not None:
channel = db.execute(
select(MeterSourceChannel).where(MeterSourceChannel.uuid == body.source_channel_uuid)
).scalar_one_or_none()
if channel is None:
raise ChannelNotFoundError("Meter source channel was not found.")
if body.reason.value == "meter_swap":
create_binding_for_meter_swap(
db,
old_meter_id=old_meter.id if old_meter is not None else None,
new_meter_id=new_meter.id,
channel_id=channel.id,
started_at=started_at_utc,
)
else:
create_binding(
db,
meter_id=new_meter.id,
channel_id=channel.id,
started_at=started_at_utc,
)
elif auto_channel is not None:
create_binding_for_meter_swap(db, old_meter_id=old_meter.id, new_meter_id=new_meter.id,
channel_id=auto_channel.id, started_at=started_at_utc)
if old_meter is not None:
close_open_bindings_for_meter(db, old_meter.id, ended_at=started_at_utc)
# Keep recompute in this transaction: a failure must not leave a new
# meter, its predecessor, or either binding at a half-applied boundary.
now = datetime.now(UTC)
if started_at_utc < now:
db.flush()
_recompute_commodity(db, body.commodity, started_at_utc, "POST /api/energy/meters")
db.commit()
except (MeterIntervalError, MeterOverlapError, MeterSourceError) as exc:
db.rollback()
raise HTTPException(
status_code=(status.HTTP_404_NOT_FOUND if isinstance(exc, ChannelNotFoundError)
else status.HTTP_422_UNPROCESSABLE_ENTITY),
detail=str(exc),
)
except Exception:
db.rollback()
raise
db.refresh(new_meter)
# Trigger HA discovery re-publish so the new active meter's energy-cost
# device/sensor configuration is pushed to Home Assistant. Best-effort:
# failures are logged and swallowed; the API response is not affected.
_trigger_discovery_republish(db)
logger.info(
"POST /api/energy/meters: declared %r meter id=%d label=%r started_at=%s",
body.commodity,
new_meter.id,
new_meter.label,
started_at_utc.isoformat(),
)
return _meter_response(new_meter)
@router.post("/meters/{meter_id}/close", response_model=MeterResponse)
def close_energy_meter(
meter_id: int, body: MeterCloseRequest, db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session), _csrf: None = Depends(require_csrf),
) -> MeterResponse:
meter = _get_meter_or_404(db, meter_id)
boundary = _localize_started_at(body.ended_at)
try:
close_meter(db, meter, ended_at=boundary)
close_open_bindings_for_meter(db, meter.id, ended_at=boundary)
db.flush()
_recompute_commodity(db, meter.commodity, boundary, f"POST /api/energy/meters/{meter_id}/close")
db.commit()
except (MeterIntervalError, MeterSourceError) as exc:
db.rollback()
raise HTTPException(status_code=422, detail=str(exc)) from exc
except Exception:
db.rollback()
raise
db.refresh(meter)
_trigger_discovery_republish(db)
return _meter_response(meter)
# ---------------------------------------------------------------------------
# PATCH /api/energy/meters/{id}
# ---------------------------------------------------------------------------
@router.patch("/meters/{meter_id}", response_model=MeterResponse)
def patch_energy_meter(
meter_id: int,
body: MeterPatchRequest,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> MeterResponse:
"""Partially update a meter epoch: rename, edit note, or correct started_at.
- ``label``: updates the human-readable label.
- ``note``: updates the free-form note.
- ``started_at``: **retroactive correction** — shifts this meter's start
boundary. The service layer maintains timeline continuity by also
updating the preceding meter's ``ended_at``. Validation:
* Must be strictly after the previous meter's own ``started_at``.
* Must be strictly before this meter's ``ended_at`` (if closed).
Violation → 422.
**Retroactive recompute when ``started_at`` changes**: billing records in
the window ``[min(old, new), now)`` are re-judged to reflect the corrected
meter attribution.
Not found → 404.
"""
meter = _get_meter_or_404(db, meter_id)
# Capture old started_at before mutation (needed for recompute window).
old_started_at: Optional[datetime] = meter.started_at
# Localise started_at if provided.
new_started_at_utc: Optional[datetime] = None
if body.started_at is not None:
new_started_at_utc = _localize_started_at(body.started_at)
try:
update_meter(
db,
meter,
label=body.label,
note=body.note,
started_at=new_started_at_utc,
)
# Retroactive recompute if started_at was changed.
if new_started_at_utc is not None and old_started_at is not None:
# Normalise old_started_at to UTC-aware for comparison.
if old_started_at.tzinfo is None:
old_started_at = old_started_at.replace(tzinfo=UTC)
# Window = [min(old, new), now) — covers all periods whose attribution
# may have changed due to the boundary shift in either direction.
window_start = min(old_started_at, new_started_at_utc)
db.flush()
_recompute_commodity(
db,
meter.commodity,
window_start,
f"PATCH /api/energy/meters/{meter_id}",
)
db.commit()
except MeterIntervalError as exc:
db.rollback()
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=str(exc),
)
except Exception:
db.rollback()
raise
db.refresh(meter)
# Trigger HA discovery re-publish so label renames on the active meter
# propagate to the HA device name. Best-effort: failures are logged and
# swallowed; the API response is not affected.
_trigger_discovery_republish(db)
logger.info(
"PATCH /api/energy/meters/%d: updated meter label=%r started_at=%s",
meter_id,
meter.label,
meter.started_at,
)
return _meter_response(meter)
+511
View File
@@ -0,0 +1,511 @@
"""Modbus device CRUD, readings, metrics, and test-read API (M5-T05).
All endpoints are under /api/modbus, require an authenticated session, and
write endpoints (POST/PATCH/DELETE + test-read) additionally require a
non-empty X-CSRF-Token header.
Deletion safety:
DELETE /api/modbus/devices/{uuid} queries the application layer for
existing modbus_reading rows before deleting. Without ``cascade`` it
returns 409 and suggests disabling the device instead a friendly guard
rather than letting the DB raise. With ``cascade=true`` it removes the
readings (and expose toggles) first, then the device. SQLite FK RESTRICT
*is* enforced at runtime here (the app sets PRAGMA foreign_keys=ON; see
app/db.py), so the cascade delete order matters.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import delete as sa_delete, func, select
from sqlalchemy.orm import Session
from app.api.routes.api.deps import require_csrf, require_session
from app.dependencies import get_db
from app.integrations.modbus import driver as modbus_driver
from app.integrations.modbus.driver import ModbusDriverError
from app.integrations.modbus.profiles import (
ProfileNotFoundError,
decode as decode_profile,
list_profiles,
load_profile,
)
from app.models.expose import ExposedEntityToggle
from app.models.modbus import ModbusDevice, ModbusReading
from app.schemas.modbus import (
MetricInfo,
ModbusDeleteResponse,
ModbusDeviceCreate,
ModbusDeviceListResponse,
ModbusDeviceResponse,
ModbusDeviceUpdate,
ModbusLatestResponse,
ModbusMetricsResponse,
ModbusProfilesResponse,
ModbusReadingResponse,
ModbusReadingsResponse,
ModbusTestReadResponse,
ProfileSummary,
)
from app.services.auth import AuthenticatedSession
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/modbus", tags=["api-modbus"])
# Maximum number of readings that can be returned per request.
_READINGS_LIMIT_MAX = 5000
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _get_device_or_404(db: Session, uuid: str) -> ModbusDevice:
"""Return the device with the given UUID or raise 404."""
device = db.execute(
select(ModbusDevice).where(ModbusDevice.uuid == uuid)
).scalar_one_or_none()
if device is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device '{uuid}' not found.",
)
return device
def _label_from_key(key: str) -> str:
"""Derive a human-readable label from a metric key.
Example: ``"active_power"`` ``"Active Power"``
"""
return key.replace("_", " ").title()
# ---------------------------------------------------------------------------
# GET /api/modbus/profiles
# ---------------------------------------------------------------------------
@router.get("/profiles", response_model=ModbusProfilesResponse)
def get_profiles(
_auth: AuthenticatedSession = Depends(require_session),
) -> ModbusProfilesResponse:
"""List all available Modbus YAML profiles (name + description).
Intended for the front-end's device-creation profile drop-down.
"""
pairs = list_profiles()
return ModbusProfilesResponse(
profiles=[ProfileSummary(name=name, description=desc) for name, desc in pairs]
)
# ---------------------------------------------------------------------------
# Device CRUD
# ---------------------------------------------------------------------------
@router.get("/devices", response_model=ModbusDeviceListResponse)
def list_devices(
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> ModbusDeviceListResponse:
"""Return all Modbus devices (no pagination — device counts stay small)."""
devices = db.execute(select(ModbusDevice)).scalars().all()
items = [ModbusDeviceResponse.model_validate(d) for d in devices]
return ModbusDeviceListResponse(items=items, total=len(items))
@router.post(
"/devices",
response_model=ModbusDeviceResponse,
status_code=status.HTTP_201_CREATED,
)
def create_device(
body: ModbusDeviceCreate,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> ModbusDeviceResponse:
"""Create a new Modbus device.
- Validates that the referenced ``profile`` exists; returns 422 if not.
- Returns 201 with the created device on success.
"""
# Validate profile exists (422 if not)
try:
load_profile(body.profile)
except ProfileNotFoundError:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Profile '{body.profile}' does not exist.",
)
now = datetime.now(UTC)
device = ModbusDevice(
friendly_name=body.friendly_name,
transport=body.transport,
host=body.host,
port=body.port,
unit_id=body.unit_id,
profile=body.profile,
poll_interval_s=body.poll_interval_s,
enabled=body.enabled,
created_at=now,
updated_at=now,
)
db.add(device)
db.commit()
db.refresh(device)
logger.info("Created Modbus device %r (uuid=%s)", device.friendly_name, device.uuid)
return ModbusDeviceResponse.model_validate(device)
@router.get("/devices/{uuid}", response_model=ModbusDeviceResponse)
def get_device(
uuid: str,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> ModbusDeviceResponse:
"""Return a single Modbus device by UUID."""
device = _get_device_or_404(db, uuid)
return ModbusDeviceResponse.model_validate(device)
@router.patch("/devices/{uuid}", response_model=ModbusDeviceResponse)
def patch_device(
uuid: str,
body: ModbusDeviceUpdate,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> ModbusDeviceResponse:
"""Partially update a Modbus device (including enable/disable).
Only fields explicitly provided in the request body are updated.
Providing ``profile`` triggers a profile-existence check (422 if unknown).
"""
device = _get_device_or_404(db, uuid)
update_data = body.model_dump(exclude_none=True)
# If profile is being changed, validate it exists.
if "profile" in update_data:
try:
load_profile(update_data["profile"])
except ProfileNotFoundError:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Profile '{update_data['profile']}' does not exist.",
)
for field, value in update_data.items():
setattr(device, field, value)
device.updated_at = datetime.now(UTC)
db.commit()
db.refresh(device)
logger.info("Updated Modbus device %r (uuid=%s)", device.friendly_name, device.uuid)
return ModbusDeviceResponse.model_validate(device)
@router.delete(
"/devices/{uuid}",
status_code=status.HTTP_204_NO_CONTENT,
response_model=None,
)
def delete_device(
uuid: str,
cascade: bool = Query(default=False),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> None | ModbusDeleteResponse:
"""Delete a Modbus device.
**Default behaviour (cascade=false)**:
Returns 409 Conflict if the device has any associated readings; use
``enabled=false`` to disable it instead.
**Cascade delete (cascade=true)**:
Permanently deletes the device together with all its readings and any
``ExposedEntityToggle`` rows whose key matches ``modbus.<uuid>.*``.
Also makes a best-effort attempt to clear the device's HA Discovery
config topics from MQTT (empty retained payload) before the DB rows
are removed. MQTT failures are swallowed the DB deletion proceeds
regardless.
Returns HTTP 200 with a ``ModbusDeleteResponse`` JSON body on success.
**Application-layer safety**: the 409 guard uses an explicit SELECT COUNT
query to return a friendly message. FK RESTRICT is enforced at runtime
(the app sets ``PRAGMA foreign_keys=ON``), so the cascade path deletes
readings before the device.
"""
from app.services.ha_discovery import clear_device_discovery
device = _get_device_or_404(db, uuid)
# Application-layer guard: refuse deletion if any readings exist.
reading_count: int = db.execute(
select(func.count(ModbusReading.id)).where(ModbusReading.device_id == device.id)
).scalar_one()
if reading_count > 0 and not cascade:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=(
f"Device '{uuid}' has {reading_count} associated reading(s) and cannot be "
"deleted. Disable the device (set enabled=false) instead to stop polling "
"without losing historical data."
),
)
if cascade:
# --- Cascade deletion path ---
logger.info(
"Cascade-deleting Modbus device %r (uuid=%s): %d reading(s)",
device.friendly_name,
uuid,
reading_count,
)
# 1. Best-effort HA Discovery cleanup (before DB rows are gone).
try:
clear_device_discovery(db, uuid)
except Exception: # noqa: BLE001
logger.exception(
"delete_device(cascade): HA discovery cleanup raised for uuid=%s; continuing",
uuid,
)
# 2. Delete all readings for this device (must happen before device row).
deleted_readings_result = db.execute(
sa_delete(ModbusReading).where(ModbusReading.device_id == device.id)
)
readings_deleted: int = deleted_readings_result.rowcount
# 3. Delete all ExposedEntityToggle rows for this device.
# Keys follow the pattern "modbus.<uuid>.<metric>".
toggle_prefix = f"modbus.{uuid}.%"
deleted_toggles_result = db.execute(
sa_delete(ExposedEntityToggle).where(ExposedEntityToggle.key.like(toggle_prefix))
)
toggles_deleted: int = deleted_toggles_result.rowcount
# 4. Delete the device itself.
db.delete(device)
db.commit()
logger.info(
"Cascade-delete complete for device uuid=%s: %d reading(s), %d toggle(s) removed",
uuid,
readings_deleted,
toggles_deleted,
)
from fastapi.responses import JSONResponse
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"deleted": True,
"readings_deleted": readings_deleted,
"toggles_deleted": toggles_deleted,
},
)
# --- Non-cascade path (no readings exist at this point) ---
logger.info("Deleting Modbus device %r (uuid=%s)", device.friendly_name, uuid)
db.delete(device)
db.commit()
# ---------------------------------------------------------------------------
# Readings endpoints
# ---------------------------------------------------------------------------
@router.get("/devices/{uuid}/latest", response_model=ModbusLatestResponse)
def get_latest_reading(
uuid: str,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> ModbusLatestResponse:
"""Return the most recent reading for a device.
If no readings exist yet, returns ``{"found": false, "recorded_at": null,
"payload": null}`` (200, not 404) so the front-end can distinguish
"device exists but has no data" from "device not found".
"""
device = _get_device_or_404(db, uuid)
row = db.execute(
select(ModbusReading)
.where(ModbusReading.device_id == device.id)
.order_by(ModbusReading.recorded_at.desc())
.limit(1)
).scalar_one_or_none()
if row is None:
return ModbusLatestResponse(found=False, recorded_at=None, payload=None)
return ModbusLatestResponse(
found=True,
recorded_at=row.recorded_at,
payload=row.payload,
)
@router.get("/devices/{uuid}/readings", response_model=ModbusReadingsResponse)
def get_readings(
uuid: str,
start: datetime | None = Query(default=None),
end: datetime | None = Query(default=None),
limit: int = Query(default=500, ge=1, le=_READINGS_LIMIT_MAX),
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> ModbusReadingsResponse:
"""Return time-range readings for a device.
When the window contains more rows than ``limit``, the **most recent** N rows
are returned (``ORDER BY recorded_at DESC LIMIT n``), then reversed to
ascending order before being sent to the client. This ensures that for long
time-range requests (e.g. 6 h / 24 h) the caller always sees the latest data
rather than the oldest segment of the window.
When the window has fewer rows than ``limit`` the full window is returned in
ascending order behaviour is identical to a plain ascending query.
The response schema is unchanged: items are always ``recorded_at`` ascending.
The query uses the ``(device_id, recorded_at)`` composite index for
efficient time-window scans.
Query parameters:
- ``start``: inclusive lower bound (ISO8601 datetime)
- ``end``: inclusive upper bound (ISO8601 datetime)
- ``limit``: max rows to return (default 500, max {_READINGS_LIMIT_MAX})
"""
device = _get_device_or_404(db, uuid)
stmt = (
select(ModbusReading)
.where(ModbusReading.device_id == device.id)
.order_by(ModbusReading.recorded_at.desc())
.limit(limit)
)
if start is not None:
stmt = stmt.where(ModbusReading.recorded_at >= start)
if end is not None:
stmt = stmt.where(ModbusReading.recorded_at <= end)
# Fetch most-recent N rows, then reverse to restore ascending order for the response.
rows = list(reversed(db.execute(stmt).scalars().all()))
items = [ModbusReadingResponse(recorded_at=r.recorded_at, payload=r.payload) for r in rows]
return ModbusReadingsResponse(items=items)
# ---------------------------------------------------------------------------
# Metrics endpoint
# ---------------------------------------------------------------------------
@router.get("/devices/{uuid}/metrics", response_model=ModbusMetricsResponse)
def get_metrics(
uuid: str,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
) -> ModbusMetricsResponse:
"""Return the metric catalogue for a device's profile.
Each entry has ``key``, ``label`` (derived from key if the profile has
none underscores spaces, title-cased), ``unit``, and ``device_class``.
This is the authoritative metadata source for front-end card labels and
chart axis labels.
"""
device = _get_device_or_404(db, uuid)
try:
profile = load_profile(device.profile)
except ProfileNotFoundError:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Device profile '{device.profile}' could not be loaded.",
)
metrics = [
MetricInfo(
key=m.key,
label=_label_from_key(m.key),
unit=m.unit,
device_class=m.device_class,
)
for m in profile.metrics
]
return ModbusMetricsResponse(profile=profile.name, metrics=metrics)
# ---------------------------------------------------------------------------
# Test-read endpoint
# ---------------------------------------------------------------------------
@router.post("/devices/{uuid}/test", response_model=ModbusTestReadResponse)
def test_read(
uuid: str,
db: Session = Depends(get_db),
_auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> ModbusTestReadResponse:
"""Immediately read and decode the device once without persisting any data.
Useful for validating gateway connectivity and Modbus address settings
before relying on the background polling job.
This is a write-class endpoint (it initiates network I/O on demand) and
therefore requires a CSRF token. The response payload is never stored.
"""
device = _get_device_or_404(db, uuid)
try:
profile = load_profile(device.profile)
except ProfileNotFoundError:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Device profile '{device.profile}' could not be loaded.",
)
try:
registers = modbus_driver.read_blocks(
device.host,
device.port,
device.unit_id,
[{"start": b.start, "count": b.count} for b in profile.blocks],
function_code=profile.function_code,
)
payload: dict[str, Any] = decode_profile(profile, registers)
return ModbusTestReadResponse(ok=True, payload=payload)
except ModbusDriverError as exc:
logger.warning(
"Test read failed for device %r (uuid=%s): %s",
device.friendly_name,
uuid,
exc,
)
return ModbusTestReadResponse(ok=False, error=str(exc))
except Exception as exc: # noqa: BLE001
logger.warning(
"Unexpected error during test read for device %r (uuid=%s): %s",
device.friendly_name,
uuid,
exc,
)
return ModbusTestReadResponse(ok=False, error=f"Unexpected error: {exc}")
+324
View File
@@ -0,0 +1,324 @@
from __future__ import annotations
import logging
from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
from sqlalchemy.orm import Session
from app.api.routes.api.deps import require_csrf, require_session
from app.config import Settings
from app.dependencies import get_app_settings, get_db
from app.schemas.session import (
LoginRequest,
PasswordChangeRequest,
SessionResponse,
SessionUser,
)
from app.schemas.totp import (
TotpDisableRequest,
TotpEnableRequest,
TotpSetupResponse,
TotpStatusResponse,
)
from app.services.auth import (
AuthPasswordChangeError,
AuthenticatedSession,
authenticate_user,
change_password,
create_session,
revoke_session,
)
from app.services import login_throttle
from app.services import totp as totp_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["api-session"])
def _build_session_response(auth: AuthenticatedSession) -> SessionResponse:
return SessionResponse(
user=SessionUser(
username=auth.user.username,
force_password_change=auth.user.force_password_change,
),
csrf_token=auth.session.csrf_token,
)
@router.get("/session", response_model=SessionResponse)
def get_session(
auth: AuthenticatedSession = Depends(require_session),
) -> SessionResponse:
"""Return the current session user and CSRF token. Returns 401 if not authenticated."""
return _build_session_response(auth)
def _get_client_ip(request: Request, *, trust_forwarded_for: bool) -> str:
"""Extract the client IP address from the request.
When ``trust_forwarded_for`` is True (reverse-proxy deployments) the
left-most value from the ``X-Forwarded-For`` header is used. Otherwise the
direct socket IP (``request.client.host``) is used.
"""
if trust_forwarded_for:
xff = request.headers.get("X-Forwarded-For", "")
if xff:
return xff.split(",")[0].strip()
if request.client is not None:
return request.client.host
return "unknown"
@router.post("/auth/login", response_model=SessionResponse)
def post_login(
body: LoginRequest,
request: Request,
response: Response,
db: Session = Depends(get_db),
settings: Settings = Depends(get_app_settings),
) -> SessionResponse:
"""
Authenticate with username and password.
On success, sets an HttpOnly session cookie and returns the session user + CSRF token.
On failure, returns 401 with no cookie set.
Repeated failures trigger exponential back-off (429 + Retry-After).
No X-CSRF-Token required (unauthenticated endpoint).
"""
client_ip = _get_client_ip(request, trust_forwarded_for=settings.auth_trust_forwarded_for)
# --- Throttle check (before any password verification) ---
if settings.auth_login_throttle_enabled:
wait_seconds = login_throttle.check_and_get_wait(
db, ip=client_ip, username=body.username
)
if wait_seconds > 0:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="too many failed login attempts; please try again later",
headers={"Retry-After": str(wait_seconds)},
)
# --- Password verification ---
user = authenticate_user(db, username=body.username, password=body.password)
if user is None:
if settings.auth_login_throttle_enabled:
login_throttle.register_failure(db, ip=client_ip, username=body.username)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid username or password",
)
# --- TOTP second-factor check (only when TOTP is enabled for the user) ---
if user.totp_enabled:
if not body.totp_code:
# Password correct but no TOTP code supplied: signal the front-end to
# prompt for the second factor. Do NOT issue a session.
# Deliberate: this is a normal two-step protocol step from a legitimate
# user — we do NOT register a throttle failure here. The attacker must
# already have the correct password to reach this branch, and counting
# each normal first-step as a failure would risk locking out the real
# admin on every login attempt.
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail={"totp_required": True},
)
# TOTP code supplied — verify against time-based code or a recovery code.
totp_ok = totp_service.verify_totp_code(user, body.totp_code)
if not totp_ok:
totp_ok = totp_service.verify_recovery_code(db, user=user, code=body.totp_code)
if not totp_ok:
# Second-factor failure is an active attack signal — register failure
# so that repeated wrong TOTP/recovery-code guesses trigger back-off.
if settings.auth_login_throttle_enabled:
login_throttle.register_failure(db, ip=client_ip, username=body.username)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid username or password",
)
# --- Success: clear back-off state and issue session ---
if settings.auth_login_throttle_enabled:
login_throttle.clear(db, ip=client_ip, username=body.username)
auth_session, raw_token = create_session(db, user=user, settings=settings)
logger.info("Created API authenticated session for user '%s'", user.username)
response.set_cookie(
key=settings.auth_session_cookie_name,
value=raw_token,
max_age=settings.auth_session_ttl_hours * 3600,
httponly=True,
secure=settings.auth_cookie_secure,
samesite="lax",
path="/",
)
auth = AuthenticatedSession(user=user, session=auth_session)
return _build_session_response(auth)
@router.post("/auth/logout")
def post_logout(
response: Response,
db: Session = Depends(get_db),
settings: Settings = Depends(get_app_settings),
auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> Response:
"""
Revoke the current session and clear the session cookie.
Requires authentication and X-CSRF-Token header.
Returns 204 No Content.
"""
revoke_session(db, auth_session=auth.session)
logger.info("Revoked API authenticated session for user '%s'", auth.user.username)
no_content = Response(status_code=status.HTTP_204_NO_CONTENT)
no_content.delete_cookie(settings.auth_session_cookie_name, path="/")
return no_content
@router.post("/auth/password")
def post_change_password(
body: PasswordChangeRequest,
db: Session = Depends(get_db),
auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> Response:
"""
Change the current user's password.
Requires authentication and X-CSRF-Token header.
On AuthPasswordChangeError returns 400 with a generic message.
On success, force_password_change becomes False (handled by the service).
Returns 204 No Content.
"""
try:
change_password(
db,
user=auth.user,
current_password=body.current_password,
new_password=body.new_password,
confirm_password=body.confirm_password,
)
except AuthPasswordChangeError as exc:
logger.info(
"Rejected password change for user '%s': %s",
auth.user.username,
exc,
)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="password change failed",
) from exc
logger.info("Password updated for user '%s'", auth.user.username)
return Response(status_code=status.HTTP_204_NO_CONTENT)
# ---------------------------------------------------------------------------
# TOTP endpoints (M4-T05)
# ---------------------------------------------------------------------------
@router.post("/auth/totp/setup", response_model=TotpSetupResponse)
def post_totp_setup(
db: Session = Depends(get_db),
settings: Settings = Depends(get_app_settings),
auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> TotpSetupResponse:
"""
Generate a new pending TOTP secret, otpauth URI, and one-time recovery codes.
The secret is stored in the DB but TOTP is NOT yet enabled (totp_enabled stays
False until the user confirms with POST /api/auth/totp/enable).
Recovery codes are returned here as plaintext exactly once; their Argon2 hashes
are persisted immediately so enable only needs to flip the enabled flag.
Repeating this call replaces any prior pending secret and regenerates codes.
Requires: session cookie + X-CSRF-Token.
"""
secret, otpauth_uri, recovery_codes = totp_service.setup(
db,
user=auth.user,
issuer=settings.effective_totp_issuer,
)
return TotpSetupResponse(
secret=secret,
otpauth_uri=otpauth_uri,
recovery_codes=recovery_codes,
)
@router.post("/auth/totp/enable", status_code=status.HTTP_204_NO_CONTENT)
def post_totp_enable(
body: TotpEnableRequest,
db: Session = Depends(get_db),
auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> Response:
"""
Enable TOTP by confirming with the current 6-digit code from the authenticator app.
Requires a prior call to POST /api/auth/totp/setup (so that a pending secret
exists). On success, totp_enabled becomes True.
Returns 400 if the code is wrong or there is no pending secret.
Requires: session cookie + X-CSRF-Token.
"""
ok = totp_service.enable(db, user=auth.user, code=body.code)
if not ok:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="invalid TOTP code or no pending setup",
)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.post("/auth/totp/disable", status_code=status.HTTP_204_NO_CONTENT)
def post_totp_disable(
body: TotpDisableRequest,
db: Session = Depends(get_db),
auth: AuthenticatedSession = Depends(require_session),
_csrf: None = Depends(require_csrf),
) -> Response:
"""
Disable TOTP. The caller must provide exactly one of:
- ``password``: the user's current login password, OR
- ``code``: the current 6-digit TOTP code.
On success: totp_enabled=False, totp_secret cleared, all recovery codes deleted.
Returns 400 if neither credential matches or neither is provided.
Requires: session cookie + X-CSRF-Token.
"""
ok = totp_service.disable(
db,
user=auth.user,
password=body.password,
code=body.code,
)
if not ok:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="invalid credential; provide a valid password or TOTP code",
)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.get("/auth/totp", response_model=TotpStatusResponse)
def get_totp_status(
auth: AuthenticatedSession = Depends(require_session),
) -> TotpStatusResponse:
"""
Return the current TOTP status for the authenticated user.
Response contains only ``{"enabled": bool}``.
Secret and recovery codes are NEVER returned here.
Requires: session cookie only (no CSRF read-only).
"""
return TotpStatusResponse(enabled=auth.user.totp_enabled)
-234
View File
@@ -1,234 +0,0 @@
import logging
from pathlib import Path
from fastapi import APIRouter, Depends, Form, Request, status
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from app.config import Settings
from app.dependencies import get_app_settings, get_auth_db, get_current_auth_session
from app.services.auth import (
AuthenticatedSession,
authenticate_user,
change_password,
create_session,
AuthPasswordChangeError,
issue_login_csrf_token,
revoke_session,
validate_csrf_token,
)
from app.services.config_page import build_config_sections, is_ticktick_oauth_ready
logger = logging.getLogger(__name__)
templates = Jinja2Templates(directory=str(Path(__file__).resolve().parents[2] / "templates"))
router = APIRouter(tags=["auth"])
LOGIN_CSRF_COOKIE_NAME = "login_csrf"
@router.get("/login", response_class=HTMLResponse)
def login_page(
request: Request,
settings: Settings = Depends(get_app_settings),
current_auth: AuthenticatedSession | None = Depends(get_current_auth_session),
) -> Response:
if current_auth is not None:
return RedirectResponse(url="/config", status_code=status.HTTP_303_SEE_OTHER)
csrf_token = issue_login_csrf_token()
response = templates.TemplateResponse(
request,
"login.html",
{
"app_name": settings.app_name,
"app_env": settings.app_env,
"csrf_token": csrf_token,
"error_message": None,
},
)
_set_login_csrf_cookie(response, settings=settings, token=csrf_token)
return response
@router.post("/login", response_class=HTMLResponse)
def login_submit(
request: Request,
username: str = Form(),
password: str = Form(),
csrf_token: str = Form(),
session: Session = Depends(get_auth_db),
settings: Settings = Depends(get_app_settings),
) -> Response:
cookie_csrf_token = request.cookies.get(LOGIN_CSRF_COOKIE_NAME)
if not validate_csrf_token(expected=cookie_csrf_token, actual=csrf_token):
logger.warning("Rejected login attempt due to CSRF validation failure")
return _render_login_error(
request,
settings=settings,
status_code=status.HTTP_400_BAD_REQUEST,
error_message="invalid login request",
)
user = authenticate_user(session, username=username, password=password)
if user is None:
return _render_login_error(
request,
settings=settings,
status_code=status.HTTP_401_UNAUTHORIZED,
error_message="invalid username or password",
)
auth_session, raw_token = create_session(session, user=user, settings=settings)
response = RedirectResponse(url="/config", status_code=status.HTTP_303_SEE_OTHER)
response.delete_cookie(LOGIN_CSRF_COOKIE_NAME, path="/login")
response.set_cookie(
key=settings.auth_session_cookie_name,
value=raw_token,
max_age=settings.auth_session_ttl_hours * 3600,
httponly=True,
secure=settings.auth_cookie_secure,
samesite="lax",
path="/",
)
logger.info("Created authenticated session for user '%s'", user.username)
return response
@router.post("/config/change-password", response_class=HTMLResponse)
def change_password_submit(
request: Request,
current_password: str = Form(),
new_password: str = Form(),
confirm_password: str = Form(),
csrf_token: str = Form(),
session: Session = Depends(get_auth_db),
settings: Settings = Depends(get_app_settings),
current_auth: AuthenticatedSession | None = Depends(get_current_auth_session),
) -> Response:
if current_auth is None:
return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)
if not validate_csrf_token(expected=current_auth.session.csrf_token, actual=csrf_token):
logger.warning("Rejected password change attempt due to CSRF validation failure")
return _render_config_page(
request,
settings=settings,
auth_db_session=session,
current_auth=current_auth,
status_code=status.HTTP_400_BAD_REQUEST,
password_change_error="invalid password change request",
)
try:
change_password(
session,
user=current_auth.user,
current_password=current_password,
new_password=new_password,
confirm_password=confirm_password,
)
except AuthPasswordChangeError as exc:
logger.info(
"Rejected password change for user '%s': %s",
current_auth.user.username,
exc,
)
return _render_config_page(
request,
settings=settings,
auth_db_session=session,
current_auth=current_auth,
status_code=status.HTTP_400_BAD_REQUEST,
password_change_error="password change failed",
)
logger.info("Password updated for user '%s'", current_auth.user.username)
return RedirectResponse(url="/config", status_code=status.HTTP_303_SEE_OTHER)
@router.post("/logout")
def logout(
request: Request,
csrf_token: str = Form(),
session: Session = Depends(get_auth_db),
settings: Settings = Depends(get_app_settings),
current_auth: AuthenticatedSession | None = Depends(get_current_auth_session),
) -> RedirectResponse:
if current_auth is not None and validate_csrf_token(
expected=current_auth.session.csrf_token, actual=csrf_token
):
revoke_session(session, auth_session=current_auth.session)
logger.info("Revoked authenticated session for user '%s'", current_auth.user.username)
else:
logger.warning("Rejected logout request due to missing session or invalid CSRF token")
response = RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)
response.delete_cookie(settings.auth_session_cookie_name, path="/")
return response
def _render_login_error(
request: Request,
*,
settings: Settings,
status_code: int,
error_message: str,
) -> HTMLResponse:
csrf_token = issue_login_csrf_token()
response = templates.TemplateResponse(
request,
"login.html",
{
"app_name": settings.app_name,
"app_env": settings.app_env,
"csrf_token": csrf_token,
"error_message": error_message,
},
status_code=status_code,
)
_set_login_csrf_cookie(response, settings=settings, token=csrf_token)
return response
def _set_login_csrf_cookie(response: HTMLResponse, *, settings: Settings, token: str) -> None:
response.set_cookie(
key=LOGIN_CSRF_COOKIE_NAME,
value=token,
max_age=1800,
httponly=True,
secure=settings.auth_cookie_secure,
samesite="lax",
path="/login",
)
def _render_config_page(
request: Request,
*,
settings: Settings,
auth_db_session: Session,
current_auth: AuthenticatedSession,
status_code: int,
password_change_error: str | None,
) -> HTMLResponse:
return templates.TemplateResponse(
request,
"config.html",
{
"app_name": settings.app_name,
"app_env": settings.app_env,
"current_username": current_auth.user.username,
"csrf_token": current_auth.session.csrf_token,
"force_password_change": current_auth.user.force_password_change,
"password_change_error": password_change_error,
"config_error": None,
"config_saved": False,
"config_sections": build_config_sections(auth_db_session, settings),
"ticktick_oauth_ready": is_ticktick_oauth_ready(settings),
"ticktick_redirect_uri": settings.ticktick_redirect_uri,
"ticktick_oauth_notice": None,
"ticktick_oauth_error": None,
},
status_code=status_code,
)
+1 -3
View File
@@ -11,7 +11,6 @@ from app.dependencies import (
get_app_settings,
get_db,
get_homeassistant_client,
get_poo_db,
get_ticktick_client,
)
from app.integrations.homeassistant import (
@@ -36,7 +35,6 @@ INTERNAL_SERVER_ERROR_MESSAGE = "internal server error"
async def publish_from_homeassistant(
request: Request,
db: Session = Depends(get_db),
poo_db: Session = Depends(get_poo_db),
settings: Settings = Depends(get_app_settings),
homeassistant_client: HomeAssistantClient = Depends(get_homeassistant_client),
ticktick_client: TickTickClient = Depends(get_ticktick_client),
@@ -49,7 +47,7 @@ async def publish_from_homeassistant(
db,
envelope,
ticktick_client=ticktick_client,
poo_session=poo_db,
poo_session=db,
settings=settings,
homeassistant_client=homeassistant_client,
)
-151
View File
@@ -1,151 +0,0 @@
import logging
from pathlib import Path
from fastapi import APIRouter, Depends, Request, status
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from fastapi.templating import Jinja2Templates
from app.config import Settings, get_settings
from app.dependencies import get_app_settings, get_auth_db, get_current_auth_session
from app.services.auth import AuthenticatedSession
from app.services.config_page import (
ConfigSaveError,
build_config_sections,
is_ticktick_oauth_ready,
save_config_updates,
)
from sqlalchemy.orm import Session
templates = Jinja2Templates(directory=str(Path(__file__).resolve().parents[2] / "templates"))
router = APIRouter(tags=["pages"])
logger = logging.getLogger(__name__)
def _ticktick_oauth_notice(status_value: str | None) -> tuple[str | None, str | None]:
if status_value == "success":
return "TickTick authorization completed successfully.", None
if status_value == "invalid-state":
return None, "TickTick authorization failed due to invalid OAuth state. Start the flow again."
if status_value == "invalid-callback":
return None, "TickTick authorization callback was missing required parameters."
if status_value == "failed":
return None, "TickTick authorization failed. Check server logs for the provider response and verify TickTick app credentials and redirect URI."
return None, None
@router.get("/", response_class=HTMLResponse)
def home(
request: Request,
current_auth: AuthenticatedSession | None = Depends(get_current_auth_session),
) -> RedirectResponse:
if current_auth is None:
return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)
return RedirectResponse(url="/config", status_code=status.HTTP_303_SEE_OTHER)
@router.get("/admin", response_class=HTMLResponse)
def admin_redirect(
request: Request,
current_auth: AuthenticatedSession | None = Depends(get_current_auth_session),
) -> RedirectResponse:
if current_auth is None:
return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)
return RedirectResponse(url="/config", status_code=status.HTTP_303_SEE_OTHER)
@router.get("/config", response_class=HTMLResponse)
def config_page(
request: Request,
auth_db_session: Session = Depends(get_auth_db),
settings: Settings = Depends(get_app_settings),
current_auth: AuthenticatedSession | None = Depends(get_current_auth_session),
) -> Response:
if current_auth is None:
return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)
ticktick_oauth_notice, ticktick_oauth_error = _ticktick_oauth_notice(
request.query_params.get("ticktick_oauth")
)
context = {
"app_name": settings.app_name,
"app_env": settings.app_env,
"current_username": current_auth.user.username,
"csrf_token": current_auth.session.csrf_token,
"force_password_change": current_auth.user.force_password_change,
"password_change_error": None,
"config_error": None,
"config_saved": request.query_params.get("saved") == "1",
"config_sections": build_config_sections(auth_db_session, settings),
"ticktick_oauth_ready": is_ticktick_oauth_ready(settings),
"ticktick_redirect_uri": settings.ticktick_redirect_uri,
"ticktick_oauth_notice": ticktick_oauth_notice,
"ticktick_oauth_error": ticktick_oauth_error,
}
return templates.TemplateResponse(request, "config.html", context)
@router.post("/config", response_class=HTMLResponse)
async def config_submit(
request: Request,
auth_db_session: Session = Depends(get_auth_db),
settings: Settings = Depends(get_app_settings),
current_auth: AuthenticatedSession | None = Depends(get_current_auth_session),
) -> Response:
if current_auth is None:
return RedirectResponse(url="/login", status_code=status.HTTP_303_SEE_OTHER)
form = await request.form()
csrf_token = form.get("csrf_token")
if csrf_token != current_auth.session.csrf_token:
logger.warning("Rejected config update due to CSRF validation failure")
context = {
"app_name": settings.app_name,
"app_env": settings.app_env,
"current_username": current_auth.user.username,
"csrf_token": current_auth.session.csrf_token,
"force_password_change": current_auth.user.force_password_change,
"password_change_error": None,
"config_error": "invalid config update request",
"config_saved": False,
"config_sections": build_config_sections(auth_db_session, settings),
"ticktick_oauth_ready": is_ticktick_oauth_ready(settings),
"ticktick_redirect_uri": settings.ticktick_redirect_uri,
"ticktick_oauth_notice": None,
"ticktick_oauth_error": None,
}
return templates.TemplateResponse(
request,
"config.html",
context,
status_code=status.HTTP_400_BAD_REQUEST,
)
try:
save_config_updates(auth_db_session, dict(form), settings)
except ConfigSaveError:
logger.warning("Rejected config update due to invalid submitted values")
refreshed_settings = get_settings()
context = {
"app_name": refreshed_settings.app_name,
"app_env": refreshed_settings.app_env,
"current_username": current_auth.user.username,
"csrf_token": current_auth.session.csrf_token,
"force_password_change": current_auth.user.force_password_change,
"password_change_error": None,
"config_error": "invalid config submission",
"config_saved": False,
"config_sections": build_config_sections(auth_db_session, refreshed_settings),
"ticktick_oauth_ready": is_ticktick_oauth_ready(refreshed_settings),
"ticktick_redirect_uri": refreshed_settings.ticktick_redirect_uri,
"ticktick_oauth_notice": None,
"ticktick_oauth_error": None,
}
return templates.TemplateResponse(
request,
"config.html",
context,
status_code=status.HTTP_400_BAD_REQUEST,
)
return RedirectResponse(url="/config?saved=1", status_code=status.HTTP_303_SEE_OTHER)
+3 -3
View File
@@ -7,7 +7,7 @@ from pydantic import ValidationError
from sqlalchemy.orm import Session
from app.config import Settings
from app.dependencies import get_app_settings, get_homeassistant_client, get_poo_db
from app.dependencies import get_app_settings, get_homeassistant_client, get_db
from app.integrations.homeassistant import HomeAssistantClient
from app.schemas.poo import PooRecordRequest
from app.services.poo import publish_latest_poo_status, record_poo
@@ -21,7 +21,7 @@ INTERNAL_SERVER_ERROR_MESSAGE = "internal server error"
@router.post("/poo/record")
async def create_poo_record(
request: Request,
db: Session = Depends(get_poo_db),
db: Session = Depends(get_db),
settings: Settings = Depends(get_app_settings),
homeassistant_client: HomeAssistantClient = Depends(get_homeassistant_client),
) -> Response:
@@ -56,7 +56,7 @@ async def create_poo_record(
@router.get("/poo/latest")
def notify_latest_poo(
db: Session = Depends(get_poo_db),
db: Session = Depends(get_db),
settings: Settings = Depends(get_app_settings),
homeassistant_client: HomeAssistantClient = Depends(get_homeassistant_client),
) -> Response:
+26
View File
@@ -0,0 +1,26 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.dependencies import get_db, get_current_auth_session
from app.schemas.public_ip import PublicIPCheckResponse
from app.config import get_settings
from app.services.auth import AuthenticatedSession
from app.services.public_ip import check_public_ipv4_and_notify
router = APIRouter(tags=["public-ip"])
@router.get("/public-ip/check", response_model=PublicIPCheckResponse)
def run_public_ip_check(
session: Session = Depends(get_db),
current_auth: AuthenticatedSession | None = Depends(get_current_auth_session),
) -> PublicIPCheckResponse:
if current_auth is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="authentication required")
result = check_public_ipv4_and_notify(session, bootstrap_settings=get_settings())
return PublicIPCheckResponse(
status=result.status,
checked_at=result.checked_at,
changed=result.changed,
)
+2 -2
View File
@@ -7,7 +7,7 @@ from sqlalchemy.orm import Session
from app.config import Settings
from app.dependencies import (
get_app_settings,
get_auth_db,
get_db,
get_current_auth_session,
get_ticktick_client,
)
@@ -39,7 +39,7 @@ def start_ticktick_auth(
@router.get("/ticktick/auth/code")
def handle_ticktick_auth_code(
request: Request,
auth_db_session: Session = Depends(get_auth_db),
auth_db_session: Session = Depends(get_db),
settings: Settings = Depends(get_app_settings),
ticktick_client: TickTickClient = Depends(get_ticktick_client),
) -> Response:
-53
View File
@@ -1,53 +0,0 @@
from collections.abc import Generator
from functools import lru_cache
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
from app.config import get_settings
class AuthBase(DeclarativeBase):
pass
def _build_connect_args(database_url: str) -> dict[str, object]:
connect_args: dict[str, object] = {}
if database_url.startswith("sqlite"):
connect_args["check_same_thread"] = False
return connect_args
@lru_cache
def _get_auth_engine(database_url: str):
return create_engine(database_url, connect_args=_build_connect_args(database_url))
@lru_cache
def _get_auth_session_local(database_url: str):
engine = _get_auth_engine(database_url)
return sessionmaker(bind=engine, autoflush=False, autocommit=False, class_=Session)
def get_auth_engine():
settings = get_settings()
return _get_auth_engine(settings.app_database_url)
def get_auth_session_local():
settings = get_settings()
return _get_auth_session_local(settings.app_database_url)
def reset_auth_db_caches() -> None:
_get_auth_session_local.cache_clear()
_get_auth_engine.cache_clear()
def get_auth_db_session() -> Generator[Session, None, None]:
session_local = get_auth_session_local()
session = session_local()
try:
yield session
finally:
session.close()
+65 -14
View File
@@ -1,7 +1,8 @@
from functools import lru_cache
from pathlib import Path
import re
from pydantic import computed_field
from pydantic import computed_field, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
@@ -12,9 +13,6 @@ class Settings(BaseSettings):
app_hostname: str = "localhost:8000"
app_database_url: str = "sqlite:///./data/app.db"
location_database_url: str = "sqlite:///./data/locationRecorder.db"
poo_database_url: str = "sqlite:///./data/pooRecorder.db"
ticktick_client_id: str = ""
ticktick_client_secret: str = ""
ticktick_token: str = ""
@@ -23,6 +21,15 @@ class Settings(BaseSettings):
home_assistant_auth_token: str = ""
home_assistant_timeout_seconds: float = 1.0
home_assistant_action_task_project_id: str = ""
smtp_enabled: bool = False
smtp_host: str = ""
smtp_port: int = 587
smtp_username: str = ""
smtp_password: str = ""
smtp_from_name: str = ""
smtp_from_address: str = ""
smtp_to_address: str = ""
smtp_use_starttls: bool = True
poo_webhook_id: str = ""
poo_sensor_entity_name: str = "sensor.test_poo_status"
poo_sensor_friendly_name: str = "Poo Status"
@@ -31,6 +38,43 @@ class Settings(BaseSettings):
auth_session_cookie_name: str = "home_automation_session"
auth_session_ttl_hours: int = 12
auth_cookie_secure_override: bool | None = True
auth_login_throttle_enabled: bool = True
auth_trust_forwarded_for: bool = False
auth_totp_issuer: str = "" # defaults to app_name when empty
# Modbus polling — global kill-switch (CONFIG_FIELDS registered in T08).
# Off by default: polling is opt-in so a fresh deploy writes no modbus_reading
# rows until the admin explicitly enables it (matches mqtt/discovery defaults).
modbus_polling_enabled: bool = False
# MQTT broker connection (T08 wires into CONFIG_FIELDS/UI; T10 builds the client).
mqtt_enabled: bool = False
mqtt_broker_host: str = ""
mqtt_broker_port: int = 1883
mqtt_username: str = ""
mqtt_password: str = ""
mqtt_tls_enabled: bool = False
mqtt_client_id: str = "home-automation"
# Home Assistant MQTT Discovery (T08 wires into CONFIG_FIELDS/UI; T11 does publishing).
ha_discovery_enabled: bool = False
ha_discovery_prefix: str = "homeassistant"
# State/availability topics use a separate prefix so they live outside the HA discovery
# namespace. HA still receives state via the state_topic declared in the discovery config.
ha_state_topic_prefix: str = "home_automation"
# DSMR smart-meter ingest via MQTT (M6; default off — opt-in).
# Subscribe to dsmr_mqtt_topic when dsmr_ingest_enabled=True.
dsmr_ingest_enabled: bool = False
dsmr_mqtt_topic: str = "dsmr/json"
dsmr_sample_interval_s: int = 10
# DSMR dual-tariff topic: publishes "1" (dal/off-peak) or "2" (normal/peak).
# Empty string = do not subscribe (tariff-aware pricing disabled).
dsmr_tariff_topic: str = "dsmr/meter-stats/electricity_tariff"
# Tibber dynamic pricing credentials (M6; only used when active contract kind=tibber).
tibber_api_token: str = ""
tibber_home_id: str = ""
model_config = SettingsConfigDict(
env_file=".env",
@@ -39,6 +83,17 @@ class Settings(BaseSettings):
extra="ignore",
)
@field_validator("mqtt_client_id", mode="before")
@classmethod
def validate_mqtt_client_id(cls, value: object) -> str:
"""Normalize a broker-safe base client identity used by every MQTT client."""
if not isinstance(value, str):
raise ValueError("MQTT client ID must be a string")
normalized = value.strip()
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]{0,63}", normalized):
raise ValueError("MQTT client ID must be a non-empty ASCII slug")
return normalized
@computed_field
@property
def is_development(self) -> bool:
@@ -68,21 +123,11 @@ class Settings(BaseSettings):
raw_path = database_url[len(prefix) :]
return Path(raw_path)
@computed_field
@property
def location_sqlite_path(self) -> Path | None:
return self._sqlite_path_from_url(self.location_database_url)
@computed_field
@property
def app_sqlite_path(self) -> Path | None:
return self._sqlite_path_from_url(self.app_database_url)
@computed_field
@property
def poo_sqlite_path(self) -> Path | None:
return self._sqlite_path_from_url(self.poo_database_url)
@computed_field
@property
def auth_cookie_secure(self) -> bool:
@@ -90,6 +135,12 @@ class Settings(BaseSettings):
return self.auth_cookie_secure_override
return not self.is_development
@computed_field
@property
def effective_totp_issuer(self) -> str:
"""The issuer label shown in Authenticator apps. Falls back to app_name."""
return self.auth_totp_issuer.strip() or self.app_name
@lru_cache
def get_settings() -> Settings:
+42 -8
View File
@@ -1,6 +1,8 @@
from collections.abc import Generator
from functools import lru_cache
from sqlalchemy import create_engine
from sqlalchemy import create_engine, event
from sqlalchemy.engine import Engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
from app.config import get_settings
@@ -10,18 +12,50 @@ class Base(DeclarativeBase):
pass
settings = get_settings()
def _build_connect_args(database_url: str) -> dict[str, object]:
connect_args: dict[str, object] = {}
if database_url.startswith("sqlite"):
connect_args["check_same_thread"] = False
return connect_args
connect_args: dict[str, object] = {}
if settings.location_database_url.startswith("sqlite"):
connect_args["check_same_thread"] = False
engine = create_engine(settings.location_database_url, connect_args=connect_args)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, class_=Session)
@lru_cache
def _get_engine(database_url: str) -> Engine:
engine = create_engine(database_url, connect_args=_build_connect_args(database_url))
if database_url.startswith("sqlite"):
@event.listens_for(engine, "connect")
def _enable_sqlite_wal(dbapi_connection, _connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close()
return engine
@lru_cache
def _get_session_local(database_url: str) -> sessionmaker:
engine = _get_engine(database_url)
return sessionmaker(bind=engine, autoflush=False, autocommit=False, class_=Session)
def get_engine() -> Engine:
return _get_engine(get_settings().app_database_url)
def get_session_local() -> sessionmaker:
return _get_session_local(get_settings().app_database_url)
def reset_db_caches() -> None:
_get_session_local.cache_clear()
_get_engine.cache_clear()
def get_db_session() -> Generator[Session, None, None]:
session = SessionLocal()
session_local = get_session_local()
session = session_local()
try:
yield session
finally:
+3 -13
View File
@@ -3,30 +3,20 @@ from collections.abc import Generator
from fastapi import Depends, Request
from sqlalchemy.orm import Session
from app.auth_db import get_auth_db_session
from app.config import Settings, get_settings
from app.db import get_db_session
from app.integrations.homeassistant import HomeAssistantClient
from app.integrations.ticktick import TickTickClient
from app.poo_db import get_poo_db_session
from app.services.auth import AuthenticatedSession, get_authenticated_session
from app.services.config_page import build_runtime_settings
def get_auth_db() -> Generator[Session, None, None]:
yield from get_auth_db_session()
def get_app_settings(session: Session = Depends(get_auth_db)) -> Settings:
return build_runtime_settings(session, get_settings())
def get_db() -> Generator[Session, None, None]:
yield from get_db_session()
def get_poo_db() -> Generator[Session, None, None]:
yield from get_poo_db_session()
def get_app_settings(session: Session = Depends(get_db)) -> Settings:
return build_runtime_settings(session, get_settings())
def get_homeassistant_client(settings: Settings = Depends(get_app_settings)) -> HomeAssistantClient:
@@ -39,7 +29,7 @@ def get_ticktick_client(settings: Settings = Depends(get_app_settings)) -> TickT
def get_current_auth_session(
request: Request,
session: Session = Depends(get_auth_db),
session: Session = Depends(get_db),
settings: Settings = Depends(get_app_settings),
) -> AuthenticatedSession | None:
raw_token = request.cookies.get(settings.auth_session_cookie_name)
File diff suppressed because it is too large Load Diff
+79
View File
@@ -2,10 +2,14 @@ from __future__ import annotations
import json
import logging
from time import monotonic
from dataclasses import dataclass, field
from typing import Any
from urllib import error, parse, request
from websockets.exceptions import WebSocketException
from websockets.sync.client import connect
from app.config import Settings
logger = logging.getLogger(__name__)
@@ -57,6 +61,81 @@ class HomeAssistantClient:
self._post_json(f"/api/webhook/{webhook_id}", body, operation="trigger_webhook")
def discovery_registry_bindings(self, unique_ids: set[str]) -> dict[str, set[str]]:
"""Return HA device identifiers currently bound to MQTT unique IDs.
This is deliberately a read-only WebSocket query. MQTT only confirms
broker receipt; the entity/device registries are the authoritative HA
observation that a discovery unload/re-add was actually processed.
"""
self._require_config()
if not unique_ids:
return {}
try:
deadline = monotonic() + self.timeout_seconds
with connect(self._websocket_url(), open_timeout=self.timeout_seconds,
close_timeout=self.timeout_seconds) as websocket:
greeting = json.loads(self._websocket_recv(websocket, deadline))
if greeting.get("type") != "auth_required":
raise HomeAssistantRequestError("Unexpected Home Assistant WebSocket greeting")
websocket.send(json.dumps({"type": "auth", "access_token": self.settings.home_assistant_auth_token}))
auth = json.loads(self._websocket_recv(websocket, deadline))
if auth.get("type") != "auth_ok":
raise HomeAssistantRequestError("Home Assistant WebSocket authentication failed")
entities = self._websocket_command(websocket, 1, "config/entity_registry/list", deadline)
devices = self._websocket_command(websocket, 2, "config/device_registry/list", deadline)
except (OSError, WebSocketException, TimeoutError, ValueError, KeyError, TypeError) as exc:
raise HomeAssistantRequestError("Home Assistant registry query failed") from exc
devices_by_id = {
device["id"]: {
identifier[1]
for identifier in device.get("identifiers", [])
if (
isinstance(identifier, (list, tuple))
and len(identifier) == 2
and identifier[0] == "mqtt"
and isinstance(identifier[1], str)
and identifier[1]
)
}
for device in devices
if isinstance(device, dict) and isinstance(device.get("id"), str)
}
return {
entity["unique_id"]: devices_by_id.get(entity.get("device_id"), set())
for entity in entities
if entity.get("platform") == "mqtt" and entity.get("unique_id") in unique_ids
}
@staticmethod
def _websocket_recv(websocket: Any, deadline: float) -> str:
remaining = deadline - monotonic()
if remaining <= 0:
raise TimeoutError("Home Assistant WebSocket registry query timed out")
return websocket.recv(timeout=remaining)
@classmethod
def _websocket_command(
cls, websocket: Any, message_id: int, command: str, deadline: float
) -> list[dict[str, Any]]:
websocket.send(json.dumps({"id": message_id, "type": command}))
while True:
response = json.loads(cls._websocket_recv(websocket, deadline))
if response.get("id") != message_id:
continue
if not response.get("success"):
raise HomeAssistantRequestError(f"Home Assistant WebSocket {command} failed")
return response.get("result", [])
def _websocket_url(self) -> str:
parsed = parse.urlsplit(self.settings.home_assistant_base_url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise HomeAssistantConfigError("HOME_ASSISTANT_BASE_URL must be an HTTP(S) URL")
scheme = "wss" if parsed.scheme == "https" else "ws"
path = f"{parsed.path.rstrip('/')}/api/websocket"
return parse.urlunsplit((scheme, parsed.netloc, path, "", ""))
def _require_config(self) -> None:
if self.is_configured():
return
+173
View File
@@ -0,0 +1,173 @@
"""Registry and configuration helpers for meter-source integrations.
The registry is deliberately I/O-free. Workers and HTTP handlers use these
helpers to share one config contract without opening a broker or serial port.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
SECRET_MASK = ""
class SourceProfileError(ValueError):
"""Raised when a source kind or its configuration is invalid."""
@dataclass(frozen=True)
class SourceConfigField:
"""One source configuration field and its public metadata."""
name: str
value_type: type
default: Any = None
required: bool = False
secret: bool = False
@dataclass(frozen=True)
class MeterSourceProfile:
"""A supported source kind's config, capabilities, and channel units."""
kind: str
fields: tuple[SourceConfigField, ...]
capabilities: frozenset[str]
allowed_units: frozenset[str]
DSMR_MQTT_PROFILE = MeterSourceProfile(
kind="dsmr_mqtt",
fields=(
SourceConfigField("broker_host", str, default=""),
SourceConfigField("broker_port", int, default=1883),
SourceConfigField("username", str, default="", secret=True),
SourceConfigField("password", str, default="", secret=True),
SourceConfigField("tls_enabled", bool, default=False),
SourceConfigField("topic", str, default="dsmr/json"),
SourceConfigField("tariff_topic", str, default="dsmr/meter-stats/electricity_tariff"),
SourceConfigField("sample_interval_s", int, default=10),
),
capabilities=frozenset({"discover", "mqtt_subscribe", "tariff"}),
allowed_units=frozenset({"kWh"}),
)
WARMTELINK_SERIAL_PROFILE = MeterSourceProfile(
kind="warmtelink_serial",
fields=(
SourceConfigField("path", str, required=True),
SourceConfigField("baudrate", int, default=115200),
SourceConfigField("data_bits", int, default=7),
SourceConfigField("parity", str, default="N"),
SourceConfigField("stop_bits", int, default=1),
),
capabilities=frozenset({"discover", "read_only_serial"}),
allowed_units=frozenset({"GJ", ""}),
)
SOURCE_PROFILES: dict[str, MeterSourceProfile] = {
DSMR_MQTT_PROFILE.kind: DSMR_MQTT_PROFILE,
WARMTELINK_SERIAL_PROFILE.kind: WARMTELINK_SERIAL_PROFILE,
}
def get_source_profile(kind: str) -> MeterSourceProfile:
"""Return the profile for *kind*, or raise a stable validation error."""
try:
return SOURCE_PROFILES[kind]
except KeyError as exc:
raise SourceProfileError(f"Unsupported meter source kind: {kind!r}") from exc
def list_source_profiles() -> list[MeterSourceProfile]:
"""Return profiles in deterministic kind order for a future API/UI."""
return [SOURCE_PROFILES[kind] for kind in sorted(SOURCE_PROFILES)]
def _check_type(field: SourceConfigField, value: Any) -> None:
# bool is a subclass of int; accept it only for explicitly boolean fields.
if type(value) is not field.value_type:
raise SourceProfileError(
f"Config field {field.name!r} must be a {field.value_type.__name__}."
)
def _validate_field_value(kind: str, field: SourceConfigField, value: Any) -> None:
_check_type(field, value)
if field.name == "path" and not value.startswith("/dev/"):
raise SourceProfileError("warmtelink_serial config path must start with '/dev/'.")
if field.name in {"broker_port", "baudrate"} and value <= 0:
raise SourceProfileError(f"Config field {field.name!r} must be greater than zero.")
if field.name == "sample_interval_s" and value < 0:
raise SourceProfileError("Config field 'sample_interval_s' must not be negative.")
if field.name == "data_bits" and value != 7:
raise SourceProfileError("warmtelink_serial data_bits must be 7.")
if field.name == "parity" and value != "N":
raise SourceProfileError("warmtelink_serial parity must be 'N'.")
if field.name == "stop_bits" and value != 1:
raise SourceProfileError("warmtelink_serial stop_bits must be 1.")
def validate_source_config(kind: str, config: dict[str, Any]) -> dict[str, Any]:
"""Validate a complete config and return it with profile defaults filled.
Unknown keys are rejected to make configuration additions explicit. Secret
masking is intentionally not interpreted here: callers must merge a PATCH
with its stored config first.
"""
profile = get_source_profile(kind)
if not isinstance(config, dict):
raise SourceProfileError("Source config must be an object.")
fields = {field.name: field for field in profile.fields}
unknown = set(config) - set(fields)
if unknown:
raise SourceProfileError(f"Unknown {kind} config field(s): {sorted(unknown)!r}")
validated: dict[str, Any] = {}
for field in profile.fields:
if field.name in config:
value = config[field.name]
elif field.required:
raise SourceProfileError(f"Missing required {kind} config field: {field.name!r}")
else:
value = field.default
_validate_field_value(kind, field, value)
validated[field.name] = value
return validated
def sanitize_source_config(kind: str, config: dict[str, Any]) -> dict[str, Any]:
"""Validate and return a response-safe config with secrets masked."""
profile = get_source_profile(kind)
sanitized = validate_source_config(kind, config)
for field in profile.fields:
if field.secret:
sanitized[field.name] = SECRET_MASK
return sanitized
def merge_source_config(kind: str, current: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]:
"""Merge a partial PATCH into stored config, retaining masked secrets.
An empty secret value is the public response mask and therefore means
"keep the old value". New sources use :func:`validate_source_config`
instead, so an explicitly empty secret can still be initially configured.
"""
profile = get_source_profile(kind)
current_validated = validate_source_config(kind, current)
if not isinstance(patch, dict):
raise SourceProfileError("Source config patch must be an object.")
fields = {field.name: field for field in profile.fields}
unknown = set(patch) - set(fields)
if unknown:
raise SourceProfileError(f"Unknown {kind} config field(s): {sorted(unknown)!r}")
merged = dict(current_validated)
for name, value in patch.items():
field = fields[name]
if field.secret and value == SECRET_MASK:
continue
merged[name] = value
return validate_source_config(kind, merged)
+1
View File
@@ -0,0 +1 @@
"""Modbus integration package — driver, profile loader, and decoder."""
+230
View File
@@ -0,0 +1,230 @@
"""Modbus TCP driver — thin wrapper around pymodbus.
This module provides a single public function ``read_blocks`` that performs
one or more block reads against a Modbus TCP gateway using either FC04
(Read Input Registers) or FC03 (Read Holding Registers), selected per call
via the ``function_code`` argument and returns a flat
``dict[register_address -> 16-bit_value]`` map. The function code comes from
the device profile (e.g. SDM120 uses FC04, DDSU666 uses FC03).
Design decisions
----------------
- **Only read function codes** (FC03/FC04) are exposed. There is no write path.
- float32 decoding uses ``struct.unpack('>f', ...)`` directly rather than the
pymodbus ``BinaryPayloadDecoder`` helper, which has had API churn across 3.x
releases. Big-endian word order + big-endian byte order means the 4 raw bytes
are already in standard network (big-endian) order.
- ``ModbusTcpClient`` is used in synchronous mode (``connect()`` / ``close()``).
The client is created fresh per call; this keeps the driver stateless and
avoids threading concerns at the cost of one TCP handshake per read cycle.
APScheduler jobs call this from a thread pool, so stateless is safer.
- pymodbus 3.13.x uses ``device_id=`` as the slave-address keyword argument
(renamed from ``slave=`` in earlier 3.x releases).
Exceptions
----------
``ModbusDriverError``
Base exception for all driver-level errors.
``ModbusConnectionError``
Raised when the TCP connection to the gateway cannot be established or is
lost during the read.
``ModbusResponseError``
Raised when the gateway responds with a Modbus exception frame or when the
returned register count does not match the requested count.
"""
from __future__ import annotations
import logging
import struct
from typing import TYPE_CHECKING
from pymodbus.client import ModbusTcpClient
from pymodbus.exceptions import ConnectionException, ModbusException
if TYPE_CHECKING:
from collections.abc import Sequence
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Custom exceptions
# ---------------------------------------------------------------------------
class ModbusDriverError(RuntimeError):
"""Base class for all Modbus driver errors."""
class ModbusConnectionError(ModbusDriverError):
"""Cannot connect to (or lost connection with) the Modbus TCP gateway."""
class ModbusResponseError(ModbusDriverError):
"""Modbus gateway returned an exception frame or an unexpected response."""
# ---------------------------------------------------------------------------
# Block definition type alias
# ---------------------------------------------------------------------------
#: A single read block: ``{"start": int, "count": int}``.
Block = dict[str, int]
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def read_blocks(
host: str,
port: int,
unit_id: int,
blocks: Sequence[Block],
*,
function_code: int = 4,
timeout: float = 3.0,
) -> dict[int, int]:
"""Read one or more contiguous register blocks via FC03 or FC04.
Parameters
----------
host:
Hostname or IP address of the Modbus TCP gateway.
port:
TCP port (typically 502).
unit_id:
Modbus slave / unit address (the device's Meter ID for SDM120).
blocks:
Sequence of ``{"start": int, "count": int}`` dicts describing the
contiguous register ranges to read. ``count`` is the number of
16-bit registers (not bytes).
function_code:
Modbus read function code: ``4`` for FC04 (Read Input Registers,
default SDM120) or ``3`` for FC03 (Read Holding Registers
DDSU666 and other devices that expose measurements as holding
registers). Comes from the device profile's ``function_code`` field.
timeout:
TCP connect/read timeout in seconds (default 3 s).
Returns
-------
dict[int, int]
Flat mapping of ``{register_address: 16-bit_register_value}`` for
every register returned across all blocks.
Raises
------
ModbusDriverError
If ``function_code`` is neither 3 nor 4 (validated before any
connection is attempted).
ModbusConnectionError
If the TCP connection to the gateway fails.
ModbusResponseError
If the gateway returns a Modbus exception frame or an unexpected
number of registers.
"""
if function_code not in (3, 4):
raise ModbusDriverError(
f"Unsupported read function code FC{function_code:02d} "
f"(only FC03 holding-register and FC04 input-register reads are supported)"
)
client = ModbusTcpClient(host, port=port, timeout=timeout)
try:
connected = client.connect()
if not connected:
raise ModbusConnectionError(
f"Could not connect to Modbus gateway at {host}:{port}"
)
registers: dict[int, int] = {}
for block in blocks:
start: int = block["start"]
count: int = block["count"]
_read_block(client, unit_id, start, count, registers, function_code=function_code)
return registers
except ConnectionException as exc:
raise ModbusConnectionError(
f"Connection to Modbus gateway {host}:{port} failed: {exc}"
) from exc
except ModbusException as exc:
raise ModbusResponseError(f"Modbus protocol error: {exc}") from exc
finally:
client.close()
def _read_block(
client: ModbusTcpClient,
unit_id: int,
start: int,
count: int,
result: dict[int, int],
*,
function_code: int,
) -> None:
"""Read one block and merge into *result*. Raises on any error.
``function_code`` is assumed already validated to be 3 or 4 by the caller
(``read_blocks``); 3 dispatches FC03 (holding) and 4 dispatches FC04 (input).
"""
try:
if function_code == 3:
response = client.read_holding_registers(start, count=count, device_id=unit_id)
else: # function_code == 4 (input registers)
response = client.read_input_registers(start, count=count, device_id=unit_id)
except ConnectionException as exc:
raise ModbusConnectionError(
f"Lost connection while reading registers 0x{start:04X}+{count}: {exc}"
) from exc
if response.isError():
raise ModbusResponseError(
f"Modbus exception reading registers 0x{start:04X}+{count}: {response}"
)
regs = response.registers
if len(regs) != count:
raise ModbusResponseError(
f"Expected {count} registers from 0x{start:04X}, got {len(regs)}"
)
for offset, value in enumerate(regs):
result[start + offset] = value
# ---------------------------------------------------------------------------
# Decoding helpers
# ---------------------------------------------------------------------------
def registers_to_float(hi_reg: int, lo_reg: int) -> float:
"""Decode two 16-bit registers to a big-endian IEEE-754 float32.
The SDM120 (and most Modbus float devices) use big-endian word order:
the high 16-bit register comes first, then the low register. Combined
with big-endian byte order within each register, the raw 4-byte sequence
is standard network-byte-order (big-endian) float32.
Parameters
----------
hi_reg:
The first (higher-address-range, most-significant) 16-bit register.
lo_reg:
The second (lower-address-range, least-significant) 16-bit register.
Returns
-------
float
The decoded IEEE-754 single-precision floating-point value.
Example
-------
>>> registers_to_float(0x4366, 0x3334)
230.20001220703125
"""
raw = struct.pack(">HH", hi_reg, lo_reg)
return struct.unpack(">f", raw)[0]
+231
View File
@@ -0,0 +1,231 @@
"""Modbus profile loader, validator, and decoder.
A *profile* is a YAML file that describes the protocol-level knowledge for
a particular Modbus device model:
- Which registers to read (``blocks`` for efficient bulk reads).
- How to decode each quantity (``metrics``: register address, type, unit, ).
- Home Assistant metadata per metric (``device_class``, ``ha_component``, ).
Profiles live in ``app/integrations/modbus/profiles/<name>.yaml`` and are
located at runtime relative to *this file* (not CWD), so they work whether
the package is installed as a wheel, run in-process, or invoked via
``python -m scripts.modbus_cli``.
Design notes
------------
- **Purely data + functions** no abstract base classes or inheritance.
- ``ModbusProfile`` and ``MetricSpec`` are Pydantic models: they validate on
construction and raise ``pydantic.ValidationError`` for malformed YAML.
- ``decode`` uses ``driver.registers_to_float`` for float32 quantities.
Unsupported types are silently skipped with a warning (future-proofing for
int16/uint16 etc.).
"""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Optional
import yaml
from pydantic import BaseModel, ValidationError
from app.integrations.modbus.driver import registers_to_float
logger = logging.getLogger(__name__)
# Directory containing the YAML profiles, located relative to *this* file.
_PROFILES_DIR = Path(__file__).parent / "profiles"
# ---------------------------------------------------------------------------
# Pydantic models for profile validation
# ---------------------------------------------------------------------------
class MetricSpec(BaseModel):
"""Specification for a single measurable quantity within a profile."""
key: str
"""Stable identifier used as the key in decoded payloads (e.g. ``"voltage"``)."""
address: int
"""Starting Modbus register address (0-based, e.g. ``0x0000`` for voltage)."""
type: str
"""Encoding type — currently only ``"float32"`` is supported."""
unit: str
"""Physical unit string (e.g. ``"V"``, ``"A"``, ``"kWh"``). Empty string for dimensionless."""
device_class: str
"""Home Assistant device class (e.g. ``"voltage"``, ``"power"``, ``"energy"``)."""
ha_component: str
"""Home Assistant component type (e.g. ``"sensor"``)."""
state_class: Optional[str] = None
"""Home Assistant state class, if applicable (e.g. ``"total_increasing"``)."""
class BlockSpec(BaseModel):
"""A contiguous register block for bulk reading."""
start: int
"""First register address in the block."""
count: int
"""Number of 16-bit registers to read."""
class ModbusProfile(BaseModel):
"""Complete description of a Modbus device's protocol-level knowledge."""
name: str
"""Short identifier matching the YAML file name (e.g. ``"sdm120"``)."""
description: str
"""Human-readable description of the device."""
function_code: int
"""Modbus function code for reading measurements (4 = FC04 input registers)."""
word_order: str
"""Word (register) order: ``"big"`` means high register first."""
byte_order: str
"""Byte order within each register: ``"big"`` means standard network order."""
blocks: list[BlockSpec]
"""Register blocks to read in bulk, reducing Modbus transaction count."""
metrics: list[MetricSpec]
"""List of individual measurable quantities and their decoding rules."""
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
class ProfileNotFoundError(FileNotFoundError):
"""Raised when the requested profile YAML file does not exist."""
class ProfileValidationError(ValueError):
"""Raised when a profile YAML file fails Pydantic validation."""
def load_profile(name: str) -> ModbusProfile:
"""Load and validate a Modbus device profile by name.
The profile file is expected at
``app/integrations/modbus/profiles/<name>.yaml``.
Parameters
----------
name:
Profile name without extension (e.g. ``"sdm120"``).
Returns
-------
ModbusProfile
Validated profile model.
Raises
------
ProfileNotFoundError
If ``profiles/<name>.yaml`` does not exist.
ProfileValidationError
If the YAML is syntactically valid but the content fails schema
validation (missing required fields, wrong types, etc.).
"""
path = _PROFILES_DIR / f"{name}.yaml"
if not path.exists():
raise ProfileNotFoundError(
f"Modbus profile '{name}' not found (looked for {path})"
)
with path.open("r", encoding="utf-8") as fh:
raw = yaml.safe_load(fh)
try:
profile = ModbusProfile.model_validate(raw)
except ValidationError as exc:
raise ProfileValidationError(
f"Profile '{name}' failed validation: {exc}"
) from exc
return profile
def list_profiles() -> list[tuple[str, str]]:
"""Return ``(name, description)`` pairs for all available profiles.
Scans ``app/integrations/modbus/profiles/*.yaml``, loads each, and
returns a sorted list of ``(name, description)`` tuples. Profiles that
fail to load are skipped with a warning.
"""
results: list[tuple[str, str]] = []
if not _PROFILES_DIR.exists():
return results
for path in sorted(_PROFILES_DIR.glob("*.yaml")):
name = path.stem
try:
profile = load_profile(name)
results.append((profile.name, profile.description))
except (ProfileNotFoundError, ProfileValidationError, Exception) as exc:
logger.warning("Skipping malformed profile '%s': %s", name, exc)
return results
def decode(profile: ModbusProfile, registers: dict[int, int]) -> dict[str, float]:
"""Decode raw register values into a mapping of ``{key: float_value}``.
For each metric in *profile*, the function looks up the two registers at
``address`` and ``address + 1`` in *registers* and decodes them as a
big-endian float32 (high register first).
Metrics whose registers are absent from *registers* are skipped (not
an error this can happen if a block was not requested or a device does
not populate that register). Metrics with unsupported ``type`` values
are also skipped.
Parameters
----------
profile:
Validated ``ModbusProfile`` describing the device.
registers:
Mapping of ``{register_address: 16-bit_value}`` as returned by
``driver.read_blocks``.
Returns
-------
dict[str, float]
Decoded engineering values keyed by each metric's ``key`` field.
"""
result: dict[str, float] = {}
for metric in profile.metrics:
if metric.type == "float32":
hi_addr = metric.address
lo_addr = metric.address + 1
if hi_addr not in registers or lo_addr not in registers:
logger.debug(
"Skipping metric '%s': registers 0x%04X/0x%04X not available",
metric.key,
hi_addr,
lo_addr,
)
continue
value = registers_to_float(registers[hi_addr], registers[lo_addr])
result[metric.key] = value
else:
logger.warning(
"Metric '%s' has unsupported type '%s', skipping",
metric.key,
metric.type,
)
return result
@@ -0,0 +1,82 @@
name: ddsu666
description: CHINT DDSU666 single-phase smart meter
function_code: 3 # holding registers (FC03) — DDSU666 has NO input registers (no FC04)
word_order: big # high register first — ASSUMED; verify with a known voltage reading
byte_order: big # high byte first within each register (confirmed by manual CRC example)
# NOTE: the manual gives no worked float-decode example, so word_order is a best-guess
# (standard big-endian, high register first, matching sdm120). After wiring the meter,
# read 0x2000 (voltage) — it should decode to ~230 V. If it decodes to garbage, the
# device uses the opposite word order and this profile (and the decoder) need adjusting.
# Byte order is confirmed big-endian from the manual (Appendix A, Table A.4: 0x1388 -> 13 88).
blocks:
# Instantaneous quantities 0x20000x200F: voltage, current, P, Q, (rsv), PF, (rsv), Freq.
# 16 contiguous registers — single bulk read. (DDSU666 manual Table 9.)
- { start: 0x2000, count: 0x0010 }
# Active energy — import (0x4000) and export (0x400A) read as two small blocks rather
# than one span, to avoid touching the undocumented/reserved 0x40020x4009 gap.
- { start: 0x4000, count: 0x0002 }
- { start: 0x400A, count: 0x0002 }
metrics:
# Addresses are the raw Modbus protocol addresses (hex) from DDSU666 manual Table 9,
# read via FC03. Each float32 occupies two consecutive 16-bit registers.
- key: voltage
address: 0x2000 # U — Voltage (V)
type: float32
unit: "V"
device_class: voltage
ha_component: sensor
- key: current
address: 0x2002 # I — Current (A)
type: float32
unit: "A"
device_class: current
ha_component: sensor
- key: active_power
address: 0x2004 # P — Active power. Manual unit is kW (NOT W like sdm120).
type: float32
unit: "kW"
device_class: power
ha_component: sensor
- key: reactive_power
address: 0x2006 # Q — Reactive power (kvar)
type: float32
unit: "kvar"
device_class: reactive_power
ha_component: sensor
- key: power_factor
address: 0x200A # PF — Power factor (dimensionless)
type: float32
unit: ""
device_class: power_factor
ha_component: sensor
- key: frequency
address: 0x200E # Freq — Frequency (Hz)
type: float32
unit: "Hz"
device_class: frequency
ha_component: sensor
- key: import_energy
address: 0x4000 # Ep — positive/forward active energy (kWh)
type: float32
unit: "kWh"
device_class: energy
state_class: total_increasing
ha_component: sensor
- key: export_energy
address: 0x400A # -Ep — reverse active energy (kWh)
type: float32
unit: "kWh"
device_class: energy
state_class: total_increasing
ha_component: sensor
@@ -0,0 +1,74 @@
name: sdm120
description: Eastron SDM120 single-phase energy meter
function_code: 4 # input registers (FC04)
word_order: big # high register first (big-endian word order)
byte_order: big # high byte first within each register
blocks:
# Registers 3000130095 (0x00000x005F): voltage through max export demand
- { start: 0x0000, count: 0x0060 }
# Registers 3034330346 (0x01560x0159): total active/reactive energy
- { start: 0x0156, count: 0x0004 }
metrics:
# Core measurements — addresses from SDM120 Modbus Protocol §4 (FC04 input registers)
# Each float32 occupies two consecutive 16-bit registers; address = Hex start in §4.
- key: voltage
address: 0x0000 # register 30001 — Voltage (V)
type: float32
unit: "V"
device_class: voltage
ha_component: sensor
- key: current
address: 0x0006 # register 30007 — Current (A)
type: float32
unit: "A"
device_class: current
ha_component: sensor
- key: active_power
address: 0x000C # register 30013 — Active power (W)
type: float32
unit: "W"
device_class: power
ha_component: sensor
- key: power_factor
address: 0x001E # register 30031 — Power factor (dimensionless)
type: float32
unit: ""
device_class: power_factor
ha_component: sensor
- key: frequency
address: 0x0046 # register 30071 — Frequency (Hz)
type: float32
unit: "Hz"
device_class: frequency
ha_component: sensor
- key: import_energy
address: 0x0048 # register 30073 — Import active energy (kWh)
type: float32
unit: "kWh"
device_class: energy
state_class: total_increasing
ha_component: sensor
- key: export_energy
address: 0x004A # register 30075 — Export active energy (kWh)
type: float32
unit: "kWh"
device_class: energy
state_class: total_increasing
ha_component: sensor
- key: total_energy
address: 0x0156 # register 30343 — Total active energy (kWh)
type: float32
unit: "kWh"
device_class: energy
state_class: total_increasing
ha_component: sensor
+581
View File
@@ -0,0 +1,581 @@
"""MQTT client integration (paho-mqtt 2.x).
Provides :class:`MqttManager`: a long-lived MQTT client that runs paho's
loop in a background thread. Designed to be started in FastAPI's lifespan
and shared across the application as a module-level singleton (``mqtt_manager``).
Key design decisions
--------------------
- **paho 2.x API**: ``Client`` requires ``CallbackAPIVersion.VERSION2`` as the
first positional argument. VERSION2 on_connect callback receives
``(client, userdata, connect_flags, reason_code, properties)`` not the
older RC int.
- **Background thread**: ``loop_start()`` spawns a daemon thread; ``loop_stop()``
joins it cleanly on shutdown.
- **Never crash the process**: all paho operations are wrapped in try/except;
connection failure is logged but does not propagate to the caller.
- **Password safety**: the MQTT password is never passed to ``logger`` calls.
- **Reconnect**: ``reconnect(settings)`` tears down the old client and
establishes a fresh connection with the new settings. Callers (e.g. PUT
/api/config) call this after saving MQTT-related config values.
- **Subscribe**: ``subscribe(topic, handler)`` registers a topic handler
mapping. Subscriptions are re-established automatically on reconnect.
The ``on_message`` callback dispatches incoming payloads to the registered
handler; handler exceptions are caught and logged so they never crash the
paho loop thread or the network connection.
"""
from __future__ import annotations
import logging
import threading
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING
import paho.mqtt.client as mqtt
if TYPE_CHECKING:
from app.config import Settings
logger = logging.getLogger(__name__)
# MQTT settings keys that, when changed, should trigger a reconnect.
MQTT_SETTINGS_KEYS = {
"mqtt_enabled",
"mqtt_broker_host",
"mqtt_broker_port",
"mqtt_username",
"mqtt_password",
"mqtt_tls_enabled",
"mqtt_client_id",
}
@dataclass
class _SourceClientState:
"""One installed source generation and its in-flight callback count."""
client: mqtt.Client
generation: int
in_flight: int = 0
def _is_configured(settings: Settings) -> bool:
"""Return True if MQTT is enabled *and* the broker host is set."""
return bool(settings.mqtt_enabled and settings.mqtt_broker_host)
def mqtt_source_client_id(base_client_id: str, source_id: int) -> str:
"""Return a stable, deployment-scoped identity for one DSMR source."""
return f"{base_client_id}-dsmr-source-{source_id}"
def mqtt_test_client_id(base_client_id: str) -> str:
"""Return a transient test identity that cannot evict a long-lived client."""
return f"{base_client_id}-test"
class MqttManager:
"""Long-lived MQTT client wrapper.
Lifecycle
---------
1. ``connect(settings)`` start background loop + connect to broker.
2. ``publish(...)`` publish messages while connected.
3. ``disconnect()`` graceful teardown (called on app shutdown).
4. ``reconnect(settings)`` disconnect then re-connect with new settings
(called after saving updated MQTT configuration).
When MQTT is not enabled or not configured, all methods are no-ops.
Connection failures are caught and logged; they do not raise.
"""
def __init__(self) -> None:
self._client: mqtt.Client | None = None
self._lock = threading.RLock()
# Source replacement/removal is serialized independently from callback
# bookkeeping. In particular, paho's loop_stop() joins its network
# thread, whose callback completion also needs ``_lock``.
self._source_lifecycle_lock = threading.Lock()
self._source_idle = threading.Condition(self._lock)
self._connected = False
# topic → handler registry; persists across reconnects so subscriptions
# are automatically re-established when the client reconnects.
self._subscriptions: dict[str, Callable[[bytes], None]] = {}
# DSMR sources are independent connections: their credentials and TLS
# configuration belong to MeterSource.config, not app_config.
self._source_clients: dict[int, mqtt.Client] = {}
self._source_subscriptions: dict[int, dict[str, Callable[[bytes], None]]] = {}
self._source_connected: set[int] = set()
# Each replacement gets a distinct identity. A paho callback can run
# after its client was stopped, so source id alone is not sufficient.
self._source_generations: dict[int, int] = {}
self._source_states: dict[int, _SourceClientState] = {}
self._next_source_generation = 0
# ------------------------------------------------------------------
# Public properties
# ------------------------------------------------------------------
@property
def is_connected(self) -> bool:
"""True if the underlying paho client is currently connected."""
return self._connected
# ------------------------------------------------------------------
# Public interface
# ------------------------------------------------------------------
def is_configured(self, settings: Settings) -> bool:
"""Return True if MQTT is enabled and broker host is configured."""
return _is_configured(settings)
def connect(self, settings: Settings) -> None:
"""Connect to the MQTT broker and start the background loop thread.
No-op if MQTT is not enabled or broker host is not set.
Connection errors are logged but do not raise.
"""
if not _is_configured(settings):
logger.debug("MQTT not configured or not enabled — skipping connect.")
return
with self._lock:
self._start_client(settings)
def disconnect(self) -> None:
"""Disconnect from the broker and stop the background loop thread.
No-op if no client is active.
"""
with self._lock:
self._stop_client()
with self._source_lifecycle_lock:
with self._lock:
source_ids = list(self._source_clients)
for source_id in source_ids:
self._stop_source_client(source_id)
def reconnect(self, settings: Settings) -> None:
"""Disconnect the current client (if any) and reconnect with *settings*.
Call this after saving updated MQTT configuration values.
No-op if MQTT is not enabled or broker host is not set.
"""
with self._lock:
self._stop_client()
self.connect(settings)
def publish(
self,
topic: str,
payload: str | bytes | None,
*,
retain: bool = False,
qos: int = 0,
) -> bool:
"""Publish a message to *topic*.
Return whether paho accepted the message for publication. If the
client is not connected, or paho raises/rejects it, return ``False``;
errors still do not escape this best-effort boundary.
"""
with self._lock:
client = self._client
if client is None or not self._connected:
logger.debug("MQTT publish skipped — not connected (topic=%s).", topic)
return False
try:
result = client.publish(topic, payload=payload, qos=qos, retain=retain)
# paho returns MQTTMessageInfo with an integer rc. Keep fakes and
# alternate clients compatible by treating an absent/non-int rc as
# accepted after the call itself succeeded.
rc = getattr(result, "rc", None)
if isinstance(rc, int) and rc != mqtt.MQTT_ERR_SUCCESS:
logger.warning("MQTT publish rejected (topic=%s, rc=%s).", topic, rc)
return False
return True
except Exception:
logger.exception("MQTT publish error (topic=%s).", topic)
return False
def subscribe(self, topic: str, handler: Callable[[bytes], None]) -> None:
"""Register *handler* to be called when a message arrives on *topic*.
If the client is already connected, the subscription is sent to the
broker immediately. Otherwise it is queued and will be established
the next time ``_on_connect`` fires (including after a reconnect).
Handler exceptions are swallowed by the ``on_message`` dispatcher so
that a buggy handler can never crash the paho loop thread.
"""
self._subscriptions[topic] = handler
# Grab the client reference outside the lock to avoid holding the lock
# while calling back into paho (which may itself acquire internal locks).
with self._lock:
client = self._client
connected = self._connected
if client is not None and connected:
try:
client.subscribe(topic)
logger.debug("MQTT subscribed to topic=%s (immediate).", topic)
except Exception:
logger.exception("MQTT subscribe error (topic=%s).", topic)
def unsubscribe(self, topic: str) -> None:
"""Remove the handler for *topic* and unsubscribe from the broker.
Idempotent: unknown topics are ignored. Used to apply config changes
without a restart (e.g. when DSMR ingest is turned off or its topic
changes). If the client is connected, the broker unsubscribe is sent
immediately; either way the handler is removed from the registry so it
will not be re-subscribed on the next ``_on_connect``.
"""
self._subscriptions.pop(topic, None)
with self._lock:
client = self._client
connected = self._connected
if client is not None and connected:
try:
client.unsubscribe(topic)
logger.debug("MQTT unsubscribed from topic=%s.", topic)
except Exception:
logger.exception("MQTT unsubscribe error (topic=%s).", topic)
def replace_source(
self,
source_id: int,
*,
host: str,
port: int,
username: str,
password: str,
tls_enabled: bool,
subscriptions: dict[str, Callable[[bytes], None]],
base_client_id: str = "home-automation",
state_handler: Callable[[str], None] | None = None,
) -> bool:
"""Replace one source-owned client and its handlers.
This intentionally does not touch the legacy app-wide client or any
other source client. It is also safe for a source to be temporarily
unconfigured: handlers are retained in the source registry but no
connection is attempted until a host is supplied.
"""
with self._source_lifecycle_lock:
self._stop_source_client(source_id)
if not host:
self._report_source_state(state_handler, "error", source_id)
return False
self._next_source_generation += 1
generation = self._next_source_generation
captured_subscriptions = dict(subscriptions)
client = mqtt.Client(
callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
client_id=mqtt_source_client_id(base_client_id, source_id),
)
def _on_connect(
connected_client: mqtt.Client,
_userdata: object,
_flags: mqtt.ConnectFlags,
reason_code: mqtt.ReasonCode,
_properties: mqtt.Properties | None,
) -> None:
with self._lock:
if not self._is_current_source_client(source_id, generation, connected_client):
return
if reason_code.is_failure:
self._source_connected.discard(source_id)
logger.warning("DSMR MQTT connection refused for source_id=%s", source_id)
state = "error"
else:
self._source_connected.add(source_id)
state = "online"
for topic in captured_subscriptions:
try:
connected_client.subscribe(topic)
except Exception:
logger.exception("DSMR MQTT re-subscribe failed for source_id=%s", source_id)
self._report_source_state(state_handler, state, source_id)
def _on_disconnect(
disconnected_client: mqtt.Client,
_userdata: object,
_flags: mqtt.DisconnectFlags,
_reason_code: mqtt.ReasonCode,
_properties: mqtt.Properties | None,
) -> None:
with self._lock:
if not self._is_current_source_client(source_id, generation, disconnected_client):
return
self._source_connected.discard(source_id)
self._report_source_state(state_handler, "error", source_id)
def _on_message(
message_client: mqtt.Client,
_userdata: object,
message: mqtt.MQTTMessage,
) -> None:
with self._lock:
if not self._is_current_source_client(source_id, generation, message_client):
return
handler = captured_subscriptions.get(message.topic)
state = self._source_states.get(source_id)
if handler is None or state is None:
return
# This permit covers the entire handler call. Teardown first
# invalidates the state and then waits for all permits, so an
# old callback cannot run after teardown returns.
state.in_flight += 1
try:
handler(message.payload)
except Exception:
logger.exception("DSMR source handler raised (source_id=%s)", source_id)
finally:
with self._lock:
state.in_flight -= 1
if state.in_flight == 0:
self._source_idle.notify_all()
client.on_connect = _on_connect
client.on_disconnect = _on_disconnect
client.on_message = _on_message
if tls_enabled:
try:
client.tls_set()
except Exception:
logger.exception("DSMR MQTT TLS setup failed for source_id=%s", source_id)
self._report_source_state(state_handler, "error", source_id)
return False
if username:
client.username_pw_set(username=username, password=password or None)
# Register ownership before network processing begins. A broker
# may deliver CONNACK synchronously from connect(), or on the loop
# thread before connect() returns.
with self._lock:
self._source_clients[source_id] = client
self._source_subscriptions[source_id] = captured_subscriptions
self._source_generations[source_id] = generation
self._source_states[source_id] = _SourceClientState(client, generation)
self._report_source_state(state_handler, "connecting", source_id)
client.loop_start()
try:
client.connect(host=host, port=port, keepalive=60)
except Exception:
logger.exception("DSMR MQTT connect failed (source_id=%s, host=%s)", source_id, host)
self._report_source_state(state_handler, "error", source_id)
self._stop_source_client(source_id)
return False
return True
def remove_source(self, source_id: int) -> None:
"""Drop one source client and its handlers, including queued callbacks."""
with self._source_lifecycle_lock:
self._stop_source_client(source_id)
def source_is_active(self, source_id: int) -> bool:
"""Whether a source-owned client is currently installed for callbacks."""
with self._lock:
return source_id in self._source_clients
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _start_client(self, settings: Settings) -> None:
"""Build a fresh paho Client, configure it, and call loop_start + connect."""
client = mqtt.Client(
callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
client_id=settings.mqtt_client_id,
)
# Callbacks — VERSION2 on_connect signature:
# (client, userdata, connect_flags, reason_code, properties)
def _on_connect(
_client: mqtt.Client,
_userdata: object,
_flags: mqtt.ConnectFlags,
reason_code: mqtt.ReasonCode,
_properties: mqtt.Properties | None,
) -> None:
if reason_code.is_failure:
logger.warning("MQTT connection refused: %s", reason_code)
self._connected = False
else:
logger.info("MQTT connected (reason_code=%s).", reason_code)
self._connected = True
# Re-establish all registered subscriptions after (re-)connect.
for sub_topic in self._subscriptions:
try:
_client.subscribe(sub_topic)
logger.debug("MQTT re-subscribed to topic=%s.", sub_topic)
except Exception:
logger.exception(
"MQTT re-subscribe failed (topic=%s).", sub_topic
)
# VERSION2 on_disconnect signature:
# (client, userdata, disconnect_flags, reason_code, properties)
def _on_disconnect(
_client: mqtt.Client,
_userdata: object,
_disconnect_flags: mqtt.DisconnectFlags,
reason_code: mqtt.ReasonCode,
_properties: mqtt.Properties | None,
) -> None:
self._connected = False
if reason_code.is_failure:
logger.warning("MQTT disconnected unexpectedly (reason_code=%s).", reason_code)
else:
logger.info("MQTT disconnected cleanly.")
# VERSION2 on_message signature: (client, userdata, message)
def _on_message(
_client: mqtt.Client,
_userdata: object,
message: mqtt.MQTTMessage,
) -> None:
handler = self._subscriptions.get(message.topic)
if handler is None:
logger.debug(
"MQTT on_message: no handler for topic=%s.", message.topic
)
return
try:
handler(message.payload)
except Exception:
logger.exception(
"MQTT message handler raised for topic=%s (swallowed).",
message.topic,
)
client.on_connect = _on_connect
client.on_disconnect = _on_disconnect
client.on_message = _on_message
# TLS
if settings.mqtt_tls_enabled:
try:
client.tls_set()
except Exception:
logger.exception("MQTT TLS setup failed.")
return
# Credentials — never log the password
if settings.mqtt_username:
client.username_pw_set(
username=settings.mqtt_username,
password=settings.mqtt_password or None,
)
# Start background loop thread *before* connect so paho can handle
# the connection handshake asynchronously.
client.loop_start()
try:
client.connect(
host=settings.mqtt_broker_host,
port=settings.mqtt_broker_port,
keepalive=60,
)
except Exception:
# Log without leaking the password
logger.exception(
"MQTT connect failed (host=%s, port=%s). Stopping loop.",
settings.mqtt_broker_host,
settings.mqtt_broker_port,
)
try:
client.loop_stop()
except Exception:
pass
return
self._client = client
logger.info(
"MQTT client started (host=%s, port=%s).",
settings.mqtt_broker_host,
settings.mqtt_broker_port,
)
def _stop_client(self) -> None:
"""Disconnect and stop the background loop. Idempotent."""
client = self._client
if client is None:
return
self._client = None
self._connected = False
try:
client.disconnect()
except Exception:
logger.debug("MQTT disconnect raised (ignoring).", exc_info=True)
try:
client.loop_stop()
except Exception:
logger.debug("MQTT loop_stop raised (ignoring).", exc_info=True)
logger.info("MQTT client stopped.")
def _stop_source_client(self, source_id: int) -> None:
"""Detach then stop a source client without blocking callback bookkeeping.
Callers hold ``_source_lifecycle_lock``. The first phase makes the
generation unreachable while holding ``_lock``. Paho operations and
the in-flight wait are deliberately outside that lock: loop_stop()
joins paho's network thread, and an active callback needs ``_lock`` to
release its permit in ``_on_message``'s finally block.
"""
with self._lock:
state = self._source_states.pop(source_id, None)
client = self._source_clients.pop(source_id, None)
self._source_subscriptions.pop(source_id, None)
self._source_connected.discard(source_id)
# Invalidate callbacks even when there was no successfully
# installed client (for example after a failed replacement).
self._source_generations.pop(source_id, None)
if client is not None:
try:
client.disconnect()
except Exception:
logger.debug("DSMR MQTT disconnect raised (source_id=%s)", source_id, exc_info=True)
try:
client.loop_stop()
except Exception:
logger.debug("DSMR MQTT loop_stop raised (source_id=%s)", source_id, exc_info=True)
if state is not None:
with self._lock:
while state.in_flight:
self._source_idle.wait()
def _is_current_source_client(
self, source_id: int, generation: int, client: mqtt.Client
) -> bool:
"""Check callback ownership while ``_lock`` is held."""
return (
self._source_generations.get(source_id) == generation
and self._source_clients.get(source_id) is client
)
@staticmethod
def _report_source_state(
state_handler: Callable[[str], None] | None, state: str, source_id: int
) -> None:
"""Invoke an optional health callback without exposing connection credentials."""
if state_handler is None:
return
try:
state_handler(state)
except Exception:
logger.exception("DSMR MQTT source state update failed for source_id=%s", source_id)
# ---------------------------------------------------------------------------
# Module-level singleton — shared across lifespan and route handlers
# ---------------------------------------------------------------------------
mqtt_manager = MqttManager()
+192
View File
@@ -0,0 +1,192 @@
"""Pure, privacy-preserving parser for DSMR and WarmteLink P1 telegrams."""
from __future__ import annotations
from dataclasses import dataclass, field as dataclass_field
from decimal import Decimal, InvalidOperation
from enum import StrEnum
import hashlib
import re
_OBIS_LINE = re.compile(r"^(?P<code>\d+-\d+:\d+\.\d+\.\d+)(?P<values>(?:\([^)]*\))*)$")
_NUMBER_WITH_UNIT = re.compile(r"^(?P<number>[+-]?\d+(?:\.\d+)?)(?:\*(?P<unit>.+))?$")
_CHANNEL_OBIS = re.compile(r"^0-(?P<channel>[1-9]\d*):(24|96)\.")
_EQUIPMENT_ID_CODES = re.compile(r"^0-(?:0|[1-9]\d*):96\.1\.[01]$")
class IntegrityStatus(StrEnum):
"""Whether a frame has a verifiable standard DSMR checksum."""
VALID = "valid"
INVALID = "invalid"
UNVERIFIABLE = "unverifiable"
class P1ParseError(ValueError):
"""A parse error whose message never includes telegram contents."""
@dataclass(frozen=True)
class ObisField:
"""One sanitized OBIS line, including values not understood by the parser."""
code: str
raw_values: tuple[str, ...]
value: Decimal | None = None
unit: str | None = None
comparison_token: str | None = dataclass_field(default=None, repr=False)
@dataclass(frozen=True)
class P1Channel:
"""Fields associated with one M-Bus channel, without its raw identifier."""
number: int
device_type: str | None
equipment_fingerprint: str | None = dataclass_field(repr=False)
readings: tuple[ObisField, ...]
@dataclass(frozen=True)
class P1Telegram:
"""A parsed telegram with only sanitized, persistence-safe data."""
frame_length: int
integrity: IntegrityStatus
integrity_reason: str
timestamp: str | None
equipment_fingerprint: str | None = dataclass_field(repr=False)
fields: tuple[ObisField, ...]
channels: tuple[P1Channel, ...]
class TelegramFramer:
"""Incrementally extract newline-terminated variable-length telegrams."""
def __init__(self) -> None:
self._buffer = bytearray()
def feed(self, chunk: bytes) -> list[bytes]:
"""Append *chunk* and return every complete frame now available."""
self._buffer.extend(chunk)
frames: list[bytes] = []
while (bang := self._buffer.find(b"!")) >= 0:
newline = self._buffer.find(b"\n", bang)
if newline < 0:
break
standard_start = self._buffer.find(b"/")
start = standard_start if 0 <= standard_start < bang else 0
frames.append(bytes(self._buffer[start : newline + 1]))
del self._buffer[: newline + 1]
return frames
def dsmr_crc16(data: bytes) -> int:
"""Return the DSMR CRC-16 over *data* (normally from ``/`` through ``!``)."""
crc = 0
for byte in data:
crc ^= byte
for _ in range(8):
crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1
return crc & 0xFFFF
def parse_telegram(frame: bytes) -> P1Telegram:
"""Parse one complete frame without retaining raw telegram bytes or IDs."""
bang = frame.find(b"!")
if bang < 0:
raise P1ParseError("telegram has no footer marker")
body = frame[:bang]
footer = frame[bang + 1 :].rstrip(b"\r\n")
integrity, reason = _integrity(frame, bang, footer)
fields, identifiers = _parse_obis_fields(body)
timestamp = _field_value(fields, "0-0:1.0.0")
return P1Telegram(
frame_length=len(frame),
integrity=integrity,
integrity_reason=reason,
timestamp=timestamp,
equipment_fingerprint=identifiers.get("0-0:96.1.1"),
fields=tuple(fields),
channels=_parse_channels(fields, identifiers),
)
def _integrity(frame: bytes, bang: int, footer: bytes) -> tuple[IntegrityStatus, str]:
if not frame.startswith(b"/"):
return IntegrityStatus.UNVERIFIABLE, "missing standard DSMR '/' header"
if len(footer) != 4 or not all(chr(byte) in "0123456789abcdefABCDEF" for byte in footer):
return IntegrityStatus.UNVERIFIABLE, "footer is not a four-digit hexadecimal CRC"
expected = int(footer, 16)
actual = dsmr_crc16(frame[: bang + 1])
if actual == expected:
return IntegrityStatus.VALID, "CRC16 verified from '/' through '!'"
return IntegrityStatus.INVALID, f"CRC16 mismatch: expected {expected:04X}, calculated {actual:04X}"
def _parse_obis_fields(body: bytes) -> tuple[list[ObisField], dict[str, str]]:
fields: list[ObisField] = []
identifiers: dict[str, str] = {}
for line in body.decode("ascii", errors="replace").splitlines()[1:]:
match = _OBIS_LINE.fullmatch(line)
if not match:
continue
code = match.group("code")
raw_values = tuple(re.findall(r"\(([^)]*)\)", match.group("values")))
if _EQUIPMENT_ID_CODES.fullmatch(code):
comparison_token = _fingerprint(raw_values[-1]) if raw_values else None
if comparison_token is not None:
identifiers[code] = comparison_token
fields.append(ObisField(code, ("<redacted>",), comparison_token=comparison_token))
continue
value, unit = _numeric_value(raw_values)
fields.append(ObisField(code, raw_values, value, unit))
return fields, identifiers
def _fingerprint(identifier: str) -> str:
"""Hash an identifier locally; callers never receive its original value."""
return hashlib.sha256(identifier.encode("ascii", errors="replace")).hexdigest()
def _numeric_value(raw_values: tuple[str, ...]) -> tuple[Decimal | None, str | None]:
if not raw_values:
return None, None
match = _NUMBER_WITH_UNIT.fullmatch(raw_values[-1])
if not match:
return None, None
try:
return Decimal(match.group("number")), match.group("unit")
except InvalidOperation:
return None, None
def _field_value(fields: list[ObisField], code: str) -> str | None:
field = next((item for item in fields if item.code == code), None)
return field.raw_values[-1] if field and field.raw_values else None
def _parse_channels(fields: list[ObisField], identifiers: dict[str, str]) -> tuple[P1Channel, ...]:
by_channel: dict[int, list[ObisField]] = {}
for field in fields:
match = _CHANNEL_OBIS.match(field.code)
if match:
by_channel.setdefault(int(match.group("channel")), []).append(field)
return tuple(
P1Channel(
number=number,
device_type=_field_value(channel_fields, f"0-{number}:24.1.0"),
equipment_fingerprint=identifiers.get(f"0-{number}:96.1.0"),
readings=tuple(
field
for field in channel_fields
if field.code == f"0-{number}:24.2.1" and field.value is not None
),
)
for number, channel_fields in sorted(by_channel.items())
)
+11
View File
@@ -0,0 +1,11 @@
"""Pricing profile framework and strategy registry.
This package provides:
- ``profiles``: Pydantic models describing the structure of pricing profiles
(``ManualProfile`` / ``TibberProfile``), YAML loaders, and contract-values
validation (``load_profile`` / ``list_profiles`` / ``validate_values``).
- ``strategies``: A lightweight registry of price-calculation strategies
(``register_strategy`` / ``get_strategy``), with built-in implementations for
the ``manual`` (fixed dual-tariff) and ``tibber`` (dynamic API) kinds.
"""
+556
View File
@@ -0,0 +1,556 @@
"""Pricing profile loader, validator, and contract-values checker.
A *pricing profile* is a YAML file that describes the **structure** of an energy
contract which fields exist, their units, and which have defaults. Actual
pricing values (the numbers the user fills in via the UI) are stored in the DB
as ``EnergyContractVersion.values`` (a JSON blob) and must conform to the
corresponding profile's structure.
Profiles live in ``app/integrations/pricing/profiles/<kind>.yaml`` and are
located at runtime relative to *this file* (not CWD), matching the pattern
established by the Modbus profile loader.
Design notes
------------
- **Purely data + functions** no abstract base classes or inheritance.
- Two Pydantic models ``ManualProfile`` and ``TibberProfile`` capture the
different structures of the two supported kinds. A thin union dispatcher in
``load_profile`` picks the right one.
- ``validate_values(kind, values)`` fills in fields that carry a ``default`` and
raises ``ProfileValidationError`` for missing required fields or wrong types.
- All errors are subclasses of built-ins so callers need not import this module
just to catch them.
"""
from __future__ import annotations
import logging
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any, Optional
import yaml
from pydantic import BaseModel, ValidationError, model_validator
logger = logging.getLogger(__name__)
# Directory containing the YAML profiles, located relative to *this* file.
_PROFILES_DIR = Path(__file__).parent / "profiles"
# ---------------------------------------------------------------------------
# Custom exceptions
# ---------------------------------------------------------------------------
class ProfileNotFoundError(FileNotFoundError):
"""Raised when the requested profile YAML file does not exist."""
class ProfileValidationError(ValueError):
"""Raised when a profile YAML fails Pydantic validation or when contract
values do not conform to the profile structure."""
# ---------------------------------------------------------------------------
# Leaf-node models (a single pricing field: unit + optional default)
# ---------------------------------------------------------------------------
class FieldSpec(BaseModel):
"""Specification for a single numeric pricing field."""
unit: str
"""Physical / monetary unit string (e.g. ``"EUR/kWh"``, ``"EUR/month"``)."""
default: Optional[float] = None
"""Default value used when the field is absent from contract values.
``None`` means the field is required (no default)."""
# ---------------------------------------------------------------------------
# ManualProfile — fixed / variable dual-tariff contract structure
# ---------------------------------------------------------------------------
class ManualBuySpec(BaseModel):
normal: FieldSpec # high-tariff buy price (delivered_2 registers)
dal: FieldSpec # low-tariff buy price (delivered_1 registers)
class ManualSellSpec(BaseModel):
normal: FieldSpec # high-tariff sell / return price
dal: FieldSpec # low-tariff sell / return price
class ManualEnergySpec(BaseModel):
dual_tariff: bool # always True for manual profiles
buy: ManualBuySpec
sell: ManualSellSpec
energy_tax: FieldSpec # added to buy price; includes VAT
ode: FieldSpec # currently merged into energy_tax; default 0
class ManualStandingSpec(BaseModel):
network_fee: FieldSpec # EUR/month
management_fee: FieldSpec # EUR/month
class ManualCreditsSpec(BaseModel):
heffingskorting: FieldSpec # EUR/year — energy-tax credit deducted at summary
class ManualProfile(BaseModel):
"""Complete structure description for a ``manual`` pricing contract."""
kind: str
label: str
energy: ManualEnergySpec
standing: ManualStandingSpec
credits: ManualCreditsSpec
@model_validator(mode="after")
def _check_kind(self) -> "ManualProfile":
if self.kind != "manual":
raise ValueError(f"ManualProfile requires kind='manual', got {self.kind!r}")
return self
# ---------------------------------------------------------------------------
# TibberProfile — dynamic Tibber API contract structure
# ---------------------------------------------------------------------------
class TibberEnergySpec(BaseModel):
source: str # must be "tibber_api"
energy_tax: FieldSpec # subtracted from total to derive sell price
sell_fee: FieldSpec # verkoopvergoeding (feed-in fee); always subtracted from sell; default 0.0248
sell_adjust: FieldSpec # additional sell-price adjustment; default 0
class TibberStandingSpec(BaseModel):
management_fee: FieldSpec # EUR/month; has a default
network_fee: FieldSpec # EUR/month
class TibberCreditsSpec(BaseModel):
heffingskorting: FieldSpec # EUR/year
class TibberProfile(BaseModel):
"""Complete structure description for a ``tibber`` pricing contract."""
kind: str
label: str
energy: TibberEnergySpec
standing: TibberStandingSpec
credits: TibberCreditsSpec
@model_validator(mode="after")
def _check_kind(self) -> "TibberProfile":
if self.kind != "tibber":
raise ValueError(f"TibberProfile requires kind='tibber', got {self.kind!r}")
return self
# ---------------------------------------------------------------------------
# DistrictHeatingProfile — user-entered thermal contract structure
# ---------------------------------------------------------------------------
class DistrictHeatingFieldSpec(BaseModel):
"""A Decimal-safe thermal tariff field displayed to the user."""
model_config = {"extra": "forbid"}
unit: str
label: str
help: str
minimum: Decimal = Decimal("0")
default: Decimal | None = None
class DistrictHeatingVariableSpec(BaseModel):
model_config = {"extra": "forbid"}
heating: DistrictHeatingFieldSpec
hot_water_heating: DistrictHeatingFieldSpec
hot_water: DistrictHeatingFieldSpec
hot_water_tax: DistrictHeatingFieldSpec
class DistrictHeatingStandingSpec(BaseModel):
model_config = {"extra": "forbid"}
heating_network: DistrictHeatingFieldSpec
metering: DistrictHeatingFieldSpec
delivery_set: DistrictHeatingFieldSpec
hot_water_network: DistrictHeatingFieldSpec
other: DistrictHeatingFieldSpec
class DistrictHeatingProfile(BaseModel):
"""Complete structure description for a ``district_heating`` contract."""
model_config = {"extra": "forbid"}
kind: str
label: str
variable: DistrictHeatingVariableSpec
standing: DistrictHeatingStandingSpec
@model_validator(mode="after")
def _check_kind(self) -> "DistrictHeatingProfile":
if self.kind != "district_heating":
raise ValueError(
"DistrictHeatingProfile requires kind='district_heating', "
f"got {self.kind!r}"
)
units = {
"heating": "EUR/GJ",
"hot_water_heating": "EUR/m³",
"hot_water": "EUR/m³",
"hot_water_tax": "EUR/m³",
}
for key, unit in units.items():
field = getattr(self.variable, key)
if field.unit != unit or field.minimum != 0 or field.default is not None:
raise ValueError(f"district_heating.variable.{key} must be required {unit} with minimum 0")
for key in DistrictHeatingStandingSpec.model_fields:
field = getattr(self.standing, key)
if field.unit != "EUR/year" or field.minimum != 0 or field.default != 0:
raise ValueError(
f"district_heating.standing.{key} must be EUR/year with default and minimum 0"
)
return self
# A union type for type hints where either profile is acceptable.
AnyProfile = ManualProfile | TibberProfile | DistrictHeatingProfile
# Map kind → Pydantic model class used for validation.
_PROFILE_MODELS: dict[str, type[ManualProfile] | type[TibberProfile] | type[DistrictHeatingProfile]] = {
"manual": ManualProfile,
"tibber": TibberProfile,
"district_heating": DistrictHeatingProfile,
}
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def load_profile(kind: str) -> AnyProfile:
"""Load and validate a pricing profile by kind name.
The profile file is expected at
``app/integrations/pricing/profiles/<kind>.yaml``.
Parameters
----------
kind:
Profile kind without extension (``"manual"`` or ``"tibber"``).
Returns
-------
ManualProfile | TibberProfile
Validated profile model.
Raises
------
ProfileNotFoundError
If ``profiles/<kind>.yaml`` does not exist.
ProfileValidationError
If the YAML is syntactically valid but fails schema validation.
"""
path = _PROFILES_DIR / f"{kind}.yaml"
if not path.exists():
raise ProfileNotFoundError(
f"Pricing profile '{kind}' not found (looked for {path})"
)
with path.open("r", encoding="utf-8") as fh:
raw = yaml.safe_load(fh)
if not isinstance(raw, dict):
raise ProfileValidationError(
f"Profile '{kind}': expected a YAML mapping, got {type(raw).__name__}"
)
# YAML's implicit float conversion must never contaminate the thermal profile.
# Existing electricity profiles intentionally retain their established defaults.
if raw.get("kind", kind) == "district_heating":
_reject_yaml_floats(raw, path)
# Choose the right Pydantic model based on the ``kind`` field in the YAML.
yaml_kind = raw.get("kind", kind)
model_cls = _PROFILE_MODELS.get(yaml_kind)
if model_cls is None:
raise ProfileValidationError(
f"Profile '{kind}' has unknown kind={yaml_kind!r}; "
f"supported: {list(_PROFILE_MODELS)}"
)
try:
return model_cls.model_validate(raw)
except ValidationError as exc:
raise ProfileValidationError(
f"Profile '{kind}' failed validation: {exc}"
) from exc
def list_profiles() -> list[dict[str, Any]]:
"""Return structural data for all available pricing profiles.
Scans ``app/integrations/pricing/profiles/*.yaml``, loads each, and returns
a list of dicts (Pydantic model dumps). Profiles that fail to load are
skipped with a warning.
Returns
-------
list[dict[str, Any]]
One entry per valid profile, suitable for JSON serialisation and
front-end form rendering.
"""
results: list[dict[str, Any]] = []
if not _PROFILES_DIR.exists():
return results
for path in sorted(_PROFILES_DIR.glob("*.yaml")):
kind = path.stem
try:
profile = load_profile(kind)
results.append(profile.model_dump())
except (ProfileNotFoundError, ProfileValidationError, Exception) as exc:
logger.warning("Skipping malformed pricing profile '%s': %s", kind, exc)
return results
# ---------------------------------------------------------------------------
# Contract-values validation
# ---------------------------------------------------------------------------
def _fill_defaults_manual(values: dict[str, Any], profile: ManualProfile) -> dict[str, Any]:
"""Return a copy of *values* with any ``ode`` default applied if missing."""
filled = dict(values)
energy = dict(filled.get("energy", {}))
# Apply default for ode (default=0) if absent.
if "ode" not in energy and profile.energy.ode.default is not None:
energy["ode"] = profile.energy.ode.default
filled["energy"] = energy
return filled
def _fill_defaults_tibber(values: dict[str, Any], profile: TibberProfile) -> dict[str, Any]:
"""Return a copy of *values* with sell_fee, sell_adjust and management_fee defaults applied."""
filled = dict(values)
energy = dict(filled.get("energy", {}))
# Apply default for sell_fee (default=0.0248) if absent.
if "sell_fee" not in energy and profile.energy.sell_fee.default is not None:
energy["sell_fee"] = profile.energy.sell_fee.default
# Apply default for sell_adjust (default=0) if absent.
if "sell_adjust" not in energy and profile.energy.sell_adjust.default is not None:
energy["sell_adjust"] = profile.energy.sell_adjust.default
filled["energy"] = energy
standing = dict(filled.get("standing", {}))
# Apply default for management_fee if absent.
if (
"management_fee" not in standing
and profile.standing.management_fee.default is not None
):
standing["management_fee"] = profile.standing.management_fee.default
filled["standing"] = standing
return filled
def _require_numeric(section: str, key: str, container: dict[str, Any]) -> None:
"""Assert that *container[key]* exists and is a number; raise ProfileValidationError."""
if key not in container:
raise ProfileValidationError(
f"Contract values missing required field '{section}.{key}'"
)
val = container[key]
if not isinstance(val, (int, float)):
raise ProfileValidationError(
f"Contract values field '{section}.{key}' must be a number, "
f"got {type(val).__name__!r}"
)
def _validate_manual_values(values: dict[str, Any], profile: ManualProfile) -> dict[str, Any]:
"""Validate and fill-defaults for manual contract values.
Returns the filled values dict on success. Raises ProfileValidationError
on missing required fields or wrong types.
"""
filled = _fill_defaults_manual(values, profile)
energy = filled.get("energy", {})
buy = energy.get("buy", {})
sell = energy.get("sell", {})
standing = filled.get("standing", {})
credits = filled.get("credits", {})
# Required energy.buy fields.
_require_numeric("energy.buy", "normal", buy)
_require_numeric("energy.buy", "dal", buy)
# Required energy.sell fields.
_require_numeric("energy.sell", "normal", sell)
_require_numeric("energy.sell", "dal", sell)
# Required energy fields.
_require_numeric("energy", "energy_tax", energy)
_require_numeric("energy", "ode", energy)
# Required standing fields.
_require_numeric("standing", "network_fee", standing)
_require_numeric("standing", "management_fee", standing)
# Required credits fields.
_require_numeric("credits", "heffingskorting", credits)
return filled
def _validate_tibber_values(values: dict[str, Any], profile: TibberProfile) -> dict[str, Any]:
"""Validate and fill-defaults for tibber contract values.
Returns the filled values dict on success. Raises ProfileValidationError
on missing required fields or wrong types.
"""
filled = _fill_defaults_tibber(values, profile)
energy = filled.get("energy", {})
standing = filled.get("standing", {})
credits = filled.get("credits", {})
# Required energy fields.
_require_numeric("energy", "energy_tax", energy)
_require_numeric("energy", "sell_fee", energy)
_require_numeric("energy", "sell_adjust", energy)
# Required standing fields.
_require_numeric("standing", "management_fee", standing)
_require_numeric("standing", "network_fee", standing)
# Required credits fields.
_require_numeric("credits", "heffingskorting", credits)
return filled
def _reject_yaml_floats(value: Any, path: Path) -> None:
"""Reject implicit YAML floats for district-heating profile metadata."""
if isinstance(value, float):
raise ProfileValidationError(
f"Profile '{path.stem}' must not contain YAML float values; use integer 0 or strings."
)
if isinstance(value, dict):
for child in value.values():
_reject_yaml_floats(child, path)
elif isinstance(value, list):
for child in value:
_reject_yaml_floats(child, path)
def _decimal_value(section: str, key: str, value: Any) -> str:
"""Validate and normalise one thermal amount without passing through float."""
if isinstance(value, bool) or isinstance(value, float) or not isinstance(value, (str, int, Decimal)):
raise ProfileValidationError(
f"Contract values field '{section}.{key}' must be a Decimal-compatible string or integer, "
f"got {type(value).__name__!r}"
)
try:
amount = Decimal(str(value))
except (InvalidOperation, ValueError) as exc:
raise ProfileValidationError(
f"Contract values field '{section}.{key}' must be a Decimal-compatible value"
) from exc
if not amount.is_finite() or amount < 0:
raise ProfileValidationError(
f"Contract values field '{section}.{key}' must be a non-negative finite Decimal"
)
return format(amount, "f")
def _validate_district_heating_values(
values: dict[str, Any], profile: DistrictHeatingProfile
) -> dict[str, Any]:
"""Validate thermal values and return a complete JSON-safe Decimal snapshot."""
if not isinstance(values, dict):
raise ProfileValidationError("District-heating contract values must be a mapping")
expected_sections = {"variable", "standing"}
unknown_sections = set(values) - expected_sections
if unknown_sections:
raise ProfileValidationError(
f"District-heating contract values contain unknown section(s): {sorted(unknown_sections)}"
)
def normalise_section(
section: str, specs: Any, *, defaults_allowed: bool
) -> dict[str, str]:
supplied = values.get(section, {})
if not isinstance(supplied, dict):
raise ProfileValidationError(f"Contract values section '{section}' must be a mapping")
expected = set(type(specs).model_fields)
unknown = set(supplied) - expected
if unknown:
raise ProfileValidationError(
f"Contract values section '{section}' contains unknown field(s): {sorted(unknown)}"
)
normalised: dict[str, str] = {}
for key in type(specs).model_fields:
if key not in supplied:
field = getattr(specs, key)
if not defaults_allowed or field.default is None:
raise ProfileValidationError(f"Contract values missing required field '{section}.{key}'")
normalised[key] = format(field.default, "f")
else:
normalised[key] = _decimal_value(section, key, supplied[key])
return normalised
return {
"variable": normalise_section("variable", profile.variable, defaults_allowed=False),
"standing": normalise_section("standing", profile.standing, defaults_allowed=True),
}
def validate_values(kind: str, values: dict[str, Any]) -> dict[str, Any]:
"""Validate a contract-values dict against the named profile structure.
Fields that carry a ``default`` in the profile (e.g. ``ode``,
``sell_fee``, ``sell_adjust``, tibber ``management_fee``) are silently
filled in when absent from *values*. Fields with no default that are
absent, or fields whose value is not a number, cause a
``ProfileValidationError``.
Parameters
----------
kind:
Profile kind (``"manual"`` or ``"tibber"``).
values:
Contract values dict as stored in ``EnergyContractVersion.values``.
Returns
-------
dict[str, Any]
A (possibly mutated) copy of *values* with defaults applied.
Raises
------
ProfileNotFoundError
If the profile YAML for *kind* does not exist.
ProfileValidationError
If required fields are missing or have wrong types.
"""
profile = load_profile(kind)
if isinstance(profile, ManualProfile):
return _validate_manual_values(values, profile)
if isinstance(profile, TibberProfile):
return _validate_tibber_values(values, profile)
if isinstance(profile, DistrictHeatingProfile):
return _validate_district_heating_values(values, profile)
# Unreachable with current kinds, but guard for future extensions.
raise ProfileValidationError(f"No validator implemented for kind={kind!r}")
@@ -0,0 +1,56 @@
kind: district_heating
label: 区域供热
variable:
heating:
unit: EUR/GJ
label: 供暖热量
help: 按供暖用热量计收;请录入合同中的实际金额。
minimum: 0
hot_water_heating:
unit: EUR/m³
label: 热水加热
help: 按热水体积计收的加热部分;请录入合同中的实际金额。
minimum: 0
hot_water:
unit: EUR/m³
label: 热水用量
help: 按热水体积计收的用量部分;请录入合同中的实际金额。
minimum: 0
hot_water_tax:
unit: EUR/m³
label: 热水税费
help: 按热水体积计收的税费部分;请录入合同中的实际金额。
minimum: 0
standing:
heating_network:
unit: EUR/year
label: 供暖网络费
help: 年度固定费用;默认零,按合同实际金额录入。
minimum: 0
default: 0
metering:
unit: EUR/year
label: 计量费
help: 年度固定费用;默认零,按合同实际金额录入。
minimum: 0
default: 0
delivery_set:
unit: EUR/year
label: 交付装置费
help: 年度固定费用;默认零,按合同实际金额录入。
minimum: 0
default: 0
hot_water_network:
unit: EUR/year
label: 热水网络费
help: 年度固定费用;默认零,按合同实际金额录入。
minimum: 0
default: 0
other:
unit: EUR/year
label: 其他固定费
help: 年度固定费用;默认零,按合同实际金额录入。
minimum: 0
default: 0
@@ -0,0 +1,20 @@
kind: manual
label: 固定 / 可变费率(NL,双费率)
energy:
dual_tariff: true # use delivered_1/2, returned_1/2 for low/high tariffs
buy:
normal: { unit: EUR/kWh } # high-tariff buy price (delivered_2 register)
dal: { unit: EUR/kWh } # low-tariff buy price (delivered_1 register)
sell:
normal: { unit: EUR/kWh } # high-tariff sell / return price
dal: { unit: EUR/kWh } # low-tariff sell / return price (currently equal to normal)
energy_tax: { unit: EUR/kWh } # energy tax added to buy price (incl. VAT)
ode: { unit: EUR/kWh, default: 0 } # currently merged into energy_tax
standing: # fixed charges; UI fills per month, engine prorates to days
network_fee: { unit: EUR/month }
management_fee: { unit: EUR/month }
credits:
heffingskorting: { unit: EUR/year } # energy-tax credit; deducted at summary layer
@@ -0,0 +1,15 @@
kind: tibber
label: Tibber 动态电价(15 分钟)
energy:
source: tibber_api # buy = total (from API); sell = total energy_tax sell_fee sell_adjust
energy_tax: { unit: EUR/kWh } # subtracted from total to derive sell price (incl. VAT)
sell_fee: { unit: EUR/kWh, default: 0.0248 } # verkoopvergoeding (feed-in fee, incl. VAT); always subtracted from sell
sell_adjust: { unit: EUR/kWh, default: 0 } # manual sell-price adjustment; net-metering: set = energy_tax to refund the tax
standing: # fixed charges; UI fills per month, engine prorates to days
management_fee: { unit: EUR/month, default: 5.99 }
network_fee: { unit: EUR/month }
credits:
heffingskorting: { unit: EUR/year } # energy-tax credit; deducted at summary layer
+301
View File
@@ -0,0 +1,301 @@
"""Price-calculation strategy registry and built-in implementations.
A *strategy* is a plain function registered under a ``kind`` string. Given
per-register kWh deltas, the period start time, the active contract-version
values, and a DB session, it returns a result dict with:
{
"import_cost": Decimal, # total cost of electricity drawn from grid
"export_revenue": Decimal, # total revenue from electricity fed to grid
"net_cost": Decimal, # import_cost export_revenue
"pricing": dict, # snapshot of the price inputs used (for auditing)
}
**Import and export are kept separate throughout** net_cost is only derived
at the end. This supports the Dutch no-netting rule (saldering afgebouwd).
**All monetary arithmetic uses Decimal** converted via ``Decimal(str(x))`` to
avoid float binary rounding errors.
Design notes
------------
- **Purely data + functions**: no ABC, no class hierarchy. A ``dict``-based
registry is the simplest structure that supports the two current kinds and
leaves the door open for future additions (e.g. ``octopus``, ``frank``).
- ``deltas`` is a plain dataclass ``PeriodDeltas`` typed, but no ORM.
- Tibber strategy queries ``TibberPrice`` directly from the session; it does not
call the Tibber API (that is T05's job).
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from typing import Any, Callable
from sqlalchemy.orm import Session
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Shared data types
# ---------------------------------------------------------------------------
@dataclass
class PeriodDeltas:
"""Per-register kWh deltas for one 15-minute billing period.
All values are ``Decimal`` and represent ``end_reading start_reading``
for the corresponding cumulative energy register.
Attributes
----------
d1: Decimal
Delivered (consumed) kWh on the low/dal tariff register (delivered_1).
d2: Decimal
Delivered (consumed) kWh on the normal/high tariff register (delivered_2).
r1: Decimal
Returned (fed-to-grid) kWh on the low/dal tariff register (returned_1).
r2: Decimal
Returned (fed-to-grid) kWh on the normal/high tariff register (returned_2).
"""
d1: Decimal # delivered low-tariff
d2: Decimal # delivered high-tariff
r1: Decimal # returned low-tariff
r2: Decimal # returned high-tariff
# Strategy callable signature.
StrategyFn = Callable[
[PeriodDeltas, datetime, dict[str, Any], Session],
dict[str, Any],
]
# ---------------------------------------------------------------------------
# Registry
# ---------------------------------------------------------------------------
_REGISTRY: dict[str, StrategyFn] = {}
def register_strategy(kind: str, fn: StrategyFn) -> None:
"""Register *fn* as the price-calculation strategy for *kind*.
Overwrites any previously registered strategy for the same kind (allows
monkey-patching in tests).
"""
_REGISTRY[kind] = fn
def get_strategy(kind: str) -> StrategyFn:
"""Return the registered strategy for *kind*.
Raises
------
KeyError
If no strategy is registered for *kind*.
"""
if kind not in _REGISTRY:
raise KeyError(
f"No price strategy registered for kind={kind!r}. "
f"Available: {sorted(_REGISTRY)}"
)
return _REGISTRY[kind]
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _to_decimal(value: Any) -> Decimal:
"""Convert *value* to Decimal via str() to avoid float binary rounding."""
return Decimal(str(value))
# ---------------------------------------------------------------------------
# Manual strategy — fixed dual-tariff
# ---------------------------------------------------------------------------
def _manual_strategy(
deltas: PeriodDeltas,
t0: datetime,
values: dict[str, Any],
session: Session,
) -> dict[str, Any]:
"""Calculate billing costs for one period using fixed dual-tariff rates.
Formula (§3.4):
- ``buy_dal = energy.buy.dal + energy.energy_tax + energy.ode``
- ``buy_normal = energy.buy.normal + energy.energy_tax + energy.ode``
- ``import_cost = Δd1 × buy_dal + Δd2 × buy_normal``
- ``sell_dal = energy.sell.dal`` (no tax on return price)
- ``sell_normal = energy.sell.normal``
- ``export_revenue = Δr1 × sell_dal + Δr2 × sell_normal``
- ``net_cost = import_cost export_revenue``
The ``pricing`` snapshot contains all per-unit prices used so that the
result is fully auditable without re-querying the contract version.
"""
energy = values.get("energy", {})
buy = energy.get("buy", {})
sell = energy.get("sell", {})
energy_tax = _to_decimal(energy.get("energy_tax", 0))
ode = _to_decimal(energy.get("ode", 0))
buy_dal_base = _to_decimal(buy.get("dal", 0))
buy_normal_base = _to_decimal(buy.get("normal", 0))
sell_dal = _to_decimal(sell.get("dal", 0))
sell_normal = _to_decimal(sell.get("normal", 0))
# Effective buy prices including all taxes.
buy_dal = buy_dal_base + energy_tax + ode
buy_normal = buy_normal_base + energy_tax + ode
import_cost = deltas.d1 * buy_dal + deltas.d2 * buy_normal
export_revenue = deltas.r1 * sell_dal + deltas.r2 * sell_normal
net_cost = import_cost - export_revenue
pricing_snapshot = {
"kind": "manual",
"buy_dal": str(buy_dal),
"buy_normal": str(buy_normal),
"sell_dal": str(sell_dal),
"sell_normal": str(sell_normal),
"energy_tax": str(energy_tax),
"ode": str(ode),
}
return {
"import_cost": import_cost,
"export_revenue": export_revenue,
"net_cost": net_cost,
"pricing": pricing_snapshot,
}
# ---------------------------------------------------------------------------
# Tibber strategy — dynamic 15-minute spot price
# ---------------------------------------------------------------------------
class TibberPriceNotFoundError(LookupError):
"""Raised when no TibberPrice row covers the requested period start.
The billing engine (T07) catches this to mark the period as ``degraded``
or skip it until a price becomes available.
"""
def _tibber_strategy(
deltas: PeriodDeltas,
t0: datetime,
values: dict[str, Any],
session: Session,
) -> dict[str, Any]:
"""Calculate billing costs for one period using Tibber dynamic pricing.
Price lookup:
Takes the most recent ``TibberPrice`` row where ``starts_at t0``
(i.e. the slot that was in effect at *t0*). This is a DESC LIMIT 1
query on ``starts_at``.
Formula (§3.4):
- ``buy = total`` (Tibber's all-inclusive price; already includes energy
tax, VAT and the buy-side ``inkoopvergoeding``)
- ``sell = total energy_tax sell_fee sell_adjust``
- ``import_cost = (Δd1 + Δd2) × buy``
- ``export_revenue = (Δr1 + Δr2) × sell``
- ``net_cost = import_cost export_revenue``
``sell_fee`` models Tibber's per-kWh **verkoopvergoeding** (feed-in fee,
0.0248/kWh incl. VAT since 2026-01-01). It is always deducted from the
feed-in payout: even under the net-metering (saldering) scheme, Tibber pays
``total verkoopvergoeding`` per returned kWh (Tibber NL: "€0,28 €0,0248
= 0,2552"). ``total`` already contains the equal buy-side
``inkoopvergoeding``, so the two fees do **not** cancel the feed-in price
sits ``sell_fee`` below the buy price. ``sell_adjust`` is a separate manual
correction: under net metering it carries back the refunded energy tax
(``sell_adjust = energy_tax``), leaving ``sell = total sell_fee``.
Tibber does not differentiate tariff slots (dal vs normal) the 15-minute
API price applies to the full delivered/returned volume.
Negative ``total`` (extreme negative spot prices):
When ``total`` is negative the ``sell`` price will also be negative,
meaning ``export_revenue`` becomes negative (feeding to grid *costs*
money). This is the mathematically correct outcome and is left as-is.
Raises
------
TibberPriceNotFoundError
If no ``TibberPrice`` row exists with ``starts_at t0``. The caller
(T07 billing engine) should catch this and mark the period as
``degraded`` or skip it for later recomputation.
"""
from app.models.energy import TibberPrice # local import to avoid circular
from sqlalchemy import desc
price_row: TibberPrice | None = (
session.query(TibberPrice)
.filter(TibberPrice.starts_at <= t0)
.order_by(desc(TibberPrice.starts_at))
.first()
)
if price_row is None:
raise TibberPriceNotFoundError(
f"No TibberPrice found covering t0={t0.isoformat()!r}; "
"period cannot be billed until price data is available."
)
energy = values.get("energy", {})
energy_tax = _to_decimal(energy.get("energy_tax", 0))
sell_fee = _to_decimal(energy.get("sell_fee", 0))
sell_adjust = _to_decimal(energy.get("sell_adjust", 0))
total = _to_decimal(price_row.total)
buy = total
sell = total - energy_tax - sell_fee - sell_adjust
total_delivered = deltas.d1 + deltas.d2
total_returned = deltas.r1 + deltas.r2
import_cost = total_delivered * buy
export_revenue = total_returned * sell
net_cost = import_cost - export_revenue
pricing_snapshot = {
"kind": "tibber",
"tibber_price_starts_at": price_row.starts_at.isoformat(),
"tibber_price_id": price_row.id,
"total": str(total),
"buy": str(buy),
"sell": str(sell),
"energy_tax": str(energy_tax),
"sell_fee": str(sell_fee),
"sell_adjust": str(sell_adjust),
}
return {
"import_cost": import_cost,
"export_revenue": export_revenue,
"net_cost": net_cost,
"pricing": pricing_snapshot,
}
# ---------------------------------------------------------------------------
# Register built-in strategies at module import time
# ---------------------------------------------------------------------------
register_strategy("manual", _manual_strategy)
register_strategy("tibber", _tibber_strategy)
+10
View File
@@ -0,0 +1,10 @@
"""Tibber dynamic electricity pricing integration.
This package provides:
- ``client``: HTTP client for the Tibber GraphQL API (price fetching).
- Custom exceptions: ``TibberError`` (base) and ``TibberAuthError`` (auth failure).
Usage::
from app.integrations.tibber.client import fetch_price_range, TibberAuthError
"""
+357
View File
@@ -0,0 +1,357 @@
"""Tibber GraphQL API client for fetching electricity price data.
Design decisions
----------------
- Uses ``httpx`` (already a project dependency) for all HTTP requests.
- Token is **never** written to log messages or exception strings to prevent
credential leakage into log aggregators.
- ``fetch_price_range`` returns a list of ``PricePoint`` objects with UTC-aware
``starts_at`` datetimes; the number of nodes is not assumed all returned
nodes are parsed regardless of count.
- ``fetch_current_price`` uses a separate, simpler query that asks for the
*current* price point only; used by the connection-test endpoint (T09) to
produce a fast three-state result (success / auth-error / network-error).
- Authentication failures (HTTP 401/403) are raised as ``TibberAuthError`` so
that callers (the test endpoint) can distinguish them from generic network or
API errors.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any
import httpx
logger = logging.getLogger(__name__)
_TIBBER_API_URL = "https://api.tibber.com/v1-beta/gql"
_DEFAULT_TIMEOUT = 15.0
# GraphQL query to fetch the forward-looking today + tomorrow price curve at
# 15-minute resolution.
#
# ``priceInfo(resolution: QUARTER_HOURLY)`` returns two node lists:
# * ``today`` — always the full current local day (96 quarter-hourly slots,
# 00:00 → 23:45 local), regardless of the current time.
# * ``tomorrow`` — the full next local day (96 slots) once Tibber publishes the
# day-ahead prices (around 13:0015:00 local); empty before that.
#
# This is deliberately NOT ``priceInfoRange``: that field is a historical cursor
# connection whose range ends at "now" (it never returns future slots), so it
# cannot supply upcoming prices. ``priceInfo`` is forward-looking, so every
# 15-minute slot's price is present in the DB *before* the slot closes — which is
# what makes per-slot billing accurate (each period finds its own exact slot
# instead of falling back to a stale earlier price) and keeps the live current-
# price entity fresh. The hourly refresh job re-runs this query, so tomorrow's
# prices are picked up within an hour of publication without a restart.
_PRICE_RANGE_QUERY = """
{
viewer {
homes {
id
currentSubscription {
priceInfo(resolution: QUARTER_HOURLY) {
today {
startsAt
total
energy
tax
currency
level
}
tomorrow {
startsAt
total
energy
tax
currency
level
}
}
}
}
}
}
"""
# GraphQL query to fetch the single *current* price point.
_CURRENT_PRICE_QUERY = """
{
viewer {
homes {
id
currentSubscription {
priceInfo {
current {
startsAt
total
energy
tax
currency
level
}
}
}
}
}
}
"""
# ---------------------------------------------------------------------------
# Custom exceptions
# ---------------------------------------------------------------------------
class TibberError(Exception):
"""Base class for all Tibber client errors.
Raised for network failures, timeouts, unexpected HTTP status codes, and
malformed API responses. The exception message will **never** contain the
API token.
"""
class TibberAuthError(TibberError):
"""Raised when the Tibber API rejects the provided token (HTTP 401/403).
Callers that implement a three-state connection test should catch this
exception separately from ``TibberError`` to distinguish auth problems
from network / API problems.
"""
# ---------------------------------------------------------------------------
# Data model
# ---------------------------------------------------------------------------
@dataclass(slots=True)
class PricePoint:
"""One 15-minute price slot returned by the Tibber API.
All monetary values are in ``currency`` and include VAT (user-facing).
``starts_at`` is always a timezone-aware UTC datetime regardless of the
timezone offset that Tibber returns in ``startsAt``.
"""
starts_at: datetime # UTC-aware
total: float # full all-in price (energy + tax)
energy: float # spot energy component
tax: float # tax component
currency: str # ISO 4217 (typically "EUR")
level: str | None # e.g. "CHEAP", "NORMAL", "EXPENSIVE"; None if absent
resolution: str # label for the slot resolution (e.g. "QUARTER_HOURLY")
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
def _parse_starts_at(raw: str) -> datetime:
"""Parse an ISO 8601 timestamp with timezone offset and convert to UTC.
Tibber returns timestamps like ``2026-06-23T00:00:00.000+02:00``.
``datetime.fromisoformat`` handles this format in Python 3.11+; the result
is then converted to UTC via ``.astimezone(UTC)``.
"""
return datetime.fromisoformat(raw).astimezone(UTC)
def _parse_node(node: dict[str, Any], resolution: str) -> PricePoint:
"""Parse a single price node dict into a ``PricePoint``."""
return PricePoint(
starts_at=_parse_starts_at(node["startsAt"]),
total=float(node["total"]),
energy=float(node["energy"]),
tax=float(node["tax"]),
currency=str(node["currency"]),
level=node.get("level") or None,
resolution=resolution,
)
def _pick_home(homes: list[dict[str, Any]], home_id: str | None) -> dict[str, Any]:
"""Return the home dict matching *home_id*, or the first home if None."""
if not homes:
raise TibberError("Tibber API returned no homes")
if home_id is not None:
for h in homes:
if h.get("id") == home_id:
return h
raise TibberError("Tibber home id not found in API response")
return homes[0]
def _post_graphql(token: str, query: str, timeout: float) -> dict[str, Any]:
"""POST the GraphQL *query* and return the parsed ``data`` dict.
Raises
------
TibberAuthError
On HTTP 401 or 403.
TibberError
On timeouts, network errors, non-2xx responses, or unexpected body shape.
"""
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
try:
response = httpx.post(
_TIBBER_API_URL,
json={"query": query},
headers=headers,
timeout=timeout,
)
except httpx.TimeoutException as exc:
raise TibberError("Tibber API request timed out") from exc
except httpx.HTTPError as exc:
raise TibberError("Tibber API request failed") from exc
if response.status_code in (401, 403):
raise TibberAuthError("Tibber API authentication failed")
try:
response.raise_for_status()
except httpx.HTTPStatusError as exc:
raise TibberError(f"Tibber API returned unexpected status {response.status_code}") from exc
try:
body = response.json()
except Exception as exc:
raise TibberError("Tibber API returned non-JSON response") from exc
if "errors" in body:
# GraphQL errors are not HTTP errors; surface them as TibberError.
# Do not include token in the message.
raise TibberError("Tibber GraphQL returned errors")
data = body.get("data")
if data is None:
raise TibberError("Tibber API response missing 'data' field")
return data
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def fetch_price_range(
token: str,
home_id: str | None = None,
*,
timeout: float = _DEFAULT_TIMEOUT,
) -> list[PricePoint]:
"""Fetch the forward-looking today + tomorrow 15-minute price curve from Tibber.
Sends the ``priceInfo(resolution: QUARTER_HOURLY) { today tomorrow }`` query
and parses every node from both lists (today first, then tomorrow) into a
``PricePoint``. ``priceInfo`` is forward-looking ``today`` is always the
full current local day and ``tomorrow`` is populated once Tibber publishes the
day-ahead prices so upcoming slots are returned, unlike ``priceInfoRange``
which only reaches "now". ``tomorrow`` may be empty (before publication); the
number of nodes is not assumed and all returned nodes are parsed.
Parameters
----------
token:
Tibber API token. **Never** logged or included in exception messages.
home_id:
If given, the home with this Tibber home ID is selected. If ``None``,
the first home in the account is used.
timeout:
HTTP request timeout in seconds (default 15 s).
Returns
-------
list[PricePoint]
List of price points with UTC-aware ``starts_at`` values.
Raises
------
TibberAuthError
If the token is rejected (HTTP 401/403).
TibberError
For network failures, timeouts, or unexpected API responses.
"""
data = _post_graphql(token, _PRICE_RANGE_QUERY, timeout)
try:
homes = data["viewer"]["homes"]
except (KeyError, TypeError) as exc:
raise TibberError("Tibber API response has unexpected shape") from exc
home = _pick_home(homes, home_id)
try:
price_info = home["currentSubscription"]["priceInfo"]
today = price_info["today"]
tomorrow = price_info["tomorrow"]
except (KeyError, TypeError) as exc:
raise TibberError("Tibber API response missing priceInfo today/tomorrow") from exc
# tomorrow is null/empty until Tibber publishes the day-ahead prices; treat
# a missing list as empty so we still return today's slots.
nodes = list(today or []) + list(tomorrow or [])
return [_parse_node(node, "QUARTER_HOURLY") for node in nodes]
def fetch_current_price(
token: str,
home_id: str | None = None,
*,
timeout: float = _DEFAULT_TIMEOUT,
) -> PricePoint:
"""Fetch the *current* price point from the Tibber API.
Uses the lighter ``priceInfo { current { ... } }`` query rather than the
full range query, making it suitable for a fast connection test.
Parameters
----------
token:
Tibber API token. **Never** logged or included in exception messages.
home_id:
If given, the home with this Tibber home ID is selected. If ``None``,
the first home in the account is used.
timeout:
HTTP request timeout in seconds (default 15 s).
Returns
-------
PricePoint
The current price point with a UTC-aware ``starts_at``.
Raises
------
TibberAuthError
If the token is rejected (HTTP 401/403).
TibberError
For network failures, timeouts, missing current price, or unexpected
API responses.
"""
data = _post_graphql(token, _CURRENT_PRICE_QUERY, timeout)
try:
homes = data["viewer"]["homes"]
except (KeyError, TypeError) as exc:
raise TibberError("Tibber API response has unexpected shape") from exc
home = _pick_home(homes, home_id)
try:
current = home["currentSubscription"]["priceInfo"]["current"]
except (KeyError, TypeError) as exc:
raise TibberError("Tibber API response missing current price") from exc
if current is None:
raise TibberError("Tibber API returned null for current price")
return _parse_node(current, "QUARTER_HOURLY")
+326 -38
View File
@@ -1,34 +1,209 @@
import logging
import os
from contextlib import asynccontextmanager
from datetime import UTC, datetime
from pathlib import Path
from typing import Callable
from fastapi import FastAPI
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.interval import IntervalTrigger
from sqlalchemy.orm import Session
from app import models # noqa: F401
from app.api.routes.auth import router as auth_router
from app.api.routes import pages, status
import app.auth_db as auth_db
from app.api.routes.api.config import router as api_config_router
from app.api.routes.api.data import router as api_data_router
from app.api.routes.api.energy import router as api_energy_router
from app.api.routes.api.energy_contracts import router as api_energy_contracts_router
from app.api.routes.api.meter_costs import router as api_meter_costs_router
from app.api.routes.api.expose import router as api_expose_router
from app.api.routes.api.meters import router as api_meters_router
from app.api.routes.api.meter_sources import router as api_meter_sources_router
from app.api.routes.api.modbus import router as api_modbus_router
from app.api.routes.api.session import router as api_session_router
from app.api.routes import status
from app.db import get_session_local
from app.api.routes.homeassistant import router as homeassistant_router
from app.api.routes.location import router as location_router
from app.api.routes.poo import router as poo_router
from app.api.routes.public_ip import router as public_ip_router
from app.api.routes.ticktick import router as ticktick_router
from app.config import get_settings
from app.integrations.mqtt import mqtt_manager
from app.services.auth import AuthBootstrapError, initialize_auth_schema
from app.services.config_page import seed_missing_config_from_bootstrap, sync_app_hostname_from_bootstrap
from app.services.config_page import build_runtime_settings, seed_missing_config_from_bootstrap, sync_app_hostname_from_bootstrap
from app.services.dsmr_ingest import apply_dsmr_subscription
from app.services.public_ip import check_public_ipv4_and_notify
from app.services.modbus_poll import poll_all_enabled_devices, BASE_POLL_TICK_SECONDS
from app.services.ha_discovery import initialize_legacy_thermal_cleanup, publish_discovery, publish_states
from app.services.tibber_prices import run_tibber_refresh_best_effort
from app.services.energy_cost import compute_closed_periods
from app.services.meter_cost import compute_closed_periods as compute_closed_meter_cost_periods
from app.services.warmtelink_worker import warmtelink_worker_manager
from app.services.timezone import local_tz
from scripts.app_db_adopt import AppDatabaseAdoptionError, validate_app_runtime_db
from scripts.location_db_adopt import LocationDatabaseAdoptionError, validate_location_runtime_db
from scripts.poo_db_adopt import PooDatabaseAdoptionError, validate_poo_runtime_db
logger = logging.getLogger(__name__)
_REPO_ROOT = Path(__file__).resolve().parents[1]
def _get_spa_dist_dir() -> Path:
env_val = os.environ.get("SPA_DIST_DIR")
if env_val:
return Path(env_val)
return _REPO_ROOT / "frontend" / "dist"
def _run_scheduled_public_ip_check() -> None:
session_local = get_session_local()
session: Session = session_local()
try:
check_public_ipv4_and_notify(session, bootstrap_settings=get_settings())
finally:
session.close()
def _run_scheduled_modbus_poll() -> None:
session_local = get_session_local()
session: Session = session_local()
try:
poll_all_enabled_devices(session, bootstrap_settings=get_settings())
finally:
session.close()
def _run_scheduled_tibber_refresh() -> None:
"""Scheduled job: fetch Tibber 15-minute prices and upsert into tibber_price.
Runs every hour so that:
- Today's prices are available from startup.
- Tomorrow's prices (published by Tibber around 13:00 CET / 11:00 UTC) are
picked up within an hour of publication without requiring a server restart.
The job is a no-op when:
- No active energy contract with kind="tibber" exists.
- The Tibber API token is empty in the runtime settings.
Any client exceptions (auth failures, network errors) are caught and logged
so that a single failed fetch does not crash the scheduler or affect the
other background jobs.
"""
run_tibber_refresh_best_effort()
def _run_scheduled_energy_cost() -> None:
"""Scheduled job: compute billing records for all uncalculated closed 15-minute periods.
Runs every minute so that a new period is picked up within 1 minute of
closing. The job is a no-op when:
- No active energy contract with a version covering the period exists.
- DSMR data has not yet arrived for the period boundaries.
- The period's billing record already exists and is not degraded.
Any unexpected exceptions are caught and logged so that a single failure
does not crash the scheduler or affect the other background jobs.
"""
session_local = get_session_local()
def run_scope(label: str, operation: Callable[[Session], None]) -> None:
"""Run one best-effort scope in an isolated transaction/session."""
session: Session | None = None
try:
session = session_local()
operation(session)
except Exception:
logger.exception("_run_scheduled_energy_cost: %s failed", label)
if session is not None:
try:
session.rollback()
except Exception:
# A failed cleanup must not replace the operation/factory
# error or prevent the following independent scope.
logger.exception("_run_scheduled_energy_cost: %s rollback failed", label)
finally:
if session is not None:
try:
session.close()
except Exception:
# Sessions are intentionally isolated; close failures are
# diagnostic only and must remain best-effort too.
logger.exception("_run_scheduled_energy_cost: %s close failed", label)
# Electricity, thermal and HA publishing must not share failed transaction
# state or accidentally commit each other's partially-flushed changes.
run_scope("electricity computation", compute_closed_periods)
run_scope("thermal computation", compute_closed_meter_cost_periods)
def publish(session: Session) -> None:
# publish_states is internally guarded by _should_publish (MQTT
# disabled / disconnected -> no-op), but gets a clean Session anyway.
from app.services.ha_discovery import publish_states
publish_states(session)
run_scope("publish_states (non-fatal)", publish)
def _run_scheduled_ha_state_publish() -> None:
"""Periodic job: publish discovery configs + state + availability for all enabled exposed entities.
Runs every 60 seconds. When the MQTT broker is connected:
- Publishes (or re-publishes) all HA Discovery configs (retained, idempotent).
- Publishes the current state / availability for all enabled entities.
This also serves as the reliable "publish discovery after connect" mechanism:
because paho connects asynchronously, a synchronous call immediately after
``mqtt_manager.connect()`` would fire before the TCP handshake completes and
be a no-op. Instead, this periodic job picks it up within 60 seconds of the
broker becoming available retained payloads make repeated publishes harmless.
Additionally, if MQTT is configured in DB but the manager is not yet connected
(e.g. MQTT was enabled via UI after startup), this job attempts to connect so
the user does not need to restart the server.
"""
session_local = get_session_local()
session: Session = session_local()
try:
runtime_settings = build_runtime_settings(session, get_settings())
# Reconnect if MQTT is configured (in DB) but not yet connected.
if mqtt_manager.is_configured(runtime_settings) and not mqtt_manager.is_connected:
logger.info("_run_scheduled_ha_state_publish: MQTT configured but not connected — attempting connect.")
mqtt_manager.connect(runtime_settings)
publish_discovery(session)
publish_states(session)
except Exception:
logger.exception("_run_scheduled_ha_state_publish: unexpected error")
finally:
session.close()
def _run_midnight_state_publish() -> None:
"""本地午夜后不久专门发布一次状态,让 *_today 的每日归零稳稳落在午夜之后
HA 钟慢几秒鲁棒best-effort失败仅记日志不影响调度器"""
session_local = get_session_local()
session = session_local()
try:
from app.services.ha_discovery import publish_states
publish_states(session)
except Exception:
logger.exception("_run_midnight_state_publish: failed (non-fatal)")
finally:
session.close()
def ensure_auth_db_ready() -> None:
session_local = auth_db.get_auth_session_local()
session_local = get_session_local()
session: Session = session_local()
try:
validate_app_runtime_db(get_settings().app_database_url)
initialize_auth_schema(session, get_settings())
seed_missing_config_from_bootstrap(session, get_settings())
sync_app_hostname_from_bootstrap(session, get_settings())
initialize_legacy_thermal_cleanup(session)
except AppDatabaseAdoptionError as exc:
raise RuntimeError(str(exc)) from exc
except AuthBootstrapError as exc:
@@ -37,42 +212,113 @@ def ensure_auth_db_ready() -> None:
session.close()
def ensure_location_db_ready() -> None:
settings = get_settings()
if settings.location_sqlite_path is None:
return
try:
validate_location_runtime_db(settings.location_database_url)
except LocationDatabaseAdoptionError as exc:
raise RuntimeError(str(exc)) from exc
def ensure_poo_db_ready() -> None:
settings = get_settings()
if settings.poo_sqlite_path is None:
return
try:
validate_poo_runtime_db(settings.poo_database_url)
except PooDatabaseAdoptionError as exc:
raise RuntimeError(str(exc)) from exc
def ensure_runtime_dirs() -> None:
settings = get_settings()
for path in (settings.app_sqlite_path, settings.location_sqlite_path, settings.poo_sqlite_path):
if path is not None:
path.parent.mkdir(parents=True, exist_ok=True)
if settings.app_sqlite_path is not None:
settings.app_sqlite_path.parent.mkdir(parents=True, exist_ok=True)
@asynccontextmanager
async def lifespan(_: FastAPI):
ensure_runtime_dirs()
ensure_auth_db_ready()
ensure_location_db_ready()
ensure_poo_db_ready()
yield
scheduler = BackgroundScheduler(timezone="UTC")
scheduler.add_job(
_run_scheduled_public_ip_check,
trigger=IntervalTrigger(hours=4),
id="public-ip-check",
replace_existing=True,
max_instances=1,
coalesce=True,
)
scheduler.add_job(
_run_scheduled_modbus_poll,
trigger=IntervalTrigger(seconds=BASE_POLL_TICK_SECONDS),
id="modbus-poll",
replace_existing=True,
max_instances=1,
coalesce=True,
)
# Periodic HA state / availability publish (60-second fallback sweep).
scheduler.add_job(
_run_scheduled_ha_state_publish,
trigger=IntervalTrigger(seconds=60),
id="ha-state-publish",
replace_existing=True,
max_instances=1,
coalesce=True,
)
# Tibber price refresh: fetch today + tomorrow every hour.
# The job is a no-op when no active tibber contract or token is configured,
# so it is safe to register unconditionally.
scheduler.add_job(
_run_scheduled_tibber_refresh,
trigger=IntervalTrigger(hours=1),
id="tibber-refresh",
replace_existing=True,
max_instances=1,
coalesce=True,
# APScheduler otherwise waits one full interval before its first run.
# This preserves the hourly cadence while requesting a non-blocking
# startup fetch as soon as the scheduler starts.
next_run_time=datetime.now(UTC),
)
# Energy cost billing: compute uncalculated closed 15-minute periods every minute.
# The job is a no-op when no active contract or DSMR data is present, so it is
# safe to register unconditionally.
scheduler.add_job(
_run_scheduled_energy_cost,
trigger=IntervalTrigger(minutes=1),
id="energy-cost",
replace_existing=True,
max_instances=1,
coalesce=True,
)
# Dedicated midnight publish: fire at local 00:00:10 so *_today grace (5 s) has
# already elapsed and the day-rolled value is pushed to HA immediately, rather
# than waiting for the next 60-second ha-state-publish sweep.
scheduler.add_job(
_run_midnight_state_publish,
trigger=CronTrigger(hour=0, minute=0, second=10, timezone=local_tz()),
id="midnight-today-publish",
replace_existing=True,
max_instances=1,
coalesce=True,
)
scheduler.start()
# MQTT: connect using DB-merged runtime settings so broker configured via UI
# is picked up on restart (not just from env/bootstrap settings).
# Discovery will be published by the first run of _run_scheduled_ha_state_publish
# (within 60 s of startup), after the async paho handshake completes.
_startup_session_local = get_session_local()
_startup_session: Session = _startup_session_local()
try:
_startup_runtime_settings = build_runtime_settings(_startup_session, get_settings())
finally:
_startup_session.close()
serial_started = False
try:
mqtt_manager.connect(_startup_runtime_settings)
# DSMR sources carry their own runtime configuration and are reconciled
# after the MQTT manager is connected.
apply_dsmr_subscription(_startup_runtime_settings)
# Mark it before reconcile: a partial reconcile can already own a fd or
# a non-daemon thread and must receive the same orderly shutdown.
serial_started = True
warmtelink_worker_manager.start()
yield
finally:
# Serial descriptors/workers must be handled first on every exit path.
if serial_started:
try:
warmtelink_worker_manager.shutdown()
except Exception:
logger.exception("WarmteLink shutdown failed")
mqtt_manager.disconnect()
scheduler.shutdown(wait=False)
def create_app() -> FastAPI:
@@ -92,12 +338,54 @@ def create_app() -> FastAPI:
app.mount("/static", StaticFiles(directory=static_dir), name="static")
app.include_router(status.router)
app.include_router(auth_router)
app.include_router(pages.router)
app.include_router(api_config_router)
app.include_router(api_data_router)
app.include_router(api_energy_router)
app.include_router(api_energy_contracts_router)
app.include_router(api_meter_costs_router)
app.include_router(api_meters_router)
app.include_router(api_meter_sources_router)
app.include_router(api_expose_router)
app.include_router(api_modbus_router)
app.include_router(api_session_router)
app.include_router(homeassistant_router)
app.include_router(location_router)
app.include_router(poo_router)
app.include_router(public_ip_router)
app.include_router(ticktick_router)
# SPA hosting: mount frontend/dist if it exists and has index.html.
# If the SPA dist is absent (e.g. backend-only CI), skip SPA serving entirely
# so that pytest stays green with only the API routes registered.
spa_dist = _get_spa_dist_dir()
spa_index = spa_dist / "index.html"
if spa_dist.is_dir() and spa_index.is_file():
spa_assets = spa_dist / "assets"
if spa_assets.is_dir():
app.mount("/assets", StaticFiles(directory=spa_assets), name="spa-assets")
# Resolve the dist root once so the containment check is fast and consistent.
_spa_root = spa_dist.resolve()
@app.get("/{full_path:path}", include_in_schema=False)
async def spa_fallback(full_path: str, request: Request) -> FileResponse: # noqa: RUF029
# Explicit 404 for unmatched /api/* — never return index.html for API paths.
if full_path.startswith("api/"):
raise HTTPException(status_code=404, detail="not found")
# Resolve candidate to an absolute path and verify it stays within the SPA
# dist root. Without this check, URL-encoded ".." sequences (e.g. "..%2f")
# bypass Starlette's path parameter handling and allow arbitrary file reads.
candidate = (spa_dist / full_path).resolve()
if candidate.is_file() and candidate.is_relative_to(_spa_root):
return FileResponse(candidate)
# For any path outside the dist root, or for SPA client routes that don't
# correspond to a real file, return index.html so the SPA router handles it.
return FileResponse(spa_index)
else:
logger.warning(
"SPA dist not found at %s — SPA hosting disabled (API-only mode).", spa_dist
)
return app
+15 -1
View File
@@ -3,5 +3,19 @@
from app.models.auth import AuthSession, AuthUser
from app.models.config import AppConfigEntry
from app.models.location import Location
from app.models.poo import PooRecord
from app.models.public_ip import PublicIPHistory, PublicIPState
from app.models.meter_source import MeterSource, MeterSourceBinding, MeterSourceChannel
__all__ = ["AppConfigEntry", "AuthSession", "AuthUser", "Location"]
__all__ = [
"AppConfigEntry",
"AuthSession",
"AuthUser",
"Location",
"MeterSource",
"MeterSourceBinding",
"MeterSourceChannel",
"PooRecord",
"PublicIPHistory",
"PublicIPState",
]
+25 -3
View File
@@ -3,10 +3,10 @@ from datetime import datetime
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.auth_db import AuthBase
from app.db import Base
class AuthUser(AuthBase):
class AuthUser(Base):
__tablename__ = "auth_users"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
@@ -15,11 +15,15 @@ class AuthUser(AuthBase):
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
force_password_change: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
# TOTP fields (Phase B, M4-T04) — nullable/false by default so existing users are unaffected
totp_secret: Mapped[str | None] = mapped_column(String(64), nullable=True)
totp_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
sessions: Mapped[list["AuthSession"]] = relationship(back_populates="user")
recovery_codes: Mapped[list["RecoveryCode"]] = relationship(back_populates="user")
class AuthSession(AuthBase):
class AuthSession(Base):
__tablename__ = "auth_sessions"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
@@ -31,3 +35,21 @@ class AuthSession(AuthBase):
revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
user: Mapped[AuthUser] = relationship(back_populates="sessions")
class RecoveryCode(Base):
"""One-time TOTP recovery codes for AuthUser.
``code_hash`` stores the Argon2 hash of the plaintext code (plaintext is
returned only at setup time and never stored). ``used_at`` is NULL while
the code is still valid; set to the consumption timestamp when consumed.
"""
__tablename__ = "auth_recovery_code"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
user_id: Mapped[int] = mapped_column(ForeignKey("auth_users.id"), nullable=False, index=True)
code_hash: Mapped[str] = mapped_column(String(255), nullable=False)
used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
user: Mapped[AuthUser] = relationship(back_populates="recovery_codes")
+31
View File
@@ -0,0 +1,31 @@
from datetime import datetime
from sqlalchemy import DateTime, Index, Integer, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
class LoginThrottle(Base):
"""Tracks per-key login failure state for exponential back-off throttling.
``scope`` is either ``'ip'`` or ``'user'``; ``key`` is the IP address or
username string respectively. The pair ``(scope, key)`` is unique one
row per tracked entity. A row is deleted on successful login (clear).
"""
__tablename__ = "auth_login_throttle"
__table_args__ = (
UniqueConstraint("scope", "key", name="uq_auth_login_throttle_scope_key"),
Index("ix_auth_login_throttle_scope_key", "scope", "key"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
key: Mapped[str] = mapped_column(String(255), nullable=False)
scope: Mapped[str] = mapped_column(String(16), nullable=False) # 'ip' | 'user'
failures: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
first_failed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
last_failed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
next_allowed_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True
)
-4
View File
@@ -1,4 +0,0 @@
from app.db import Base
__all__ = ["Base"]
+2 -2
View File
@@ -3,10 +3,10 @@ from datetime import datetime
from sqlalchemy import DateTime, Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from app.auth_db import AuthBase
from app.db import Base
class AppConfigEntry(AuthBase):
class AppConfigEntry(Base):
__tablename__ = "app_config"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
+558
View File
@@ -0,0 +1,558 @@
"""SQLAlchemy models for the energy pricing and DSMR metering subsystem.
Six tables:
- meter: physical electricity meter lifecycle epoch.
- dsmr_reading: raw DSMR telegram blobs (10-second down-sampled).
- energy_contract: contract head (manual or tibber, one active at a time).
- energy_contract_version: versioned pricing values; append-only for auditability.
- tibber_price: cached Tibber 15-minute spot prices (immutable).
- energy_cost_period: computed 15-minute billing periods (immutable snapshot).
"""
from __future__ import annotations
import uuid as _uuid
from datetime import datetime, timezone
from decimal import Decimal
from typing import Any
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
Float,
ForeignKey,
Index,
Integer,
Numeric,
String,
UniqueConstraint,
event,
text,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship, synonym, validates
from sqlalchemy.types import JSON, TypeDecorator
from app.db import Base
from app.models.meter_source import MeterSourceBinding
def _uuid4_str() -> str:
return str(_uuid.uuid4())
def _decimal_json(value: Any) -> Any:
"""Make auditable JSON portable without admitting binary numeric values."""
if isinstance(value, Decimal):
return format(value, "f")
if isinstance(value, float) or (isinstance(value, int) and not isinstance(value, bool)):
raise ValueError("JSON amounts and quantities must be decimal strings, not numeric JSON values")
if isinstance(value, dict):
return {key: _decimal_json(child) for key, child in value.items()}
if isinstance(value, list):
return [_decimal_json(child) for child in value]
return value
def _validate_fixed_decimal(value: Decimal, precision: int, scale: int, field: str) -> Decimal:
if not isinstance(value, Decimal):
raise ValueError(f"{field} must be a Decimal, not a binary float or other numeric type")
if not value.is_finite():
raise ValueError(f"{field} must be finite")
if -value.as_tuple().exponent > scale:
raise ValueError(f"{field} exceeds scale {scale}")
integer_digits = 0 if value.is_zero() else max(value.copy_abs().adjusted() + 1, 0)
if integer_digits > precision - scale:
raise ValueError(f"{field} exceeds precision {precision},{scale}")
return value
class ExactDecimal(TypeDecorator[Decimal]):
"""Fixed-point Decimal which uses SQLite TEXT, never a binary float."""
impl = Numeric
cache_ok = True
def __init__(self, precision: int, scale: int) -> None:
self.precision = precision
self.scale = scale
super().__init__(precision=precision, scale=scale)
def load_dialect_impl(self, dialect):
if dialect.name == "sqlite":
return dialect.type_descriptor(String(self.precision + 2))
return dialect.type_descriptor(Numeric(self.precision, self.scale, asdecimal=True))
def process_bind_param(self, value: Decimal | None, dialect) -> Decimal | str | None:
if value is None:
return None
value = _validate_fixed_decimal(value, self.precision, self.scale, "decimal value")
if dialect.name == "sqlite":
return format(value, f".{self.scale}f")
return value
def process_result_value(self, value: Decimal | str | None, _dialect) -> Decimal | None:
return None if value is None else Decimal(value)
class DecimalJSON(TypeDecorator[dict]):
"""JSON which serializes Decimal values as strings on every write path."""
impl = JSON
cache_ok = True
def process_bind_param(self, value: Any, _dialect) -> Any:
return None if value is None else _decimal_json(value)
class UTCDateTime(TypeDecorator[datetime]):
"""UTC timestamps that preserve instant identity on SQLite and other dialects."""
impl = DateTime(timezone=True)
cache_ok = True
def __init__(self, field: str) -> None:
self.field = field
super().__init__()
def process_bind_param(self, value: datetime | None, _dialect) -> datetime | None:
return None if value is None else _normalise_utc_period(value, self.field)
def process_result_value(self, value: datetime | None, _dialect) -> datetime | None:
if value is None:
return None
if value.tzinfo is None or value.utcoffset() is None:
return value.replace(tzinfo=timezone.utc)
return value.astimezone(timezone.utc)
def _require_aware_period(start: datetime, end: datetime) -> None:
if start.tzinfo is None or start.utcoffset() is None:
raise ValueError("period_start must be timezone-aware")
if end.tzinfo is None or end.utcoffset() is None:
raise ValueError("period_end must be timezone-aware")
if end <= start:
raise ValueError("period_end must be after period_start")
def _normalise_utc_period(value: datetime, field: str) -> datetime:
if value.tzinfo is None or value.utcoffset() is None:
raise ValueError(f"{field} must be timezone-aware")
return value.astimezone(timezone.utc)
class Meter(Base):
"""One physical electricity meter's installation epoch.
A ``meter`` record represents the period ``[started_at, ended_at)`` during
which a particular physical meter was installed and active. Replacing a meter
(swap, home move, etc.) is modelled by closing the current record
(``ended_at = swap_timestamp``) and opening a new one
(``started_at = swap_timestamp``).
**Invariant**: for each ``commodity`` there is at most one active meter
(``ended_at IS NULL``) at any point in time. The service layer enforces
this no DB-level constraint is added to keep the migration simple and to
allow the application to return a meaningful error message.
``commodity`` defaults to ``"electricity"``; the field is a free-form string
(no CHECK constraint) so future commodities (``gas``, ``heating``) can be
added without a schema change.
``reason`` captures why this epoch started one of ``initial``,
``meter_swap``, ``home_move``, or ``other`` stored as a plain string so
the application layer controls the allowed set.
"""
__tablename__ = "meter"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
# Stable internal identity — used as HA Discovery unique_id anchor.
uuid: Mapped[str] = mapped_column(String(36), unique=True, nullable=False, default=_uuid4_str)
# Human-readable label for this physical meter (e.g. address, serial, tariff zone).
label: Mapped[str] = mapped_column(String(255), nullable=False)
# Energy commodity this meter measures. Defaults to "electricity".
commodity: Mapped[str] = mapped_column(String(32), nullable=False, default="electricity")
# UTC timestamp when this meter epoch starts (inclusive). May be in the past
# (retroactive declaration); effective billing start = max(started_at, data start).
started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
# UTC timestamp when this meter epoch ends (exclusive). NULL = currently active.
ended_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
# Why this epoch was created. Application-layer validation enforces the
# allowed set; no CHECK constraint to keep migrations simple.
reason: Mapped[str] = mapped_column(String(64), nullable=False)
# Free-form note (e.g. location, physical meter id, reason details).
note: Mapped[str | None] = mapped_column(String(1024), nullable=True)
# UTC timestamp of when this row was created.
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
# Relationship to cost periods attributed to this meter epoch (not loaded eagerly).
cost_periods: Mapped[list["EnergyCostPeriod"]] = relationship(
back_populates="meter", cascade="save-update, merge"
)
source_bindings: Mapped[list["MeterSourceBinding"]] = relationship(
back_populates="meter", cascade="save-update, merge"
)
class DsmrReading(Base):
"""One down-sampled DSMR telegram stored as a full JSON blob.
Identity & idempotency are **independent of the DSMR Reader's telegram id**
(that field overflows and must be manually reset to zero a known DSMR
quirk so relying on it for uniqueness risks silently dropping new data).
The table's own autoincrement ``id`` PK is the stable internal identity, and
``(meter_source_id, recorded_at)`` is the UNIQUE de-duplication key: each
configured P1 source emits at most one telegram per timestamp, while
different sources may legitimately emit at the same instant.
``recorded_at`` is a real column (not inside the payload) so time-range
queries are efficient. The entire telegram frame is stored verbatim in
``payload``; no field allow-list is applied so future commodities (gas,
heating, three-phase) are accommodated without a schema change.
"""
__tablename__ = "dsmr_reading"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
# UTC timestamp of the sample. Idempotency is per configured source, so
# distinct P1 sources may legitimately emit at the same instant.
recorded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
# Telegram's own id (DSMR Reader assigns it). Stored only as a reference /
# debugging aid — NOT used for uniqueness or idempotency (it overflows and
# gets reset to zero). Nullable because some DSMR sources may not emit one.
telegram_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
# Compatibility for the pre-M8 ingest implementation. This is an ORM
# alias only; the physical database column is ``telegram_id``.
source_id = synonym("telegram_id")
# The configured source is the durable identity of the cumulative reading
# stream. It is non-null after the revision-16 historical adoption.
meter_source_id: Mapped[int] = mapped_column(
ForeignKey("meter_source.id", ondelete="RESTRICT"), nullable=False, index=True
)
# Full telegram frame as a JSON object; values are typically JSON strings
# (e.g. "20915.154") — callers must cast to Decimal before arithmetic.
payload: Mapped[dict] = mapped_column(JSON, nullable=False)
__table_args__ = (
UniqueConstraint(
"meter_source_id", "recorded_at", name="uq_dsmr_reading_source_recorded_at"
),
)
@event.listens_for(DsmrReading, "before_insert")
def _supply_legacy_dsmr_source(_mapper, connection, target: DsmrReading) -> None:
"""Keep the pre-T04 single-source writer working during the schema handoff."""
if target.meter_source_id is None:
target.meter_source_id = connection.execute(
text("SELECT id FROM meter_source WHERE kind = 'dsmr_mqtt' ORDER BY id LIMIT 1")
).scalar_one()
class EnergyContract(Base):
"""Contract head: a named energy contract with a chosen pricing strategy.
``kind`` determines which price strategy is used (``manual`` for fixed
dual-tariff rates entered by the user, ``tibber`` for dynamic API prices).
A contract belongs to an energy ``scope`` (currently electricity; thermal
profiles are reserved for the next milestone). Only one contract may be
``active`` per scope; the service layer enforces mutual exclusion. Specific
pricing values live in ``EnergyContractVersion``
so that price changes can be tracked without modifying historical records.
"""
__tablename__ = "energy_contract"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
# Human-readable label; freely editable by the user.
name: Mapped[str] = mapped_column(String(255), nullable=False)
# Strategy selector: "manual" or "tibber". Application-layer validation
# enforces the allowed set; no DB CHECK constraint is added to keep the
# migration simple and the strategy registry extensible.
kind: Mapped[str] = mapped_column(String(32), nullable=False)
# Billing domain. The service registry derives this from ``kind`` so API
# callers cannot move a pricing strategy into an incompatible domain.
scope: Mapped[str] = mapped_column(
String(32), nullable=False, default="electricity", index=True
)
# Whether this is the currently active contract (at most one should be True).
active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
# ISO 4217 currency code for all monetary values in this contract.
currency: Mapped[str] = mapped_column(String(8), nullable=False, default="EUR")
# Audit timestamps.
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
# Relationship to versions (back-reference; not loaded eagerly).
versions: Mapped[list["EnergyContractVersion"]] = relationship(
back_populates="contract", cascade="save-update, merge"
)
class EnergyContractVersion(Base):
"""One time-bounded version of an energy contract's pricing values.
Pricing changes are modelled as new versions (append-only); existing versions
are never modified so that historical ``EnergyCostPeriod`` records remain
fully auditable. ``effective_to`` is ``NULL`` for the currently open version.
"""
__tablename__ = "energy_contract_version"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
# FK to the parent contract. RESTRICT prevents deletion of a contract that
# still has versioned pricing rows attached to it.
contract_id: Mapped[int] = mapped_column(
ForeignKey("energy_contract.id", ondelete="RESTRICT"), nullable=False
)
# Start of this version's validity window (inclusive, UTC).
effective_from: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
# End of this version's validity window (exclusive, UTC). NULL means open-ended
# (i.e. this is the most recent / current version).
effective_to: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
# Pricing values as a JSON object conforming to the profile structure for
# ``contract.kind`` (validated by the application layer against the YAML profile).
values: Mapped[dict] = mapped_column(JSON, nullable=False)
# Creation timestamp.
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
# Relationship back to the parent contract.
contract: Mapped["EnergyContract"] = relationship(back_populates="versions")
# Relationship to cost periods that reference this version.
cost_periods: Mapped[list["EnergyCostPeriod"]] = relationship(
back_populates="contract_version", cascade="save-update, merge"
)
class TibberPrice(Base):
"""Cached Tibber 15-minute spot price point (immutable once fetched).
``starts_at`` is unique so that upserts are idempotent. Past prices are
never overwritten; the fetch job only adds rows for future time slots.
"""
__tablename__ = "tibber_price"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
# UTC start of the 15-minute slot; unique so upsert is idempotent.
starts_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, unique=True
)
# Resolution label as returned by the Tibber API (e.g. "QUARTER_HOURLY").
resolution: Mapped[str] = mapped_column(String(32), nullable=False)
# Price components in the contract currency (all include VAT, user-facing).
energy: Mapped[float] = mapped_column(Float, nullable=False)
tax: Mapped[float] = mapped_column(Float, nullable=False)
total: Mapped[float] = mapped_column(Float, nullable=False)
# Tibber price level (e.g. "NORMAL", "CHEAP", "EXPENSIVE"); may be absent.
level: Mapped[str | None] = mapped_column(String(32), nullable=True)
# ISO 4217 currency code as returned by the API.
currency: Mapped[str] = mapped_column(String(8), nullable=False)
# UTC timestamp of when this row was fetched/inserted.
fetched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
class EnergyCostPeriod(Base):
"""Computed billing record for one 15-minute metering period (immutable snapshot).
Each row captures the per-register kWh deltas, the resulting import cost and
export revenue, and a full snapshot of the pricing values used so that the
calculation is fully auditable and reproducible without re-querying the
contract version. Rows are written once and never modified; explicit
recomputation via the API is the only way to overwrite a period.
"""
__tablename__ = "energy_cost_period"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
# UTC start of the 15-minute period; unique so upsert is idempotent.
period_start: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, unique=True
)
# Per-register kWh deltas for the period (end minus start of cumulative registers).
# _1 = dal/low-tariff, _2 = normal/high-tariff (NL convention).
d1_kwh: Mapped[float] = mapped_column(Float, nullable=False) # delivered low
d2_kwh: Mapped[float] = mapped_column(Float, nullable=False) # delivered high
r1_kwh: Mapped[float] = mapped_column(Float, nullable=False) # returned low
r2_kwh: Mapped[float] = mapped_column(Float, nullable=False) # returned high
# Computed monetary amounts for the period (in ``currency``).
import_cost: Mapped[float] = mapped_column(Float, nullable=False)
export_revenue: Mapped[float] = mapped_column(Float, nullable=False)
net_cost: Mapped[float] = mapped_column(Float, nullable=False)
# ISO 4217 currency code matching the contract.
currency: Mapped[str] = mapped_column(String(8), nullable=False)
# Full snapshot of the pricing inputs used during computation. This makes
# each row self-contained and auditable even if the contract is later changed.
pricing: Mapped[dict] = mapped_column(JSON, nullable=False)
# FK to the exact contract version whose values were used. RESTRICT prevents
# deletion of a version that has cost records attached. Nullable to support
# periods computed in ``degraded`` mode (missing price data).
contract_version_id: Mapped[int | None] = mapped_column(
ForeignKey("energy_contract_version.id", ondelete="RESTRICT"), nullable=True
)
# FK to the meter epoch this period belongs to. RESTRICT prevents deletion of
# a meter that still has attributed cost periods. Nullable for backwards
# compatibility (pre-M7 rows) and degraded periods where the meter was not
# determinable.
meter_id: Mapped[int | None] = mapped_column(
ForeignKey("meter.id", ondelete="RESTRICT"), nullable=True
)
# Nullable for historical and degraded rows. Every new normal period
# points at the one binding that supplied both cumulative endpoints.
source_binding_id: Mapped[int | None] = mapped_column(
ForeignKey("meter_source_binding.id", ondelete="RESTRICT"), nullable=True
)
# True when the period was computed with incomplete data (missing readings or
# missing price); serves as a flag for later recomputation.
degraded: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
# UTC timestamp of when this row was computed/inserted.
computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
# Relationship back to the contract version.
contract_version: Mapped["EnergyContractVersion | None"] = relationship(
back_populates="cost_periods"
)
# Relationship back to the meter epoch.
meter: Mapped["Meter | None"] = relationship(back_populates="cost_periods")
source_binding: Mapped["MeterSourceBinding | None"] = relationship(
back_populates="cost_periods"
)
class MeterCostPeriod(Base):
"""Auditable commodity-scoped ledger row for one half-open metering period.
A degraded row intentionally permits missing audit links; services must
still require them before writing a normal row.
"""
__tablename__ = "meter_cost_period"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
commodity: Mapped[str] = mapped_column(String(32), nullable=False)
period_start: Mapped[datetime] = mapped_column(UTCDateTime("period_start"), nullable=False)
period_end: Mapped[datetime] = mapped_column(UTCDateTime("period_end"), nullable=False)
meter_id: Mapped[int | None] = mapped_column(
ForeignKey("meter.id", ondelete="RESTRICT"), nullable=True
)
source_binding_id: Mapped[int | None] = mapped_column(
ForeignKey("meter_source_binding.id", ondelete="RESTRICT"), nullable=True
)
contract_version_id: Mapped[int | None] = mapped_column(
ForeignKey("energy_contract_version.id", ondelete="RESTRICT"), nullable=True
)
# SQLite reliably round-trips at most fifteen significant decimal digits.
# WarmteLink itself reports 0.001 units, so nine cost fractional digits
# retain a six-place tariff times that source precision without float loss.
quantity: Mapped[Decimal] = mapped_column(ExactDecimal(15, 6), nullable=False)
cost: Mapped[Decimal] = mapped_column(ExactDecimal(15, 9), nullable=False)
currency: Mapped[str] = mapped_column(String(8), nullable=False)
cost_breakdown: Mapped[dict] = mapped_column(DecimalJSON(), nullable=False, default=dict)
pricing_snapshot: Mapped[dict] = mapped_column(DecimalJSON(), nullable=False, default=dict)
quality: Mapped[str] = mapped_column(String(32), nullable=False, default="valid")
degraded: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
degraded_reason: Mapped[str | None] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
meter: Mapped["Meter | None"] = relationship()
source_binding: Mapped["MeterSourceBinding | None"] = relationship()
contract_version: Mapped["EnergyContractVersion | None"] = relationship()
__table_args__ = (
CheckConstraint(
"degraded OR (meter_id IS NOT NULL AND source_binding_id IS NOT NULL "
"AND contract_version_id IS NOT NULL)",
name="ck_meter_cost_period_normal_audit_links",
),
CheckConstraint("period_end > period_start", name="ck_meter_cost_period_positive_interval"),
CheckConstraint(
"NOT degraded OR (degraded_reason IS NOT NULL AND length(trim(degraded_reason)) > 0)",
name="ck_meter_cost_period_degraded_reason",
),
UniqueConstraint("commodity", "period_start", name="uq_meter_cost_period_commodity_start"),
Index("ix_meter_cost_period_commodity_start", "commodity", "period_start"),
Index("ix_meter_cost_period_source_binding_id", "source_binding_id"),
)
@validates("cost_breakdown", "pricing_snapshot")
def _validate_decimal_json(self, _key: str, value: dict) -> dict:
return _decimal_json(value)
@validates("quantity", "cost")
def _validate_fixed_decimal(self, key: str, value: Decimal) -> Decimal:
precision, scale = (15, 6) if key == "quantity" else (15, 9)
return _validate_fixed_decimal(value, precision, scale, key)
@validates("period_start", "period_end")
def _normalise_period(self, key: str, value: datetime) -> datetime:
return _normalise_utc_period(value, key)
@event.listens_for(MeterCostPeriod, "before_insert")
@event.listens_for(MeterCostPeriod, "before_update")
def _validate_meter_cost_period(_mapper, _connection, target: MeterCostPeriod) -> None:
_require_aware_period(target.period_start, target.period_end)
if not target.degraded and (
target.meter_id is None
or target.source_binding_id is None
or target.contract_version_id is None
):
raise ValueError("normal meter cost periods require meter, binding, and contract version")
if target.degraded and not target.degraded_reason:
raise ValueError("degraded meter cost periods require a degraded_reason")
# Index on recorded_at for efficient time-range queries on DSMR readings.
# (The ORM-level index=True on recorded_at already creates ix_dsmr_reading_recorded_at;
# no composite index is needed for single-meter deployments.)
# Index on period_start is covered by the unique constraint (SQLite creates an
# implicit index for UNIQUE columns), so no additional index is required.
# Index on starts_at for TibberPrice is covered by the unique constraint similarly.
+49
View File
@@ -0,0 +1,49 @@
"""SQLAlchemy model for the exposed-entity toggle table.
``ExposedEntityToggle`` stores the per-entity enable/disable state for the
MQTT / HA Discovery expose framework. The *catalog* of what *can* be
exposed is computed dynamically by provider functions (see
``app/integrations/expose.py``); this table only records which entries the
user has explicitly enabled.
Key design decisions
--------------------
- ``key`` is a stable string identifier derived from device uuid + metric key
(e.g. ``"modbus.<uuid>.voltage"``), so it does not drift if rows are
deleted and re-inserted.
- Default state for an entity not yet in this table is **disabled** (false).
``build_catalog`` in expose.py treats a missing row as ``enabled=False``.
- Only one row per entity key (``key`` is UNIQUE).
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import Boolean, DateTime, Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
class ExposedEntityToggle(Base):
"""Per-entity on/off switch for MQTT / HA Discovery publishing.
Rows are created on demand (first toggle); entities with no row are
treated as disabled.
"""
__tablename__ = "exposed_entity_toggle"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
# Stable entity key, e.g. "modbus.<uuid>.voltage" or "modbus.<uuid>.online".
key: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
# Whether this entity should be published via MQTT / HA Discovery.
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
# Last time this row was created or modified.
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False
)
+165
View File
@@ -0,0 +1,165 @@
"""Protocol-agnostic source, channel, and meter-binding identity models."""
from __future__ import annotations
import uuid as _uuid
from datetime import datetime
from decimal import Decimal
from typing import TYPE_CHECKING
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
Numeric,
String,
UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.types import JSON
from app.db import Base
if TYPE_CHECKING:
from app.models.energy import EnergyCostPeriod, Meter
def _uuid4_str() -> str:
return str(_uuid.uuid4())
def half_open_intervals_overlap(
started_at: datetime,
ended_at: datetime | None,
other_started_at: datetime,
other_ended_at: datetime | None,
) -> bool:
"""Return whether two ``[started_at, ended_at)`` intervals overlap.
``None`` denotes an open-ended interval. Equal boundaries do not overlap,
which lets a source binding hand off at one exact timestamp.
"""
return (other_ended_at is None or started_at < other_ended_at) and (
ended_at is None or other_started_at < ended_at
)
class MeterSource(Base):
"""A configured protocol connection that discovers one or more channels."""
__tablename__ = "meter_source"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
uuid: Mapped[str] = mapped_column(String(36), unique=True, nullable=False, default=_uuid4_str)
name: Mapped[str] = mapped_column(String(255), nullable=False)
kind: Mapped[str] = mapped_column(String(64), nullable=False)
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
config: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
status: Mapped[str] = mapped_column(String(32), nullable=False, default="unknown")
last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_error: Mapped[str | None] = mapped_column(String(1024), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
channels: Mapped[list["MeterSourceChannel"]] = relationship(
back_populates="source", cascade="save-update, merge"
)
class MeterSourceChannel(Base):
"""A stable cumulative measurement identity discovered from a source."""
__tablename__ = "meter_source_channel"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
uuid: Mapped[str] = mapped_column(String(36), unique=True, nullable=False, default=_uuid4_str)
source_id: Mapped[int] = mapped_column(
ForeignKey("meter_source.id", ondelete="RESTRICT"), nullable=False, index=True
)
channel_key: Mapped[str] = mapped_column(String(128), nullable=False)
label: Mapped[str] = mapped_column(String(255), nullable=False)
suggested_commodity: Mapped[str | None] = mapped_column(String(32), nullable=True)
unit: Mapped[str] = mapped_column(String(32), nullable=False)
device_type: Mapped[str | None] = mapped_column(String(64), nullable=True)
fingerprint: Mapped[str | None] = mapped_column(String(64), nullable=True)
latest_value: Mapped[float | None] = mapped_column(Numeric(20, 6), nullable=True)
latest_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
latest_quality: Mapped[str | None] = mapped_column(String(32), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
source: Mapped["MeterSource"] = relationship(back_populates="channels")
bindings: Mapped[list["MeterSourceBinding"]] = relationship(
back_populates="channel", cascade="save-update, merge"
)
warmtelink_readings: Mapped[list["WarmteLinkReading"]] = relationship(
back_populates="channel", cascade="save-update, merge"
)
__table_args__ = (
UniqueConstraint("source_id", "channel_key", name="uq_meter_source_channel_source_key"),
)
class WarmteLinkReading(Base):
"""One accepted scalar cumulative reading from a WarmteLink channel."""
__tablename__ = "warmtelink_reading"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
channel_id: Mapped[int] = mapped_column(
ForeignKey("meter_source_channel.id", ondelete="RESTRICT"), nullable=False
)
# These timestamps retain their UTC-aware application semantics. SQLite
# stores them without an offset, so callers must always supply aware UTC.
recorded_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
# SQLite's ORM Numeric path can exactly round-trip this 12-integer-digit
# range at scale 3. That is ample for a long-lived cumulative meter while
# retaining the protocol's 0.001 resolution without float conversion.
value: Mapped[Decimal] = mapped_column(Numeric(15, 3), nullable=False)
unit: Mapped[str] = mapped_column(String(32), nullable=False)
quality: Mapped[str] = mapped_column(String(32), nullable=False)
equipment_fingerprint: Mapped[str] = mapped_column(String(64), nullable=False)
channel: Mapped["MeterSourceChannel"] = relationship(back_populates="warmtelink_readings")
__table_args__ = (
CheckConstraint(
"quality IN ('valid', 'invalid', 'unverifiable')",
name="ck_warmtelink_reading_quality",
),
UniqueConstraint("channel_id", "recorded_at", name="uq_warmtelink_reading_channel_recorded_at"),
Index("ix_warmtelink_reading_recorded_at", "recorded_at"),
)
class MeterSourceBinding(Base):
"""Connect one source channel to one physical meter for a half-open window."""
__tablename__ = "meter_source_binding"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
uuid: Mapped[str] = mapped_column(String(36), unique=True, nullable=False, default=_uuid4_str)
meter_id: Mapped[int] = mapped_column(
ForeignKey("meter.id", ondelete="RESTRICT"), nullable=False, index=True
)
channel_id: Mapped[int] = mapped_column(
ForeignKey("meter_source_channel.id", ondelete="RESTRICT"), nullable=False, index=True
)
started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
ended_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
meter: Mapped["Meter"] = relationship(back_populates="source_bindings")
channel: Mapped["MeterSourceChannel"] = relationship(back_populates="bindings")
cost_periods: Mapped[list["EnergyCostPeriod"]] = relationship(
back_populates="source_binding", cascade="save-update, merge", passive_deletes="all"
)
Index("ix_meter_source_kind_enabled", MeterSource.kind, MeterSource.enabled)
+114
View File
@@ -0,0 +1,114 @@
"""SQLAlchemy models for Modbus device management and telemetry.
Two tables:
- modbus_device: deployment/configurable metadata for each polled device.
- modbus_reading: generic telemetry rows (one per device per poll cycle).
"""
from __future__ import annotations
import uuid as _uuid
from datetime import datetime
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Integer, String
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.types import JSON
from app.db import Base
def _uuid4_str() -> str:
return str(_uuid.uuid4())
class ModbusDevice(Base):
"""Deployment-layer record for a Modbus slave device reachable via a TCP gateway.
Protocol knowledge (register map, decoding rules) lives in the YAML profile
referenced by ``profile``. Per-device variables (network address, slave ID,
display name, poll rate) live here.
"""
__tablename__ = "modbus_device"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
# Stable internal identity — used as the API path key and HA Discovery unique_id anchor.
uuid: Mapped[str] = mapped_column(
String(36), unique=True, nullable=False, default=_uuid4_str
)
# Human-readable label (may be changed; changing it triggers re-publish of HA Discovery).
friendly_name: Mapped[str] = mapped_column(String(255), nullable=False)
# Transport protocol — only "tcp" is supported for now.
transport: Mapped[str] = mapped_column(String(16), nullable=False, default="tcp")
# TCP gateway address.
host: Mapped[str] = mapped_column(String(255), nullable=False)
port: Mapped[int] = mapped_column(Integer, nullable=False, default=502)
# Modbus slave address (set on the device panel; different meters on the same gateway
# must have distinct unit_ids).
unit_id: Mapped[int] = mapped_column(Integer, nullable=False, default=1)
# Which YAML profile to use for register mapping and decoding (e.g. "sdm120").
profile: Mapped[str] = mapped_column(String(64), nullable=False)
# Polling interval in seconds.
poll_interval_s: Mapped[int] = mapped_column(Integer, nullable=False, default=5)
# Whether this device is included in the periodic poll sweep.
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
# Poll-status fields (updated by the poll service after each attempt).
last_poll_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True
)
last_poll_ok: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
# Audit timestamps.
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False
)
# Relationship to readings (back-reference; not loaded eagerly).
readings: Mapped[list["ModbusReading"]] = relationship(
back_populates="device", cascade="save-update, merge"
)
class ModbusReading(Base):
"""Generic telemetry row: one device, one poll instant, all decoded metrics as JSON.
``payload`` contains the full dict of engineering values produced by the YAML profile
decoder, e.g. ``{"voltage": 230.2, "current": 1.3, ...}``. The profile is the key
to interpreting which keys exist and what units they carry.
"""
__tablename__ = "modbus_reading"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
# FK to the device that produced this reading.
# ON DELETE RESTRICT: prevents accidental deletion of a device that has historical data.
device_id: Mapped[int] = mapped_column(
ForeignKey("modbus_device.id", ondelete="RESTRICT"), nullable=False
)
# The UTC timestamp of when the sample was taken — real indexed column, NOT embedded in payload.
recorded_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, index=True
)
# Profile-decoded engineering values as a JSON object.
payload: Mapped[dict] = mapped_column(JSON, nullable=False)
device: Mapped["ModbusDevice"] = relationship(back_populates="readings")
# Composite index for efficient time-range queries scoped to a single device.
Index("ix_modbus_reading_device_recorded", ModbusReading.device_id, ModbusReading.recorded_at)
+2 -2
View File
@@ -1,10 +1,10 @@
from sqlalchemy import Float, String
from sqlalchemy.orm import Mapped, mapped_column
from app.poo_db import PooBase
from app.db import Base
class PooRecord(PooBase):
class PooRecord(Base):
__tablename__ = "poo_records"
timestamp: Mapped[str] = mapped_column(String, primary_key=True)
+30
View File
@@ -0,0 +1,30 @@
from datetime import datetime
from sqlalchemy import DateTime, Integer, String
from sqlalchemy.orm import Mapped, mapped_column
from app.db import Base
class PublicIPState(Base):
__tablename__ = "public_ip_state"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
current_ipv4: Mapped[str] = mapped_column(String(45), nullable=False)
previous_ipv4: Mapped[str | None] = mapped_column(String(45), nullable=True)
first_seen_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
last_checked_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
last_changed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
last_check_status: Mapped[str] = mapped_column(String(32), nullable=False)
last_check_error: Mapped[str | None] = mapped_column(String(255), nullable=True)
last_provider: Mapped[str | None] = mapped_column(String(64), nullable=True)
class PublicIPHistory(Base):
__tablename__ = "public_ip_history"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
ipv4: Mapped[str] = mapped_column(String(45), nullable=False)
observed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
change_type: Mapped[str] = mapped_column(String(32), nullable=False)
provider: Mapped[str | None] = mapped_column(String(64), nullable=True)
-28
View File
@@ -1,28 +0,0 @@
from collections.abc import Generator
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
from app.config import get_settings
class PooBase(DeclarativeBase):
pass
settings = get_settings()
connect_args: dict[str, object] = {}
if settings.poo_database_url.startswith("sqlite"):
connect_args["check_same_thread"] = False
poo_engine = create_engine(settings.poo_database_url, connect_args=connect_args)
PooSessionLocal = sessionmaker(bind=poo_engine, autoflush=False, autocommit=False, class_=Session)
def get_poo_db_session() -> Generator[Session, None, None]:
session = PooSessionLocal()
try:
yield session
finally:
session.close()
+47
View File
@@ -0,0 +1,47 @@
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel
class ConfigField(BaseModel):
env_name: str
label: str
value: str
secret: bool
input_type: str
configured: bool
class ConfigSection(BaseModel):
name: str
fields: list[ConfigField]
class ConfigResponse(BaseModel):
sections: list[ConfigSection]
class ConfigUpdateRequest(BaseModel):
"""Flat mapping of env_name → value, mirroring the existing form semantics."""
updates: dict[str, str]
class ConfigUpdateResponse(BaseModel):
sections: list[ConfigSection]
class SmtpTestResponse(BaseModel):
"""Response from POST /api/config/smtp/test."""
result: Literal["success", "config-error", "failed"]
message: str
class MqttTestResponse(BaseModel):
"""Response from POST /api/config/mqtt/test."""
result: Literal["success", "config-error", "failed"]
message: str
+92
View File
@@ -0,0 +1,92 @@
from __future__ import annotations
from datetime import datetime
from pydantic import BaseModel
# ---------------------------------------------------------------------------
# Location
# ---------------------------------------------------------------------------
class LocationRecord(BaseModel):
person: str
datetime: str
latitude: float
longitude: float
altitude: float | None
class LocationsResponse(BaseModel):
items: list[LocationRecord]
limit: int
offset: int
class LocationUpdateRequest(BaseModel):
"""PATCH body for a location record — all fields optional; PK fields excluded."""
latitude: float | None = None
longitude: float | None = None
altitude: float | None = None
# ---------------------------------------------------------------------------
# Poo
# ---------------------------------------------------------------------------
class PooRecord(BaseModel):
timestamp: str
status: str
latitude: float
longitude: float
class PooResponse(BaseModel):
items: list[PooRecord]
limit: int
offset: int
class PooUpdateRequest(BaseModel):
"""PATCH body for a poo record — all fields optional; PK field excluded."""
status: str | None = None
latitude: float | None = None
longitude: float | None = None
# ---------------------------------------------------------------------------
# Public IP
# ---------------------------------------------------------------------------
class PublicIPStateSchema(BaseModel):
id: int
current_ipv4: str
previous_ipv4: str | None
first_seen_at: datetime
last_checked_at: datetime
last_changed_at: datetime | None
last_check_status: str
last_check_error: str | None
last_provider: str | None
model_config = {"from_attributes": True}
class PublicIPHistorySchema(BaseModel):
id: int
ipv4: str
observed_at: datetime
change_type: str
provider: str | None
model_config = {"from_attributes": True}
class PublicIPResponse(BaseModel):
state: PublicIPStateSchema | None
history: list[PublicIPHistorySchema]
+253
View File
@@ -0,0 +1,253 @@
"""Pydantic schemas for the Energy data API (M6-T09).
Covers six endpoint groups under /api/energy:
- GET /prices price curve (tibber 15min points or manual tariff)
- GET /costs energy_cost_period rows (time-range, paginated)
- GET /costs/summary aggregated metered + standing charges credits
- GET /dsmr/latest most recent dsmr_reading blob
- POST /costs/recompute explicit idempotent recompute (returns count)
- POST /tibber/test three-state Tibber connection test
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Literal
from pydantic import BaseModel, Field
# ---------------------------------------------------------------------------
# GET /api/energy/prices
# ---------------------------------------------------------------------------
class PricePointSchema(BaseModel):
"""A single 15-minute price point (tibber) or placeholder entry."""
starts_at: datetime
buy: float = Field(description="All-in buy price in EUR/kWh (including taxes).")
sell: float = Field(description="Net sell price in EUR/kWh.")
level: str | None = Field(
default=None,
description="Tibber price level (CHEAP / NORMAL / EXPENSIVE); null for manual.",
)
class ManualTariffSchema(BaseModel):
"""Fixed-tariff breakdown for manual contracts.
Prices are the *effective* buy prices as used by the billing engine
(energy_buy_x + energy_tax + ode) and the raw sell prices.
"""
buy_dal: float = Field(description="Effective buy price, low-tariff / dal (EUR/kWh).")
buy_normal: float = Field(description="Effective buy price, normal / high-tariff (EUR/kWh).")
sell_dal: float = Field(description="Sell price, low-tariff / dal (EUR/kWh).")
sell_normal: float = Field(description="Sell price, normal / high-tariff (EUR/kWh).")
class PricesResponse(BaseModel):
"""Response for GET /api/energy/prices.
``kind`` mirrors the active contract kind:
- ``"tibber"`` ``points`` has actual 15-min price entries; ``tariff`` is null.
- ``"manual"`` ``points`` is empty; ``tariff`` carries the fixed-rate table.
- ``None`` no active contract; both ``points`` and ``tariff`` are empty/null.
``currency`` comes from the active contract (or "EUR" fallback).
``points`` is always ascending by ``starts_at``.
"""
kind: str | None = Field(
description="Active contract kind ('tibber' or 'manual'), or null if no active contract."
)
currency: str = Field(description="ISO 4217 currency code.")
points: list[PricePointSchema] = Field(
description=(
"15-minute price points for tibber contracts (ascending by starts_at). "
"Empty for manual contracts or when no active contract exists."
)
)
tariff: ManualTariffSchema | None = Field(
default=None,
description=(
"Fixed tariff table for manual contracts. "
"Null for tibber contracts and when no active contract exists."
),
)
contract_version_id: int | None = Field(
default=None,
description="Thermal active contract version identifier; omitted for electricity.",
)
effective_from: datetime | None = Field(
default=None,
description="Thermal contract version start; omitted for electricity.",
)
effective_to: datetime | None = Field(
default=None,
description="Thermal contract version end; omitted for electricity.",
)
values: dict[str, dict[str, str]] | None = Field(
default=None,
description="Thermal normalized Decimal-string contract values; omitted for electricity.",
)
model_config = {"ser_json_exclude_none": True}
# ---------------------------------------------------------------------------
# GET /api/energy/costs
# ---------------------------------------------------------------------------
class CostPeriodSchema(BaseModel):
"""One 15-minute billing record from the energy_cost_period table."""
period_start: datetime
d1_kwh: float = Field(description="Delivered low-tariff kWh for this period.")
d2_kwh: float = Field(description="Delivered normal-tariff kWh for this period.")
r1_kwh: float = Field(description="Returned low-tariff kWh for this period.")
r2_kwh: float = Field(description="Returned normal-tariff kWh for this period.")
import_cost: float = Field(description="Cost of electricity drawn from grid (EUR).")
export_revenue: float = Field(description="Revenue from electricity fed to grid (EUR).")
net_cost: float = Field(description="import_cost export_revenue (EUR).")
currency: str = Field(description="ISO 4217 currency code.")
degraded: bool = Field(description="True when the period was computed with incomplete data.")
contract_version_id: int | None = Field(
default=None,
description="FK to the contract version used for this billing period (null when degraded).",
)
source_binding_id: int | None = Field(
default=None,
description=(
"FK to the source binding that supplied both cumulative endpoints "
"(null for legacy or degraded periods)."
),
)
model_config = {"from_attributes": True}
class CostsResponse(BaseModel):
"""Response for GET /api/energy/costs."""
items: list[CostPeriodSchema]
total: int = Field(description="Number of items returned.")
# ---------------------------------------------------------------------------
# GET /api/energy/costs/summary
# ---------------------------------------------------------------------------
class SummaryResponse(BaseModel):
"""Response for GET /api/energy/costs/summary.
Monetary values are in ``currency``; the ``*_kwh`` fields are energy totals
in kWh. ``metered_import``/``metered_export`` are **money**, not energy
only the ``_kwh``-suffixed fields carry kWh.
``total_payable = metered_net + fixed_costs credits``
"""
currency: str
metered_import: float = Field(
description="Σ import_cost for non-degraded periods (money, in `currency`)."
)
metered_export: float = Field(
description="Σ export_revenue for non-degraded periods (money, in `currency`)."
)
metered_net: float = Field(
description="Σ net_cost for non-degraded periods (money, in `currency`)."
)
metered_import_kwh: float = Field(
description="Σ (d1_kwh + d2_kwh) for non-degraded periods (energy imported, kWh)."
)
metered_export_kwh: float = Field(
description="Σ (r1_kwh + r2_kwh) for non-degraded periods (energy exported, kWh)."
)
fixed_costs: float = Field(
description="Standing charges (network_fee + management_fee) apportioned over the interval."
)
credits: float = Field(
description="Energy-tax credit (heffingskorting) apportioned over the interval."
)
total_payable: float = Field(
description="metered_net + fixed_costs credits (actual amount owed)."
)
period_count: int = Field(description="Number of non-degraded billing periods in range.")
degraded_count: int = Field(description="Number of degraded billing periods in range.")
days: float = Field(description="Interval length in days.")
# ---------------------------------------------------------------------------
# GET /api/energy/dsmr/latest
# ---------------------------------------------------------------------------
class DsmrLatestResponse(BaseModel):
"""Response for GET /api/energy/dsmr/latest.
``found`` is False when no dsmr_reading rows exist yet. The front-end
should check ``found`` before reading ``recorded_at`` or ``payload``.
"""
found: bool
recorded_at: datetime | None = None
payload: dict[str, Any] | None = None
# ---------------------------------------------------------------------------
# POST /api/energy/costs/recompute
# ---------------------------------------------------------------------------
class RecomputeResponse(BaseModel):
"""Response for POST /api/energy/costs/recompute."""
recomputed: int = Field(
description=(
"Number of 15-minute periods for which a billing record was written "
"(inserted or updated). Periods skipped due to missing contract or "
"missing Tibber price are not counted."
)
)
# ---------------------------------------------------------------------------
# POST /api/energy/tibber/test
# ---------------------------------------------------------------------------
class TibberTestPriceSchema(BaseModel):
"""Current Tibber price point returned on a successful test.
Carries enough fields for the front-end to confirm the API is working and
display the live price. The API token is **never** included.
"""
starts_at: datetime
total: float
energy: float
tax: float
currency: str
level: str | None = None
class TibberTestResponse(BaseModel):
"""Three-state response for POST /api/energy/tibber/test.
Possible ``result`` values:
- ``"success"`` Tibber API responded with a valid price.
- ``"config-error"`` Token is missing or not configured.
- ``"failed"`` API call failed (auth rejected, network error, timeout, etc.).
``price`` is populated only on ``"success"``; it is null otherwise.
``message`` always contains a human-readable explanation.
"""
result: Literal["success", "config-error", "failed"]
message: str
price: TibberTestPriceSchema | None = None
+151
View File
@@ -0,0 +1,151 @@
"""Pydantic schemas for the EnergyContract CRUD + versioning API (M6-T04).
Schema hierarchy
----------------
ContractVersionResponse single version row (id, dates, values, created_at)
ContractResponse contract head (id, name, kind, active, currency, timestamps)
ContractDetailResponse contract head + embedded versions list (for GET{id})
ContractListResponse paginated list of ContractResponse items
ContractCreate POST /api/energy/contracts body
ContractPatch PATCH /api/energy/contracts/{id} body (all fields optional)
VersionCreate POST /api/energy/contracts/{id}/versions body
ProfilesResponse GET /api/energy/profiles response
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from pydantic import BaseModel, Field
# ---------------------------------------------------------------------------
# Version schemas
# ---------------------------------------------------------------------------
class ContractVersionResponse(BaseModel):
"""Response schema for a single EnergyContractVersion row."""
id: int
effective_from: datetime
effective_to: datetime | None
values: dict[str, Any]
created_at: datetime
model_config = {"from_attributes": True}
# ---------------------------------------------------------------------------
# Contract schemas
# ---------------------------------------------------------------------------
class ContractResponse(BaseModel):
"""Response schema for a single EnergyContract (without embedded versions).
Used for list responses where embedding all versions would be expensive.
"""
id: int
name: str
kind: str
scope: str
active: bool
currency: str
created_at: datetime
updated_at: datetime
model_config = {"from_attributes": True}
class ContractDetailResponse(BaseModel):
"""Response schema for a single EnergyContract with full version history.
Returned by GET /api/energy/contracts/{id} and by successful POST / PATCH
operations where the caller needs to see all version data.
"""
id: int
name: str
kind: str
scope: str
active: bool
currency: str
created_at: datetime
updated_at: datetime
versions: list[ContractVersionResponse]
model_config = {"from_attributes": True}
class ContractListResponse(BaseModel):
"""Response schema for GET /api/energy/contracts."""
items: list[ContractResponse]
total: int
# ---------------------------------------------------------------------------
# Request schemas
# ---------------------------------------------------------------------------
class ContractCreate(BaseModel):
"""Request body for POST /api/energy/contracts.
``effective_from`` defaults to the current UTC time if not provided,
giving the first version an open-ended start from "now".
``kind`` is validated at the application layer against the profile registry;
clients should send ``"manual"`` or ``"tibber"``.
"""
name: str = Field(..., min_length=1, max_length=255)
kind: str = Field(..., min_length=1, max_length=32)
scope: str | None = Field(default=None, min_length=1, max_length=32)
currency: str = Field(default="EUR", min_length=1, max_length=8)
values: dict[str, Any]
effective_from: datetime | None = Field(
default=None,
description=(
"UTC datetime from which the first pricing version is effective. "
"Defaults to the current UTC time when omitted."
),
)
class ContractPatch(BaseModel):
"""Request body for PATCH /api/energy/contracts/{id}.
All fields are optional. Sending ``active=true`` activates this contract
(deactivating all others); ``active=false`` deactivates it without affecting
other contracts.
"""
name: str | None = Field(default=None, min_length=1, max_length=255)
active: bool | None = None
class VersionCreate(BaseModel):
"""Request body for POST /api/energy/contracts/{id}/versions."""
effective_from: datetime
values: dict[str, Any]
# ---------------------------------------------------------------------------
# Profile response schemas
# ---------------------------------------------------------------------------
class ProfilesResponse(BaseModel):
"""Response schema for GET /api/energy/profiles.
``profiles`` is a list of raw profile dicts as produced by
``list_profiles()`` (Pydantic model dumps). Each entry contains at minimum
``kind`` and ``label``; the full nested structure allows the front-end to
render a type-appropriate form for each pricing profile.
"""
profiles: list[dict[str, Any]]
+95
View File
@@ -0,0 +1,95 @@
"""Pydantic schemas for the Expose API (M5-T12).
Three endpoints:
GET /api/expose catalog + toggle state + MQTT/Discovery status
PUT /api/expose set toggles (map key bool)
POST /api/expose/republish trigger discovery re-publish
"""
from __future__ import annotations
from pydantic import BaseModel
# ---------------------------------------------------------------------------
# Nested schemas
# ---------------------------------------------------------------------------
class DeviceInfoSchema(BaseModel):
"""HA device grouping info for an exposable entity."""
identifiers: list[str]
name: str
class ExposableEntitySchema(BaseModel):
"""One exposable entity in the catalog.
``value_getter`` is intentionally excluded it is a non-serialisable
callable and is only used internally by the HA Discovery service.
"""
key: str
component: str
device: DeviceInfoSchema
device_class: str | None
unit: str
name: str
state_class: str | None = None
class CatalogEntrySchema(BaseModel):
"""An entity from the catalog with its current toggle state."""
entity: ExposableEntitySchema
enabled: bool
class MqttStatusSchema(BaseModel):
"""Connection status for MQTT and HA Discovery."""
mqtt_configured: bool
mqtt_connected: bool
discovery_enabled: bool
# ---------------------------------------------------------------------------
# Response schemas
# ---------------------------------------------------------------------------
class ExposeResponse(BaseModel):
"""Response for GET /api/expose."""
catalog: list[CatalogEntrySchema]
mqtt_status: MqttStatusSchema
class ExposeUpdateResponse(BaseModel):
"""Response for PUT /api/expose (returns updated catalog + status)."""
catalog: list[CatalogEntrySchema]
mqtt_status: MqttStatusSchema
class RepublishResponse(BaseModel):
"""Response for POST /api/expose/republish."""
ok: bool
message: str
# ---------------------------------------------------------------------------
# Request schemas
# ---------------------------------------------------------------------------
class ExposeUpdateRequest(BaseModel):
"""Request body for PUT /api/expose.
``toggles`` is a map from entity key to desired enabled state (bool).
Only keys present in the map are updated; absent keys are untouched.
"""
toggles: dict[str, bool]
+154
View File
@@ -0,0 +1,154 @@
"""Pydantic schemas for the Meter CRUD + swap declaration API (M7-T05).
Schema hierarchy
----------------
MeterResponse single meter row (id/label/commodity/started_at/ended_at/reason/note/created_at)
MeterListResponse ordered list of MeterResponse items
MeterDeclareRequest POST /api/energy/meters body (declare a swap or initial meter)
MeterPatchRequest PATCH /api/energy/meters/{id} body (all fields optional)
"""
from __future__ import annotations
from datetime import datetime
from enum import Enum
from pydantic import BaseModel, Field
# ---------------------------------------------------------------------------
# Enums
# ---------------------------------------------------------------------------
class MeterReason(str, Enum):
"""Allowed values for the meter epoch creation reason."""
initial = "initial"
meter_swap = "meter_swap"
home_move = "home_move"
other = "other"
# ---------------------------------------------------------------------------
# Response schemas
# ---------------------------------------------------------------------------
class MeterResponse(BaseModel):
"""Response schema for a single Meter epoch row.
``ended_at`` is ``null`` for the currently active meter.
"""
id: int
label: str
commodity: str
started_at: datetime
ended_at: datetime | None
reason: str
note: str | None
created_at: datetime
bindings: list["MeterBindingSummary"] = Field(default_factory=list)
model_config = {"from_attributes": True}
class MeterBindingSummary(BaseModel):
"""Stable, non-sensitive binding identity embedded in meter responses."""
uuid: str
source_channel_uuid: str
source_uuid: str
started_at: datetime
ended_at: datetime | None
class MeterListResponse(BaseModel):
"""Response schema for GET /api/energy/meters.
Meters are returned in ascending ``started_at`` order so the caller sees
the historical installation sequence.
"""
items: list[MeterResponse]
total: int
# ---------------------------------------------------------------------------
# Request schemas
# ---------------------------------------------------------------------------
_VALID_REASONS = ", ".join(r.value for r in MeterReason)
class MeterDeclareRequest(BaseModel):
"""Request body for POST /api/energy/meters.
Declares a new meter epoch (swap, home move, or initial declaration). The
service layer closes the current active meter for the given commodity at
``started_at`` and opens a new one.
``started_at`` follows the Principle-A localisation convention: a
timezone-naive value is interpreted as the **server's local wall-clock time**
(e.g. CEST midnight stored as UTC the night before); a timezone-aware
value is converted to UTC as-is. Omitting ``started_at`` is not allowed
every meter declaration must carry an explicit start timestamp.
``commodity`` defaults to ``"electricity"``; the field is available for
future use with ``gas`` or ``heating``.
"""
label: str = Field(..., min_length=1, max_length=255)
started_at: datetime = Field(
...,
description=(
"UTC (or server-local naive) datetime from which this meter epoch starts. "
"May be in the past (retroactive declaration)."
),
)
reason: MeterReason = Field(
...,
description=f"Why this epoch was created. One of: {_VALID_REASONS}.",
)
note: str | None = Field(default=None, max_length=1024)
commodity: str = Field(
default="electricity",
min_length=1,
max_length=32,
description="Energy commodity this meter measures. Defaults to 'electricity'.",
)
source_channel_uuid: str | None = Field(
default=None,
min_length=1,
max_length=36,
description="Optional compatible source channel to bind atomically to this meter.",
)
class MeterPatchRequest(BaseModel):
"""Request body for PATCH /api/energy/meters/{id}.
All fields are optional. Only non-``None`` values are applied.
Updating ``started_at`` is a **retroactive correction**: the service layer
maintains timeline continuity (adjusting the preceding meter's ``ended_at``)
and the API layer triggers ``recompute_range`` over the affected window so
that billing attribution is re-judged.
"""
label: str | None = Field(default=None, min_length=1, max_length=255)
note: str | None = Field(default=None, max_length=1024)
started_at: datetime | None = Field(
default=None,
description=(
"Retroactive correction of the meter epoch start timestamp. "
"Triggers billing recompute over the affected window."
),
)
class MeterCloseRequest(BaseModel):
"""Close the active meter epoch at an exclusive end boundary."""
ended_at: datetime
+62
View File
@@ -0,0 +1,62 @@
"""Schemas for the commodity-scoped thermal cost ledger."""
from __future__ import annotations
from datetime import datetime
from typing import Literal
from pydantic import BaseModel, Field
class MeterCostPeriodSchema(BaseModel):
"""One auditable thermal ledger row; all Decimal values are JSON strings."""
commodity: Literal["heating", "hot_water"]
period_start: datetime
period_end: datetime
meter_id: int | None
source_binding_id: int | None
contract_version_id: int | None
quantity: str
cost: str
currency: str
cost_breakdown: dict[str, str]
pricing_snapshot: dict[str, dict[str, str]]
quality: str
degraded: bool
degraded_reason: str | None
class MeterCostsResponse(BaseModel):
items: list[MeterCostPeriodSchema]
total: int = Field(description="Total matching rows before pagination.")
class ThermalFixedBreakdown(BaseModel):
"""D11 annual-standing charges accrued per settled local day, as Decimal strings."""
heating_network: str
metering: str
delivery_set: str
hot_water_network: str
other: str
class ThermalCostSummaryResponse(BaseModel):
currency: str
heating: str
hot_water_heating: str
hot_water: str
hot_water_tax: str
variable_subtotal: str
fixed_breakdown: ThermalFixedBreakdown
fixed_subtotal: str
all_in: str
period_count: int
degraded_count: int
class MeterCostRecomputeResponse(BaseModel):
processed: int
normal: int
degraded: int
+162
View File
@@ -0,0 +1,162 @@
"""Public schemas for protocol-agnostic meter sources and bindings."""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from typing import Any
from pydantic import BaseModel, Field
class SourceConfigFieldResponse(BaseModel):
name: str
value_type: str
default: Any = None
required: bool
secret: bool
class SourceProfileResponse(BaseModel):
kind: str
fields: list[SourceConfigFieldResponse]
defaults: dict[str, Any]
capabilities: list[str]
allowed_units: list[str]
class SourceProfilesResponse(BaseModel):
items: list[SourceProfileResponse]
class MeterSourceCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=255)
kind: str = Field(..., min_length=1, max_length=64)
config: dict[str, Any] = Field(default_factory=dict)
enabled: bool = True
class MeterSourcePatch(BaseModel):
name: str | None = Field(default=None, min_length=1, max_length=255)
config: dict[str, Any] | None = None
enabled: bool | None = None
class MeterSourceResponse(BaseModel):
uuid: str
name: str
kind: str
enabled: bool
config: dict[str, Any]
status: str
last_seen_at: datetime | None
last_error: str | None
created_at: datetime
updated_at: datetime
class MeterSourceListResponse(BaseModel):
items: list[MeterSourceResponse]
total: int
class DiscoverResponse(BaseModel):
requested: bool
supported: bool
status: str
request_id: int | None = None
detail: str | None = None
channels: list["DiscoverChannelResponse"] = Field(default_factory=list)
class DiscoverChannelResponse(BaseModel):
uuid: str
label: str
unit: str
latest_value: Decimal | None
latest_at: datetime | None
latest_quality: str | None
class ChannelBindingSummaryResponse(BaseModel):
count: int
meter_ids: list[int]
class CommodityResponse(BaseModel):
key: str
unit: str
capabilities: list[str]
class CommoditiesResponse(BaseModel):
items: list[CommodityResponse]
class MeterSourceChannelResponse(BaseModel):
uuid: str
label: str
suggested_commodity: str | None
unit: str
device_type: str | None
latest_value: Decimal | None
latest_at: datetime | None
latest_quality: str | None
binding_count: int
bound_meter_ids: list[int]
binding_summary: ChannelBindingSummaryResponse
class MeterSourceChannelListResponse(BaseModel):
items: list[MeterSourceChannelResponse]
total: int
source_status: str
class ChannelReadingResponse(BaseModel):
recorded_at: datetime
value: Decimal | None = None
quality: str | None = None
class ChannelReadingsResponse(BaseModel):
items: list[ChannelReadingResponse]
total: int
class BindingCreate(BaseModel):
source_channel_uuid: str = Field(..., min_length=1, max_length=36)
started_at: datetime
ended_at: datetime | None = None
class BindingPatch(BaseModel):
started_at: datetime | None = None
ended_at: datetime | None = None
class BindingTransferRequest(BaseModel):
from_binding_uuid: str = Field(..., min_length=1, max_length=36)
to_source_channel_uuid: str = Field(..., min_length=1, max_length=36)
effective_at: datetime
class BindingResponse(BaseModel):
uuid: str
meter_id: int
source_channel_uuid: str
source_uuid: str
started_at: datetime
ended_at: datetime | None
created_at: datetime
updated_at: datetime
class BindingListResponse(BaseModel):
items: list[BindingResponse]
total: int
class BindingTransferResponse(BaseModel):
closed_binding: BindingResponse
created_binding: BindingResponse
+171
View File
@@ -0,0 +1,171 @@
"""Pydantic schemas for the Modbus device CRUD + readings + metrics API (M5-T05)."""
from __future__ import annotations
from datetime import datetime
from typing import Any
from pydantic import BaseModel, Field
# ---------------------------------------------------------------------------
# Device schemas
# ---------------------------------------------------------------------------
class ModbusDeviceCreate(BaseModel):
"""Request body for POST /api/modbus/devices."""
friendly_name: str = Field(..., min_length=1, max_length=255)
transport: str = Field(default="tcp", max_length=16)
host: str = Field(..., min_length=1, max_length=255)
port: int = Field(default=502, ge=1, le=65535)
unit_id: int = Field(default=1, ge=0, le=247)
profile: str = Field(..., min_length=1, max_length=64)
poll_interval_s: int = Field(default=5, ge=1, le=3600)
enabled: bool = Field(default=True)
class ModbusDeviceUpdate(BaseModel):
"""Request body for PATCH /api/modbus/devices/{uuid} — all fields optional."""
friendly_name: str | None = Field(default=None, min_length=1, max_length=255)
transport: str | None = Field(default=None, max_length=16)
host: str | None = Field(default=None, min_length=1, max_length=255)
port: int | None = Field(default=None, ge=1, le=65535)
unit_id: int | None = Field(default=None, ge=0, le=247)
profile: str | None = Field(default=None, min_length=1, max_length=64)
poll_interval_s: int | None = Field(default=None, ge=1, le=3600)
enabled: bool | None = None
class ModbusDeviceResponse(BaseModel):
"""Response schema for a single Modbus device."""
uuid: str
friendly_name: str
transport: str
host: str
port: int
unit_id: int
profile: str
poll_interval_s: int
enabled: bool
last_poll_at: datetime | None
last_poll_ok: bool | None
created_at: datetime
updated_at: datetime
model_config = {"from_attributes": True}
class ModbusDeviceListResponse(BaseModel):
"""Response schema for listing Modbus devices."""
items: list[ModbusDeviceResponse]
total: int
# ---------------------------------------------------------------------------
# Reading schemas
# ---------------------------------------------------------------------------
class ModbusReadingResponse(BaseModel):
"""A single reading row: timestamp + decoded payload."""
recorded_at: datetime
payload: dict[str, Any]
model_config = {"from_attributes": True}
class ModbusReadingsResponse(BaseModel):
"""Response schema for the readings time-range endpoint."""
items: list[ModbusReadingResponse]
class ModbusLatestResponse(BaseModel):
"""Response for the /latest endpoint.
``found`` is False and ``recorded_at``/``payload`` are None when the device
has no readings yet. Callers should check ``found`` before using the values.
"""
found: bool
recorded_at: datetime | None
payload: dict[str, Any] | None
# ---------------------------------------------------------------------------
# Metrics / profile schemas
# ---------------------------------------------------------------------------
class MetricInfo(BaseModel):
"""Metadata for a single measurable quantity in a device's profile."""
key: str
label: str
unit: str
device_class: str
class ModbusMetricsResponse(BaseModel):
"""Response schema for GET /api/modbus/devices/{uuid}/metrics."""
profile: str
metrics: list[MetricInfo]
# ---------------------------------------------------------------------------
# Profile list schema
# ---------------------------------------------------------------------------
class ProfileSummary(BaseModel):
"""One entry in the GET /api/modbus/profiles response."""
name: str
description: str
class ModbusProfilesResponse(BaseModel):
"""Response schema for GET /api/modbus/profiles."""
profiles: list[ProfileSummary]
# ---------------------------------------------------------------------------
# Test-read schema
# ---------------------------------------------------------------------------
class ModbusTestReadResponse(BaseModel):
"""Response for POST /api/modbus/devices/{uuid}/test.
On success ``ok=True`` and ``payload`` contains the decoded values.
On failure ``ok=False`` and ``error`` describes the problem.
"""
ok: bool
payload: dict[str, Any] | None = None
error: str | None = None
# ---------------------------------------------------------------------------
# Cascade-delete schema
# ---------------------------------------------------------------------------
class ModbusDeleteResponse(BaseModel):
"""Response for DELETE /api/modbus/devices/{uuid}?cascade=true.
Returned only when cascade deletion succeeds (HTTP 200). Non-cascade
successful deletes continue to return HTTP 204 (no body).
"""
deleted: bool
readings_deleted: int
toggles_deleted: int
+13
View File
@@ -0,0 +1,13 @@
from datetime import datetime
from typing import Literal
from pydantic import BaseModel
PublicIPCheckStatus = Literal["first_seen", "unchanged", "changed", "error"]
class PublicIPCheckResponse(BaseModel):
status: PublicIPCheckStatus
checked_at: datetime
changed: bool
+25
View File
@@ -0,0 +1,25 @@
from __future__ import annotations
from pydantic import BaseModel
class SessionUser(BaseModel):
username: str
force_password_change: bool
class SessionResponse(BaseModel):
user: SessionUser
csrf_token: str
class LoginRequest(BaseModel):
username: str
password: str
totp_code: str | None = None
class PasswordChangeRequest(BaseModel):
current_password: str
new_password: str
confirm_password: str
+59
View File
@@ -0,0 +1,59 @@
"""Pydantic schemas for TOTP setup / enable / disable / status endpoints (M4-T05)."""
from __future__ import annotations
from pydantic import BaseModel
# ---------------------------------------------------------------------------
# Setup (POST /api/auth/totp/setup) — response
# ---------------------------------------------------------------------------
class TotpSetupResponse(BaseModel):
"""Returned once after a setup call.
``secret`` and ``recovery_codes`` are **one-time plaintext values**.
They are never returned again by any subsequent API call.
The frontend must display and instruct the user to save them before confirming.
"""
secret: str
otpauth_uri: str
recovery_codes: list[str]
# ---------------------------------------------------------------------------
# Enable (POST /api/auth/totp/enable) — request
# ---------------------------------------------------------------------------
class TotpEnableRequest(BaseModel):
"""The user confirms setup by providing the 6-digit TOTP code."""
code: str
# ---------------------------------------------------------------------------
# Disable (POST /api/auth/totp/disable) — request
# ---------------------------------------------------------------------------
class TotpDisableRequest(BaseModel):
"""Disable TOTP by proving identity.
Exactly one of ``password`` or ``code`` must be provided.
"""
password: str | None = None
code: str | None = None
# ---------------------------------------------------------------------------
# Status (GET /api/auth/totp) — response
# ---------------------------------------------------------------------------
class TotpStatusResponse(BaseModel):
"""Minimal status response — never exposes secret or recovery codes."""
enabled: bool
+91 -11
View File
@@ -7,7 +7,7 @@ from typing import Any
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.auth_db import reset_auth_db_caches
from app.db import reset_db_caches
from app.config import Settings, get_settings
from app.models.config import AppConfigEntry
@@ -25,8 +25,17 @@ class ConfigField:
CONFIG_FIELDS: tuple[ConfigField, ...] = (
ConfigField("System", "APP_NAME", "app_name", "App Name"),
ConfigField("System", "APP_ENV", "app_env", "App Env"),
ConfigField("System", "APP_DEBUG", "app_debug", "App Debug"),
ConfigField("System", "APP_DEBUG", "app_debug", "App Debug", input_type="checkbox"),
ConfigField("System", "APP_HOSTNAME", "app_hostname", "App Hostname"),
ConfigField("SMTP", "SMTP_ENABLED", "smtp_enabled", "SMTP Enabled", input_type="checkbox"),
ConfigField("SMTP", "SMTP_HOST", "smtp_host", "SMTP Host"),
ConfigField("SMTP", "SMTP_PORT", "smtp_port", "SMTP Port"),
ConfigField("SMTP", "SMTP_USERNAME", "smtp_username", "SMTP Username"),
ConfigField("SMTP", "SMTP_PASSWORD", "smtp_password", "SMTP Password", secret=True),
ConfigField("SMTP", "SMTP_FROM_NAME", "smtp_from_name", "SMTP From Name"),
ConfigField("SMTP", "SMTP_FROM_ADDRESS", "smtp_from_address", "SMTP From Address"),
ConfigField("SMTP", "SMTP_TO_ADDRESS", "smtp_to_address", "SMTP To Address"),
ConfigField("SMTP", "SMTP_USE_STARTTLS", "smtp_use_starttls", "SMTP Use STARTTLS", input_type="checkbox"),
ConfigField(
"Authentication",
"AUTH_SESSION_COOKIE_NAME",
@@ -40,6 +49,13 @@ CONFIG_FIELDS: tuple[ConfigField, ...] = (
"auth_cookie_secure_override",
"Cookie Secure Override",
),
ConfigField(
"Authentication",
"AUTH_LOGIN_THROTTLE_ENABLED",
"auth_login_throttle_enabled",
"Login Throttle Enabled",
input_type="checkbox",
),
ConfigField("Poo", "POO_WEBHOOK_ID", "poo_webhook_id", "Poo Webhook ID", secret=True),
ConfigField(
"Poo",
@@ -87,6 +103,41 @@ CONFIG_FIELDS: tuple[ConfigField, ...] = (
"home_assistant_action_task_project_id",
"Home Assistant Action Task Project ID",
),
ConfigField("MQTT", "MQTT_ENABLED", "mqtt_enabled", "MQTT Enabled", input_type="checkbox"),
ConfigField("MQTT", "MQTT_BROKER_HOST", "mqtt_broker_host", "MQTT Broker Host"),
ConfigField("MQTT", "MQTT_BROKER_PORT", "mqtt_broker_port", "MQTT Broker Port", input_type="number"),
ConfigField("MQTT", "MQTT_USERNAME", "mqtt_username", "MQTT Username"),
ConfigField("MQTT", "MQTT_PASSWORD", "mqtt_password", "MQTT Password", secret=True),
ConfigField("MQTT", "MQTT_TLS_ENABLED", "mqtt_tls_enabled", "MQTT TLS Enabled", input_type="checkbox"),
ConfigField("MQTT", "MQTT_CLIENT_ID", "mqtt_client_id", "MQTT Client ID"),
ConfigField(
"Home Assistant Discovery",
"HA_DISCOVERY_ENABLED",
"ha_discovery_enabled",
"HA Discovery Enabled",
input_type="checkbox",
),
ConfigField(
"Home Assistant Discovery",
"HA_DISCOVERY_PREFIX",
"ha_discovery_prefix",
"HA Discovery Prefix",
),
ConfigField(
"Home Assistant Discovery",
"HA_STATE_TOPIC_PREFIX",
"ha_state_topic_prefix",
"HA State Topic Prefix",
),
ConfigField("Modbus", "MODBUS_POLLING_ENABLED", "modbus_polling_enabled", "Modbus Polling Enabled", input_type="checkbox"),
ConfigField(
"Tibber",
"TIBBER_API_TOKEN",
"tibber_api_token",
"Tibber API Token",
secret=True,
),
ConfigField("Tibber", "TIBBER_HOME_ID", "tibber_home_id", "Tibber Home ID"),
)
@@ -118,7 +169,7 @@ def sync_app_hostname_from_bootstrap(session: Session, bootstrap_settings: Setti
current_values["APP_HOSTNAME"] = bootstrap_hostname
_persist_config_values(session, current_values)
get_settings.cache_clear()
reset_auth_db_caches()
reset_db_caches()
def build_runtime_settings(session: Session, bootstrap_settings: Settings) -> Settings:
@@ -172,10 +223,15 @@ def save_config_updates(session: Session, form_data: dict[str, str], bootstrap_s
else:
merged_values[field.env_name] = submitted_value
_validate_config_values(merged_values, bootstrap_settings)
validated_settings = _validate_config_values(merged_values, bootstrap_settings)
# Persist the canonical client identity as well as using it at runtime. A
# whitespace-padded value must not survive in app_config and unexpectedly
# reappear in another consumer of the stored settings.
if "MQTT_CLIENT_ID" in merged_values:
merged_values["MQTT_CLIENT_ID"] = validated_settings.mqtt_client_id
_persist_config_values(session, merged_values)
get_settings.cache_clear()
reset_auth_db_caches()
reset_db_caches()
def save_config_value(
@@ -187,10 +243,12 @@ def save_config_value(
) -> None:
current_values = _read_config_values(session)
current_values[env_name] = value
_validate_config_values(current_values, bootstrap_settings)
validated_settings = _validate_config_values(current_values, bootstrap_settings)
if env_name == "MQTT_CLIENT_ID":
current_values[env_name] = validated_settings.mqtt_client_id
_persist_config_values(session, current_values)
get_settings.cache_clear()
reset_auth_db_caches()
reset_db_caches()
def is_ticktick_oauth_ready(settings: Settings) -> bool:
@@ -206,14 +264,14 @@ def _read_config_values(session: Session) -> dict[str, str]:
return {row.key: row.value for row in rows}
def _validate_config_values(config_values: dict[str, str], bootstrap_settings: Settings) -> None:
def _validate_config_values(config_values: dict[str, str], bootstrap_settings: Settings) -> Settings:
payload = _settings_payload(bootstrap_settings)
for field in CONFIG_FIELDS:
if field.env_name in config_values:
payload[field.setting_attr] = config_values[field.env_name]
try:
Settings(_env_file=None, **payload)
return Settings(_env_file=None, **payload)
except Exception as exc:
raise ConfigSaveError("invalid config submission") from exc
@@ -251,8 +309,6 @@ def _settings_payload(settings: Settings) -> dict[str, Any]:
"app_debug": settings.app_debug,
"app_hostname": settings.app_hostname,
"app_database_url": settings.app_database_url,
"location_database_url": settings.location_database_url,
"poo_database_url": settings.poo_database_url,
"ticktick_client_id": settings.ticktick_client_id,
"ticktick_client_secret": settings.ticktick_client_secret,
"ticktick_token": settings.ticktick_token,
@@ -260,6 +316,15 @@ def _settings_payload(settings: Settings) -> dict[str, Any]:
"home_assistant_auth_token": settings.home_assistant_auth_token,
"home_assistant_timeout_seconds": settings.home_assistant_timeout_seconds,
"home_assistant_action_task_project_id": settings.home_assistant_action_task_project_id,
"smtp_enabled": settings.smtp_enabled,
"smtp_host": settings.smtp_host,
"smtp_port": settings.smtp_port,
"smtp_username": settings.smtp_username,
"smtp_password": settings.smtp_password,
"smtp_from_name": settings.smtp_from_name,
"smtp_from_address": settings.smtp_from_address,
"smtp_to_address": settings.smtp_to_address,
"smtp_use_starttls": settings.smtp_use_starttls,
"poo_webhook_id": settings.poo_webhook_id,
"poo_sensor_entity_name": settings.poo_sensor_entity_name,
"poo_sensor_friendly_name": settings.poo_sensor_friendly_name,
@@ -268,4 +333,19 @@ def _settings_payload(settings: Settings) -> dict[str, Any]:
"auth_session_cookie_name": settings.auth_session_cookie_name,
"auth_session_ttl_hours": settings.auth_session_ttl_hours,
"auth_cookie_secure_override": settings.auth_cookie_secure_override,
"auth_login_throttle_enabled": settings.auth_login_throttle_enabled,
"auth_trust_forwarded_for": settings.auth_trust_forwarded_for,
"modbus_polling_enabled": settings.modbus_polling_enabled,
"mqtt_enabled": settings.mqtt_enabled,
"mqtt_broker_host": settings.mqtt_broker_host,
"mqtt_broker_port": settings.mqtt_broker_port,
"mqtt_username": settings.mqtt_username,
"mqtt_password": settings.mqtt_password,
"mqtt_tls_enabled": settings.mqtt_tls_enabled,
"mqtt_client_id": settings.mqtt_client_id,
"ha_discovery_enabled": settings.ha_discovery_enabled,
"ha_discovery_prefix": settings.ha_discovery_prefix,
"ha_state_topic_prefix": settings.ha_state_topic_prefix,
"tibber_api_token": settings.tibber_api_token,
"tibber_home_id": settings.tibber_home_id,
}
+409
View File
@@ -0,0 +1,409 @@
"""Service layer for EnergyContract CRUD, versioning, and activation.
All functions accept an explicit SQLAlchemy Session; callers are responsible
for committing or rolling back the transaction.
Design decisions
----------------
- ``create_contract``: validates values against the pricing profile *before*
writing any rows; raises ``ProfileValidationError`` on non-compliance.
- ``add_version``: append-only; closes the previous open version by
setting its ``effective_to`` to the new version's ``effective_from``; raises
``ContractVersionError`` if the new date is strictly earlier than the previous
version's ``effective_from``.
- ``activate_contract``: scope-local mutual exclusion; sets other contracts in
the target scope inactive, then sets the given contract active.
- ``active_contract_version_at``: returns the single version of the currently
active contract that covers *ts* (``effective_from ts < effective_to``,
or open-ended when ``effective_to`` is None).
SQLite timezone note
--------------------
SQLite stores ``DateTime(timezone=True)`` columns as naive UTC strings; on
read-back they come out as **timezone-naive** datetimes. Wherever this code
compares timestamps from the DB against timezone-aware values (e.g. from
Pydantic or ``datetime.now(UTC)``), it calls ``_as_utc()`` to make both sides
comparable without tripping on "offset-naive vs offset-aware" TypeErrors.
"""
from __future__ import annotations
import logging
from datetime import UTC, datetime
from typing import Any
from sqlalchemy import select, update
from sqlalchemy.orm import Session
from app.integrations.pricing.profiles import validate_values
from app.models.energy import EnergyContract, EnergyContractVersion
logger = logging.getLogger(__name__)
# This is deliberately separate from the pricing-profile loader. T12 needs to
# reserve the thermal domain before T13 supplies its actual profile.
CONTRACT_KIND_SCOPES: dict[str, str] = {
"manual": "electricity",
"tibber": "electricity",
"district_heating": "thermal",
}
class ContractScopeError(ValueError):
"""Raised when a contract kind is unknown or its supplied scope disagrees."""
def contract_scope_for_kind(kind: str, requested_scope: str | None = None) -> str:
"""Return the registry-owned scope for *kind*, rejecting client mismatches."""
try:
scope = CONTRACT_KIND_SCOPES[kind]
except KeyError as exc:
raise ContractScopeError(f"Unknown energy contract kind: {kind!r}") from exc
if requested_scope is not None and requested_scope != scope:
raise ContractScopeError(
f"Contract kind {kind!r} belongs to scope {scope!r}, not {requested_scope!r}."
)
return scope
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
def _as_utc(dt: datetime) -> datetime:
"""Return *dt* as a timezone-aware UTC datetime.
SQLite's DateTime(timezone=True) column type stores datetimes as naive UTC
strings and gives them back as naive datetimes on read. This helper
re-attaches the UTC timezone info when it is missing, making cross-origin
comparisons safe.
"""
if dt.tzinfo is None:
return dt.replace(tzinfo=UTC)
return dt
# ---------------------------------------------------------------------------
# Custom exception
# ---------------------------------------------------------------------------
class ContractVersionError(ValueError):
"""Raised when a new contract version has an invalid effective date.
Specifically: the new version's ``effective_from`` must be greater than or
equal to the previous open version's ``effective_from``. Allowing equal
timestamps would cause ambiguous overlap; the service therefore also rejects
strictly-equal values (same second) to avoid silent data loss.
"""
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def get_contract_or_none(session: Session, contract_id: int) -> EnergyContract | None:
"""Return the contract with the given id, or None if not found."""
return session.execute(
select(EnergyContract).where(EnergyContract.id == contract_id)
).scalar_one_or_none()
def list_contracts(session: Session, *, scope: str = "electricity") -> list[EnergyContract]:
"""Return contracts in one scope, ordered by id (ascending)."""
return list(
session.execute(
select(EnergyContract)
.where(EnergyContract.scope == scope)
.order_by(EnergyContract.id)
).scalars().all()
)
def _open_version(session: Session, contract: EnergyContract) -> EnergyContractVersion | None:
"""Return the current open version (effective_to IS NULL) for *contract*, or None."""
return session.execute(
select(EnergyContractVersion)
.where(
EnergyContractVersion.contract_id == contract.id,
EnergyContractVersion.effective_to.is_(None),
)
.order_by(EnergyContractVersion.effective_from.desc())
.limit(1)
).scalar_one_or_none()
# ---------------------------------------------------------------------------
# Core service functions
# ---------------------------------------------------------------------------
def create_contract(
session: Session,
*,
name: str,
kind: str,
currency: str = "EUR",
scope: str | None = None,
values: dict[str, Any],
effective_from: datetime,
) -> EnergyContract:
"""Create a new energy contract with its first pricing version.
Parameters
----------
session:
Active SQLAlchemy session. Caller must commit after this returns.
name:
Human-readable label for the contract.
kind:
Pricing strategy identifier (``"manual"``, ``"tibber"``, or
``"district_heating"``).
currency:
ISO 4217 currency code (default ``"EUR"``).
values:
Pricing values dict conforming to the named profile's structure. The
district-heating profile normalises its Decimal-safe values to strings
before the JSON snapshot is stored.
Validated via ``validate_values(kind, values)`` before any writes.
effective_from:
UTC datetime at which the first pricing version takes effect.
Returns
-------
EnergyContract
The newly created contract (not yet committed).
Raises
------
ProfileNotFoundError
If no YAML profile exists for *kind*.
ProfileValidationError
If *values* does not conform to the profile structure.
"""
resolved_scope = contract_scope_for_kind(kind, scope)
# Validate (and fill defaults) before any DB write.
filled_values = validate_values(kind, values)
now = datetime.now(UTC)
contract = EnergyContract(
name=name,
kind=kind,
scope=resolved_scope,
currency=currency,
active=False, # New contracts are inactive; caller must explicitly activate.
created_at=now,
updated_at=now,
)
session.add(contract)
session.flush() # Assign contract.id so we can reference it in the version FK.
version = EnergyContractVersion(
contract_id=contract.id,
effective_from=effective_from,
effective_to=None,
values=filled_values,
created_at=now,
)
session.add(version)
logger.info("Created energy contract %r (kind=%s, id=%d)", name, kind, contract.id)
return contract
def add_version(
session: Session,
contract: EnergyContract,
*,
effective_from: datetime,
values: dict[str, Any],
) -> EnergyContractVersion:
"""Add a new pricing version to an existing contract (append-only).
The previous open version's ``effective_to`` is automatically set to the
new version's ``effective_from`` (version closure), ensuring there is never
a gap or overlap between consecutive versions.
The new ``effective_from`` **must be strictly greater than** the previous
open version's ``effective_from``. Equal timestamps are rejected because
they would produce two versions starting at the same instant, making it
impossible to determine which is current. If this constraint is not met,
``ContractVersionError`` is raised and **no rows are written**.
Parameters
----------
session:
Active SQLAlchemy session. Caller must commit after this returns.
contract:
The parent ``EnergyContract`` to append a version to.
effective_from:
UTC datetime at which this version's pricing takes effect.
values:
New pricing values dict conforming to the contract's profile.
Returns
-------
EnergyContractVersion
The newly created version (not yet committed).
Raises
------
ContractVersionError
If *effective_from* is not strictly after the previous open version's
``effective_from``.
ProfileNotFoundError
If no YAML profile exists for the contract's kind.
ProfileValidationError
If *values* does not conform to the profile structure.
"""
# Validate (and fill defaults) before any DB write.
filled_values = validate_values(contract.kind, values)
prev = _open_version(session, contract)
if prev is not None:
# Enforce strictly-after constraint to prevent ambiguous overlap.
# Use _as_utc() on both sides: the incoming value may be tz-aware
# while the DB-read value is tz-naive (SQLite limitation).
if _as_utc(effective_from) <= _as_utc(prev.effective_from):
raise ContractVersionError(
f"New version effective_from ({effective_from.isoformat()}) must be strictly "
f"after the previous open version's effective_from "
f"({prev.effective_from.isoformat()})."
)
# Close the previous open version.
prev.effective_to = effective_from
now = datetime.now(UTC)
new_version = EnergyContractVersion(
contract_id=contract.id,
effective_from=effective_from,
effective_to=None,
values=filled_values,
created_at=now,
)
session.add(new_version)
logger.info(
"Added version to contract id=%d (kind=%s, effective_from=%s)",
contract.id,
contract.kind,
effective_from.isoformat(),
)
return new_version
def activate_contract(session: Session, contract: EnergyContract) -> None:
"""Activate a contract with mutual exclusion.
Sets every other contract in the same scope inactive, then sets the given
contract active. This guarantees at most one active contract per scope.
Caller must commit after this returns.
"""
# This bulk update is a single write statement inside the caller's
# transaction. SQLite serializes writers, and another scope is never touched.
session.execute(
update(EnergyContract)
.where(EnergyContract.scope == contract.scope, EnergyContract.id != contract.id)
.values(active=False)
)
contract.active = True
contract.updated_at = datetime.now(UTC)
logger.info("Activated contract %r (id=%d)", contract.name, contract.id)
def deactivate_contract(session: Session, contract: EnergyContract) -> None:
"""Deactivate a contract without touching other contracts.
Caller must commit after this returns.
"""
contract.active = False
contract.updated_at = datetime.now(UTC)
logger.info("Deactivated contract %r (id=%d)", contract.name, contract.id)
def active_contract_versions(
session: Session, *, scope: str = "electricity"
) -> list[EnergyContractVersion]:
"""Return all versions of the currently active contract, ordered by effective_from ascending.
Returns an empty list when there is no active contract. The list spans the
full history of the active contract (all closed + the current open version)
and is used to iterate over pricing-rate segments for cross-version fixed-
cost / credit accumulation (Principle C).
"""
active = session.execute(
select(EnergyContract)
.where(EnergyContract.active.is_(True), EnergyContract.scope == scope)
.limit(1)
).scalar_one_or_none()
if active is None:
return []
return list(
session.execute(
select(EnergyContractVersion)
.where(EnergyContractVersion.contract_id == active.id)
.order_by(EnergyContractVersion.effective_from)
)
.scalars()
.all()
)
def active_contract_version_at(
session: Session, ts: datetime, *, scope: str = "electricity"
) -> EnergyContractVersion | None:
"""Return the active contract's version that covers *ts*.
A version covers *ts* when:
``effective_from ts`` AND (``effective_to IS NULL`` OR ``ts < effective_to``)
Returns None when:
- There is no active contract.
- The active contract has no version covering *ts*.
Parameters
----------
session:
Active SQLAlchemy session (read-only usage).
ts:
UTC datetime to look up.
Returns
-------
EnergyContractVersion | None
"""
active = session.execute(
select(EnergyContract)
.where(EnergyContract.active.is_(True), EnergyContract.scope == scope)
.limit(1)
).scalar_one_or_none()
if active is None:
return None
# Build a query for all versions of the active contract covering ts.
stmt = (
select(EnergyContractVersion)
.where(
EnergyContractVersion.contract_id == active.id,
EnergyContractVersion.effective_from <= ts,
)
.order_by(EnergyContractVersion.effective_from.desc())
.limit(1)
)
version = session.execute(stmt).scalar_one_or_none()
if version is None:
return None
# Exclude versions whose effective window has already closed before ts.
if version.effective_to is not None and _as_utc(ts) >= _as_utc(version.effective_to):
return None
return version

Some files were not shown because too many files have changed in this diff Show More