Files
MeterVault/README.md
T
Florian Schmidt 8940ef25c3
ci / build-test (push) Successful in 2m31s
Analysis: one selected period, one set of numbers, on every page
The dashboards told several stories at once. Overview asked for full
calendar years, meter detail for a fixed 12-month window that was really
13, Trends for 24 months with an Apply button, and the energy pages for
60. Each page derived "today" from UTC, so the first hours of a local day
belonged to yesterday. A missing tariff, a month nobody measured and a
genuine zero all rendered as 0. And a virtual meter -- the one thing the
spreadsheet leans on hardest -- was excluded from analysis outright:
MeterPeriodService returned null for it and the page offered a flow
diagram instead.

docs/DASHBOARD_ANALYSIS_CHANGE_BRIEF.md is the work order. Every choice it
left open is settled in docs/ANALYSIS_IMPLEMENTATION_NOTE.md as D-01..D-58
plus amendments A-01..A-30; code, tests and release notes cite those ids.

The analysis layer

Core/Analysis holds the pure rules: period presets resolved once in the
instance zone into a local date range and a half-open UTC range, bucket
plans, calendar-unit comparisons, coverage runs with a resolution class,
normalized quantities and units, the totals policy, the virtual formula
parser/validator/evaluator, and the cost calculator. "Now" comes from
TimeProvider; services never read the clock.

Normalization now writes, in the same transaction as consumption and by
diff, per-meter rollups by local day and month plus coverage runs and a
rollup state (AnalysisDataWriter). AnalysisReader answers a request from
those tables -- month rollups for month and year buckets, day rollups
otherwise, at most two partial edge days from consumption -- and
CostReader prices the result month by month. Pages, /api/v1 and the CSV
export read nothing else. The unused continuous aggregates are dropped.

The reader's statement count per request is constant whether it covers one
meter or a thousand. On a synthetic 1,000-meter, ten-year instance the
brief's target request (100 meters, ten years, monthly) takes 374 ms
against a two-second target, and the Overview went from 48,244 SQL
statements per load to 205.

Missing is not zero

Every bucket carries a status -- available, partial, missing, unresolved,
invalid, pending -- derived from coverage, never from the amount, with
provenance and a reason code beside it. A true zero is a number and a bar
on the baseline; an unknown bucket is a gap that says why; a month whose
data only exists monthly says so instead of inventing daily detail; a
scope with no tariff says "not priced" instead of 0. Rows whose interval
closes after now are reported separately rather than counted.

Virtual meters are analysis subjects

A virtual meter stores a canonical definition -- expression over m<id>
references, result kind, unit and cost rule -- validated on save and on
read for syntax, unknown or self references, loops and unit/kind rules.
It is evaluated on read from its sources' rollups over their joint
coverage: a missing source makes the bucket missing, an observed zero is
a valid input, a non-finite result is invalid with its dependency path,
and the page lists each source's contribution. Topology links are
topology only and never rewrite a saved calculation; expression-less
meters from older installs are converted once at startup. The editor has
Sum, Difference and Advanced modes with a live preview.

Totals and the bill

Per energy type the totals policy separates use, grid import, export,
generation and runtime, marks breakdown meters as breakdowns and virtual
meters as views, and never adds across units. The bill follows it: grid
import where there is one, separately priced subsections at their own
price, feed-in only on export meters, standing charges once per scope per
local day, manual costs once on their start day, categories as
non-overlapping covers whose composition reconciles to the bill. The
seeded demo's yearly totals now match the spreadsheet.

Pages and navigation

The period lives in the URL and every page reads the same contract, so a
link, a reload and the browser's Back button keep it. Shared components
carry it: page header with breadcrumbs, period toolbar, theme-aware chart
with an accessible table beside it, metric cards, comparison and
availability states, attention items that each link to the one action
that fixes them. Meter detail leads with an Analysis tab and resolves its
tabs by key; the energy page has Overview, History, Flow and Meters; the
old cost-only Trends page is a general Analysis page over portfolio, type,
category, meter or a meter comparison. Records tabs are paged server-side
instead of showing the latest 200. Everything is English and German,
light and dark, down to 360px.

Some figures change on purpose; docs/RELEASE_NOTES.md lists each one and
what the first start after the update does (it rebuilds all analysis data
before the web server listens). docs/SDD.md and CLAUDE.md describe the
system as it now is.

Tests: 1,733 Core and 746 integration, all green, plus an opt-in
performance suite with a synthetic 1,000-meter generator.
2026-09-20 10:29:13 +02:00

229 lines
15 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# MeterVault
A self-hosted, local-first **energy & utility metering platform**. MeterVault pulls meter data
from Home Assistant, Tasmota and raw MQTT on a schedule, stores every reading timestamped and
immutable, normalizes it into consumption, and turns it into cost dashboards. Energy types
(electricity, water, heating oil, gas, district heat, …) and meters are **user-defined — nothing
is hardcoded**.
Successor to a hand-maintained *Energiebilanz* spreadsheet. See [`docs/SDD.md`](docs/SDD.md) for the
full design.
## Features
- **Automatic ingestion** from MQTT/Tasmota (persistent subscriptions) and Home Assistant (REST
poll or push), plus manual entry, a REST push API, and CSV import.
- **Immutable raw readings** on a TimescaleDB hypertable; a normalized, append-only **consumption**
layer on top — reproducible, auditable.
- **Seven measurement modes** (cumulative/generation registers, burner runtime, tank/consumable,
direct delta, instant rate, virtual). Handles meter swaps, counter resets and tank dip-sticks with
calibration.
- **Virtual meters** with a validated formula over other meters: sum, difference or free formula,
e.g. `Solar 1 + Solar 2`, or self-consumption as `Haus Netz`. They are analysed exactly like
physical meters: history, comparisons, source contributions, and costs where a cost rule applies.
They are computed from their sources on every read, so they never go stale. A missing source month
reads "no data", never a silent zero.
- **Tariff engine** with time-ranged price history (unit/base/feed-in), scoped global / per type /
per meter. The bill counts each energy type's grid import (or its household use), not every meter
that happens to exist. Standing charges are counted once per scope. **Cost categories** are
decoupled from energy types. Meterless manual costs are supported. The currency is configurable.
- **Rollups by local day and month**, written together with the consumption, so dashboards never
scan raw readings. The Settings page shows how far each meter's analysis data is built.
- **One period everywhere**: every page shares a period toolbar (month to date, last month, year
to date, previous year, last 12/24 months, all history, custom dates), a bucket size (day, week,
month or year) and a comparison (previous period, previous year, or any calendar year). The
selection lives in the URL, so reload, Back and shared links keep it.
- **Pages:**
- **Overview** of the selected period: cost with its composition, one card per energy type,
history chart, "what changed", and attention items with a direct fix.
- **Analysis** page to explore the portfolio, an energy type, a cost category, one meter or up to
six meters side by side, by quantity or cost.
- **Energy type** pages with Overview, History, a **Sankey flow** of the meter chain, and a meter
list. A downstream meter is a *subsection* of an upstream one (main → car, pool, garden, …), and
the unmetered remainder is shown as "Other".
- A **meter hub** with tabs for Analysis, Readings, Normalized data, Events, Tariffs and Sources
(Calculation for virtual meters). The record tabs are paged over the full history.
- **Solar** (generation, self-consumption, feed-in, autarky, savings, with setup help for missing
meter roles) and **Tanks & consumables** (last dipstick, estimate now, deliveries, burner
runtime, forecast).
- **Honest numbers**: a true zero, missing data, data that is only monthly, and a missing price
are shown differently everywhere, in cards, charts, tables and the **CSV export** of any view.
- **Admin UI**: full create/edit/delete for energy types, meters (with a calculation editor and
live preview for virtual meters, friendly meter roles, and a recompute when a change needs one),
ingest sources, tariffs (unit check; "Add tariff" links from a missing price open the editor
prefilled), cost categories, and MQTT/Home-Assistant connectors. Includes a "Test connection" for
Home Assistant and an effective-settings view.
- English and German UI, light and dark theme, usable down to phone width.
- **REST API + OpenAPI/Swagger**, API-key auth, reverse-proxy trust (Authelia/Traefik).
- **JSON config export/import** for portability; Docker Compose + multi-arch image.
## Upgrading to 0.4.0
0.4.0 reworks the dashboards and how analysis and costs are computed. Read
[`docs/RELEASE_NOTES.md`](docs/RELEASE_NOTES.md) first: some figures change on purpose. Back up the
database (`pg_dump`), then start the new image once and let it finish:
- **The first start rebuilds every meter's analysis data** (normalization revision 3): consumption,
the new day/month rollups and coverage. This happens before the web server listens, so the app is
unreachable while it runs and Compose may report the container unhealthy. Let it finish rather
than killing it. The time grows with the number of raw readings: about 0.1 s per monthly meter,
~0.6 s per meter with ten years of daily readings, ~1.4 s per meter with a year of hourly
readings. A 1,000-meter test dataset (1.3 M readings) took about six minutes. Progress is logged,
and a meter that fails is retried at the next start.
- **Virtual meters without a formula** get the sum their links imply stored as an explicit formula.
The log names the meters converted and those that still need configuration.
- **The bill changes**: the grid meter is billed instead of every meter of a type, feed-in is
credited only on a grid-export meter, a missing tariff is "not priced" instead of 0, and standing
charges count once per scope. The seeded demo now matches the spreadsheet's yearly costs.
- **The REST API only adds fields**: see the release notes for `costStatus`, `costAvailability`,
`costRule`, `notCosted`, `missingPrices`, `status` and `latestMonth`.
- **Rolling back** to 0.3.0: the old version ignores the new tables and never read the dropped
continuous aggregates. Consumption stays as 0.4.0 booked it until each meter next ingests a
reading. Stored virtual-meter formulas remain; 0.3.0 ignores them and sums links again.
## Upgrading to 0.3.0
This release changes where consumption lands. Back the database up first (`pg_dump`), then start the
new image once and let it finish:
- **The first start re-derives all stored consumption** before the web server listens. The app is
unreachable while it runs (Compose may report the container unhealthy after ~105 s) — let it finish
rather than killing it. Progress and any meter it could not rebuild are logged.
- **Figures change once.** Consumption between two readings is now attributed to the months it
accrued in instead of landing entirely on the later reading, so historical months and their costs
can shift; rows that had to be divided are marked *estimated*.
- **Imported monthly tables are marked as such** in place before anything is recomputed, so they keep
reconciling. If that step fails nothing is rebuilt and the whole upgrade simply runs again next
start.
- **Check the log once** for `had its dates auto-detected`: a CSV imported through the wizard with the
date format left on auto-detect is treated as a monthly table when all its rows sit on the 1st.
If such a sheet really was day-dated, revert that batch on `/import` and import it again with the
day format.
- **Rolling back** to 0.2.0 leaves the re-attributed consumption in place; it is re-derived under the
old rules only as each meter next ingests a reading.
## Quick start (Docker)
```bash
docker compose -f deploy/docker-compose.yml up -d
# open http://localhost:8760 → Import → "Load reference data" for a populated demo
# ...or start pre-populated: METERVAULT_SEED=true docker compose -f deploy/docker-compose.yml up -d
# API docs at http://localhost:8760/swagger
```
## Quick start (Proxmox VE LXC)
A community-scriptsstyle installer builds a self-contained LXC (Debian + PostgreSQL/TimescaleDB +
the app as a systemd service). Run **on the Proxmox host**:
```bash
bash -c "$(curl -fsSL https://git.finalfactory.de/FinalFactory/MeterVault/raw/branch/master/deploy/ct/metervault.sh)"
```
It asks the standard container questions, optionally loads the demo dataset, and prints the URL
(`http://<ct-ip>:8760`) plus the generated DB password. Re-run `update` inside the container to pull
the latest source and rebuild. It builds from this public Gitea repo (there is no prebuilt tarball —
releases ship as a container image). See [`deploy/ct/metervault.sh`](deploy/ct/metervault.sh) and
[`deploy/install/metervault-install.sh`](deploy/install/metervault-install.sh).
Configuration is via environment variables (`Section__Key` double-underscore mapping), e.g.:
| Variable | Purpose |
|----------|---------|
| `ConnectionStrings__Default` | PostgreSQL/Timescale connection string |
| `MeterVault__TimeZone` | IANA timezone for buckets, display **and month attribution** (default `Europe/Berlin`). Changing it re-derives every meter's stored consumption at the next start, and historical monthly figures can shift. It must be an id both .NET and PostgreSQL know; anything else falls back to UTC and is reported in the log. |
| `MeterVault__Locale` | Default UI language, `en` or `de` (default `en`). Each visitor can switch it from the app bar; the choice is remembered in a cookie. |
| `MeterVault__Currency` | Currency code of every amount (default `EUR`). Tariffs in another currency are reported as not fitting, never converted. |
| `MeterVault__RawRetentionDays` | Shown on the Settings page but **not enforced**: raw readings are kept, because every recompute rebuilds a meter from them. |
| `MeterVault__ApiKeys__0` | An API key accepted on the `X-Api-Key` header |
| `MeterVault__AllowAnonymousApi` | `true` to open the REST API without a key (trusted LAN only) |
| `MeterVault__ReverseProxyTrust` | `true` to honour `X-Forwarded-User` behind an auth proxy |
| `MeterVault__EnableLiveIngestion` | `false` to disable the MQTT/HA workers |
| `MeterVault__SeedReferenceData` | `true` to load the bundled demo dataset on first start (idempotent) |
| `MeterVault__DataProtectionKeyPath` | Where the key ring for UI-entered connector secrets lives (default `/var/lib/metervault/keys`) |
| `MeterVault__UpdateCheckEnabled` | `false` to stop the dashboard checking for a newer release |
| `MeterVault__AllowInAppUpdate` | `true` to allow updates triggered from the UI/API — no key required, so anything that can reach MeterVault can trigger one; see below |
| `MeterVault__UpdateCheckUrl` | Tag listing consulted by that check (repoint at a fork; blank also disables it) |
The REST API is **closed by default**: with no `ApiKeys` configured and `AllowAnonymousApi` off, it
returns 401. Set at least one API key (or open it explicitly for a trusted network).
> **The web UI has no authentication.** There is no login: anything that can reach the port can read
> and change everything, including connectors and their stored secrets. Put it behind a reverse proxy
> with auth (Authelia, Traefik forward-auth, …) — `MeterVault__ReverseProxyTrust` then honours the
> user header — or keep it on a trusted network.
The dashboard compares the running build against the newest tag in the source repository and shows a
banner when it is behind. That is a plain GET of a public tag list — nothing about the instance is
sent — cached for six hours, and it never blocks or fails a page render. Turn it off with
`MeterVault__UpdateCheckEnabled=false`.
### Updating from the UI (opt-in)
`MeterVault__AllowInAppUpdate=true` adds an **Update now** button to that banner, and a
`POST /api/v1/system/update` endpoint for scripting it from Home Assistant or `curl`:
```bash
curl -X POST http://metervault:8760/api/v1/system/update -H "X-MeterVault-Update: 1"
```
Both pull the latest source, rebuild, and restart the service — a few minutes during which MeterVault
is unavailable. Readings are untouched; ingestion resumes on restart. LXC only: containers are
replaced by pulling a new image, and the endpoint reports that rather than pretending.
> **That flag is the whole gate — there is no key and no prompt.** With it on, anything that can
> reach MeterVault can trigger a rebuild and restart. Realistically that is a repeatable denial of
> service (minutes of downtime and a busy CPU per request), not code injection, because the build
> comes from your own repository — but it becomes remote code execution if that repository is ever
> compromised. It defaults off. Enable it only on a network you trust, or behind an authenticating
> proxy.
>
> The `X-MeterVault-Update` header is **not** authentication: it stops a *different website* driving
> the endpoint through the browser of someone on your network, which a plain HTML form could
> otherwise do. The UI button does not need it — it runs over the Blazor circuit, which a foreign
> page cannot reach. Every triggered update is logged as a warning, since with no key there is no
> caller to attribute it to.
Secrets (broker/HA tokens) are **never** stored in the database as plaintext. Each connector picks
one of two forms: the *name* of an environment variable, resolved at runtime, or the secret typed
into the admin UI and encrypted at rest under the data-protection key ring. Either way a `pg_dump`
or JSON export carries nothing usable.
Keep the key ring on persistent storage outside the app directory — the default
`/var/lib/metervault/keys` survives an LXC update, and the Compose file mounts a named volume for it.
Lose it and every UI-entered secret must be re-entered. The key ring is on disk, so this protects
against leaked database content, not against an attacker who already has the host; that is the same
trust boundary an environment variable has.
## Pushing readings (Home Assistant)
```bash
curl -X POST http://localhost:8760/api/v1/readings \
-H "X-Api-Key: $METERVAULT_API_KEY" -H "Content-Type: application/json" \
-d '[{"meterId": 1, "time": "2026-01-01T12:00:00Z", "value": 47200}]'
```
See [`docs/wiring.md`](docs/wiring.md) for wiring up Tasmota, MQTT and Home Assistant.
## Development
```bash
dotnet build
dotnet test # integration tests spin a TimescaleDB via Testcontainers (needs Docker)
dotnet test tests/Core.Tests # fast unit tests, no Docker
dotnet run --project src/App
```
Architecture, project layout and conventions live in [`CLAUDE.md`](CLAUDE.md).
## Releasing
Edit the [`VERSION`](VERSION) file on `master`; Gitea Actions tags `vX.Y.Z` and builds/pushes a
multi-arch image to the Gitea container registry (`.gitea/workflows/`). Locally:
`pwsh deploy/build-and-push.ps1 -Registry git.finalfactory.de -Image finalfactory/metervault -Push`.
Requires a Docker-capable `act_runner`; the image build itself is self-contained.
## License
Not yet chosen (see SDD §14). Add a `LICENSE` before the first public tag.