diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3f36ba6..7de7733 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,7 +72,9 @@ jobs: frontend: name: Frontend - runs-on: ubuntu-latest + # Pinned: Playwright 1.56.1 cannot install Chromium on the ubuntu-latest image + # (ubuntu 26.04, "Playwright does not support chromium on ubuntu26.04-x64"). + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v5 with: diff --git a/README.md b/README.md index 8d7526d..b7bfe4c 100644 --- a/README.md +++ b/README.md @@ -4,18 +4,20 @@ planner and a real-time surplus controller in one app – explainable, safe by default, set up in minutes.** -> Status: **pre-alpha, Phase 3 implemented** (waiting for the maintainer's -> shadow-mode test on real hardware). The beta app has a guided **setup -> assistant**, a device template gallery (LG ThinQ air conditioner, generic -> switch, climate and adjustable load, water heaters, Tibber, Solcast), the live -> energy-flow view and a **real-time surplus controller** with a safety layer: -> priorities, hysteresis, minimum run times, no grid import caused by SunCore, -> respect for manual changes, an emergency stop, and a "Why?" and decision log -> for every decision. Everything starts in **shadow mode** and switches nothing -> until you set a device to automatic; the controller has never run against real -> hardware yet. Forecasts, planner and battery control follow in Phase 4. See -> [Surplus control](docs/user/en/surplus-control.md), the -> [roadmap](docs/roadmap.md) and [status](docs/STATUS.md). +> Status: **pre-alpha, Phase 4 implemented** (waiting for the maintainer's shadow-mode +> tests on real hardware: first Phase 3, then Phase 4). The beta app has a guided **setup +> assistant**, a device template gallery (LG ThinQ air conditioner, generic switch, climate and +> adjustable load, water heaters, Tibber, Nord Pool, ENTSO-E, EPEX Spot, Octopus Energy, Solcast, +> Forecast.Solar, Open-Meteo Solar Forecast, battery adapters), the live energy-flow view, a +> **real-time surplus controller** and, new in Phase 4, **forecasts, tariffs, a 48 hour planner +> and battery control**: a plan with a reason for every interval, a risk level and buffers, and +> limits on your home battery (generic Home Assistant entities, Kostal Plenticore), all behind a +> safety layer. Everything starts in **shadow mode** and switches or writes nothing until you +> set a device or the battery to automatic or assisted; neither the controller nor the planner +> and battery control have run against real hardware yet. See +> [Planning and battery control](docs/user/en/planning-and-battery.md), +> [Surplus control](docs/user/en/surplus-control.md), the [roadmap](docs/roadmap.md) and +> [status](docs/STATUS.md). ![SunCore "Now" view: live energy flow between solar, grid, battery and house](docs/assets/screenshots/now-tablet-light-en.png) @@ -68,6 +70,8 @@ young: see the roadmap. [Schnellstart](docs/user/de/quick-start.md) - [Surplus control](docs/user/en/surplus-control.md) · [Überschusssteuerung](docs/user/de/surplus-control.md) +- [Planning and battery control](docs/user/en/planning-and-battery.md) · + [Planung und Akkusteuerung](docs/user/de/planning-and-battery.md) - [Contribute a device template](docs/user/en/device-templates.md) · [Compatibility list](docs/user/compatibility.md) - [Roadmap](docs/roadmap.md) · [Status](docs/STATUS.md) @@ -79,8 +83,9 @@ young: see the roadmap. Once the first beta is released, add `https://github.com/pxljake/suncore` as an app repository in Home Assistant (Settings → Apps → App store → menu → Repositories) and install **SunCore (beta)**. The beta guides you through -the setup, shows the live energy flow and runs the surplus controller in shadow -mode; there are no forecasts or planner yet. +the setup, shows the live energy flow, runs the surplus controller, the planner and +the battery control in shadow mode and lets you take them to assisted and automatic +one step at a time. Start with the [quick start](docs/user/en/quick-start.md) ([Deutsch](docs/user/de/quick-start.md)). Menu names differ between Home Assistant versions (older ones say "Add-ons" and "Add-on store"). diff --git a/addon/suncore/DOCS.md b/addon/suncore/DOCS.md index bcc3048..df73540 100644 --- a/addon/suncore/DOCS.md +++ b/addon/suncore/DOCS.md @@ -3,33 +3,64 @@ Energy management for Home Assistant: forecasts, a cost-optimising planner and a real-time surplus controller in one app. -## What SunCore does today (Phase 3) +## What SunCore does today (Phase 4) SunCore is **pre-alpha**. This version helps you describe your installation, -shows your energy flow live and can distribute your solar surplus to devices: +shows your energy flow live, distributes your solar surplus to devices, plans +the next 48 hours and can set limits on your home battery: - **Setup assistant**: ten steps for region, Energy dashboard import, grid, - solar, battery, tariff, devices, priorities and goals, operating mode and - a system check. Entities are detected and ranked, and a live sign check + solar (with forecast sources), battery (adapter, model, strategy, risk + level), tariff (price formula, HT/NT), devices, priorities and goals (grid + charging, self-sufficiency weight), operating mode and a system check with a + first plan preview. Entities are detected and ranked, and a live sign check catches inverted sensors. - **Device templates** (LG ThinQ air conditioner, generic switch, climate and - adjustable load, Tibber, Solcast, regions) with a gallery; see the + adjustable load, water heaters, Tibber, Nord Pool, ENTSO-E, EPEX Spot, + Octopus Energy, Solcast, Forecast.Solar, Open-Meteo Solar Forecast, battery + adapters for generic entities and Kostal Plenticore, regions) with a gallery; + see the [compatibility list](https://github.com/pxljake/suncore/blob/main/docs/user/compatibility.md). +- **Forecasts**: several solar forecast sources blended by their measured + accuracy, a bias calibration that becomes active after 30 days, clipping + recognised, a load forecast learnt from Home Assistant's statistics (base + load without the controlled devices, workday and weather inputs), and an + accuracy panel. +- **Tariffs**: dynamic prices from Tibber, Nord Pool, ENTSO-E, EPEX Spot and + Octopus Energy, fixed and HT/NT prices, a price formula for spot prices, + fixed, tiered or no feed-in remuneration and the negative-price rule of the + region. +- **Planner**: a 48 hour plan in 15 minute steps, recomputed every 15 minutes + and on events, with an optimiser (HiGHS) and a rule-based fallback, a risk + level (cautious by default: targets met in about 9 of 10 cases), morning + buffer, evening target, bridging a poor next day, strategies + (self-consumption, keep the battery as full as possible, target by a time), + optional grid charging (off by default) and a reason for every interval + ("Why?"). The **Plan** view shows it. +- **Battery control**: through adapters (generic Home Assistant entities, + Kostal Plenticore through the core integration, Kostal Plenticore G3 through + Modbus) SunCore sets **limits only**, never power set-points, behind the + safety layer with read-back, release to the inverter's own control, respect + for manual changes and the effective reserve. The battery starts in **shadow + mode**; the Kostal Modbus adapter is capped at assisted until the inverter's + fallback timer has been measured. - **Live energy flow** between solar, grid, battery and house. - **Surplus control** every 5 seconds: free surplus by priority, with hysteresis, minimum run and pause times and smoothing against cloud flicker, and no grid import caused by SunCore. Climate units get their set-point shifted inside your comfort band; switches, adjustable loads and stepped water - heaters (simulator only) follow the surplus. -- **Shadow mode is the default**, for the whole system and for every new - device: SunCore only logs what it *would have* done. A device is controlled - only after you set the overall mode **and** the device to automatic (or to - assisted, where you confirm every action). + heaters (simulator only) follow the surplus. The plan sets bands (battery + first until the morning buffer) that the controller follows. +- **Shadow mode is the default**, for the whole system, for every new device + and for the battery: SunCore only logs what it *would have* done. A device + or the battery is controlled only after you set the overall mode **and** its + own mode to automatic (or to assisted, where you confirm every action). - **Safety layer**: invariants, manual changes are respected, watchdogs, - hand-back of devices on shutdown, crash recovery and connection loss, and a - persisted **Emergency stop** in the header of every view. -- **"Why?" and decision log**: every decision has its reasons in plain - language. + hand-back of devices and the battery on shutdown, crash recovery and + connection loss, and a persisted **Emergency stop** in the header of every + view. +- **"Why?" and decision log**: every decision and every plan interval has its + reasons in plain language. - Values that are outdated, unavailable or invalid are marked as such instead of being guessed. @@ -84,6 +115,20 @@ for you if not. On a sunny day with a charging battery, PV must be positive and the battery arrow must point into the battery. Power sensors in W and kW are understood; other units are rejected rather than guessed. +## Planning and battery control + +Forecasts, tariffs, how the plan is made, risk levels and buffers, grid +charging, the battery modes, the adapters (including how to enable the Kostal +`Battery:MinSoc` entity and how to measure the Kostal Modbus fallback timer), +a walk-through for your first battery in assisted mode and the known +limitations are in +[Planning and battery control](https://github.com/pxljake/suncore/blob/main/docs/user/en/planning-and-battery.md) +([Deutsch](https://github.com/pxljake/suncore/blob/main/docs/user/de/planning-and-battery.md)). +Short version: keep everything in shadow mode first, read the **Plan** view for +a day or two, then switch the battery to **assisted** and confirm the first +proposals yourself. Planner and battery control have never run against real +hardware yet; the guide lists what is unverified. + ## Surplus control How the controller decides, the three operating modes, what happens when you @@ -122,9 +167,13 @@ Some timing and budget settings of the price service and the planner are not app With `demo_mode` switched on, SunCore does not read your entities. A simulated house (a sunny summer day) feeds the panel, a banner says "Demo -mode", and nothing from your installation is used or modified. Use it to -look around, to take screenshots or to report a UI problem. Switch it off -again and restart to see your own data. +mode", and nothing from your installation is used or modified. The demo +includes simulated prices, solar forecasts and a plan. Use it to look around, +to take screenshots or to report a UI problem. Switch it off again and restart +to see your own data. Experts can also set `SUNCORE_DEMO_START_TIME` (time of +day the demo starts, default `10:00`) and `SUNCORE_DEMO_BATTERY_CONTROL=1` +(gives the simulated house a controllable inverter, so the battery card can be +tried; off by default). ## Troubleshooting @@ -144,6 +193,9 @@ again and restart to see your own data. connection to SunCore; it retries automatically. - **"Access denied. Open SunCore from Home Assistant."**: use the sidebar entry; direct access to the app's port is blocked on purpose. +- **No plan, a rule-based plan, a stale plan, a spot price without a formula**: + see the troubleshooting section of + [Planning and battery control](https://github.com/pxljake/suncore/blob/main/docs/user/en/planning-and-battery.md#9-troubleshooting). - **Logs**: the app's **Log** tab. Set `log_level` to `debug` for more detail and attach the log when you report a problem. Tokens are redacted. - **Health**: the app serves `/health` internally; Home Assistant uses it @@ -153,8 +205,14 @@ again and restart to see your own data. ## What is not there yet -No forecasts, planner, history charts or tariff prices in use (they are -only stored), no battery or inverter control, no charge point (wallbox) +Nothing of the planner and the battery control has run on real hardware yet. +Kostal Plenticore cannot be told to charge from the grid (the plan only shows +it), and a Kostal Modbus battery stays capped at assisted mode until you have +measured the inverter's fallback timer. There are no history charts, what-if +analysis or backtesting (the plan view is minimal), no machine-learning load +model, no built-in internet fallbacks for solar forecasts and prices, no thermal +models for air conditioners and water heaters in the plan, no export limiting +through the inverter, no charge point (wallbox), heat pump or shiftable program control, and no Home Assistant entities (MQTT discovery follows in a later phase; the Mosquitto app is not needed yet). See the [roadmap](https://github.com/pxljake/suncore/blob/main/docs/roadmap.md). @@ -162,7 +220,8 @@ phase; the Mosquitto app is not needed yet). See the ## Privacy SunCore runs locally. It needs no account, sends no telemetry and makes no -cloud requests of its own in this version. Your configuration stays in the app's +cloud requests of its own: forecasts and prices come from the integrations you +already run in Home Assistant. Your configuration stays in the app's `/data` folder. ## Support diff --git a/addon/suncore_beta/DOCS.md b/addon/suncore_beta/DOCS.md index 76c640b..050bca1 100644 --- a/addon/suncore_beta/DOCS.md +++ b/addon/suncore_beta/DOCS.md @@ -6,33 +6,64 @@ and a real-time surplus controller in one app. > This is the **beta channel**. It receives new versions earlier than the > stable app and may contain bugs. Please report what you find. -## What SunCore does today (Phase 3) +## What SunCore does today (Phase 4) SunCore is **pre-alpha**. This version helps you describe your installation, -shows your energy flow live and can distribute your solar surplus to devices: +shows your energy flow live, distributes your solar surplus to devices, plans +the next 48 hours and can set limits on your home battery: - **Setup assistant**: ten steps for region, Energy dashboard import, grid, - solar, battery, tariff, devices, priorities and goals, operating mode and - a system check. Entities are detected and ranked, and a live sign check + solar (with forecast sources), battery (adapter, model, strategy, risk + level), tariff (price formula, HT/NT), devices, priorities and goals (grid + charging, self-sufficiency weight), operating mode and a system check with a + first plan preview. Entities are detected and ranked, and a live sign check catches inverted sensors. - **Device templates** (LG ThinQ air conditioner, generic switch, climate and - adjustable load, Tibber, Solcast, regions) with a gallery; see the + adjustable load, water heaters, Tibber, Nord Pool, ENTSO-E, EPEX Spot, + Octopus Energy, Solcast, Forecast.Solar, Open-Meteo Solar Forecast, battery + adapters for generic entities and Kostal Plenticore, regions) with a gallery; + see the [compatibility list](https://github.com/pxljake/suncore/blob/main/docs/user/compatibility.md). +- **Forecasts**: several solar forecast sources blended by their measured + accuracy, a bias calibration that becomes active after 30 days, clipping + recognised, a load forecast learnt from Home Assistant's statistics (base + load without the controlled devices, workday and weather inputs), and an + accuracy panel. +- **Tariffs**: dynamic prices from Tibber, Nord Pool, ENTSO-E, EPEX Spot and + Octopus Energy, fixed and HT/NT prices, a price formula for spot prices, + fixed, tiered or no feed-in remuneration and the negative-price rule of the + region. +- **Planner**: a 48 hour plan in 15 minute steps, recomputed every 15 minutes + and on events, with an optimiser (HiGHS) and a rule-based fallback, a risk + level (cautious by default: targets met in about 9 of 10 cases), morning + buffer, evening target, bridging a poor next day, strategies + (self-consumption, keep the battery as full as possible, target by a time), + optional grid charging (off by default) and a reason for every interval + ("Why?"). The **Plan** view shows it. +- **Battery control**: through adapters (generic Home Assistant entities, + Kostal Plenticore through the core integration, Kostal Plenticore G3 through + Modbus) SunCore sets **limits only**, never power set-points, behind the + safety layer with read-back, release to the inverter's own control, respect + for manual changes and the effective reserve. The battery starts in **shadow + mode**; the Kostal Modbus adapter is capped at assisted until the inverter's + fallback timer has been measured. - **Live energy flow** between solar, grid, battery and house. - **Surplus control** every 5 seconds: free surplus by priority, with hysteresis, minimum run and pause times and smoothing against cloud flicker, and no grid import caused by SunCore. Climate units get their set-point shifted inside your comfort band; switches, adjustable loads and stepped water - heaters (simulator only) follow the surplus. -- **Shadow mode is the default**, for the whole system and for every new - device: SunCore only logs what it *would have* done. A device is controlled - only after you set the overall mode **and** the device to automatic (or to - assisted, where you confirm every action). + heaters (simulator only) follow the surplus. The plan sets bands (battery + first until the morning buffer) that the controller follows. +- **Shadow mode is the default**, for the whole system, for every new device + and for the battery: SunCore only logs what it *would have* done. A device + or the battery is controlled only after you set the overall mode **and** its + own mode to automatic (or to assisted, where you confirm every action). - **Safety layer**: invariants, manual changes are respected, watchdogs, - hand-back of devices on shutdown, crash recovery and connection loss, and a - persisted **Emergency stop** in the header of every view. -- **"Why?" and decision log**: every decision has its reasons in plain - language. + hand-back of devices and the battery on shutdown, crash recovery and + connection loss, and a persisted **Emergency stop** in the header of every + view. +- **"Why?" and decision log**: every decision and every plan interval has its + reasons in plain language. - Values that are outdated, unavailable or invalid are marked as such instead of being guessed. @@ -87,6 +118,20 @@ for you if not. On a sunny day with a charging battery, PV must be positive and the battery arrow must point into the battery. Power sensors in W and kW are understood; other units are rejected rather than guessed. +## Planning and battery control + +Forecasts, tariffs, how the plan is made, risk levels and buffers, grid +charging, the battery modes, the adapters (including how to enable the Kostal +`Battery:MinSoc` entity and how to measure the Kostal Modbus fallback timer), +a walk-through for your first battery in assisted mode and the known +limitations are in +[Planning and battery control](https://github.com/pxljake/suncore/blob/main/docs/user/en/planning-and-battery.md) +([Deutsch](https://github.com/pxljake/suncore/blob/main/docs/user/de/planning-and-battery.md)). +Short version: keep everything in shadow mode first, read the **Plan** view for +a day or two, then switch the battery to **assisted** and confirm the first +proposals yourself. Planner and battery control have never run against real +hardware yet; the guide lists what is unverified. + ## Surplus control How the controller decides, the three operating modes, what happens when you @@ -125,9 +170,13 @@ Some timing and budget settings of the price service and the planner are not app With `demo_mode` switched on, SunCore does not read your entities. A simulated house (a sunny summer day) feeds the panel, a banner says "Demo -mode", and nothing from your installation is used or modified. Use it to -look around, to take screenshots or to report a UI problem. Switch it off -again and restart to see your own data. +mode", and nothing from your installation is used or modified. The demo +includes simulated prices, solar forecasts and a plan. Use it to look around, +to take screenshots or to report a UI problem. Switch it off again and restart +to see your own data. Experts can also set `SUNCORE_DEMO_START_TIME` (time of +day the demo starts, default `10:00`) and `SUNCORE_DEMO_BATTERY_CONTROL=1` +(gives the simulated house a controllable inverter, so the battery card can be +tried; off by default). ## Troubleshooting @@ -147,6 +196,9 @@ again and restart to see your own data. connection to SunCore; it retries automatically. - **"Access denied. Open SunCore from Home Assistant."**: use the sidebar entry; direct access to the app's port is blocked on purpose. +- **No plan, a rule-based plan, a stale plan, a spot price without a formula**: + see the troubleshooting section of + [Planning and battery control](https://github.com/pxljake/suncore/blob/main/docs/user/en/planning-and-battery.md#9-troubleshooting). - **Logs**: the app's **Log** tab. Set `log_level` to `debug` for more detail and attach the log when you report a problem. Tokens are redacted. - **Health**: the app serves `/health` internally; Home Assistant uses it @@ -156,8 +208,14 @@ again and restart to see your own data. ## What is not there yet -No forecasts, planner, history charts or tariff prices in use (they are -only stored), no battery or inverter control, no charge point (wallbox) +Nothing of the planner and the battery control has run on real hardware yet. +Kostal Plenticore cannot be told to charge from the grid (the plan only shows +it), and a Kostal Modbus battery stays capped at assisted mode until you have +measured the inverter's fallback timer. There are no history charts, what-if +analysis or backtesting (the plan view is minimal), no machine-learning load +model, no built-in internet fallbacks for solar forecasts and prices, no thermal +models for air conditioners and water heaters in the plan, no export limiting +through the inverter, no charge point (wallbox), heat pump or shiftable program control, and no Home Assistant entities (MQTT discovery follows in a later phase; the Mosquitto app is not needed yet). See the [roadmap](https://github.com/pxljake/suncore/blob/main/docs/roadmap.md). @@ -165,7 +223,8 @@ phase; the Mosquitto app is not needed yet). See the ## Privacy SunCore runs locally. It needs no account, sends no telemetry and makes no -cloud requests of its own in this version. Your configuration stays in the app's +cloud requests of its own: forecasts and prices come from the integrations you +already run in Home Assistant. Your configuration stays in the app's `/data` folder. ## Support diff --git a/docs/STATUS.md b/docs/STATUS.md index d351318..37e5046 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -3,11 +3,12 @@ Read this first in every session, then `CLAUDE.md` (once it exists) and the ADRs relevant to your task. Keep it short; history lives in git. -**Last update:** 2026-10-25 · **Phase:** 4 in progress – PR 4-A contracts, 4-B storage, 4-C -tariffs, 4-D PV forecast, 4-E load forecast and risk model, 4-F planner and runtime (WP8, WP9), -4-G battery control (WP10; UI and docs 4-H next); Phase 3 (3-A -`phase-3/a-safety`, 3-B `phase-3/b-controller`, 3-C `phase-3/c-ui`) implemented, waiting for the -maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4/f-planner`) +**Last update:** 2026-10-28 · **Phase:** 4 implemented in the stacked PRs 4-A (contracts), 4-B +(storage), 4-C (tariffs), 4-D (PV forecast), 4-E (load forecast and risk model), 4-F (planner and +runtime), 4-G (battery control) and 4-H (UI and docs, WP11 + WP13); only the optional 4-I (ML load +model) is open; waiting for the maintainer's acceptance on his system. Phase 3 (3-A `phase-3/a-safety`, +3-B `phase-3/b-controller`, 3-C `phase-3/c-ui`) is implemented, waiting for the maintainer's shadow +test · **Branch:** `phase-4/h-ui-docs` (stacked on `phase-4/g-battery`) ## Done @@ -28,7 +29,7 @@ maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4 `BatteryBand.priority_until_soc_pct`; v1 still loads); config `TariffConfig` v3, `ForecastConfig` v2, `goals` v2; template schema v1 additions (kind `battery`, `series`, HT/NT). - - ADR-0013 "Battery as a controlled asset" **proposed** (prerequisite of WP10). + - ADR-0013 "Battery as a controlled asset" **proposed** (prerequisite of WP10; accepted 2026-10-19). - Review fixes: in progress (`fix(...)` commits on the branch). - **Phase 4 – PR 4-B (WP3, storage and statistics; branch `phase-4/b-storage`, stacked on 4-A)**: @@ -149,6 +150,72 @@ maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4 value SunCore wrote or attempted while in control is taken for SunCore's and reset to the baseline at release (accepted by the reviewer). +- **Phase 4 – PR 4-H, WP13 docs, translations, STATUS (branch `phase-4/h-ui-docs`; `docs-writer`)**: + - User guide `docs/user//planning-and-battery.md` (en/de, same structure): the planner + (48 h, 15 min, every 15 min and on events, solver or rule-based fallback, "Why?"), forecasts + (sources, blending by measured accuracy, calibration after 30 days, clipping, accuracy panel, + Open-Meteo CC BY 4.0), load forecast (base load without controlled devices, workday/weather, + `days_offset`, 28 days from HA statistics), tariffs (price formula for spot prices only, tiered + feed-in, negative-price rule), risk level, morning buffer, evening target, bridging, strategies, + the self-sufficiency weight, grid charging, battery control (shadow, assisted, automatic, + limits only, effective reserve, release and hardware fallback, manual changes until 04:00 with + the documented corner case, emergency stop), adapters with the step-by-step enabling of the + Kostal `Battery:MinSoc` entity and a **procedure to measure the Kostal §3.5 fallback timer** + (with abort criteria), a "first battery to assisted" walk-through, troubleshooting, known + limitations. Screenshots `plan-*`, `now-battery-*`, `wizard-battery-*` from the demo. + - Quick start (steps 4, 5, 6, 8, 10, Now view, settings, "cannot do yet"), surplus control + (the plan sets bands, battery first until the morning buffer, your target is a floor, schema 4), + both app `DOCS.md` (Phase 4 features, planning section, demo variables, "not there yet"), + README status, architecture §4 (planner paragraph, deviation events), roadmap Phase 4 table. + - The generated compatibility list was already current (`scripts/gen_compat.py --check`). + Translations checked: the frontend catalogues have identical key sets (1311 keys), argument + names match, `scripts/check_reasons.py` is clean (383 backend keys), the app options + translations match `schema:` in both apps; no gaps found, nothing changed. + - Facts found while writing: a normal app stop **releases** the battery first, so measuring the + Kostal timer needs an abrupt end of the container (`docker kill`); `battery.fallback_measured` + has no switch in the panel (the guide uses export, edit, import). The gate caps only adapters + with the `hardware_fallback` capability (Kostal Modbus); the generic and Kostal REST adapters + are not capped (the card's "generic" cap note cannot appear). +- **Phase 4 – PR 4-H, part WP11 UI (branch `phase-4/h-ui-docs`, on 4-G; `frontend-engineer`)**: + - Plan view `#/plan` (own lazy chunk; ECharts 5.6 tree-shaken to line and bar series, grid, + tooltip, legend, markLine, inside zoom and the canvas renderer, its own `echarts` chunk that + is not reachable from `index.html`): three panels (power with the PV P10-P90 band and P50, + house load, battery power and grid import/export bars; planned SoC with morning-buffer and + evening-target lines; import/export price steps), 24/48 h toggle, tooltip with the reasons of + the interval, solver/heuristic/default and stale badges, "Replan" (debounced, server answer + `accepted`/earliest start shown), planner status (last run, trigger, next run, failures), a + text alternative (planned actions with "Why?", hourly table). "Now" is the server's + hand-over time (the demo runs on a simulated clock). + - Forecast panel: sources and their freshness, MAE/bias/n per source and horizon (collecting + chip below `min_samples`), blend weights with their basis, calibration state per source, "ML + load model: not available yet", Open-Meteo CC BY 4.0 attribution with links when an Open-Meteo + source is configured. + - Now view: battery card (mode switch with confirmation for assisted and automatic, identity + token like a device, SoC/power, held or current limits, paused reason, last decision, the + assisted cap note while the adapter's hardware fallback is not measured) and "next planned + actions" with "Why?"; battery proposals read like device proposals (limit parts). + - Wizard: step 4 several sources with weight mode and share, Forecast.Solar config entry + (choices from `energy/get_prefs`, additive field `solar_forecast_entries` of the + energy-prefs answer; manual id when none), workday and weather inputs (new site roles + `workday`, `weather`); step 5 adapter or observe only, adapter entities, Kostal REST and + Modbus hints, modbus link, model parameters, strategy, risk level, morning buffer, bridge; + step 6 HT/NT editor (`tou`, periods with weekdays, midnight windows and months), price + contents and price formula with time-variable grid fees; step 8 grid-charge policy (price + level and weekly schedule, off by default) and the self-sufficiency weight; step 10 first plan + preview. Settings overview shows sources and battery control and offers the battery section's + history. The tariff and forecast forms no longer drop `role_entities`, `action_params`, + `series_key`, `price_includes` and `config_entry_id` (round-trip tests). + - Demo: `SUNCORE_DEMO_BATTERY_CONTROL=1` gives the simulated house a controllable inverter and + stores a `generic.battery` adapter (used by Playwright and the screenshots); off by default. + - Not done: the "too-new `timeseries.db`" hint (the API exposes no such state), editing of + `action_params`/`series_key`, `learning` settings and the periodic calibration charge (carried + through unchanged), a mini chart in the summary beyond a sparkline. + - Verified (2026-10-28): `./scripts/check.sh` green (4654 pytest, coverage 96 %, 267 Vitest), + Playwright against the demo 228 passed on desktop, phone and tablet (axe on plan, Now and the + wizard steps), markdownlint clean. + - Bundle: first paint 119 kB gzip (was about 100 kB: the two catalogues grew by about 170 + keys), everything but ECharts 182 kB (budget 250 kB), ECharts chunk 177 kB on demand. + - **Phase 4 – PR 4-F, part WP8 planner (branch `phase-4/f-planner`, on 4-E merged with 4-C)**: - `suncore/planner/` (depends on `core` only; boundary test extended; `mypy --strict`): `inputs.py` (`build_inputs`: pure snapshot on the 15-minute grid now → +48 h from the @@ -563,9 +630,26 @@ maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4 (WP3) → 4-C tariffs (WP4) and 4-D PV forecast (WP5) → 4-E load + risk (WP6, WP7) → 4-F planner and runtime (WP8, WP9) → 4-G battery control (WP10) → 4-H frontend + docs (WP11, WP13); 4-I ML load (WP12, optional, after 4-E). Merge only after the Phase 3 acceptance. -- **WP10 done** (4-G, see Done); next: 4-H UI and docs (battery card with mode, identity and the - assisted cap; wizard step for the battery adapter incl. enabling the Kostal number and the modbus - YAML; WP13 docs). ADR-0013 file still says "proposed" - record the maintainer's acceptance. +- **WP10, WP11 and WP13 done** (4-G and 4-H, see Done). All Phase 4 PRs are open and stacked; merge + order **#25 → #26 → #27/#29 → #30 → #31 → #33 → 4-H** (merge commits are fine; **squash is + recommended**, one commit per PR on `main`), **only after the Phase 3 acceptance** (plan §6). + ADR-0013 accepted by the maintainer on 2026-10-19. Open: 4-I (optional ML load model), and the + follow-ups below. +- **Safety note:** the documented fallback-timer measurement lifts the assisted cap (via + `fallback_measured`); the procedure gets a `control-safety` review (the lead runs it). It needs + the app's Watchdog switch off, otherwise the Supervisor restarts the killed app and SunCore itself + releases and writes within the 60 s (false positive); Supervisor behaviour read in the source, + `UNVERIFIED` on HA OS. +- **Calibration charge:** only a configuration field so far, the planner does not use it (plan §6 + question 11 said "built"; corrected in the plan's deviations). Open. +- **S1 (code, separate PR):** bind `fallback_measured` to the measured `fallback_timeout_s` (store + the measured timeout, the gate caps unless equal); needs an ADR-0013 addendum and a gate test. + The `control-safety` review of the measurement procedure approved it with changes R1-R7, applied + in the guide (2026-10-29). +- Follow-ups from 4-H and the docs: `fallback_timeout_s` changes should drop the battery mode to + shadow on the server (follows); a switch for `battery.fallback_measured` in the panel (today: + export, edit, import), a hint for a too-new `timeseries.db` (the API exposes no such state), the + panel for editing `action_params`/`series_key`/`learning`. - Maintainer questions from 4-G (PR description): grid charging on the Kostal (generic force-charge entity or a §3.4 ADR); the fallback timer measurement procedure for `battery.fallback_measured`. Answered: no permanent reserve floor on the inverter. @@ -763,18 +847,30 @@ maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4 ## Next steps -1. Maintainer: install the beta (export a configuration backup first: schema 3 cannot be opened - by earlier versions), keep everything in **shadow mode**, read `docs/user/en/surplus-control.md` - (or `de`) and check the **Decision log** after a day with sun: are the "would have" entries - plausible? Check the summary system check at noon. -2. ~~Answer the open questions~~ Answered 2026-10-16: keep everything as built (safe and simple), - see the plan's "Answers after implementation". -3. Phase 3 exit: switch **one** device to automatic following the guide's walk-through and report - the first live writes (the climate unit's counter-only estimate and the cloud echo delay are - the interesting parts). Then merge 3-A, 3-B, 3-C and release. -4. Release the next release-please PR for the stable app after acceptance. -5. Phase 4: finish the 4-A review fixes, open PR 4-A; maintainer decides on ADR-0013 and the 4-A - questions; continue with 4-B (storage/time series). +1. Maintainer: **Phase 3 shadow test first.** Install the beta (export a configuration backup first: + schema 4 cannot be opened by earlier versions), keep everything in **shadow mode**, read + `docs/user/en/surplus-control.md` (or `de`) and check the **Decision log** after a day with sun: + are the "would have" entries plausible? Check the summary system check at noon. Then switch + **one** device to automatic and report the first live writes. Then merge 3-A, 3-B, 3-C. +2. Then **Phase 4**, following `docs/user/en/planning-and-battery.md` (or `de`): + 1. Wizard: step 4 (forecast sources, workday and weather inputs), step 5 (battery model, + strategy, risk level), step 6 (price formula for a spot source, HT/NT), step 8 (grid charging + stays off), step 10 (first plan). + 2. Look at the **Plan** view in shadow for a day or two: are the reasons and the evening target + plausible, is the accuracy panel filling up (calibration needs 30 days)? + 3. Enable the disabled Kostal `Battery:MinSoc` number entity in Home Assistant, map it in step 5 + (adapter "Kostal Plenticore, minimum SoC"), compare the signs, then switch the battery to + **assisted** and confirm the first proposals. + 4. Optional, later: enable external battery management via Modbus on the inverter, add the modbus + hub, and measure the fallback timer with the documented procedure; then set + `battery.fallback_measured`. +3. Merge the stacked PRs in order **#25 → #26 → #27/#29 → #30 → #31 → #33 → 4-H** (squash + recommended), after the Phase 3 acceptance; each rebase onto `main` after the previous merge. + Release the next release-please PR for the stable app after acceptance (schema 4: release note + "export before updating"). +4. Answer the open questions in `docs/plans/phase-4.md` §6 ("Offene Fragen aus PR 4-A" and "4-C"), + in particular grid charging on the Kostal (generic force-charge entity or a §3.4 ADR) and the + fallback timer procedure. ## Known problems and `UNVERIFIED` items @@ -804,14 +900,15 @@ maintainer's shadow test · **Branch:** `phase-4/g-battery` (stacked on `phase-4 | Section 51 EEG 2023 text could not be fetched; region `de` feed-in tiers are empty until the official BNetzA table is cited | `templates/region/de.yaml` | maintainer provides the table or a session with access to gesetze-im-internet.de | | Whether Tibber's `total` includes grid fees (country dependent) | `templates/tariff/tibber.price.yaml` | live check on the maintainer's Tibber account | | LG translation keys (inferred from source and unique ids; LG entity ids, modes and units checked live on 2026-10-14), other LG models' modes (Solcast default day-sensor count verified from source in 4-A; Tibber publication time: see the price row above) | `research/device-integrations.md` | maintainer's HA with LG ThinQ, Tibber, Solcast (Phase 2 wizard test) | -| Wording of the quick start steps and the HA menu names in the new docs (written from the UI catalogues, not clicked through on a real HA); the surplus control guide is written from the code and the demo, its walk-through has not been followed on a real system | `docs/user/*/quick-start.md`, `docs/user/*/surplus-control.md` | maintainer follows the quick start and the first-device walk-through on HA OS | +| Wording of the quick start steps and the HA menu names in the new docs (written from the UI catalogues, not clicked through on a real HA); the surplus control and planning guides are written from the code and the demo, their walk-throughs have not been followed on a real system | `docs/user/*/quick-start.md`, `surplus-control.md`, `planning-and-battery.md` | maintainer follows the quick start and the first-device and first-battery walk-throughs on HA OS | +| Steps to enable the disabled Kostal `Battery:MinSoc` entity (HA menu names for disabled entities), the `docker kill` way to end the app without a hand-back, the container name, and the sensor behaviour while measuring the §3.5 timer (what exactly shows the fall-back: battery power and grid power are assumed) | `docs/user/*/planning-and-battery.md` (adapters, "Measuring the fallback timer") | maintainer's HA OS with a Kostal inverter | | Which Home Assistant tool lets users place files in the app's `/data/templates` | `docs/user/*/device-templates.md` | maintainer checks on HA OS | | Water heater templates (`generic.water_heater_steps`, `_relays`), drivers for select/number/relays/mode, `ClimateDriver` paths other than `lg_thinq` source reading: simulator only, no hardware; `lg_thinq` `step is None` `TypeError` on `set_temperature`, push latency after a command, `climate.turn_on` fallback for modes not in `hvac_modes` | `templates/device/generic.water_heater_*.yaml`, `suncore/devices/drivers/`, `research/device-integrations.md` | first limited live write on the maintainer's AC; a user with a water heater | | Default sensor cadences (power sensor 60 s = the client resync, energy counter without `counter_update_s` 300 s); whether a quiet plug re-reports an unchanged value so that `last_reported` moves | `suncore/app/cadence.py`, `research/ha-websocket-api.md` | shadow-mode run on the maintainer's system; set `power_update_s`/`counter_update_s` where a sensor is slower (`power_update_s` is in the device editor since WP10) | | Controller tuning (deficit delay/budget, downside spread of the smoothing, counter-only climate needs `nominal + span + hysteresis` free surplus to shift; battery share without a goal = battery first) | `suncore/controller/`, `tests/controller/test_climate_equivalence.py` | shadow-mode run on the maintainer's system (plan exit criterion) | | evcc REST API paths | `research/competitors.md` | Phase 6, MQTT API is verified and sufficient | | Solcast day sensors d3/d4: translation keys `total_kwh_forecast_d3`/`_d4` from the research notes; the date-time format the fallback action `query_forecast_data` accepts for `start_date_time`/`end_date_time` (SunCore sends ISO 8601 with offset) | `templates/forecast/solcast.pv.yaml`, `suncore/forecast/pv/adapter.py` | maintainer's HA with Solcast | -| Open-Meteo Solar Forecast: translation key assumed equal to the description key; CC BY 4.0 attribution still to be shown in the UI (4-H) | `templates/forecast/open_meteo_solar_forecast.pv.yaml` | a running integration; PR 4-H | +| Open-Meteo Solar Forecast: translation key assumed equal to the description key (the CC BY 4.0 attribution is shown in the plan view since 4-H) | `templates/forecast/open_meteo_solar_forecast.pv.yaml` | a running integration | | Forecast.Solar `wh_hours`/`watt_hours_period` keys read as period *start* (vendor API unreachable) | `templates/forecast/forecast_solar.pv.yaml`, `suncore/forecast/pv/parsing.py` | live comparison with the integration's sensors | | Supervisor proxy forwards `energy/solar_forecast` | `suncore/ha/` (`fetch_solar_forecast`) | first run on HA OS | | PV calibration constants (classes kt 0.3/0.65, shrink k = 16, decay 0.98, factor 0.5–1.5) and the clipping thresholds (plateau ±0.3 % for ≥ 1 h on ≥ 2 days; export within max(3 %, 50 W)) are reasoned, not fitted to real data | `suncore/forecast/pv/` | 30+ days of the maintainer's data | diff --git a/docs/adr/0013-battery-as-controlled-asset.md b/docs/adr/0013-battery-as-controlled-asset.md index 31c8b9b..976a90d 100644 --- a/docs/adr/0013-battery-as-controlled-asset.md +++ b/docs/adr/0013-battery-as-controlled-asset.md @@ -1,6 +1,6 @@ # ADR-0013: Battery as a controlled asset -- **Status:** proposed +- **Status:** accepted (maintainer took the recommendation as default on 2026-10-19) - **Date:** 2026-10-16 - **Deciders:** maintainer, lead engineer (`architect`), `control-safety` - **Research:** [`integrations.md`](../research/integrations.md) (Kostal Plenticore, summary diff --git a/docs/adr/README.md b/docs/adr/README.md index 6e7cd90..3442f4c 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -18,4 +18,4 @@ the status line; a new ADR supersedes an old one. Template: | [0010](0010-target-platform.md) | Target platform | accepted | HA OS app on aarch64/amd64, HA connection abstracted | | [0011](0011-two-control-layers.md) | Two control layers and safety boundary | accepted (addendum 2026-10-16: new action kinds rejected until their invariants exist) | Planner → Controller → Safety (single writer) → Actuators | | [0012](0012-template-schema-v1.md) | Template schema v1 – review before freeze | accepted | Required changes (matcher regex/lists, same-device role, `ControlSpec`, series source, capability enum) before freeze; `battery` kind added later under the v1 compatibility policy | -| [0013](0013-battery-as-controlled-asset.md) | Battery as a controlled asset | proposed | `BatteryAction` as limits (not set-points); one reserve source of truth; planned grid charging as the only bounded exception to "no SunCore-caused import"; adapter heartbeat with hardware fallback; battery identity in the fingerprint; prerequisite of Phase 4 WP10 | +| [0013](0013-battery-as-controlled-asset.md) | Battery as a controlled asset | accepted | `BatteryAction` as limits (not set-points); one reserve source of truth; planned grid charging as the only bounded exception to "no SunCore-caused import"; adapter heartbeat with hardware fallback; battery identity in the fingerprint; prerequisite of Phase 4 WP10 | diff --git a/docs/architecture.md b/docs/architecture.md index 003fcb5..7c3368d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -141,11 +141,13 @@ convert at the boundary (e.g. Kostal reports battery positive = discharging). ## 4. Planner, controller, safety in time -The planner arrives in Phase 4; until then the controller consumes `Plan.default()`, which allows -everything. Phase 4 WP8 added `suncore/planner` (`inputs.py` → `model.py` LP for HiGHS behind a -`SolverBackend` protocol → `run.py` with the heuristic fallback and `explain.py` reasons); it -depends on `core` only: the scheduler (WP9) collects prices, forecasts and the risk targets and -hands them over through `build_inputs`, and runs `run()` in a worker thread. +The planner (Phase 4) is in place: `suncore/planner` (`inputs.py` → `model.py` LP for HiGHS +behind a `SolverBackend` protocol → `run.py` with the heuristic fallback and `explain.py` +reasons) depends on `core` only. The scheduler (`suncore/app/planning.py`, `PlanningService`) +collects prices, forecasts and the risk targets, hands them over through `build_inputs`, runs +`run()` in a daemon worker thread (budget 8 s) every quarter hour and on events, and hands the +plan to the controller once per tick. A missing, expired or stale plan (older than 2 h) means the +controller consumes `Plan.default()`, which allows everything (the Phase 3 behaviour). The control layer (Phase 3) is composed in one place, `suncore/app/control.py` (`ControlStack`): entity cache, one driver and one power model per device, the controller (`suncore/controller`), the safety gate with its watchdog (`suncore/safety`) and the connection @@ -244,8 +246,10 @@ back-off (also during an emergency stop) and nothing else is written. Devices ke Phase 3 rule "no SunCore-caused import" unchanged, and the charging power of a forced grid charge is never surplus for them. -Deviation events: the controller reports when actual SoC, PV or load leave the plan's assumption -corridor; the scheduler then re-plans early (rate limited to once per 5 minutes) from Phase 4 on. +Deviation events: the planning service itself watches the live state of charge against the plan +(more than 10 %-points off) and the grid power against the planned net power (more than 1500 W +for 30 minutes, smoothed); either triggers an early re-plan. Event runs are debounced (at least +60 s between starts) and merged into one run. ## 5. Safety state machine (per device and global) diff --git a/docs/assets/screenshots/decisions-phone-dark-en.png b/docs/assets/screenshots/decisions-phone-dark-en.png index 91738e2..a88827b 100644 Binary files a/docs/assets/screenshots/decisions-phone-dark-en.png and b/docs/assets/screenshots/decisions-phone-dark-en.png differ diff --git a/docs/assets/screenshots/decisions-phone-light-de.png b/docs/assets/screenshots/decisions-phone-light-de.png index f4721b9..0184da3 100644 Binary files a/docs/assets/screenshots/decisions-phone-light-de.png and b/docs/assets/screenshots/decisions-phone-light-de.png differ diff --git a/docs/assets/screenshots/decisions-phone-light-en.png b/docs/assets/screenshots/decisions-phone-light-en.png index 24f9485..86a8faf 100644 Binary files a/docs/assets/screenshots/decisions-phone-light-en.png and b/docs/assets/screenshots/decisions-phone-light-en.png differ diff --git a/docs/assets/screenshots/decisions-tablet-dark-en.png b/docs/assets/screenshots/decisions-tablet-dark-en.png index 74b5b33..db04621 100644 Binary files a/docs/assets/screenshots/decisions-tablet-dark-en.png and b/docs/assets/screenshots/decisions-tablet-dark-en.png differ diff --git a/docs/assets/screenshots/decisions-tablet-light-de.png b/docs/assets/screenshots/decisions-tablet-light-de.png index 9173c01..1dd446e 100644 Binary files a/docs/assets/screenshots/decisions-tablet-light-de.png and b/docs/assets/screenshots/decisions-tablet-light-de.png differ diff --git a/docs/assets/screenshots/decisions-tablet-light-en.png b/docs/assets/screenshots/decisions-tablet-light-en.png index a5af8ec..b4f547e 100644 Binary files a/docs/assets/screenshots/decisions-tablet-light-en.png and b/docs/assets/screenshots/decisions-tablet-light-en.png differ diff --git a/docs/assets/screenshots/device-duplicate-hint-tablet-light-de.png b/docs/assets/screenshots/device-duplicate-hint-tablet-light-de.png index cb261a1..0505398 100644 Binary files a/docs/assets/screenshots/device-duplicate-hint-tablet-light-de.png and b/docs/assets/screenshots/device-duplicate-hint-tablet-light-de.png differ diff --git a/docs/assets/screenshots/device-duplicate-hint-tablet-light-en.png b/docs/assets/screenshots/device-duplicate-hint-tablet-light-en.png index 338cedb..324ba3d 100644 Binary files a/docs/assets/screenshots/device-duplicate-hint-tablet-light-en.png and b/docs/assets/screenshots/device-duplicate-hint-tablet-light-en.png differ diff --git a/docs/assets/screenshots/estop-phone-dark-en.png b/docs/assets/screenshots/estop-phone-dark-en.png index 43c974c..3a3d1dd 100644 Binary files a/docs/assets/screenshots/estop-phone-dark-en.png and b/docs/assets/screenshots/estop-phone-dark-en.png differ diff --git a/docs/assets/screenshots/estop-phone-light-de.png b/docs/assets/screenshots/estop-phone-light-de.png index 50a85ad..40a3452 100644 Binary files a/docs/assets/screenshots/estop-phone-light-de.png and b/docs/assets/screenshots/estop-phone-light-de.png differ diff --git a/docs/assets/screenshots/estop-phone-light-en.png b/docs/assets/screenshots/estop-phone-light-en.png index 9b8e510..c93bc56 100644 Binary files a/docs/assets/screenshots/estop-phone-light-en.png and b/docs/assets/screenshots/estop-phone-light-en.png differ diff --git a/docs/assets/screenshots/estop-tablet-dark-en.png b/docs/assets/screenshots/estop-tablet-dark-en.png index c49906e..a50d7f4 100644 Binary files a/docs/assets/screenshots/estop-tablet-dark-en.png and b/docs/assets/screenshots/estop-tablet-dark-en.png differ diff --git a/docs/assets/screenshots/estop-tablet-light-de.png b/docs/assets/screenshots/estop-tablet-light-de.png index f8101ee..504aa83 100644 Binary files a/docs/assets/screenshots/estop-tablet-light-de.png and b/docs/assets/screenshots/estop-tablet-light-de.png differ diff --git a/docs/assets/screenshots/estop-tablet-light-en.png b/docs/assets/screenshots/estop-tablet-light-en.png index 802de17..2018e0c 100644 Binary files a/docs/assets/screenshots/estop-tablet-light-en.png and b/docs/assets/screenshots/estop-tablet-light-en.png differ diff --git a/docs/assets/screenshots/now-battery-phone-dark-de.png b/docs/assets/screenshots/now-battery-phone-dark-de.png new file mode 100644 index 0000000..150905e Binary files /dev/null and b/docs/assets/screenshots/now-battery-phone-dark-de.png differ diff --git a/docs/assets/screenshots/now-battery-phone-dark-en.png b/docs/assets/screenshots/now-battery-phone-dark-en.png new file mode 100644 index 0000000..1bc03ab Binary files /dev/null and b/docs/assets/screenshots/now-battery-phone-dark-en.png differ diff --git a/docs/assets/screenshots/now-battery-phone-light-de.png b/docs/assets/screenshots/now-battery-phone-light-de.png new file mode 100644 index 0000000..6474017 Binary files /dev/null and b/docs/assets/screenshots/now-battery-phone-light-de.png differ diff --git a/docs/assets/screenshots/now-battery-phone-light-en.png b/docs/assets/screenshots/now-battery-phone-light-en.png new file mode 100644 index 0000000..7dab913 Binary files /dev/null and b/docs/assets/screenshots/now-battery-phone-light-en.png differ diff --git a/docs/assets/screenshots/now-battery-tablet-dark-de.png b/docs/assets/screenshots/now-battery-tablet-dark-de.png new file mode 100644 index 0000000..de39d28 Binary files /dev/null and b/docs/assets/screenshots/now-battery-tablet-dark-de.png differ diff --git a/docs/assets/screenshots/now-battery-tablet-dark-en.png b/docs/assets/screenshots/now-battery-tablet-dark-en.png new file mode 100644 index 0000000..155511b Binary files /dev/null and b/docs/assets/screenshots/now-battery-tablet-dark-en.png differ diff --git a/docs/assets/screenshots/now-battery-tablet-light-de.png b/docs/assets/screenshots/now-battery-tablet-light-de.png new file mode 100644 index 0000000..f3c36df Binary files /dev/null and b/docs/assets/screenshots/now-battery-tablet-light-de.png differ diff --git a/docs/assets/screenshots/now-battery-tablet-light-en.png b/docs/assets/screenshots/now-battery-tablet-light-en.png new file mode 100644 index 0000000..7e53b79 Binary files /dev/null and b/docs/assets/screenshots/now-battery-tablet-light-en.png differ diff --git a/docs/assets/screenshots/now-phone-dark-de.png b/docs/assets/screenshots/now-phone-dark-de.png index 458fc4c..2b58dd7 100644 Binary files a/docs/assets/screenshots/now-phone-dark-de.png and b/docs/assets/screenshots/now-phone-dark-de.png differ diff --git a/docs/assets/screenshots/now-phone-dark-en.png b/docs/assets/screenshots/now-phone-dark-en.png index 6e50bd1..3bee4ff 100644 Binary files a/docs/assets/screenshots/now-phone-dark-en.png and b/docs/assets/screenshots/now-phone-dark-en.png differ diff --git a/docs/assets/screenshots/now-phone-light-de.png b/docs/assets/screenshots/now-phone-light-de.png index f464c5b..a97067e 100644 Binary files a/docs/assets/screenshots/now-phone-light-de.png and b/docs/assets/screenshots/now-phone-light-de.png differ diff --git a/docs/assets/screenshots/now-phone-light-en.png b/docs/assets/screenshots/now-phone-light-en.png index 796b840..2faa359 100644 Binary files a/docs/assets/screenshots/now-phone-light-en.png and b/docs/assets/screenshots/now-phone-light-en.png differ diff --git a/docs/assets/screenshots/now-tablet-dark-de.png b/docs/assets/screenshots/now-tablet-dark-de.png index 5642a6d..7e0ef4e 100644 Binary files a/docs/assets/screenshots/now-tablet-dark-de.png and b/docs/assets/screenshots/now-tablet-dark-de.png differ diff --git a/docs/assets/screenshots/now-tablet-dark-en.png b/docs/assets/screenshots/now-tablet-dark-en.png index c496a9b..06c0df2 100644 Binary files a/docs/assets/screenshots/now-tablet-dark-en.png and b/docs/assets/screenshots/now-tablet-dark-en.png differ diff --git a/docs/assets/screenshots/now-tablet-light-de.png b/docs/assets/screenshots/now-tablet-light-de.png index 0c36f35..e8a66b3 100644 Binary files a/docs/assets/screenshots/now-tablet-light-de.png and b/docs/assets/screenshots/now-tablet-light-de.png differ diff --git a/docs/assets/screenshots/now-tablet-light-en.png b/docs/assets/screenshots/now-tablet-light-en.png index 4c6a9c7..f2de243 100644 Binary files a/docs/assets/screenshots/now-tablet-light-en.png and b/docs/assets/screenshots/now-tablet-light-en.png differ diff --git a/docs/assets/screenshots/plan-phone-dark-de.png b/docs/assets/screenshots/plan-phone-dark-de.png new file mode 100644 index 0000000..858e71e Binary files /dev/null and b/docs/assets/screenshots/plan-phone-dark-de.png differ diff --git a/docs/assets/screenshots/plan-phone-dark-en.png b/docs/assets/screenshots/plan-phone-dark-en.png new file mode 100644 index 0000000..8f0c75f Binary files /dev/null and b/docs/assets/screenshots/plan-phone-dark-en.png differ diff --git a/docs/assets/screenshots/plan-phone-light-de.png b/docs/assets/screenshots/plan-phone-light-de.png new file mode 100644 index 0000000..42603a8 Binary files /dev/null and b/docs/assets/screenshots/plan-phone-light-de.png differ diff --git a/docs/assets/screenshots/plan-phone-light-en.png b/docs/assets/screenshots/plan-phone-light-en.png new file mode 100644 index 0000000..6c992f5 Binary files /dev/null and b/docs/assets/screenshots/plan-phone-light-en.png differ diff --git a/docs/assets/screenshots/plan-tablet-dark-de.png b/docs/assets/screenshots/plan-tablet-dark-de.png new file mode 100644 index 0000000..a6ff326 Binary files /dev/null and b/docs/assets/screenshots/plan-tablet-dark-de.png differ diff --git a/docs/assets/screenshots/plan-tablet-dark-en.png b/docs/assets/screenshots/plan-tablet-dark-en.png new file mode 100644 index 0000000..a765b65 Binary files /dev/null and b/docs/assets/screenshots/plan-tablet-dark-en.png differ diff --git a/docs/assets/screenshots/plan-tablet-light-de.png b/docs/assets/screenshots/plan-tablet-light-de.png new file mode 100644 index 0000000..5f7b2b4 Binary files /dev/null and b/docs/assets/screenshots/plan-tablet-light-de.png differ diff --git a/docs/assets/screenshots/plan-tablet-light-en.png b/docs/assets/screenshots/plan-tablet-light-en.png new file mode 100644 index 0000000..815ba5f Binary files /dev/null and b/docs/assets/screenshots/plan-tablet-light-en.png differ diff --git a/docs/assets/screenshots/settings-tablet-light-de.png b/docs/assets/screenshots/settings-tablet-light-de.png index b1bd2a8..aa2e19b 100644 Binary files a/docs/assets/screenshots/settings-tablet-light-de.png and b/docs/assets/screenshots/settings-tablet-light-de.png differ diff --git a/docs/assets/screenshots/settings-tablet-light-en.png b/docs/assets/screenshots/settings-tablet-light-en.png index 2209f37..0d260b7 100644 Binary files a/docs/assets/screenshots/settings-tablet-light-en.png and b/docs/assets/screenshots/settings-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-battery-phone-dark-de.png b/docs/assets/screenshots/wizard-battery-phone-dark-de.png new file mode 100644 index 0000000..80c99ad Binary files /dev/null and b/docs/assets/screenshots/wizard-battery-phone-dark-de.png differ diff --git a/docs/assets/screenshots/wizard-battery-phone-dark-en.png b/docs/assets/screenshots/wizard-battery-phone-dark-en.png new file mode 100644 index 0000000..4a8a472 Binary files /dev/null and b/docs/assets/screenshots/wizard-battery-phone-dark-en.png differ diff --git a/docs/assets/screenshots/wizard-battery-phone-light-de.png b/docs/assets/screenshots/wizard-battery-phone-light-de.png new file mode 100644 index 0000000..b4cf870 Binary files /dev/null and b/docs/assets/screenshots/wizard-battery-phone-light-de.png differ diff --git a/docs/assets/screenshots/wizard-battery-phone-light-en.png b/docs/assets/screenshots/wizard-battery-phone-light-en.png new file mode 100644 index 0000000..5033a7c Binary files /dev/null and b/docs/assets/screenshots/wizard-battery-phone-light-en.png differ diff --git a/docs/assets/screenshots/wizard-battery-tablet-dark-de.png b/docs/assets/screenshots/wizard-battery-tablet-dark-de.png new file mode 100644 index 0000000..231939c Binary files /dev/null and b/docs/assets/screenshots/wizard-battery-tablet-dark-de.png differ diff --git a/docs/assets/screenshots/wizard-battery-tablet-dark-en.png b/docs/assets/screenshots/wizard-battery-tablet-dark-en.png new file mode 100644 index 0000000..2564b7b Binary files /dev/null and b/docs/assets/screenshots/wizard-battery-tablet-dark-en.png differ diff --git a/docs/assets/screenshots/wizard-battery-tablet-light-de.png b/docs/assets/screenshots/wizard-battery-tablet-light-de.png index fd70f40..7a9cfe6 100644 Binary files a/docs/assets/screenshots/wizard-battery-tablet-light-de.png and b/docs/assets/screenshots/wizard-battery-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-battery-tablet-light-en.png b/docs/assets/screenshots/wizard-battery-tablet-light-en.png index 6c38a02..34bf08a 100644 Binary files a/docs/assets/screenshots/wizard-battery-tablet-light-en.png and b/docs/assets/screenshots/wizard-battery-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-devices-tablet-dark-de.png b/docs/assets/screenshots/wizard-devices-tablet-dark-de.png index 4f47652..802c9e9 100644 Binary files a/docs/assets/screenshots/wizard-devices-tablet-dark-de.png and b/docs/assets/screenshots/wizard-devices-tablet-dark-de.png differ diff --git a/docs/assets/screenshots/wizard-devices-tablet-dark-en.png b/docs/assets/screenshots/wizard-devices-tablet-dark-en.png index 6d2e192..62486d1 100644 Binary files a/docs/assets/screenshots/wizard-devices-tablet-dark-en.png and b/docs/assets/screenshots/wizard-devices-tablet-dark-en.png differ diff --git a/docs/assets/screenshots/wizard-devices-tablet-light-de.png b/docs/assets/screenshots/wizard-devices-tablet-light-de.png index 2b57b7c..2846c8f 100644 Binary files a/docs/assets/screenshots/wizard-devices-tablet-light-de.png and b/docs/assets/screenshots/wizard-devices-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-devices-tablet-light-en.png b/docs/assets/screenshots/wizard-devices-tablet-light-en.png index 507f569..7338db3 100644 Binary files a/docs/assets/screenshots/wizard-devices-tablet-light-en.png and b/docs/assets/screenshots/wizard-devices-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-energy-tablet-light-de.png b/docs/assets/screenshots/wizard-energy-tablet-light-de.png index 26e881a..048570c 100644 Binary files a/docs/assets/screenshots/wizard-energy-tablet-light-de.png and b/docs/assets/screenshots/wizard-energy-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-energy-tablet-light-en.png b/docs/assets/screenshots/wizard-energy-tablet-light-en.png index 396c3ed..3d982c5 100644 Binary files a/docs/assets/screenshots/wizard-energy-tablet-light-en.png and b/docs/assets/screenshots/wizard-energy-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-grid-tablet-light-de.png b/docs/assets/screenshots/wizard-grid-tablet-light-de.png index 6bb941a..2d87c0d 100644 Binary files a/docs/assets/screenshots/wizard-grid-tablet-light-de.png and b/docs/assets/screenshots/wizard-grid-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-grid-tablet-light-en.png b/docs/assets/screenshots/wizard-grid-tablet-light-en.png index ec516c5..f3b4739 100644 Binary files a/docs/assets/screenshots/wizard-grid-tablet-light-en.png and b/docs/assets/screenshots/wizard-grid-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-mode-tablet-light-de.png b/docs/assets/screenshots/wizard-mode-tablet-light-de.png index d1b22ef..0e91784 100644 Binary files a/docs/assets/screenshots/wizard-mode-tablet-light-de.png and b/docs/assets/screenshots/wizard-mode-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-mode-tablet-light-en.png b/docs/assets/screenshots/wizard-mode-tablet-light-en.png index 259d020..0441c13 100644 Binary files a/docs/assets/screenshots/wizard-mode-tablet-light-en.png and b/docs/assets/screenshots/wizard-mode-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-priorities-tablet-light-de.png b/docs/assets/screenshots/wizard-priorities-tablet-light-de.png index 9438353..0885048 100644 Binary files a/docs/assets/screenshots/wizard-priorities-tablet-light-de.png and b/docs/assets/screenshots/wizard-priorities-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-priorities-tablet-light-en.png b/docs/assets/screenshots/wizard-priorities-tablet-light-en.png index 7730d9b..d379055 100644 Binary files a/docs/assets/screenshots/wizard-priorities-tablet-light-en.png and b/docs/assets/screenshots/wizard-priorities-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-pv-tablet-light-de.png b/docs/assets/screenshots/wizard-pv-tablet-light-de.png index d55116e..64e28e9 100644 Binary files a/docs/assets/screenshots/wizard-pv-tablet-light-de.png and b/docs/assets/screenshots/wizard-pv-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-pv-tablet-light-en.png b/docs/assets/screenshots/wizard-pv-tablet-light-en.png index 7af5532..49fc579 100644 Binary files a/docs/assets/screenshots/wizard-pv-tablet-light-en.png and b/docs/assets/screenshots/wizard-pv-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-region-tablet-light-de.png b/docs/assets/screenshots/wizard-region-tablet-light-de.png index 698697c..dbcd5a7 100644 Binary files a/docs/assets/screenshots/wizard-region-tablet-light-de.png and b/docs/assets/screenshots/wizard-region-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-region-tablet-light-en.png b/docs/assets/screenshots/wizard-region-tablet-light-en.png index 5786d86..551f6a0 100644 Binary files a/docs/assets/screenshots/wizard-region-tablet-light-en.png and b/docs/assets/screenshots/wizard-region-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-summary-duplicate-tablet-light-de.png b/docs/assets/screenshots/wizard-summary-duplicate-tablet-light-de.png index 05d4dce..96267b2 100644 Binary files a/docs/assets/screenshots/wizard-summary-duplicate-tablet-light-de.png and b/docs/assets/screenshots/wizard-summary-duplicate-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-summary-duplicate-tablet-light-en.png b/docs/assets/screenshots/wizard-summary-duplicate-tablet-light-en.png index 106f4cd..3f2bd5a 100644 Binary files a/docs/assets/screenshots/wizard-summary-duplicate-tablet-light-en.png and b/docs/assets/screenshots/wizard-summary-duplicate-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-summary-tablet-dark-de.png b/docs/assets/screenshots/wizard-summary-tablet-dark-de.png index 63ddb07..131deab 100644 Binary files a/docs/assets/screenshots/wizard-summary-tablet-dark-de.png and b/docs/assets/screenshots/wizard-summary-tablet-dark-de.png differ diff --git a/docs/assets/screenshots/wizard-summary-tablet-dark-en.png b/docs/assets/screenshots/wizard-summary-tablet-dark-en.png index 12015c3..1660d2a 100644 Binary files a/docs/assets/screenshots/wizard-summary-tablet-dark-en.png and b/docs/assets/screenshots/wizard-summary-tablet-dark-en.png differ diff --git a/docs/assets/screenshots/wizard-summary-tablet-light-de.png b/docs/assets/screenshots/wizard-summary-tablet-light-de.png index f7a5a82..fc9ad14 100644 Binary files a/docs/assets/screenshots/wizard-summary-tablet-light-de.png and b/docs/assets/screenshots/wizard-summary-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-summary-tablet-light-en.png b/docs/assets/screenshots/wizard-summary-tablet-light-en.png index 80b5277..ae0afdf 100644 Binary files a/docs/assets/screenshots/wizard-summary-tablet-light-en.png and b/docs/assets/screenshots/wizard-summary-tablet-light-en.png differ diff --git a/docs/assets/screenshots/wizard-tariff-tablet-light-de.png b/docs/assets/screenshots/wizard-tariff-tablet-light-de.png index e5a016f..fa53f53 100644 Binary files a/docs/assets/screenshots/wizard-tariff-tablet-light-de.png and b/docs/assets/screenshots/wizard-tariff-tablet-light-de.png differ diff --git a/docs/assets/screenshots/wizard-tariff-tablet-light-en.png b/docs/assets/screenshots/wizard-tariff-tablet-light-en.png index acbf0cc..1482abe 100644 Binary files a/docs/assets/screenshots/wizard-tariff-tablet-light-en.png and b/docs/assets/screenshots/wizard-tariff-tablet-light-en.png differ diff --git a/docs/plans/phase-4.md b/docs/plans/phase-4.md index dc440f7..7104ef2 100644 --- a/docs/plans/phase-4.md +++ b/docs/plans/phase-4.md @@ -377,6 +377,14 @@ shadow and assisted run is the acceptance test. write at all (the inverter's own self-consumption logic does it). - Self-sufficiency weight: explained to the maintainer, default 0.01 currency/kWh kept. +### Answers (2026-10-19) + +- ADR-0013: the maintainer takes the recommendation as default → **accepted**; WP10 may start + once 4-F is done. +- All open questions of PRs 4-A, 4-B and 4-C: **defaults** as written in each PR. +- Phase 3 acceptance (shadow run, one device to automatic) is postponed because of the weather; + Phase 4 keeps being built, the PRs are merged only after that acceptance. + ### Offene Fragen aus PR 4-A (an den Maintainer) 1. **Doppelter Netzladeplan:** `goals.grid_charge_night_only` wird zu einem Zeitplan migriert, @@ -609,6 +617,25 @@ shadow and assisted run is the acceptance test. - **Answered (maintainer default):** SunCore enforces the effective reserve in plan and gate only, it holds no permanent min-SoC floor on the inverter. +- PR 4-H, WP11 (UI; `frontend-engineer`): + - The plan view's "now" is the browser clock corrected by the server offset measured at each + plan fetch, ticking every minute (the demo runs on a simulated clock). + - The calibration charge (answer 11) is only a configuration field (`battery.calibration`); the + planner does not use it yet, planner support follows. Corrects "built" in §6 question 11. + - ECharts is registered with line and bar only (no `custom` series: the PV band is a stacked + pair of lines). It is 177 kB gzip in its own chunk, loaded with the plan view; the Phase 1 + budget of 250 kB now applies to everything else, first paint has its own budget of 125 kB. + - Additive backend pieces the UI needed: `solar_forecast_entries` in the energy-prefs answer + (choices for a Forecast.Solar `config_entry_id`), site roles `workday` and `weather` for the + entity pickers, and the demo flag `SUNCORE_DEMO_BATTERY_CONTROL` (a controllable inverter and a + `generic.battery` adapter in the demo, off by default). + - HT/NT is a full editor (base price, periods with weekdays, midnight crossing and months) + instead of the "tou stored" hint. + - No hint for a too-new `timeseries.db`: the API exposes neither that state nor the size + report (4-B follow-up); it stays in the log. + - The battery card shows what the control state contains; there is no separate "release + pending" field in `BatteryControlState`, so that state is only visible through the reasons. + ## 7. Out of scope for Phase 4 Full plan chart with device Gantt, zoom/pan, history, savings vs baselines, what-if and diff --git a/docs/roadmap.md b/docs/roadmap.md index d451c7d..8e81f03 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -75,23 +75,29 @@ Exit: climate surplus control runs in shadow mode on the maintainer's system with plausible "would have" entries; maintainer switches one device to automatic. ⏸ waiting for the maintainer (shadow run on HA OS, then one device to automatic). -## Phase 4 – Forecasts, tariffs, planner, battery 🟨 +## Phase 4 – Forecasts, tariffs, planner, battery ⏸ -In progress in stacked PRs 4-A…4-I ([`plans/phase-4.md`](plans/phase-4.md)); PR 4-A -(contracts) first. Battery control (WP10) waits for ADR-0013. +Implemented in the stacked PRs 4-A…4-H ([`plans/phase-4.md`](plans/phase-4.md)); waiting for the +maintainer's acceptance on his system (Phase 3 shadow test first, then the plan in shadow mode and +the battery to assisted). The optional ML load model (4-I) is not built yet. -| Milestone | Acceptance | -|---|---| -| Forecast adapters | Solcast, Forecast.Solar, Open-Meteo Solar Forecast, generic attribute, built-in fallback; blending and bias calibration; accuracy stats | -| Load forecast | profiles from statistics (weekday/holiday/temperature), controlled loads excluded | -| Tariffs | Tibber, Nord Pool, ENTSO-E/EPEX via HACS, fixed/HT-NT, price formula, EEG tiered export, negative-price region rule | -| Planner | HiGHS model, heuristic fallback, warm start, time budget, benchmark on aarch64 < 10 s | -| Battery strategies | self-consumption, target SoC by time, grid charging on spread, discharge lock, reserve, calibration charge | -| Battery adapters | generic HA entities, Kostal REST (min SoC), Kostal Modbus (only with verified register map) | -| Explanations | per-interval reasons rendered in UI | - -Exit: plan with battery strategy and "Why?" on the maintainer's system, -battery control in shadow mode, then assisted. +| Milestone | Acceptance | Status | +|---|---|---| +| Forecast adapters | Solcast, Forecast.Solar, Open-Meteo Solar Forecast, generic attribute; blending and bias calibration; accuracy stats (the built-in fallback moved to Phase 6) | ✅ | +| Load forecast | profiles from statistics (weekday/holiday/temperature), controlled loads excluded | ✅ | +| Risk model and buffers | learnt net error per weather class, risk level cautious/balanced/bold, morning buffer, evening target | ✅ | +| Tariffs | Tibber, Nord Pool, ENTSO-E/EPEX via HACS, Octopus, fixed/HT-NT, price formula, EEG tiered export, negative-price region rule | ✅ | +| Planner | HiGHS model, heuristic fallback, warm start, time budget, benchmark on aarch64 < 10 s | ✅ (aarch64 not measured yet) | +| Battery strategies | self-consumption, prefer full, target SoC by time, next-day bridging, grid charging by price level and schedule, discharge lock, reserve; the calibration charge exists only as a config field, planner support follows | ✅ (calibration charge ⬜) | +| Battery adapters | generic HA entities, Kostal REST (min SoC), Kostal Modbus §3.5 (simulator only, capped at assisted until the fallback timer is measured) | ✅ | +| Explanations | per-interval reasons rendered in UI | ✅ | +| UI | plan view, forecast accuracy, battery card, wizard steps 4, 5, 6, 8 and 10 | ✅ | +| Docs | planning and battery guide (en/de), quick start, app description | ✅ | +| ML load model in shadow | NumPy KNN scored next to the profiles (PR 4-I, optional) | ⬜ | + +Exit: plan with battery strategy and "Why?" on the maintainer's system, battery control in shadow +mode, then assisted. ⏸ waiting for the maintainer (after the Phase 3 acceptance: wizard steps, plan +in shadow, enabling the Kostal `Battery:MinSoc` entity, the battery to assisted). ## Phase 5 – Visualisation, analysis, expert mode ⬜ diff --git a/docs/user/de/planning-and-battery.md b/docs/user/de/planning-and-battery.md new file mode 100644 index 0000000..82cfd69 --- /dev/null +++ b/docs/user/de/planning-and-battery.md @@ -0,0 +1,609 @@ +# Planung und Akkusteuerung + +SunCore kann vorausschauen. Es liest die Solarprognosen und Preise der Integrationen, die du +ohnehin betreibst, lernt den Verbrauch deines Hauses, berechnet einen Plan für die nächsten +48 Stunden und setzt, wenn du es erlaubst, Grenzen an deinem Heimakku. Diese Seite erklärt, was +der Planer tut, was du einstellen kannst, wie der Akku **sicher** gesteuert wird und wie du +deinen ersten Akku vom Schattenmodus in den assistierten Modus nimmst. + +Alles hier beginnt im **Schattenmodus**: Der Plan wird berechnet und angezeigt, und **in deinen +Akku oder Wechselrichter wird nichts geschrieben, bevor du es erlaubst**. Lies +[Bekannte Grenzen und UNVERIFIED](#10-bekannte-grenzen-und-unverified), bevor du dich darauf +verlässt: Planer und Akkusteuerung sind noch nie an echter Hardware gelaufen. + +## 1. Was der Planer tut + +Der Planer berechnet einen Fahrplan für die **nächsten 48 Stunden in Schritten von 15 Minuten**. +Er läuft **alle 15 Minuten** und noch einmal, **wenn sich etwas ändert**: neue Preise, eine neue +Prognose, eine geänderte Einstellung, ein manueller Eingriff an einem Gerät, eine große +Abweichung vom Plan (der Akku liegt mehr als 10 Prozentpunkte neben dem geplanten Ladestand, +oder die Netzleistung weicht 30 Minuten lang um mehr als 1,5 kW ab) oder wenn du **Jetzt neu +planen** drückst. Läufe, die weniger als eine Minute auseinanderliegen, werden zusammengelegt. + +Für jedes 15-Minuten-Intervall enthält der Plan die erwartete Solarleistung, die Hauslast, die +Akkuleistung, Netzbezug und Einspeisung, den geplanten Ladestand des Akkus und die Preise, +**und die Gründe**. Er minimiert, was du zahlst (Bezugskosten minus Einspeiseerlös plus ein +kleiner Verschleißkostenanteil für den Akku), innerhalb der Grenzen, die du setzt. Die Kosten sind +nicht alles: Deine Ziele (Morgenpuffer, Abendziel, dein eigener Ziel-Ladestand) gehören zum +Modell, und ein kleiner Bonus für Autarkie hält den Plan bei flachen Preisen vernünftig (siehe +[Das Autarkie-Gewicht](#das-autarkie-gewicht)). + +- **Optimierer oder regelbasiert.** Normalerweise findet ein Optimierer (HiGHS) den Plan. Er hat + ein Zeitbudget (standardmäßig 8 Sekunden), und vorher wird als Sicherheitsnetz ein + regelbasierter Plan berechnet. Wird der Optimierer nicht rechtzeitig fertig, kann er das Modell + nicht lösen, ist nicht verfügbar oder liefert einen Plan, der die Zulässigkeitsprüfung nicht + besteht, gilt der **regelbasierte Plan**, und die Planansicht sagt es (Marke **Regelbasiert** + statt **Optimierer**, mit dem Grund). Der regelbasierte Plan ist einfacher: erst der Akku bis + zum Morgenpuffer, danach Verbraucher mit Überschuss, solange das Abendziel erreichbar bleibt, + Netzladen nur, um ein Ziel zu erreichen. +- **„Warum?“** Jedes Intervall trägt Gründe in verständlicher Sprache, zum Beispiel „Abendziel + 60,6 % (Risikostufe vorsichtig): Die Nacht braucht 4,6 kWh“ oder „Akku halten bei 0,287/kWh: + Seine Energie ist um 19:00 mehr wert“. Du findest sie in der Planansicht (Tooltip, Liste + **Nächste geplante Aktionen**) und in der Ansicht **Jetzt**. +- **Der Plan führt, der Regler entscheidet.** Der Echtzeit-Regler aus der + [Überschusssteuerung](surplus-control.md) hat alle paar Sekunden das letzte Wort. Der Plan setzt + Bänder (wie viel Leistung ein Gerät nutzen darf, „Akku zuerst bis X %“), und der Regler vergleicht + sie mit dem, was wirklich passiert. Ein **veralteter Plan** (älter als 2 Stunden) oder gar kein + Plan heißt: Der Regler verhält sich genau wie ohne Planer. Schatten, assistiert und Automatik + gelten für die Wirkung des Plans wie bisher. + +![Planansicht mit Diagramm, nächsten geplanten Aktionen und Prognosefeld](../../assets/screenshots/plan-tablet-light-de.png) + +Die Ansicht **Plan** zeigt ein Diagramm der nächsten 24 oder 48 Stunden (Solar mit seinem +P10-bis-P90-Band, Hauslast, Akkuleistung, Netzbezug und Einspeisung, den geplanten Ladestand mit +Morgenpuffer und Abendziel als Linien sowie Bezugs- und Einspeisepreis), den Zustand des Planers +(letzter Lauf, Auslöser, nächster Lauf, Fehlschläge), die **Nächsten geplanten Aktionen** mit +**Warum?**, eine Tabellenfassung des Diagramms für Screenreader und das Feld **Prognosen und +Genauigkeit**. Der Plan ist ein Plan, kein Schaltbefehl: Jedes Gerät folgt weiterhin seinem +eigenen Betriebsmodus. + +## 2. Prognosen + +### Solar + +SunCore ruft von sich aus keinen Wetterdienst auf. Es liest die Prognosen von Integrationen, die +du installiert hast, im Einrichtungsschritt 4 (**Photovoltaik**, Abschnitt **Prognosequellen**): + +| Quelle | Hinweise | +|---|---| +| Solcast | Liest die Prognose-Attribute der Integration (P10, P50, P90) oder deren lesende Abfrage-Aktion. SunCore ruft nie die Solcast-API auf. | +| Forecast.Solar | Die Core-Integration, gelesen über das Energie-Dashboard. Bei mehreren Einträgen wählst du den für diese Anlage. | +| Open-Meteo Solar Forecast | Die HACS-Integration. | +| Generisch | Eine Vorlage, die Attribute einer Entität auf eine Prognosekurve abbildet. | + +Du kannst **mehrere Quellen** gleichzeitig nutzen. Ihre Prognosen werden **nach gemessener +Treffsicherheit gemischt**: SunCore vergleicht jede Nacht jede Quelle mit dem, was deine Module +in den letzten 14 Tagen wirklich erzeugt haben, und gibt besseren Quellen mehr Gewicht (jede +Quelle behält einen Mindestanteil). Solange noch nicht genug Tage verglichen wurden, zählen alle +Quellen gleich. Du kannst auch je Quelle einen festen Anteil setzen (**Gewicht in der +Mischung**). + +Darüber hinaus lernt SunCore den **systematischen Fehler** jeder Quelle (zum Beispiel „morgens +bei Bewölkung zu hoch“) je Tagesstunde, Jahreszeit und Wetterklasse und korrigiert ihn. Diese +**Kalibrierung wird nach 30 Tagen mit Daten aktiv**; davor werden die Prognosen so genutzt, wie +sie geliefert werden, und das Feld zeigt „0 von 30 Tagen mit Daten“. Stunden, in denen der +Wechselrichter oder die Einspeisegrenze die Leistung **abgeregelt** hat, werden erkannt und aus +dem Lernen herausgehalten, damit eine gedrosselte Anlage der Prognose nicht beibringt, zu +pessimistisch zu sein. + +Das Feld **Prognosen und Genauigkeit** (unter dem Plandiagramm) zeigt je Quelle, wie frisch ihre +Daten sind, ihren Fehler (MAE) und ihre Abweichung (Bias) je Vorlaufzeit (0 bis 6, 6 bis 24 und +24 bis 48 Stunden voraus), die Mischgewichte und den Stand der Kalibrierung. Bias ist Ist minus +Prognose: Positiv heißt, die Quelle lag zu niedrig. Werte erscheinen nach der ersten Nacht mit +genug Daten (bis dahin **Daten werden gesammelt**). + +**Open-Meteo:** Die Daten der Integration Open-Meteo Solar Forecast stehen unter **CC BY 4.0**. +SunCore zeigt die Namensnennung „Solardaten von Open-Meteo.com, lizenziert unter CC BY 4.0“ im +Feld, sobald eine Open-Meteo-Quelle eingerichtet ist. SunCore bringt in dieser Version keinen +eingebauten Open-Meteo- oder anderen Internet-Ersatz mit; ohne Prognosequelle rechnet der Plan +ganz ohne Solarstrom. + +### Hauslast + +Die Lastprognose lernt, was dein Haus **ohne die gesteuerten Geräte** verbraucht: Die Grundlast +ist der Hausverbrauch minus jedes Geräts, das SunCore steuern darf (diese werden getrennt +geplant). Sie baut für jede Viertelstunde ein Profil für **Werktage, Wochenenden und Feiertage** +auf, mit langsam verblassender Erinnerung (die letzten Wochen zählen mehr), und baut beim ersten +Start die letzten **28 Tage** aus den Langzeitstatistiken von Home Assistant nach, sodass sie +nicht bei null anfängt. Bis drei Tage bekannt sind, nutzt sie eine flache Schätzung mit breitem +Band; ganz ohne Verlauf rechnet der Plan mit flachen 500 W und plant keine Verbraucher (ein +Planhinweis sagt es). + +Zwei optionale Eingaben in Schritt 4 (**Eingaben der Lastprognose**) verbessern sie: + +- Ein **Arbeitstag-Sensor** (die Home-Assistant-Integration Workday). SunCore nutzt seinen Zustand + für heute und fragt für andere Tage `workday.check_date`. Hat dein Sensor einen `days_offset`, + berücksichtigt SunCore ihn: Home Assistant wertet den Sensor für das Datum plus Versatz aus, + und SunCore gleicht das aus. +- Eine **Wetter-Entität**. Home Assistant führt keine Statistik über eine Wetter-Entität, deshalb + zeichnet SunCore deren Außentemperatur selbst auf. Der Temperaturterm der Lastprognose wird + nach 14 Tagen mit aufgezeichneter Temperatur aktiv. + +Ein Lastmodell mit maschinellem Lernen ist **noch nicht verfügbar**; das Feld sagt es. Die Profile +funktionieren vom ersten Tag an. + +## 3. Tarife + +Schritt 6 (**Tarif**) sagt dem Planer, was Energie kostet. Der Bezugspreis kann sein: + +- **Dynamisch** von Tibber, Nord Pool, ENTSO-E, EPEX Spot oder Octopus Energy über die + Integration, die du ohnehin betreibst (wähle die Tarif-Vorlage; Nord Pool braucht die ID seines + Konfigurationseintrags, die du unter **Entwicklerwerkzeuge → Aktionen** nachschlagen kannst), + oder eine **generische Preisliste** oder nur ein **Preissensor**. +- **Fest** oder **fester Zeittarif (HT/NT)** mit Zeiträumen je Wochentag, Mitternachtsübergang + und Monaten. + +**Preisformel.** Viele Quellen liefern nur den **Börsenpreis** (den Marktpreis). Darauf kann der +Planer nicht optimieren, weil du Netzentgelt, Abgaben, Aufschlag und Mehrwertsteuer dazu zahlst. +Wähle unter **Was der Preis enthält** die Option **Nur Börsenpreis (Gebühren und Steuern kommen +dazu)**, schalte **Börsenpreis in meinen Endpreis umrechnen** ein und trage Faktor, Netzentgelt, +Abgaben, Aufschlag und MwSt ein (Endpreis = (Börsenpreis × Faktor + Netzentgelt + Abgaben + +Aufschlag) × (1 + MwSt)); optionale zeitvariable Netzentgelte (§14a EnWG Modul 3) lassen sich als +Zeitfenster ergänzen. Die Formel gilt **nur für Börsenpreise**: Der `price` von Tibber ist ein +Endpreis mit allem (wähle **Endpreis (alles enthalten)**), und ein fester Preis braucht keine +Formel. Eine Quelle, die reine Börsenpreise **ohne** Formel liefert, lehnt der Planer ab: Er +plant ohne Preisoptimierung (nur auf Autarkie) und sagt es („liefert reine Börsenpreise und es ist +keine Preisformel eingerichtet“), und die Systemprüfung warnt. + +Die **Einspeisevergütung** ist **fest**, **gestaffelt nach Anlagengröße** (du trägst den Satz +jeder Stufe ein, zum Beispiel die zwei deutschen Sätze bis und über 10 kWp; die letzte Stufe muss +die ganze Anlage abdecken, das Regionsprofil enthält die amtliche Tabelle noch nicht) oder +**keine**. **Negativpreis-Regel:** In einer Region, in der bei negativen Preisen nicht vergütet +wird (Profil `de`), bewertet der Plan die Einspeisung in diesen Intervallen mit null und steckt +den Überschuss lieber in Akku und Verbraucher. Ein tatsächliches Abregeln des Wechselrichters wird +noch nicht gesteuert. + +Die Day-ahead-Preise für morgen werden ab 13:00 Ortszeit erwartet; bis sie da sind, werden spätere +Stunden ohne Preis mit dem Median gefüllt und gekennzeichnet („mit dem Medianpreis geplant“), und +**Netzladen verlässt sich nie auf einen geschätzten oder unbekannten Preis**. + +## 4. Ziele und Strategien + +Das alles stellst du in Schritt 5 (**Batterie**: Abschnitte **Akkumodell für den Planer** und +**Strategie**) und Schritt 8 (**Prioritäten und Ziele**) ein. + +### Risikostufe + +Prognosen liegen manchmal daneben, und der Akku soll deshalb nicht leerlaufen. Die +**Risikostufe** sagt, wie sicher der Plan die Akkuziele erreichen muss: + +| Risikostufe | Plant mit | Bedeutung | +|---|---|---| +| **Vorsichtig** (Standard) | einer schlechten Prognose (90 %) | Die Ziele werden in etwa **9 von 10 Fällen** erreicht. | +| **Ausgewogen** | 75 % | Die Ziele werden in etwa 3 von 4 Fällen erreicht. | +| **Mutig** | der mittleren Prognose (Median) | Die Ziele werden in etwa der Hälfte der Fälle erreicht. | + +SunCore lernt, wie falsch die Prognosen tatsächlich sind, je Wetterklasse, aus dem Unterschied +zwischen der prognostizierten Nettoenergie (Solar minus Last) und dem, was passiert ist. Bis 30 +Tage Verlauf vorliegen, nutzt es die P10/P90-Bänder der Quellen selbst (so gekennzeichnet). Der +gelernte Fehler bestimmt die Größe der Puffer: mehr Unsicherheit, größerer Puffer. + +### Morgenpuffer, Abendziel, Überbrücken + +- **Morgenpuffer** („Akku zuerst bis X %“). Bis der Akku X % erreicht hat, lädt der Solarüberschuss + den Akku, bevor Verbraucher ihn bekommen. X wird aus der Prognose berechnet: höher, wenn der Tag + unsicher ist, niedriger, wenn viel Solarenergie erwartet wird. Im Plandiagramm ist es die + gestrichelte Linie **Morgenpuffer**. Der **Mindest-Morgenpuffer** (Schritt 5) ist deine eigene + Untergrenze unter dem gelernten Wert; leer heißt nur gelernt. Oberhalb von X geht der Überschuss + an Verbraucher, **solange der Plan sagt, dass das Abendziel noch erreichbar ist**. SunCore + vergleicht X alle paar Sekunden mit dem **aktuellen** Ladestand, damit ein Tag, der vom Plan + abweicht, richtig behandelt wird. +- **Abendziel** (gestrichelte Linie **Abendziel**). Der Ladestand, den der Akku zu Beginn des + abendlichen Defizits haben soll, damit er das Haus durch die Nacht trägt: der Verbrauch der Nacht + plus, bei eingeschaltetem **Bis in den nächsten Tag überbrücken**, die fehlende Energie eines + schwachen Folgetags (der 48-Stunden-Horizont zeigt sie), auf der gewählten Risikostufe, höchstens + bis zu deinem maximalen Ladestand. Er liegt nie unter deinem eigenen Ziel. +- **Dein Ziel.** Das Ziel **Batterie zu einer Uhrzeit auf einen Ziel-Ladestand bringen** + (Schritt 8) ist eine **Untergrenze**: Der Plan hält den Akku zu dieser Zeit mindestens auf diesem + Ladestand, und der Echtzeit-Regler hält den Akku vorn, solange er darunter liegt. Der Plan kann + mehr verlangen, nie weniger. + +Harte Grenzen (Reserve, maximaler Ladestand, dein Ziel, der Mindest-Morgenpuffer) setzt immer du, +und sie gewinnen immer gegen das Gelernte. + +### Strategien + +| Strategie (Schritt 5) | Was sie tut | +|---|---| +| **Eigenverbrauch** (Standard) | Gelernte Puffer wie oben; der Akku deckt die Nacht und überbrückt einen schwachen Folgetag, wo es sich lohnt. | +| **Akku möglichst voll halten** (`prefer_full`) | „Akku zuerst“ bis zum maximalen Ladestand, immer. Verbraucher bekommen nur Überschuss, den der Akku nicht aufnehmen kann. | +| **Zielladestand zu einer Uhrzeit erreichen** (`target_by_time`) | Nutzt das Ziel aus Schritt 8 (Ziel-Ladestand und Uhrzeit) als festes Ziel, zusätzlich zu den Puffern. | + +### Das Autarkie-Gewicht + +Schritt 8 hat das Expertenfeld **Autarkie-Gewicht je kWh**, Standard **0,01** (1 Cent je kWh in +deiner Währung). Stell es dir als winzigen Bonus für jede kWh vor, die du aus den eigenen Modulen +nutzt, statt sie zu kaufen: Der Plan bewertet sie mit 1 ct/kWh mehr als dem Preis. Es entscheidet +nur zwischen Möglichkeiten, deren Kosten sich um **weniger als 1 ct/kWh** unterscheiden, kostet +also höchstens 1 ct je kWh; es verhindert, dass der Optimierer bei flachem Tarif beliebig unter +gleich teuren Plänen wählt. **0** bedeutet reine Kosten. + +### Netzladen + +**Standardmäßig aus.** In Schritt 8, **Laden aus dem Netz**, wirkt **Laden des Akkus aus dem Netz +erlauben** nur zusammen mit mindestens einer Regel: + +- einer **Preisgrenze** („nur bei einem Bezugspreis bis höchstens … laden“) und/oder +- einem **Wochenplan** (Zeitfenster, in denen Laden erlaubt ist; **Mit dem Nachtfenster + 22:00–06:00 füllen** gibt dir einen Anfang). Sind beide gesetzt, müssen beide erfüllt sein. + +Bei einem **dynamischen Tarif** kommt eine dritte Regel dazu, der **Preisabstand**: SunCore lädt +nur, wenn ein späterer Preis hoch genug über dem Ladepreis liegt (plus Verschleißkosten und einem +Aufschlag von etwa 3 ct je kWh), um die Verluste zu bezahlen. **Ohne bekannten Preis lädt SunCore +nie aus dem Netz**, und es braucht deine **Anschlussgrenze für Bezug** (Schritt 3), damit es den +Anschluss nie überschreiten kann. Geladen wird nur in Intervallen, die der Plan erlaubt, und der +aktuelle Preis wird bei der Ausführung noch einmal geprüft. + +Ob dein Wechselrichter tatsächlich zum Laden aufgefordert werden kann, ist eine Frage des Adapters, +siehe [Abschnitt 7](#7-adapter). **Kostal Plenticore lässt sich von SunCore nicht zum Laden aus dem +Netz zwingen:** Der Plan zeigt es als „würde laden“, und es wird nichts geschrieben. + +## 5. Steuerung: Schatten, assistiert, Automatik + +Der Akku hat in der Ansicht **Jetzt** eine eigene **Akku**-Karte und einen eigenen Modus, wie ein +Gerät: + +![Akku-Karte und nächste geplante Aktionen in der Ansicht Jetzt](../../assets/screenshots/now-battery-tablet-light-de.png) + +| Modus | Was SunCore mit dem Akku tut | +|---|---| +| **Schattenmodus** (Standard) | Berechnet und zeigt, was es setzen **würde** („SunCore würde setzen“). Schreibt nichts. | +| **Assistierter Modus** | Schlägt Grenzen unter **Vorschläge warten auf dich** vor; **Bestätigen** führt einen aus, und er durchläuft trotzdem die Sicherheitsprüfungen. | +| **Automatikmodus** | Schreibt Grenzen selbst, innerhalb aller Grenzen. | + +Der Akku handelt im **niedrigeren** von Gesamtmodus und eigenem Modus, genau wie ein Gerät. Das +**Umstellen des Akkus auf assistiert oder Automatik** verlangt eine Bestätigung, die die +**Identität** des Akkus trägt (den Adapter, seine zugeordneten Entitäten und die Ladestand- und +Leistungssensoren der Anlage). Änderst du den Adapter oder diese Entitäten oder importierst eine +Konfiguration, **fällt der Akku in den Schattenmodus zurück**, und ein gespeichertes +Einstellungsdokument kann den Modus nicht von allein anheben. + +**Was SunCore schreibt: nur Grenzen.** Nie einen Leistungs-Sollwert. SunCore sagt dem +Wechselrichter, wie viel der Akku laden oder entladen **darf** oder bei welchem Ladestand er +aufhören muss (ein Mindest-Ladestand), und die eigene Eigenverbrauchsregelung des Wechselrichters +erledigt den Rest. Laden aus Solar braucht gar keinen Schreibvorgang. Braucht der Plan keine +Grenze, **gibt** SunCore den Akku **zurück**: Es stellt wieder her, was der Wechselrichter vorher +hatte (seine „Basis“), und der Wechselrichter arbeitet wieder selbstständig. SunCore schreibt nie +Werte über diese Basis hinaus, kann also nur **einschränken**, nie freigeben. + +**Die wirksame Reserve** schützt die Energie, auf die du dich verlässt. Sie ist der **höhere** Wert +aus dem Mindest-Ladestand deines Wechselrichters (Schritt 5, **Mindest-Ladestand**) und der +**Reserve plus BMS-Driftreserve** (**Akkumodell für den Planer**; die Driftreserve, standardmäßig +5 %, ist für Akkus, deren Anzeige nachts absackt). Der Plan geht nie darunter, und die +Sicherheitsschicht verweigert einen Mindest-Ladestand darunter. SunCore hält **keine dauerhafte +Untergrenze** am Wechselrichter: Es schreibt einen Mindest-Ladestand nur für geplante Intervalle, in +denen der Plan Energie für später aufheben will, und deine eigene, niedrigere Untergrenze außerhalb +eines solchen Intervalls bleibt, wie sie ist. + +**Prüfungen.** Jeder Schreibvorgang wird vom Gerät zurückgelesen (beide Kostal-Wege können ohne +Fehlermeldung scheitern), erfolgt nur bei Änderung und ist in der Rate begrenzt. Drei fehlgeschlagene +Schreibvorgänge in Folge pausieren die Akkusteuerung. Ein eingefrorener Akkuwert, ein unbekannter +Ladestand, ein veralteter Plan oder jede Störung pausiert die Steuerung und **gibt** den Akku +**zurück**. Eine Rückgabe ist erst vollständig, wenn das Zurücklesen die ursprünglichen Werte zeigt; +bis dahin versucht SunCore es erneut und schreibt nichts anderes. + +**Wenn du selbst etwas änderst.** Eine Grenze, die du von Hand setzt (in der App des +Wechselrichters oder in Home Assistant), wird am Wert erkannt und **respektiert**: SunCore lässt los, +ohne zu schreiben, und hält sich bis **04:00 Uhr am nächsten Tag** zurück. Ein dokumentierter +Sonderfall: Ein Wert, den du wählst und den SunCore **selbst in derselben Regelphase schon versucht +oder geschrieben** hatte, sieht aus wie SunCores eigener Wert und wird bei der Rückgabe auf die +Basis zurückgesetzt. Das ist die sichere Richtung (die eigenen Einstellungen des Wechselrichters), +heißt aber, dass deine manuelle Wahl in diesem einen Fall verloren geht; wiederhole sie nach der +Rückgabe. Alles andere, was du geändert hast, bleibt. + +**Not-Aus.** Die rote Taste in der Kopfzeile gibt den Akku wie jedes Gerät innerhalb von 10 +Sekunden zurück, und es wird nichts geschrieben, bis du den Stopp beendest. Auch ein normales +**Stoppen**, ein Neustart oder ein Update der App gibt den Akku zurück, bevor die Verbindung +schließt. Nach einem Absturz ist die Aufzeichnung, was SunCore gehalten hat, gespeichert, und beim +nächsten Start wird der Akku zurückgegeben, sobald Home Assistant verbunden ist. + +**Assistiert, bis der Timer gemessen ist.** Manche Adapter können von selbst auf die eigenen +Grenzen des Wechselrichters zurückfallen, wenn SunCore verstummt (Kostal Modbus kann das über einen +Timer im Wechselrichter). Bis du diesen Timer an deiner Anlage **gemessen** hast (siehe +[Abschnitt 7](#den-rückfall-timer-messen)), ist ein solcher Akku **auf den assistierten Modus +begrenzt**: Die Karte sagt es, und Automatik wirkt wie assistiert. + +## 6. Ablauf: dein erster Akku in den assistierten Modus + +Mach das an einem Tag mit Sonne (die Rückfall-Messung in +Abschnitt 7 braucht stattdessen den Abend), mit einem Akku weit über seiner Reserve und +während du zu Hause bist. + +1. **Vorbereiten.** Beende den Einrichtungs-Assistenten. Trage in Schritt 5 die Kapazität, die + maximale Lade- und Entladeleistung und die Reserve ein (**Akkumodell für den Planer**), wähle + **Strategie** und **Risikostufe** (die Vorgaben passen) und einen **Akku-Adapter** (siehe + [Abschnitt 7](#7-adapter)). Trage in Schritt 3 deine **Anschlussgrenze für Bezug** ein. Exportiere + unter **Einstellungen** eine Sicherung. +2. **Im Schatten bleiben.** Sieh dir die Ansicht **Plan** einen oder zwei Tage an. Wirkt das + Diagramm plausibel? Lies die Gründe unter **Nächste geplante Aktionen**. Liegt das Abendziel + nahe an dem, was die Nacht wirklich braucht? Steht im Plan „Regelbasiert“ oder gibt es Warnungen + (siehe [Fehlersuche](#9-fehlersuche))? In der Ansicht **Jetzt** zeigt die Akku-Karte **Aktuelle + Grenzen** (was der Wechselrichter jetzt hat) und, wenn es passt, **SunCore würde setzen**. +3. **Prognosen prüfen.** Sieh dir nach der ersten Nacht **Prognosen und Genauigkeit** an. Eine + Quelle mit riesigem Bias oder sehr alten Daten solltest du zuerst in Ordnung bringen. +4. **Akku auf assistiert stellen.** Wähle auf der Akku-Karte **Assistierter Modus**, lies den Dialog + und bestätige. Auch der Gesamtmodus muss **Assistiert** oder **Automatik** sein (Schritt 9 oder + **Einstellungen → Betriebsmodus**), sonst bleibt der Akku im niedrigeren. Die Geräte behalten + ihre eigenen Modi. +5. **Auf einen Vorschlag warten.** Vorschläge erscheinen, wenn der Plan eine Grenze will, zum + Beispiel eine Entladesperre („Akkuentladung zurückgehalten“ in **Nächste geplante Aktionen**). + Das kann Stunden oder Tage dauern: Bei flachem Tarif und vollem Akku braucht der Plan vielleicht + nie einen. Ein Vorschlag gilt 2 Minuten. **Bestätige** nur, wenn der Grund einleuchtet, + sonst **Verwerfen**. +6. **Den ersten Schreibvorgang beobachten.** Nach **Bestätigen** zeigt die Karte **SunCore hält + diese Grenzen**. Sieh auf das Display des Wechselrichters oder die Home-Assistant-Entität: Der Wert + muss stimmen (SunCore prüft das selbst und meldet eine Abweichung). Kostal REST braucht bis zu 35 + Sekunden. +7. **Deine Ausgänge kennen.** **Schattenmodus** auf der Karte gibt den Akku zurück. **Not-Aus** in + der Kopfzeile gibt ihn sofort zurück. Setzt du selbst eine Grenze, lässt SunCore bis 04:00 Uhr los. +8. **Erst dann über Automatik nachdenken**, nach mehreren Tagen sinnvoller Vorschläge. Adapter ohne + Hardware-Rückfall (generisch, Kostal REST) sind nicht begrenzt, aber eine Grenze bleibt im + Wechselrichter, bis SunCore sie zurückgibt oder neu startet: Bleib lange im assistierten Modus + und betrachte das als bewusste Entscheidung. + +## 7. Adapter + +Wähle in Schritt 5 unter **Steuerung** den **Akku-Adapter**. Vorgabe ist **Nur beobachten (SunCore +schreibt nie)**: Der Akku gehört zum Plan, aber du stellst ihn selbst ein. Die Akku-Karte listet, +was der Adapter **einstellen kann**. + +![Einrichtungsschritt 5: Akkusensoren, Modell, Adapter und Strategie](../../assets/screenshots/wizard-battery-tablet-light-de.png) + +### Generisch: Home-Assistant-Entitäten + +**Akku mit Zahlen-Entitäten (generisch).** Ordnet bis zu vier optionale `number`-Entitäten deiner +Akku-Integration zu: Mindest-Ladestand (%), maximale Ladeleistung, maximale Entladeleistung (W oder +kW) und eine Zwangsladeleistung aus dem Netz. SunCore setzt, was du zuordnest; leere Rollen +werden nicht genutzt. Es stellt auch wieder her, was die Zahlen vorher hatten. Der Adapter wurde +noch nie an einem echten Akku betrieben (**Nicht an echter Hardware geprüft**); beginne im Schatten +und vergleiche. Das ist der Adapter, wenn deine Integration über eine Zahl ein Laden aus dem Netz +erzwingen kann. + +### Kostal Plenticore über die Home-Assistant-Integration + +Adapter **KOSTAL PLENTICORE (Home-Assistant-Integration, Mindest-Ladestand)**. Er kann **nur den +Mindest-Ladestand** setzen (`Battery:MinSoc`): SunCore nutzt ihn als **Entladesperre** für geplante +Intervalle und gibt ihn danach zurück. Er kann **die Leistung nicht begrenzen und nicht aus dem Netz +laden** (die REST-Schnittstelle hat keinen solchen Sollwert): Ein geplantes Netzladen wird nur +**angezeigt** („würde aus dem Netz laden, aber der Adapter kann kein Laden erzwingen“), nie +ausgeführt. Weil die Zahl des Wechselrichters in 5-%-Schritten läuft, rundet SunCore **auf**. Ein +fehlgeschlagener Schreibvorgang bleibt in dieser Integration stumm, deshalb liest SunCore den Wert +nach etwa 35 Sekunden zurück und glaubt nur, was es sieht. Ohne Hardware-Rückfall bleibt die Sperre, +bis SunCore sie zurückgibt: SunCore sperrt nur für geplante Intervalle, nie unbegrenzt. + +**Die Entität `Battery:MinSoc` ist in Home Assistant standardmäßig deaktiviert.** Aktiviere sie: + +1. Öffne **Einstellungen → Geräte & Dienste** und die Integration **Kostal Plenticore**, dann dein + Wechselrichter-Gerät. +2. Zeige die deaktivierten Entitäten an (ein Hinweis wie „+N Entitäten nicht angezeigt“ lässt sie + aufklappen, oder nutze den Filter für deaktivierte Entitäten) und öffne die Zahl **Battery min + SoC**. +3. Öffne ihre **Einstellungen** (Zahnrad), schalte **Aktiviert** ein und speichere. Home Assistant + lädt die Integration nach etwa 30 Sekunden neu; die Entität zeigt dann einen Wert zwischen 5 und + 100 %. +4. Vergleiche den Wert mit dem Mindest-Ladestand auf dem Display deines Wechselrichters. +5. Wähle in SunCore Schritt 5 unter **Steuerung** den Kostal-Adapter und ordne die Rolle **Zahl + „Battery min SoC“ des Wechselrichters** zu. Listet die Auswahl sie noch nicht, hake **Auch + ausgeblendete und Diagnose-Entitäten anzeigen** an. Die optionale Auswahl **Battery charging / + usage mode** wird nur gelesen. +6. Prüfe die Vorzeichen im Feld **Vorzeichen prüfen** von Schritt 5 (das Akkuvorzeichen der + Kostal-REST-Integration ist `UNVERIFIED`), lass den Akku im **Schattenmodus** und beobachte die + ersten Vorschläge im assistierten Modus. + +(Die Menünamen stammen aus der Erinnerung an Home Assistant und wurden für diese Anleitung nicht +durchgeklickt; sie unterscheiden sich je nach Version.) + +### Kostal Plenticore über Modbus (Grenzen nach §3.5) + +Adapter **KOSTAL PLENTICORE G3 Akku-Grenzen über Modbus (§3.5)**. Er kann die **maximale Lade- und +Entladeleistung** setzen und hat einen **Hardware-Rückfall**: SunCore schreibt die Grenzen alle 20 +Sekunden neu; hört es auf, kehrt der Wechselrichter nach einem Timer (standardmäßig 60 Sekunden) zu +seinen Rückfallgrenzen zurück. Auch er kann kein Laden aus dem Netz erzwingen. Er braucht: + +- **Vom Installateur aktiviertes externes Batteriemanagement über Modbus** (Register 1080 muss `2` + melden; sonst weigert sich SunCore zu schreiben). Wie es aktiviert wird, ist hier nicht + dokumentiert. +- Einen **`modbus`-Hub** in Home Assistant (ob er sich in der Oberfläche anlegen lässt, ist + `UNVERIFIED`; nimm YAML an) mit der Unit-ID des Wechselrichters (Kostal-Standard 71) und je einen + Sensor pro Register: 1080, 1280, 1282, 1284, 1286, 1288, 1076, 1078 und Register 5. Jeder wird in + Schritt 5 der Rolle mit dem Namen seines Registers zugeordnet. +- Die **Wortreihenfolge von Register 5** (**Little Endian** oder **Big Endian**), eingetragen unter + **Modbus-Verbindung**. SunCore rät sie nie. + +Dieser Adapter **läuft bisher nur im Simulator**, weil beim Wechselrichter des Maintainers das +externe Batteriemanagement noch nicht aktiviert ist. Er ist **auf assistiert begrenzt**, bis +`fallback_measured` gesetzt ist. + +#### Den Rückfall-Timer messen + +Mach das **einmal**, während du zu Hause bist. Es beweist, dass der Wechselrichter wirklich auf +seine eigenen Grenzen zurückfällt, wenn SunCore verstummt, und genau deshalb ist Automatik +überhaupt erlaubt. + +**Sicherer Test, kurz:** Alle Geräte im Schattenmodus, den Akku im assistierten Modus, abends +(Hauslast über der Solarleistung) eine Entladesperre bestätigen, SunCore abrupt beenden, sodass +es nichts zurückgeben kann, und beobachten, wann der Akku wieder entlädt. Erwartet: 40 bis 60 +Sekunden nach dem Beenden (der eingestellte Timer minus die Zeit seit SunCores letztem +Neuschreiben), plus die Verzögerung deines Leistungssensors. + +Bevor du anfängst: + +- Der Akku liegt weit über seiner Reserve (zum Beispiel 30 Punkte), die Hauslast ist niedrig und + es startet keine große Last (keine Wallbox, kein Wärmepumpen-Boost, kein Kochen). Die + Solarleistung liegt **unter** der Hauslast, der Akku entlädt also schon vor dem Test (Abend oder + trüber Tag). Die Sperre, die SunCore vorschlägt, ist eine **volle Entladesperre** (0 W): Das Haus + bezieht seine ganze Last für ein paar Minuten aus dem Netz und, falls der Wechselrichter nicht + zurückfällt, bis du ihn wiederherstellst. Es ist keine Not-Aus-Lage. +- Stelle **jede Gerätekarte auf Schattenmodus** (der Gesamtmodus bleibt Assistiert). Ein + beendetes SunCore kann nichts zurückgeben: Ein Gerät, das es eingeschaltet hatte, bliebe bei + gesperrtem Akku an, und keine Bezugsgrenze wird mehr überwacht. +- Lass den Modbus-Timer auf der Vorgabe (`fallback_timeout_s` 60 s, `heartbeat_s` 20 s). Der + Sensor von Register 1080 zeigt `2`, und du kennst die eigenen Grenzen des Akkus (1076, 1078). + Die Rückfall-Register werden in Schritt 2 geprüft. +- Du siehst **Akkuleistung** und **Netzleistung** mit Zeitstempeln (ein Verlaufsdiagramm). +- Du kommst an die Shell des Home-Assistant-Hosts (zum Beispiel mit der App „Advanced SSH & Web + Terminal“ bei ausgeschaltetem Schutzmodus) **oder** kannst die App anderweitig abrupt beenden. + Schalte den Schutzmodus nach dem Test wieder ein. +- **Schalte den Watchdog der App AUS** (Seite **Info** der App), bevor du testest. Bei + eingeschaltetem Watchdog startet der Supervisor einen beendeten Container sofort neu, SunCore + gibt den Akku zurück und schreibt die Grenzen innerhalb der 60 Sekunden selbst, und der Test + zeigt einen Rückfall, der nie stattgefunden hat (falsch positiv). Schalte den Watchdog danach + wieder ein. (Verhalten aus dem Supervisor-Quelltext `supervisor/apps/app.py` gelesen am + 2026-10-28; auf HA OS `UNVERIFIED`.) +- **Abbruchkriterien:** ein Modbus-Fehler im Protokoll, Register 1080 nicht `2`, ein Sensor, der + nicht zeigt, was SunCore geschrieben hat, ein Ladestand, der sich der Reserve nähert, Netzbezug + nahe deiner Anschlussgrenze, die Solarleistung deckt die Last, SunCore läuft wieder, bevor du + den Rückfall beobachtet hast (siehe Schritt 4), oder irgendetwas, das du nicht verstehst. Dann + nicht weitermachen: Starte die App (sie gibt den Akku nach dem Verbinden zurück), stelle die + Akku-Karte auf **Schattenmodus** und sieh ins Protokoll. Kehrt die Grenze nicht von allein + zurück: Starte SunCore und prüfe, ob der Sensor von Register 1282 die eigene Entladegrenze des + Akkus zeigt und der Akku wieder entlädt. Klappt auch das nicht, lass deinen Installateur (oder + den Installateurzugang zur Weboberfläche des Wechselrichters) das externe Batteriemanagement + über Modbus ausschalten. Halte bis dahin große Lasten aus: Eine hängende Entladesperre kostet + Netzbezug, schadet dem Akku aber nicht. Lass `fallback_measured` auf false. + +Schritte: + +1. Stelle den Akku auf **Assistierter Modus** (siehe + [Abschnitt 6](#6-ablauf-dein-erster-akku-in-den-assistierten-modus)). +2. Warte auf einen Vorschlag, der eine **Entladegrenze** enthält (der Plan zeigt „Akkuentladung + zurückgehalten“). **Bestätige** ihn einmal. Die Karte zeigt **SunCore hält diese Grenzen**, und + der Sensor von Register 1282 zeigt den Wert. Prüfe jetzt die Rückfall-Register, die SunCore vor + diesem Schreiben gesetzt hat: 1288 zeigt 60, und 1284 und 1286 zeigen die eigenen Grenzen des + Akkus oder höhere. Wenn nicht, brich ab. +3. Prüfe die Wirkung: Bei einer Entladegrenze von 0 W geht die Akkuleistung auf etwa 0 W, und das + Haus bezieht aus dem Netz. Warte mindestens 20 Sekunden (ein Heartbeat), damit der Wert sichtbar + gehalten wird. Entlud der Akku vorher nicht (die Solarleistung deckt die Last), kann der Test + den Rückfall nicht zeigen: Lass den Vorschlag auslaufen und versuche es an einem anderen Abend. +4. Notiere die Uhrzeit (sekundengenau). Solange die Karte noch **SunCore hält diese Grenzen** + zeigt, beende den Container mit `docker kill ` ohne Option `--signal` (das sendet + SIGKILL). Den Namen findest du mit `docker ps` (er endet auf `suncore`; der genaue Name ist + `UNVERIFIED`). Nutze nie `docker stop`, `docker restart`, `docker kill --signal=TERM`, + `ha apps stop` oder die Stopp-Schaltfläche: Sie lassen SunCore sauber herunterfahren und den + Akku zurückgeben, was nichts beweist. Prüfe auf der App-Seite und mit `docker ps`, dass die App + **gestoppt bleibt**. Suche später, nach dem Start, im **Entscheidungsprotokoll** den Eintrag + „Neustart nach unsauberem Stopp“ (`safety.crash_recovery`): Seine Zeit muss **nach** dem + beobachteten Rückfall liegen, sonst hat SunCore die Grenzen selbst geschrieben, und die Messung + ist ungültig. +5. Beobachte Akkuleistung und Netzleistung. Fällt der Wechselrichter zurück, beginnt der Akku, ins + Haus zu entladen, und der Netzbezug sinkt. Notiere die Zeit, zu der das passiert. Die Zeit vom + Beenden bis zu diesem Moment ist dein Ergebnis. Sie ist der Timer minus die Zeit seit SunCores + letztem Neuschreiben (0 bis 20 s), plus deine Sensorverzögerung. Nutze dafür nicht die Sensoren + 1280/1282: Sie zeigen nach dem Rückfall möglicherweise weiter SunCores letzten Wert + (`UNVERIFIED`). +6. **Erwartet:** Der Akku entlädt wieder zwischen etwa 40 und 60 Sekunden nach dem Beenden, plus + einem Sensorschritt (angenommen 15 Sekunden). Deutlich schneller als 35 Sekunden heißt, dass + etwas anderes als der Timer des Wechselrichters die Grenzen zurückgegeben hat (SunCore wurde + nicht abrupt beendet, oder etwas anderes hat sie geschrieben): Der Lauf ist ungültig. Hat der + Akku nach dem Dreifachen des eingestellten Timers (3 Minuten) nicht begonnen zu entladen, + **brich ab**: Starte SunCore und nimm den Wechselrichter wie oben beschrieben von Hand zurück. +7. Starte die App wieder. Sie findet die Aufzeichnung, was sie gehalten hat, und gibt den Akku + zurück (schreibt die eigenen Grenzen), sobald Home Assistant verbunden ist. Schalte den + Watchdog der App wieder ein und stelle die Gerätekarten auf ihre früheren Modi zurück. +8. Wiederhole es zur Sicherheit einmal. Ist der Wechselrichter in beiden Läufen wie erwartet + zurückgefallen: **Exportiere** die Konfiguration unter **Einstellungen**, setze in der Datei im + Abschnitt `battery` `"fallback_measured": true` (`sections → battery → body`) und + **importiere** sie wieder. Die Akku-Karte zeigt dann die Begrenzung auf assistiert nicht mehr + (die Einstellung hat im Panel noch keinen Schalter). `fallback_measured` ist deine eigene + Aussage; SunCore prüft sie nicht. Sie hebt nur die Begrenzung auf: Sie schaltet nichts auf + Automatik und ändert weder Timer noch Heartbeat. Sie gilt nur für den Timer, mit dem du + gemessen hast, an diesem Wechselrichter und dieser Firmware. Änderst du `fallback_timeout_s` + oder `heartbeat_s`, aktualisierst du die Firmware, tauschst den Wechselrichter oder verkabelst + den Modbus-Hub neu, setze sie wieder auf false und miss erneut. Ein Import setzt Gesamtmodus + und Akku wie immer auf Schatten zurück: Stelle sie wieder um, einen Schritt nach dem anderen. + +Ist in einem Lauf der Rückfall ausgeblieben, später als 60 Sekunden plus einem Sensorschritt +eingetreten oder der Lauf ungültig, lass `fallback_measured` auf false (die Begrenzung bleibt) und +eröffne ein Issue mit deinen Messwerten. + +## 8. Was du sonst noch siehst + +- **Einstellungen** listet **Akku (Steuerung und Planung)** (Adapter, Strategie, Risikostufe) und + **PV-Prognose** (die Zahl der Quellen). Beide lassen sich wie jeder Abschnitt öffnen, + wiederherstellen und exportieren. +- **Einrichtungsschritt 10** zeigt den **Ersten Plan**: erwartete Solarenergie, Verbrauch, Bezug und + Einspeisung der nächsten Stunden sowie tiefsten, höchsten und letzten Ladestand des Akkus. + **Vorschau aktualisieren** berechnet ihn neu. +- Das **Entscheidungsprotokoll** listet auch Akku-Entscheidungen mit Gründen. +- Der Planer braucht den Ladestand des Akkus. Ohne ihn („Warte auf den Ladestand der Batterie, bevor + geplant wird“) gibt es keinen Plan. + +## 9. Fehlersuche + +- **„Es gibt noch keinen Plan: SunCore regelt nur nach den Überschussregeln.“** Der Planer ist noch + nicht gelaufen. Er wartet auf Preise und Prognosen und startet spätestens 5 Minuten nach der + ersten Verbindung; der Hinweis in der Planansicht nennt, was fehlt (zum Beispiel „Warte auf den + Ladestand der Batterie“ oder „Noch nichts zu planen: Die Anlage ist nicht eingerichtet oder Home + Assistant ist nicht verbunden“). Drücke **Jetzt neu planen**, wenn du es behoben hast. +- **„Der Plan ist älter als … h“ / veraltet.** Nach 2 Stunden ohne neuen Plan nutzt SunCore ihn nicht + mehr und regelt nur nach den Überschussregeln (das Verhalten von Phase 3). Sieh im Block **Planer** + nach Fehlschlägen und ins Protokoll; der letzte gute Plan bleibt sichtbar, als veraltet markiert. +- **Der Plan ist „Regelbasiert“.** Der Optimierer hat nicht geliefert; der Grund an der Marke sagt + warum (Zeitbudget, Löser nicht verfügbar, …). Der regelbasierte Plan ist sicher, aber weniger + klug. +- **„Keine Strompreise: Planung nur auf Autarkie, ohne Preisoptimierung“** oder **„… liefert reine + Börsenpreise und es ist keine Preisformel eingerichtet“** (dieselbe Warnung erscheint in der + Systemprüfung von Schritt 10). Der Plan läuft in einem flachen Modus ohne Preisoptimierung. + Prüfe die Preisquelle (Status unter **Tarif**) oder ergänze in Schritt 6 die Preisformel. +- **„Der Ladestand des Akkus ist unbekannt: Der Akku bleibt aus dem Plan“**, **„Keine + Solarprognose“**, **„Noch keine Lastprognose“.** Behebe die Entität oder ergänze eine + Prognosequelle (Schritt 4); der Plan nennt jede fehlende Eingabe. +- **Ein Ziel „ist nicht erreichbar“.** Der Plan sagt „Das Abendziel von 70 % um 18:00 ist nicht + erreichbar: Der Plan erwartet 55 %“: Der Tag bietet auf deiner Risikostufe zu wenig Energie, oder + deine Grenzen (maximale Ladeleistung, Anschlussgrenze) sind zu eng. +- **Die Akku-Karte sagt „Pausiert: …“.** Die Akkusteuerung ist aus einem Grund pausiert (eingefrorener + Wert, veraltete Eingaben, eine unvollständige Rückgabe, drei fehlgeschlagene Schreibvorgänge). Der + Grund nennt es; sie läuft weiter, sobald die Werte wieder plausibel sind. +- **„Der Akku-Adapter kann kein Laden erzwingen: nur angezeigt“.** Bei Kostal Plenticore zu + erwarten: Netzladen wird geplant und angezeigt, ist aber nicht ausführbar. +- **Keine Genauigkeitswerte.** Sie werden jede Nacht berechnet; warte auf die erste Nacht mit Daten. +- **Mehr** im Abschnitt zur Fehlersuche der [App-Beschreibung](../../../addon/suncore/DOCS.md) + (englisch) und in der [Überschusssteuerung](surplus-control.md). + +## 10. Bekannte Grenzen und UNVERIFIED + +- **Vom Projekt bisher nie an echter Hardware betrieben.** Planer, Prognosen, Tarife und der + Akkupfad sind im Simulator und mit Testdaten nach dem Quellcode der Integrationen geprüft. + Formulierungen und Menüpfade in dieser Anleitung wurden nicht in einem echten Home Assistant + durchgeklickt. +- **Kostal Modbus** läuft nur im Simulator: Wie das externe Batteriemanagement aktiviert wird, der + Rückfall-Timer des Wechselrichters und die Bytereihenfolge von Register 5 und des Timer-Registers 1288 + sind unbestätigt. Das Verfahren oben soll den Timer messen. +- **Kostal REST:** Das Vorzeichen von Akku- und Netzleistung, wie schnell der Mindest-Ladestand + zurückgelesen wird (35 Sekunden angenommen) und ob Werte außerhalb des Bereichs begrenzt werden, + sind unbestätigt. +- **Netzladen ist bei Kostal Plenticore nicht ausführbar** (keiner der beiden Wege hat einen + Lade-Sollwert). Es wird nur geplant und angezeigt. Ein generischer Adapter mit einer + Zwangslade-Zahl kann es, wenn deine Integration eine anbietet. +- **Generischer Adapter:** nur im Simulator erprobt. +- **Gewichte und Regeln des Planers** (Strafen für verfehlte Ziele, der Wert der am Horizontende + übrigen Energie, das Gerätebudget) sind begründet, nicht angepasst. An einem Tag mit weit weniger + Sonne als prognostiziert (unter etwa der Hälfte der geplanten Solarenergie) kann das Abendziel um + einige Prozentpunkte verfehlt werden, weil die Verbraucher zuerst ihren Anteil bekamen. Rechenzeiten + auf einem Raspberry Pi (aarch64) sind nicht gemessen; auf einem PC sind es einige Millisekunden. +- **Kalibrierungs- und Risikokonstanten** (Klarhimmel-Klassen, Schrumpfung, Grenzen 0,5–1,5, + Standardbänder je Wetterklasse) sind begründet, nicht an echten Daten angepasst; sie brauchen + deine 30 Tage. +- **Tarife:** Wie die MwSt. auf negative Börsenpreise wirkt, ist angenommen; die Negativpreis-Regel + nutzt bei All-in-Quellen wie Tibber den Endpreis als Ersatz; die Veröffentlichungszeit der Preise für + morgen (13:00) ist angenommen; die Konfigurations-ID von Nord Pool musst du von Hand eintragen; die + amtliche deutsche Einspeisestufen-Tabelle ist nicht eingebaut. +- **Nicht modelliert:** das thermische Verhalten von Klimageräten und Warmwasserbereitern im Plan + (sie bekommen nur den Überschuss), Einspeisebegrenzung über den Wechselrichter (Abregelung wird + angezeigt, nicht gesteuert), Lastspitzenkappung, Wallbox, Wärmepumpe, verschiebbare Programme. +- **Kein Verlauf, kein Was-wäre-wenn.** Die Planansicht ist minimal; das volle Diagramm, Verlauf und + Analyse folgen in Phase 5. +- **Nach einem Neustart** wird der erste Plan neu berechnet (gespeicherte Pläne werden nicht + zurückgelesen). +- **Zeitreihen** (`timeseries.db`) gehören nicht zur App-Sicherung; SunCore baut 28 Tage + Viertelstundenverlauf aus den Statistiken von Home Assistant neu auf. Die gelernten Korrekturen + brauchen neue Tage. +- **Downgrade:** Diese Version speichert ihre Daten im Datenbankschema 4, das frühere Versionen nicht + öffnen können. Exportiere die Konfiguration vor dem Update. +- **Im Vergleich zu EMHASS und Predbat:** Beide sind deutlich ausgereiftere Optimierer mit jahrelanger + Praxis; SunCores Planer ist neu und an Hardware unerprobt. SunCore ergänzt eine App mit Prognosen, + Plan, Akkusteuerung, Sicherheitsschicht, Schattenmodus und einer Begründung für jede + Entscheidung, eingerichtet über einen Assistenten. Für Ladepunkte bleibt evcc die bessere Wahl. + +Siehe auch: [Schnellstart](quick-start.md), [Überschusssteuerung](surplus-control.md), +[Gerätevorlage beitragen](device-templates.md), [Kompatibilitätsliste](../compatibility.md). diff --git a/docs/user/de/quick-start.md b/docs/user/de/quick-start.md index 652841f..23c0a13 100644 --- a/docs/user/de/quick-start.md +++ b/docs/user/de/quick-start.md @@ -1,12 +1,14 @@ # Schnellstart -SunCore ist **Pre-Alpha** (Phase 3). Diese Version hilft dir mit einem +SunCore ist **Pre-Alpha** (Phase 4). Diese Version hilft dir mit einem Einrichtungs-Assistenten, deine Anlage zu beschreiben, zeigt deinen -Energiefluss live an und kann Geräte aus deinem Solarüberschuss steuern. Sie -startet im **Schattenmodus**: Es wird nichts geschaltet und kein Sollwert -geschrieben, bis du selbst ein Gerät auf Automatik stellst, siehe -[Überschusssteuerung](surplus-control.md). Die vollständige App-Beschreibung -(englisch) steht in [`addon/suncore/DOCS.md`](../../../addon/suncore/DOCS.md). +Energiefluss live an, steuert Geräte aus deinem Solarüberschuss und plant mit +Prognosen, Preisen und deinem Akku die nächsten 48 Stunden. Sie startet im +**Schattenmodus**: Es wird nichts geschaltet und keine Grenze und kein +Sollwert geschrieben, bis du selbst ein Gerät oder den Akku auf Automatik (oder +assistiert) stellst, siehe [Überschusssteuerung](surplus-control.md) und +[Planung und Akkusteuerung](planning-and-battery.md). Die vollständige +App-Beschreibung (englisch) steht in [`addon/suncore/DOCS.md`](../../../addon/suncore/DOCS.md). ## 1. Installieren @@ -83,26 +85,51 @@ noch einmal, wenn deutlich etwas fließt. Füge jede PV-Anlage mit ihrem **Leistungssensor**, der installierten Leistung in kWp sowie Neigung und Ausrichtung hinzu (Azimut: 0 = Nord, -180 = Süd). Optional wählst du eine **Prognosequelle**, etwa Solcast, wenn -die Integration installiert ist. +180 = Süd). Unter **Prognosequellen** wählst du eine oder **mehrere** +Solarprognosen (Solcast, Forecast.Solar, Open-Meteo Solar Forecast oder eine +generische Vorlage); SunCore bietet die an, die es in Home Assistant findet, +und mischt sie danach, wie gut jede lag (das **Gewicht in der Mischung** ist +automatisch, solange du keinen festen Anteil setzt). Bei Forecast.Solar mit +mehreren verknüpften Einträgen wählst du den **Forecast.Solar-Eintrag** dieser +Anlage. Optional ergänzt du unter **Eingaben der Lastprognose** einen +**Arbeitstag-Sensor** und eine **Wetter-Entität**: Sie verbessern die Prognose +der Hauslast. Ganz ohne Prognosequelle geht es auch; der Plan rechnet dann +ohne Solarstrom. Siehe [Prognosen](planning-and-battery.md#2-prognosen). ![Schritt Photovoltaik](../../assets/screenshots/wizard-pv-tablet-light-de.png) ### Batterie Wähle den Sensor für die Batterieleistung (positiv = Laden) und den für den -Ladestand, oder **Keine Batterie**. Kapazität sowie Mindest- und maximaler -Ladestand sind optional. SunCore beobachtet die Batterie vorerst nur. +Ladestand, oder **Keine Batterie**. Kapazität, Mindest- und maximaler +Ladestand und die Leistungsgrenzen sind zum Beobachten optional, der Planer +braucht sie aber. Unter **Steuerung** wählst du einen **Akku-Adapter**: Die +Vorgabe **Nur beobachten (SunCore schreibt nie)** überlässt den Akku dir; ein +Adapter (generische Home-Assistant-Entitäten, Kostal Plenticore über die +Home-Assistant-Integration oder über Modbus) lässt SunCore später Grenzen +setzen, und der Akku startet trotzdem im Schattenmodus. Danach füllst du das +**Akkumodell für den Planer** (Kapazität, Leistungsgrenzen, Reserve, +BMS-Driftreserve) und wählst die **Strategie** (Eigenverbrauch, Akku möglichst +voll halten oder Zielladestand zu einer Uhrzeit erreichen), die +**Risikostufe** (vorsichtig ist die Vorgabe, die Ziele werden dann in etwa 9 +von 10 Fällen erreicht), einen optionalen **Mindest-Morgenpuffer** und **Bis +in den nächsten Tag überbrücken**. Alles ist in +[Planung und Akkusteuerung](planning-and-battery.md#4-ziele-und-strategien) +erklärt, die Adapter in [Adapter](planning-and-battery.md#7-adapter). ![Schritt Batterie](../../assets/screenshots/wizard-battery-tablet-light-de.png) ### Tarif -Gib den **Bezugspreis** (**Fester Preis** oder **Dynamischer Preis**) und -die **Einspeisevergütung** ein (fest, gestaffelt nach Anlagengröße oder -keine). Ein dynamischer Preis braucht einen Preissensor oder eine -Tarif-Vorlage wie Tibber. Die Preise werden für spätere Versionen -gespeichert; der Planer nutzt sie noch nicht. +Gib den **Bezugspreis** (**Fester Preis**, **Fester Zeittarif (HT/NT)** oder +**Dynamischer Preis**) und die **Einspeisevergütung** ein (fest, gestaffelt nach +Anlagengröße oder keine). Ein dynamischer Preis braucht einen Preissensor oder +eine Tarif-Vorlage (Tibber, Nord Pool, ENTSO-E, EPEX Spot, Octopus Energy oder +eine generische Preisliste). Liefert die Quelle nur den reinen Börsenpreis, +wähle unter **Was der Preis enthält** die Option **Nur Börsenpreis** und trage +deine **Preisformel** ein (Netzentgelt, Abgaben, Aufschlag, MwSt); ohne sie kann +der Planer nicht nach Preisen optimieren. Der Planer nutzt diese Preise; siehe +[Tarife](planning-and-battery.md#3-tarife). ![Schritt Tarif](../../assets/screenshots/wizard-tariff-tablet-light-de.png) @@ -143,12 +170,14 @@ Fehlt dein Gerät? Siehe Ziehe die Geräte am Griff oder nutze die Pfeil-Schaltflächen oder die Pfeiltasten, um festzulegen, wer den Überschuss zuerst bekommt. Position 1 wird zuerst bedient. Ziele -(Ziel-Ladestand der Batterie zu einer Uhrzeit, Klimagerät vor der -Einspeisung, nur nachts aus dem Netz laden) entscheiden -jetzt, ob die Ladeleistung der Batterie für Geräte als Überschuss zählt (Ziel-Ladestand, -Klimagerät vor Einspeisung); siehe -[Batterie und Ziele](surplus-control.md#batterie-und-ziele). Nur nachts aus dem Netz laden wird -für eine spätere Version gespeichert. +entscheiden, ob die Ladeleistung der Batterie für Geräte als Überschuss zählt +(Ziel-Ladestand der Batterie zu einer Uhrzeit, Klimagerät vor Einspeisung); +siehe [Batterie und Ziele](surplus-control.md#batterie-und-ziele). Unter **Laden +aus dem Netz** kannst du erlauben, den Akku aus dem Netz zu laden, nur unter +einer Preisgrenze und in einem Wochenplan (standardmäßig aus; siehe +[Netzladen](planning-and-battery.md#netzladen)). Das Expertenfeld +**Autarkie-Gewicht je kWh** ist ein kleiner Gleichstand-Entscheider für den +Planer ([erklärt hier](planning-and-battery.md#das-autarkie-gewicht)). ![Schritt Prioritäten und Ziele](../../assets/screenshots/wizard-priorities-tablet-light-de.png) @@ -168,7 +197,13 @@ Automatik braucht also beides. Lass es vorerst auf Schatten. Der **Systemcheck** prüft Einheiten, Vorzeichen, die Leistungsbilanz und ob die Sensoren aktuelle Werte liefern. Behebe alles, was mit einem Kreuz markiert ist (Schritt über die Liste öffnen), wähle **Erneut prüfen** und -dann **Einrichtung abschließen**. Warnungen blockieren nicht. +dann **Einrichtung abschließen**. Warnungen blockieren nicht. Eine Warnung, +dass der Tarif reine Börsenpreise ohne Preisformel liefert, heißt: Der Plan +kann nicht nach Preisen optimieren, ergänze die Formel im Schritt **Tarif**. +Die Zusammenfassung zeigt außerdem den **Ersten Plan**: erwartete +Solarenergie, Verbrauch, Bezug und Einspeisung der nächsten Stunden sowie +tiefsten, höchsten und letzten Ladestand des Akkus. **Vorschau aktualisieren** +berechnet ihn neu. ![Schritt Zusammenfassung und Check](../../assets/screenshots/wizard-summary-tablet-light-de.png) @@ -191,23 +226,31 @@ Schritt-für-Schritt-Anleitung ist ## 5. Die Ansicht Jetzt Nach **Einrichtung abschließen** zeigt die Ansicht **Jetzt** Solar, Netz, -Batterie und Haus mit animierten Flüssen, die Karte **Überschuss** und eine -Karte je Gerät mit Zustand, geschätzter Leistung, Modus-Umschalter und -**Warum?**. Die rote Schaltfläche **Not-Aus** in der Kopfzeile gibt alle Geräte -sofort zurück. +Batterie und Haus mit animierten Flüssen, die Karte **Überschuss**, eine +**Akku**-Karte (Ladestand, Leistung, geltende Grenzen, Modus-Umschalter des Akkus +und **Warum?**), die **Nächsten geplanten Aktionen** und eine Karte je Gerät mit +Zustand, geschätzter Leistung, Modus-Umschalter und **Warum?**. Die rote +Schaltfläche **Not-Aus** in der Kopfzeile gibt alle Geräte und den Akku sofort +zurück. Die Seite **Plan** zeigt den 24- oder 48-Stunden-Plan mit den Prognosen +und ihrer Genauigkeit. ![Ansicht Jetzt auf einem Tablet, helles Design](../../assets/screenshots/now-tablet-light-de.png) +![Akku-Karte und nächste geplante Aktionen](../../assets/screenshots/now-battery-tablet-light-de.png) + Das **Entscheidungsprotokoll** (Ansicht **Entscheidungen**) listet jede Entscheidung mit ihren Gründen. Wie das alles funktioniert, was passiert, wenn du ein Gerät selbst änderst, und was SunCore bei Fehlern tut, steht in der -[Überschusssteuerung](surplus-control.md). +[Überschusssteuerung](surplus-control.md); Plan, Prognosen und Akku stehen in +[Planung und Akkusteuerung](planning-and-battery.md), mit einem Ablauf, um deinen +ersten Akku in den assistierten Modus zu nehmen. ## 6. Später ändern Öffne **Einstellungen**. Dort stehen alle Bereiche deiner Einrichtung (**Region**, **Anlage (Netz, PV, Batterie)**, **Tarif**, **PV-Prognose**, -**Verbraucher**, **Ziele**, **Betriebsmodus**) mit einer Kurzfassung und +**Akku (Steuerung und Planung)**, **Verbraucher**, **Ziele**, +**Betriebsmodus**) mit einer Kurzfassung und einem Link **Öffnen** zum passenden Schritt. ![Einstellungen als Übersicht](../../assets/screenshots/settings-tablet-light-de.png) @@ -255,13 +298,19 @@ einem Link **Öffnen** zum passenden Schritt. ## Was SunCore noch nicht kann -Bedenke das, bevor du dich darauf verlässt. Diese Version hat keine -Prognosen und keinen Planer (deine Tarif- und Prognose-Angaben werden nur -gespeichert), keine Verlaufsdiagramme, keine Batteriesteuerung, keine -Wallbox-Steuerung und keine Home-Assistant-Entitäten. Die Überschusssteuerung -lief noch nie an echter Hardware: Dafür ist dein Schattenlauf da. Verglichen -mit evcc (Ladepunkte und Heizstäbe), EMHASS und Predbat (Batterieoptimierung) -steuert SunCore derzeit nur Verbraucher aus echtem Überschuss. Die Liste der +Bedenke das, bevor du dich darauf verlässt. SunCore hat jetzt Prognosen, Tarife, +einen 48-Stunden-Planer und Akkusteuerung, aber **nichts davon ist je an echter +Hardware gelaufen**: Dafür ist dein Schattenlauf da. Der Akku startet im +Schattenmodus, und bis der Rückfall-Timer des Wechselrichters an deiner Anlage +gemessen ist, bleibt ein Kostal-Modbus-Akku auf den assistierten Modus +begrenzt. Kostal Plenticore lässt sich nicht zum Laden aus dem Netz +auffordern. Es gibt noch keine Verlaufsdiagramme und keine Was-wäre-wenn-Analyse +(die Planansicht ist minimal), keine thermischen Modelle für Klimageräte und +Warmwasserbereiter im Plan, keine Wallbox-Steuerung und keine +Home-Assistant-Entitäten. Verglichen mit evcc (Ladepunkte und Heizstäbe), EMHASS +und Predbat (Batterieoptimierung) ist SunCores Planer neu und unerprobt; +Überschusssteuerung und Sicherheitsschicht sind seine Stärken. Die Liste der offenen Punkte steht in den -[Bekannten Grenzen](surplus-control.md#bekannte-grenzen-und-unverified); die -[Roadmap](../../roadmap.md) zeigt, wann welcher Teil kommt. +[Bekannten Grenzen](planning-and-battery.md#10-bekannte-grenzen-und-unverified) +und in der [Überschusssteuerung](surplus-control.md#bekannte-grenzen-und-unverified); +die [Roadmap](../../roadmap.md) zeigt, wann welcher Teil kommt. diff --git a/docs/user/de/surplus-control.md b/docs/user/de/surplus-control.md index fac0058..62c8d42 100644 --- a/docs/user/de/surplus-control.md +++ b/docs/user/de/surplus-control.md @@ -77,12 +77,13 @@ Geräte ab, solange nicht die gesteuerten Geräte der Grund sind. ### Batterie und Ziele -In dieser Version steuert SunCore die Batterie nicht; es entscheidet nur, ob die **Ladeleistung** -der Batterie für Geräte als Überschuss zählt: +Ohne Plan entscheidet dieser Regler nur, ob die **Ladeleistung** der Batterie für Geräte als +Überschuss zählt: - Mit dem Ziel *Batterie zu einer Uhrzeit auf einen Ziel-Ladestand bringen* und einem Ladestand - unter dem Ziel: Die Batterie lädt zuerst, Geräte bekommen nichts von der Ladeleistung. Die - Uhrzeit wird noch nicht ausgewertet, das Ziel gilt den ganzen Tag. + unter dem Ziel: Die Batterie lädt zuerst, Geräte bekommen nichts von der Ladeleistung. Ohne + Plan wird die Uhrzeit nicht ausgewertet, das Ziel gilt den ganzen Tag. **Dein Ziel ist eine + Untergrenze**: Auch mit Plan bleibt die Batterie vorn, solange sie unter deinem Ziel liegt. - Mit *Klimagerät laufen lassen, bevor eingespeist wird* oder bei erreichtem Ziel steht die Ladeleistung den Geräten zur Verfügung. - Mit **gar keinem Ziel**: Die Batterie hat Vorrang, und Geräte bekommen nur, was sonst @@ -90,6 +91,17 @@ der Batterie für Geräte als Überschuss zählt: tatsächlich willst; setze eines der beiden Ziele, wenn Geräte den Strom nutzen sollen, der sonst die Batterie laden würde. +**Mit Plan** (siehe [Planung und Akkusteuerung](planning-and-battery.md)) setzt jetzt der Planer +die Bänder, denen der Regler folgt. **Die Batterie kommt zuerst bis zum Morgenpuffer** („Akku +zuerst bis X %“), den der Plan aus der Prognose und deiner Risikostufe berechnet; der Regler +vergleicht X alle paar Sekunden mit dem **aktuellen** Ladestand. Oberhalb von X geht der +Überschuss an die Geräte, **solange der Plan sagt, dass das Abendziel noch erreichbar ist**, und +der Plan drosselt ein Gerät auf eine maximale Leistung oder sperrt es, wenn das Ziel knapp +wird. Ein Plan **schränkt** Geräte gegenüber dem Regler ohne Plan nur ein. Ein veralteter Plan +(älter als 2 Stunden) oder keiner heißt: das Verhalten oben. Die Batterie selbst wird getrennt +gesteuert, über ihren eigenen Modus auf der Akku-Karte; siehe +[Steuerung](planning-and-battery.md#5-steuerung-schatten-assistiert-automatik). + ## 2. Betriebsmodi Es gibt drei Modi, je Gerät und für das ganze System (den **Gesamtmodus**). @@ -308,21 +320,24 @@ anhand von Belegen, nicht aus Hoffnung. erkannt; echter Netzbezug lässt SunCore trotzdem zurücknehmen. Ob ein hängender Plenticore „nicht verfügbar“ oder eingefrorene Werte zeigt, ist `UNVERIFIED`. Die Standard-Sensortakte (Leistungssensor 60 s, Energiezähler 300 s, sofern nicht gesetzt) sind Annahmen. -- **Kein Plan**: Prognosen, Tarife und Planer steuern noch nichts. SunCore verschiebt keine Last in - günstigere Stunden, heizt nicht nach dem Wetter vor und schreibt weder auf Batterie noch auf - Wechselrichter. Die Ziele *Batterie-Ziel* und *Klimagerät vor Einspeisung* entscheiden nur, ob - die Ladeleistung der Batterie als Überschuss zählt; die Uhrzeit des Ziels wird nicht ausgewertet. +- **Der Plan ist neu.** Prognosen, Tarife, Planer und Akkusteuerung gibt es jetzt + ([Planung und Akkusteuerung](planning-and-battery.md)), aber auch sie sind noch nie an echter + Hardware gelaufen. SunCore verschiebt keine Geräte-Last in günstigere Stunden, heizt nicht nach dem + Wetter vor und modelliert kein thermisches Verhalten von Geräten. Ohne Plan entscheiden die Ziele + *Batterie-Ziel* und *Klimagerät vor Einspeisung* nur, ob die Ladeleistung der Batterie als + Überschuss zählt, und die Uhrzeit des Ziels wird nicht ausgewertet. - **Zeitfenster und Ruhezeiten** beachtet der Regler, sie lassen sich im Panel aber noch nicht bearbeiten (nur über Vorlagen und importierte Konfiguration). - Ein entferntes oder neu zugeordnetes Gerät, das nicht zurückgegeben werden kann (etwa nach einem Absturz), wird gemeldet („bitte von Hand prüfen“), nicht endlos wiederholt. -- **Downgrade**: Diese Version speichert ihre Daten in Datenbankschema 3, das frühere Versionen +- **Downgrade**: Diese Version speichert ihre Daten in Datenbankschema 4, das frühere Versionen nicht öffnen können. Exportiere die Konfiguration vor dem Update. - **Im Vergleich zu evcc, EMHASS und Predbat**: evcc ist die bessere Wahl für Ladepunkte und hat Jahre an Hardware-Erfahrung; SunCore hat noch keine Wallbox-Steuerung. EMHASS und Predbat - optimieren die Batterie über die Zeit, SunCore noch nicht. Was SunCore bietet, ist eine App mit - Sicherheitsschicht, Schattenmodus und einer Begründung zu jeder Entscheidung; siehe die - [Roadmap](../../roadmap.md). + optimieren die Batterie über die Zeit, mit jahrelanger Praxis; SunCores Planer ist neu und an + Hardware unerprobt. Was SunCore bietet, ist eine App mit Sicherheitsschicht, Schattenmodus und + einer Begründung zu jeder Entscheidung; siehe die [Roadmap](../../roadmap.md). -Siehe auch: [Schnellstart](quick-start.md), [Gerätevorlage beitragen](device-templates.md), +Siehe auch: [Schnellstart](quick-start.md), [Planung und Akkusteuerung](planning-and-battery.md), +[Gerätevorlage beitragen](device-templates.md), [Kompatibilitätsliste](../compatibility.md). diff --git a/docs/user/en/planning-and-battery.md b/docs/user/en/planning-and-battery.md new file mode 100644 index 0000000..2f738da --- /dev/null +++ b/docs/user/en/planning-and-battery.md @@ -0,0 +1,575 @@ +# Planning and battery control + +SunCore can look ahead. It reads the solar forecasts and prices of the integrations you already +run, learns your house's consumption, computes a plan for the next 48 hours and, if you allow it, +sets limits on your home battery. This page explains what the planner does, what you can set, +how the battery is controlled **safely**, and how you take your first battery from shadow to +assisted mode. + +Everything here starts in **shadow mode**: the plan is calculated and shown, and **nothing is +written to your battery or inverter until you say so**. Read +[Known limitations and UNVERIFIED](#10-known-limitations-and-unverified) before you rely on it: +the planner and the battery control have never run against real hardware yet. + +## 1. What the planner does + +The planner computes a schedule for the **next 48 hours in steps of 15 minutes**. It runs +**every 15 minutes** and again **when something changes**: new prices, a new forecast, a changed +setting, a manual change on a device, a large deviation from the plan (the battery is more than +10 percentage points away from the planned charge, or the grid power is more than 1.5 kW off for +30 minutes), or when you press **Replan now**. Runs closer than a minute are merged. + +For every 15-minute interval the plan holds the expected solar power, house load, battery power, +grid import and export, the planned charge of the battery and the prices, **and the reasons**. +It minimises what you pay (import cost, minus feed-in revenue, plus a small wear cost for the +battery), within the limits you set. Cost is not everything: your targets (morning buffer, +evening target, your own target charge) are part of the model, and a small bonus for +self-sufficiency keeps the plan sensible when prices are flat (see +[the self-sufficiency weight](#the-self-sufficiency-weight)). + +- **Solver or rule-based.** Normally an optimiser (HiGHS) finds the plan. It has a time budget + (8 seconds by default) and a rule-based plan is computed first as a safety net. If the + optimiser does not finish in time, cannot solve the model, is not available or produces a plan + that fails the feasibility check, the **rule-based plan** is used and the plan view says so + (badge **Rule-based** instead of **Optimiser**, with the reason). The rule-based plan is + simpler: battery first up to the morning buffer, then consumers on surplus while the evening + target stays reachable, grid charging only to reach a target. +- **"Why?"** Every interval carries reasons in plain language, for example "Evening target + 60.6 % (cautious risk level): the night needs 4.6 kWh" or "Hold the battery at 0.287/kWh: its + energy is worth more at 19:00". You find them in the plan view (tooltip, list **Next planned + actions**) and on the **Now** view. +- **The plan guides, the controller decides.** The real-time controller of + [Surplus control](surplus-control.md) keeps the last word every few seconds. The plan sets + bands (how much power a device may use, "battery first until X %") and the controller compares + them with what really happens. A **stale plan** (older than 2 hours) or no plan at all means + the controller behaves exactly as without a planner. Shadow, assisted and automatic apply to + the plan's effects as before. + +![Plan view with chart, next planned actions and the forecast panel](../../assets/screenshots/plan-tablet-light-en.png) + +The **Plan** view shows a chart of the next 24 or 48 hours (solar with its P10 to P90 band, +house load, battery power, grid import and export, the planned charge with the morning buffer +and evening target as lines, and the import and export price), the planner's status (last run, +trigger, next run, failures), the **Next planned actions** with **Why?**, a table version of the +chart for screen readers and the panel **Forecasts and accuracy**. The plan is a plan, not a +switching command: every device still follows its own operating mode. + +## 2. Forecasts + +### Solar + +SunCore does not call a weather service by itself. It reads the forecasts of integrations you +have installed, in setup step 4 (**Solar**, section **Forecast sources**): + +| Source | Notes | +|---|---| +| Solcast | Reads the integration's forecast attributes (P10, P50, P90), or its read-only query action. SunCore never calls the Solcast API. | +| Forecast.Solar | The core integration, read through the Energy dashboard. With several entries you choose the one for this plant. | +| Open-Meteo Solar Forecast | The HACS integration. | +| Generic | A template that maps an entity's attributes to a forecast curve. | + +You can use **several sources** at once. Their forecasts are **blended by their measured +accuracy**: each night SunCore compares every source with what your solar panels really produced +over the last 14 days and gives better sources more weight (every source keeps a minimum share). +Until enough days have been compared all sources count equally. You can also set a fixed share +per source (**Weight in the blend**). + +On top of that SunCore learns each source's **systematic error** (for example "too high in the +morning when it is overcast") per hour of the day, season and weather class, and corrects it. +This **calibration becomes active after 30 days with data**; before that the forecasts are used +as delivered, and the panel shows "0 of 30 days with data". Hours in which the inverter or the +export limit **clipped** the output are recognised and left out of the learning, so a limited +plant does not teach the forecast to be too pessimistic. + +The panel **Forecasts and accuracy** (below the plan chart) shows for every source how fresh +its data is, its error (MAE) and bias per lead time (0 to 6, 6 to 24 and 24 to 48 hours ahead), +the blend weights and the state of the calibration. Bias is actual minus forecast: positive means +the source was too low. Figures appear after the first night with enough data (**Collecting +data** until then). + +**Open-Meteo:** the data of the Open-Meteo Solar Forecast integration is licensed under +**CC BY 4.0**. SunCore shows the attribution "Solar data from Open-Meteo.com, licensed under +CC BY 4.0" in the panel as soon as an Open-Meteo source is configured. SunCore itself ships no +built-in Open-Meteo or other internet fallback in this version; without a forecast source the +plan assumes no solar power at all. + +### House load + +The load forecast learns what your house uses **without the controlled devices**: the base load +is the house consumption minus every device SunCore may control (those are planned separately). +It builds a profile for every quarter hour of **workdays, weekends and holidays** with a slowly +fading memory (recent weeks count more), and rebuilds the last **28 days** at the first start +from Home Assistant's long-term statistics, so it does not start from zero. Until three days are +known it uses a flat guess with a wide band; without any history the plan uses a flat 500 W and +plans no consumers (a plan hint says so). + +Two optional inputs in step 4 (**Load forecast inputs**) improve it: + +- A **workday sensor** (the Home Assistant Workday integration). SunCore uses its state for + today and asks `workday.check_date` for other days. If your sensor has a `days_offset`, SunCore + handles it: Home Assistant evaluates the sensor for the date plus the offset, and SunCore + corrects for that. +- A **weather entity**. Home Assistant keeps no statistics of a weather entity, so SunCore + records its outdoor temperature itself. The temperature term of the load forecast becomes + active after 14 days with a recorded temperature. + +A machine-learning load model is **not available yet**; the panel says so. The profiles work from +day one. + +## 3. Tariffs + +Step 6 (**Tariff**) tells the planner what energy costs. Import prices can be: + +- **Dynamic** from Tibber, Nord Pool, ENTSO-E, EPEX Spot or Octopus Energy, through the + integration you already run (choose the tariff template; Nord Pool needs the id of its + configuration entry, which you can look up under **Developer tools → Actions**), or a + **generic price list** or a **price sensor** only. +- **Fixed**, or **fixed time-of-use (HT/NT)** with periods per weekday, midnight crossing and + months. + +**Price formula.** Many sources deliver only the **spot price** (the market price). The planner +cannot optimise on that, because you pay grid fees, levies, margin and VAT on top. In **What the +price contains** choose **Spot price only (fees and taxes on top)**, switch on **Turn the spot +price into my end price** and enter the multiplier, grid fee, levies, margin and VAT (end price = +(spot × multiplier + grid fee + levies + margin) × (1 + VAT)); optional time-variable grid fees +(section 14a EnWG module 3) can be added as time windows. The formula is **only for spot +prices**: Tibber's `price` is an all-in end price (choose **End price (everything included)**), and a +fixed price needs no formula. A source that delivers bare spot prices **without** a formula is +refused by the planner: it plans without price optimisation (self-sufficiency only) and says so +("delivers bare spot prices and no price formula is configured"), and the system check warns. + +**Feed-in** is **fixed**, **tiered by plant size** (you enter the rate of every tier, for example +the two German rates up to and above 10 kWp, and the last tier must cover the whole plant; the +region profile does not carry the official table yet) or **none**. **Negative-price rule:** in a +region where feed-in is not remunerated at negative prices (profile `de`), the plan values export +at zero in those intervals and prefers to put the surplus into the battery and consumers instead. +Actual curtailment of the inverter is not controlled yet. + +Tomorrow's day-ahead prices are expected from 13:00 local time; until they arrive, later hours +without a price are filled with the median and marked ("planned with the median price"), and +**grid charging never relies on an estimated or unknown price**. + +## 4. Targets and strategies + +All of this is set in step 5 (**Battery**: sections **Battery model for the planner** and +**Strategy**) and step 8 (**Priorities and goals**). + +### Risk level + +Forecasts are wrong sometimes, and the battery should not run empty because of it. The **risk +level** says how sure the plan must be to reach the battery targets: + +| Risk level | Plans for | Meaning | +|---|---|---| +| **Cautious** (default) | a poor forecast (90 %) | The targets are met in about **9 of 10 cases**. | +| **Balanced** | 75 % | The targets are met in about 3 of 4 cases. | +| **Bold** | the median forecast | The targets are met in about half of the cases. | + +SunCore learns how wrong the forecasts really are, per weather class, from the difference between +the net energy that was forecast (solar minus load) and what happened. Until 30 days of history +exist it uses the sources' own P10/P90 bands (labelled as such). The learnt error decides how +large the buffers are: more uncertainty, bigger buffer. + +### Morning buffer, evening target, bridging + +- **Morning buffer** ("battery first until X %"). Until the battery has reached X %, solar surplus + charges the battery before consumers get it. X is computed from the forecast: higher when the + day is uncertain, lower when plenty of solar is expected. In the plan chart it is the dashed + line **Morning buffer**. **Minimum morning buffer** (step 5) is your own floor under the + learnt value; empty means learnt only. Above X the surplus goes to consumers **as long as the + plan says the evening target is still reachable**. SunCore compares X with the **live** charge + every few seconds, so a day that deviates from the plan is handled correctly. +- **Evening target** (dashed line **Evening target**). The charge the battery should have at the + start of the evening deficit, so that it carries the house through the night: the night's + consumption plus, with **Bridge into the next day** on, the missing energy of a weak next day + (the 48-hour horizon shows it), at the chosen risk level, up to your maximum charge. It is + never below your own target. +- **Your target.** The goal **Have the battery at a target charge by a time** (step 8) is a + **floor**: the plan keeps the battery at least at that charge at that time, and the real-time + controller keeps the battery first while it is below. The plan can ask for more, never less. + +Hard limits (reserve, maximum charge, your target, the minimum morning buffer) are always set by +you and always win over what is learnt. + +### Strategies + +| Strategy (step 5) | What it does | +|---|---| +| **Self-consumption** (default) | Learnt buffers as above; the battery covers the night and bridges a poor next day where that pays. | +| **Keep the battery as full as possible** (`prefer_full`) | "Battery first" up to the maximum charge, always. Consumers only get surplus the battery cannot take. | +| **Reach a target by a time** (`target_by_time`) | Uses the goal of step 8 (target charge and time) as a firm target, on top of the buffers. | + +### The self-sufficiency weight + +Step 8 has the expert field **Self-sufficiency weight per kWh**, default **0.01** (1 cent per +kWh in your currency). Think of it as a tiny bonus for every kWh you use from your own panels +instead of buying: the plan values it at 1 ct/kWh more than the price. It only decides between +options whose cost differs by **less than 1 ct/kWh**, so it costs at most 1 ct per kWh; it prevents +the optimiser from picking arbitrarily among equal-cost plans on a flat tariff. **0** means pure +cost. + +### Grid charging + +**Off by default.** In step 8, **Charging from the grid**: **Allow charging the battery from the +grid** only works together with at least one rule: + +- a **price level** ("charge only at or below this import price"), and/or +- a **weekly schedule** (windows in which charging is allowed; **Fill with the night window + 22:00–06:00** gives you a start). With both set, both must hold. + +On a **dynamic tariff** there is a third rule, the **spread**: SunCore only charges when a later +price is high enough above the charging price (plus the wear cost and a margin of about 3 ct per +kWh) to pay for the losses. **Without a known price SunCore never charges from the grid**, and it +needs your **import limit** (step 3) so it can never exceed the connection. Charging is only +planned for intervals the plan allows, with the live price checked again at execution. + +Whether your inverter can actually be told to charge is a question of the adapter, see +[section 7](#7-adapters). **Kostal Plenticore cannot be forced to charge from the grid by +SunCore:** the plan shows it as "would charge", and nothing is written. + +## 5. Control: shadow, assisted, automatic + +The battery has its own **Battery** card on the **Now** view and its own mode, like a device: + +![Battery card and next planned actions on the Now view](../../assets/screenshots/now-battery-tablet-light-en.png) + +| Mode | What SunCore does with the battery | +|---|---| +| **Shadow mode** (default) | Calculates and shows what it **would** set ("SunCore would set"). Writes nothing. | +| **Assisted mode** | Proposes limits under **Suggestions waiting for you**; **Confirm** carries one out, and it still passes the safety checks. | +| **Automatic mode** | Writes limits itself within all limits. | + +The battery acts in the **lower** of the overall mode and its own mode, exactly like a device. +**Switching the battery to assisted or automatic** asks for a confirmation that carries the +battery's **identity** (the adapter, its mapped entities and the site's charge and power +sensors). If you change the adapter or those entities, or import a configuration, the battery +**falls back to shadow**, and a stored settings document cannot raise the mode by itself. + +**What SunCore writes: limits only.** Never a power set-point. SunCore tells the inverter how +much the battery **may** charge or discharge, or at which charge it must stop (a minimum charge), +and the inverter's own self-consumption control does the rest. Charging from solar needs no write +at all. When the plan needs no limit, SunCore **releases** the battery: it restores what the +inverter had before (its "baseline"), and the inverter works on its own again. SunCore never +writes values above that baseline, so it can only **restrict**, never open up. + +**The effective reserve** protects the energy you rely on. It is the **higher** of the minimum +charge of your inverter (step 5, **Minimum charge**) and the **reserve plus the BMS drift +margin** (**Battery model for the planner**; the drift margin, 5 % by default, is for batteries +whose reading sags at night). The plan never goes below it, and the safety layer refuses to +write a minimum charge below it. SunCore holds **no permanent minimum-charge floor** on the +inverter: it writes a minimum charge only for planned intervals where the plan wants to keep +energy for later, and your own, lower floor outside such an interval stays as it is. + +**Checks.** Every write is read back from the device (both Kostal paths can fail without an +error), only happens on change and is limited in rate. Three failed writes in a row pause +battery control. A battery value that freezes, an unknown charge, a stale plan or any +fault pauses control and **releases** the battery. A release is complete only when the read-back +shows the original values; until then SunCore retries and writes nothing else. + +**If you change something yourself.** A limit you set by hand (in the inverter's app or in Home +Assistant) is recognised by its value and **respected**: SunCore lets go without writing and keeps +its hands off until **04:00 the next day**. One documented corner case: a value you choose that +SunCore **itself had already tried or written in the same control phase** looks like SunCore's +own value, and is reset to the baseline at the release. That is the safe direction (the +inverter's own settings), but it means your manual choice is lost in that one case; repeat it +after the release. Anything else you changed stays. + +**Emergency stop.** The red button in the header releases the battery like every device within +10 seconds and nothing is written until you end the stop. A normal **Stop**, restart or update of +the app also releases the battery before the connection closes. After a crash the record of what +SunCore held is persisted, and at the next start, once Home Assistant is connected, the battery is +released. + +**Assisted until the timer is measured.** Some adapters can fall back to the inverter's own +limits by themselves when SunCore goes silent (Kostal Modbus does, through a timer in the +inverter). Until you have **measured** that timer on your system (see +[section 7](#measuring-the-fallback-timer)), such a battery is **capped at assisted mode**: the +card says so, and automatic acts like assisted. + +## 6. Walk-through: your first battery to assisted + +Do this on a day with sun (the fallback measurement in +section 7 needs the evening instead), with the battery well above its reserve and while you are at home. + +1. **Prepare.** Finish the setup assistant. In step 5 enter the capacity, the maximum charging + and discharging power and the reserve (**Battery model for the planner**), choose the + **strategy** and **risk level** (the defaults are fine), and choose a **Battery adapter** + (see [section 7](#7-adapters)). In step 3 enter your **import limit**. Export a backup under + **Settings**. +2. **Stay in shadow.** Open the **Plan** view for a day or two. Does the chart look plausible? + Read the reasons under **Next planned actions**. Is the evening target near what the night + really needs? Does the plan say "Rule-based" or show warnings (see + [Troubleshooting](#9-troubleshooting))? On the **Now** view the battery card shows + **Current limits** (what the inverter has now) and, when relevant, **SunCore would set**. +3. **Check the forecasts.** After the first night look at **Forecasts and accuracy**. A source + with a huge bias or very stale data is worth fixing first. +4. **Switch the battery to assisted.** On the battery card choose **Assisted mode**, read the + dialog and confirm. The overall mode must be **Assisted** or **Automatic** as well (step 9 or + **Settings → Operating mode**), otherwise the battery stays in the lower one. Devices keep + their own modes. +5. **Wait for a proposal.** Proposals appear when the plan wants a limit, for example a + discharge lock ("Battery discharge held back" in **Next planned actions**). That can take + hours or days: with a flat tariff and a full battery the plan may never need one. A proposal + is valid for 2 minutes. **Confirm** only if the reason makes sense; **Dismiss** otherwise. +6. **Watch the first write.** After **Confirm** the card shows **SunCore holds these limits**. + Look at the inverter's own display or the Home Assistant entity: the value must match (SunCore + checks this itself and reports a mismatch). Kostal REST needs up to 35 seconds. +7. **Know your exits.** **Shadow mode** on the card releases the battery. **Emergency stop** in + the header releases it at once. Setting a limit yourself makes SunCore let go until 04:00. +8. **Only then think about automatic**, after several days of sensible proposals. Adapters + without a hardware fallback (generic, Kostal REST) are not capped, but a limit stays on the + inverter until SunCore releases it or restarts: stay in assisted for a long time, and consider + that a conscious choice. + +## 7. Adapters + +In step 5, **Control**, choose the **Battery adapter**. The default is **Observe only (SunCore +never writes)**: the battery is part of the plan, but you set it yourself. The battery card +lists what the adapter **can set**. + +![Wizard step 5: battery sensors, model, adapter and strategy](../../assets/screenshots/wizard-battery-tablet-light-en.png) + +### Generic: Home Assistant entities + +**Battery with number entities (generic).** Maps up to four optional `number` entities of your +battery integration: minimum charge (%), maximum charge power, maximum discharge power (W or kW) +and a forced grid-charge power. SunCore sets whichever you map; roles you leave empty are not +used. It also restores whatever the numbers held before. The adapter has never been driven on a +real battery (**Not verified with real hardware**); start in shadow and compare. This is the +adapter to use if your integration can force grid charging through a number. + +### Kostal Plenticore through the Home Assistant integration + +Adapter **KOSTAL PLENTICORE (Home Assistant integration, minimum SoC)**. It can set **only the +minimum charge** (`Battery:MinSoc`): SunCore uses it as a **discharge lock** for planned +intervals and gives it back afterwards. It **cannot limit the power and cannot charge from the +grid** (the REST interface has no such set-point): a planned grid charge is only **shown** +("would charge from the grid, but the adapter cannot force charging"), never executed. Because +the inverter's number has steps of 5 %, SunCore rounds **up**. A failed write is silent in this +integration, so SunCore reads the value back after about 35 seconds and only believes what it +sees. Without hardware fallback the lock stays until SunCore releases it: SunCore only locks for +planned intervals, never open-ended. + +**The `Battery:MinSoc` entity is disabled by default in Home Assistant.** Enable it: + +1. Open **Settings → Devices & services** and the **Kostal Plenticore** integration, then your + inverter device. +2. Show the disabled entities (a note such as "+N entities not shown" lets you expand them, or + use the filter for disabled entities) and open the number **Battery min SoC**. +3. Open its **settings** (gear icon), switch **Enabled** on and save. Home Assistant reloads the + integration after about 30 seconds; the entity then shows a value between 5 and 100 %. +4. Compare the value with the minimum charge of your inverter's own display. +5. In SunCore step 5, **Control**, choose the Kostal adapter and map the role **"Battery min SoC" + number of the inverter**. If the picker does not list it yet, tick **Also show hidden and + diagnostic entities**. The optional select **Battery charging / usage mode** is read only. +6. Check the signs in the **Check the sign** panel of step 5 (the battery sign of the Kostal REST + integration is `UNVERIFIED`), then keep the battery in **shadow** and watch the first + proposals in assisted mode. + +(The menu names are from memory of Home Assistant, not clicked through for this guide; they differ +between versions.) + +### Kostal Plenticore through Modbus (§3.5 limits) + +Adapter **KOSTAL PLENTICORE G3 battery limits over Modbus (§3.5)**. It can set the **maximum +charge and discharge power** and has a **hardware fallback**: SunCore re-writes the limits every +20 seconds; if it stops, the inverter returns to its fallback limits after a timer (60 seconds +by default). It cannot force grid charging either. It needs: + +- **External battery management via Modbus enabled by the installer** (register 1080 must read + `2`; SunCore refuses to write otherwise). How it is enabled is not documented here. +- A **`modbus` hub** in Home Assistant (whether it can be created in the UI is `UNVERIFIED`; + assume YAML) with the inverter's unit id (Kostal default 71) and one sensor per register: + 1080, 1280, 1282, 1284, 1286, 1288, 1076, 1078, and register 5. Each is mapped to the role + with that register's name in step 5. +- The **word order of register 5** (**Little endian** or **Big endian**) entered under **Modbus + link**. SunCore never guesses it. + +This adapter **runs in the simulator only** so far, because the maintainer's inverter does not +have external battery management enabled yet. It is **capped at assisted** until +`fallback_measured` is set. + +#### Measuring the fallback timer + +Do this **once**, while you are at home. It proves that the inverter really returns to its own +limits when SunCore goes silent, which is why automatic is allowed at all. + +**Safe test, in short:** with all devices in shadow and the battery in assisted, confirm one +discharge lock in the evening (house load above solar), kill SunCore abruptly so that it cannot +hand anything back, and watch when the battery starts discharging again. Expected: 40 to 60 +seconds after the kill (the configured timer minus the time since SunCore's last re-write), plus +the delay of your power sensor. + +Before you start: + +- The battery is well above its reserve (for example 30 points), the house load is low and no + large load starts (no wallbox, no heat-pump boost, no cooking). Solar is **below** the house + load, so the battery is discharging before the test (evening or a dull day). The lock SunCore + proposes is a **full discharge lock** (0 W): the house imports its whole load for a few + minutes, and, if the inverter does not fall back, until you restore it. It is not an + emergency-stop situation. +- Put **every device card in Shadow mode** (the overall mode stays Assisted). A killed SunCore + can release nothing: a device it had switched on would stay on while the battery is locked, + and no import limit is watched any more. +- Leave the Modbus timer at its default (`fallback_timeout_s` 60 s, `heartbeat_s` 20 s). The + sensor of register 1080 shows `2`, and you know the battery's own limits (1076, 1078). The + fallback registers are checked in step 2. +- You can see the **battery power** and the **grid power** with timestamps (a history graph). +- You know how to reach the Home Assistant host's shell (for example the "Advanced SSH & Web + Terminal" app with protection mode off) **or** can otherwise end the app abruptly. Turn + protection mode back on after the test. +- **Turn the app's Watchdog switch OFF** (the app's **Info** page) before the test. With the + watchdog on, the Supervisor restarts a killed container at once, SunCore releases the battery + and writes the limits itself within the 60 seconds, and the test shows a fall-back that never + happened (a false positive). Turn the watchdog back on afterwards. (Behaviour read in the + Supervisor source, `supervisor/apps/app.py` watchdog, on 2026-10-28; `UNVERIFIED` on HA OS.) +- **Abort criteria:** a modbus error in the log, register 1080 not `2`, a sensor that does not + show what SunCore wrote, the charge approaching the reserve, grid import near your connection + limit, solar starting to cover the load, SunCore running again before you observed the + fall-back (see step 4), or anything you do not understand. Then do not continue: start the + app (it releases the battery after reconnecting), switch the battery card to **Shadow mode** + and check the log. If the limit does not return on its own: start SunCore and check that the + register 1282 sensor shows the battery's own discharge limit and that the battery discharges + again. If that fails too, have your installer (or installer access to the inverter's web + interface) switch off external battery management via Modbus. Until then keep large loads + off: a stuck discharge lock costs grid import but does not harm the battery. Leave + `fallback_measured` at false. + +Steps: + +1. Set the battery to **Assisted mode** (see [section 6](#6-walk-through-your-first-battery-to-assisted)). +2. Wait for a proposal that contains a **discharge limit** (the plan shows "Battery discharge + held back"). **Confirm** it once. The card shows **SunCore holds these limits**, and the + register 1282 sensor shows the value. Now check the fallback registers SunCore armed before + this write: 1288 shows 60, and 1284 and 1286 show the battery's own limits or higher. If not, + abort. +3. Confirm the effect: with a discharge limit of 0 W the battery power goes to about 0 W and the + house imports. Wait for at least one heartbeat (20 s) to see the value held. If the battery + was not discharging before (solar covers the load), the test cannot show the fall-back: let + the proposal run out and try another evening. +4. Note the time (to the second). While the card still shows **SunCore holds these limits**, + end the container with `docker kill ` without a `--signal` option (that sends SIGKILL). + Find the name with `docker ps` (it ends in `suncore`; the exact name is `UNVERIFIED`). Never + use `docker stop`, `docker restart`, `docker kill --signal=TERM`, `ha apps stop` or the Stop + button: they let SunCore shut down cleanly and hand the battery back, which proves nothing. + Check on the app page and with `docker ps` that the app **stays stopped**. Later, after you + start it, look in the **Decision log** for the entry "Restart after an unclean stop" + (`safety.crash_recovery`): its time must be **after** the fall-back you observed, otherwise + SunCore wrote the limits itself and the measurement is void. +5. Watch the battery power and the grid power. When the inverter falls back, the battery starts + to discharge into the house and the grid import drops. Note the time when that happens. The + time from the kill to that moment is your result. It is the timer minus the time since + SunCore's last re-write (0 to 20 s), plus your sensor delay. Do not use the 1280/1282 + sensors for this: they may keep showing SunCore's last value after the fall-back + (`UNVERIFIED`). +6. **Expected:** the battery discharges again between about 40 and 60 seconds after the kill, + plus one sensor step (15 seconds assumed). Much faster than 35 seconds means something other + than the inverter's timer gave the limits back (SunCore was not killed abruptly, or something + else wrote them): the run is void. If the battery has not started to discharge after three + times the configured timer (3 minutes), **abort**: start SunCore, and take the inverter back + by hand as described above. +7. Start the app again. It finds the record of what it held and releases the battery (writes the + own limits) once Home Assistant is connected. Turn the app's Watchdog back on and set the + device cards back to their earlier modes. +8. Repeat once for confidence. If both runs fell back as expected: **export** the configuration + under **Settings**, set `"fallback_measured": true` in the `battery` section of the file + (`sections → battery → body`), and **import** it again. The battery card then no longer shows + the assisted cap (the setting has no switch in the panel yet). `fallback_measured` is your + own statement; SunCore does not check it. It only lifts the cap: it does not switch anything + to automatic and does not change the timer or the heartbeat. It is valid only for the timer + you measured with, on this inverter and firmware. If you change `fallback_timeout_s` or + `heartbeat_s`, update the inverter firmware, replace the inverter or re-wire the modbus hub, + set it back to false and measure again. An import resets the overall mode and the battery to + shadow, as it always does: switch them again, one step at a time. + +If either run did not fall back, fell back later than 60 seconds plus one sensor step, or was +void, leave `fallback_measured` at false (the cap stays) and open an issue with your +measurements. + +## 8. What else you will see + +- **Settings** lists **Battery (control and planning)** (adapter, strategy, risk level) and + **PV forecast** (the number of sources). Both can be opened, restored and exported like every + section. +- **Setup step 10** shows the **First plan**: expected solar, consumption, import and export of + the next hours and the battery's lowest, highest and final charge. **Update the preview** + recomputes it. +- The **Decision log** also lists battery decisions with reasons. +- The planner needs the battery's charge. Without it ("Waiting for the battery's state of charge + before planning") there is no plan. + +## 9. Troubleshooting + +- **"There is no plan yet: SunCore controls on surplus rules only."** The planner has not run. + It waits for prices and forecasts and starts at the latest 5 minutes after the first + connection; the plan view's hint names what is missing (for example "Waiting for the + battery's state of charge" or "Nothing to plan yet: the site is not set up or Home Assistant is + not connected"). Press **Replan now** after you fixed it. +- **"The plan is older than … h" / stale.** After 2 hours without a new plan SunCore stops + using it and controls on surplus rules only (the Phase 3 behaviour). Look at the **Planner** + block for failures and the log; the last good plan stays shown, flagged as stale. +- **Plan is "Rule-based".** The optimiser did not deliver; the badge's reason says why (time + budget, solver not available, ...). The rule-based plan is safe but less clever. +- **"No electricity prices: planning for self-sufficiency only"** or **"… delivers bare spot + prices and no price formula is configured"** (the same warning appears in the system check of + step 10). The plan runs in a flat mode without price optimisation. Check the price source + (**Tariff** status) or add the price formula in step 6. +- **"The battery's state of charge is unknown: the battery is left out of the plan"**, **"No + solar forecast"**, **"No load forecast yet"**. Fix the entity or add a forecast source (step 4); + the plan names every missing input. +- **A target "cannot be reached".** The plan says "Evening target of 70 % at 18:00 cannot be + reached: the plan expects 55 %": the day offers too little energy at your risk level, or your + limits (maximum charge power, import limit) are too tight. +- **The battery card says "Paused: …".** Battery control is paused for a reason (frozen + reading, stale inputs, a failed release, three failed writes). The reason names it; it + resumes after the values are plausible again. +- **"The battery adapter cannot force charging: shown only".** Expected for Kostal Plenticore: + grid charging is planned and shown, but not executable. +- **No accuracy figures.** They are computed each night; wait for the first night with data. +- **More** in the troubleshooting section of the + [app description](../../../addon/suncore/DOCS.md) and in + [Surplus control](surplus-control.md). + +## 10. Known limitations and UNVERIFIED + +- **Never run on real hardware by the project so far.** Planner, forecasts, tariffs and the + battery path are tested in the simulator and with fixtures read from the integrations' source + code. Wording and menu paths in this guide were not clicked through on a real Home Assistant. +- **Kostal Modbus** runs in the simulator only: how external battery management is enabled, the + inverter's fallback timer and the byte order of register 5 and of the timer register 1288 + are unverified. The procedure + above is meant to measure it. +- **Kostal REST:** the sign of the battery and grid power, how soon the minimum charge is read + back (35 seconds assumed) and whether out-of-range values are clamped are unverified. +- **Grid charging is not executable on Kostal Plenticore** (neither path has a charge + set-point). It is planned and shown only. A generic adapter with a forced-charge number can do + it if your integration offers one. +- **Generic adapter:** exercised in the simulator only. +- **The planner's weights and rules** (penalties for missed targets, the value of energy left at + the end of the horizon, the device budget) are reasoned, not fitted. On a day with far less sun + than forecast (below about half of the planned solar energy) the evening target can be + missed by a few percentage points, because the consumers took their share first. Solve times on a + Raspberry Pi (aarch64) are not measured; on a PC they are a few milliseconds. +- **Calibration and risk constants** (clear-sky classes, shrinkage, bounds 0.5–1.5, default bands + per weather class) are reasoned, not fitted to real data; they need your 30 days. +- **Tariffs:** how VAT applies to negative spot prices is assumed; the negative-price rule for + all-in sources such as Tibber uses the end price as a stand-in; the publication time of + tomorrow's prices (13:00) is assumed; Nord Pool's configuration entry id must be entered by hand; + the official German feed-in tier table is not built in. +- **Not modelled:** thermal behaviour of air conditioners and water heaters in the plan (they + only get the surplus), export limiting through the inverter (curtailment is shown, not + controlled), peak shaving, wallbox, heat pump, shiftable programs. +- **No history, no what-if.** The plan view is minimal; the full chart, history and analysis + follow in Phase 5. +- **After a restart** the first plan is computed from scratch (stored plans are not read back). +- **Time series** (`timeseries.db`) are not part of the app backup; SunCore rebuilds 28 days of + quarter-hour history from Home Assistant's statistics. The learnt corrections need new days. +- **Downgrade:** this version stores its data in database schema 4, which earlier versions + cannot open. Export the configuration before updating. +- **Compared with EMHASS and Predbat:** both are far more mature optimisers with years of + field experience; SunCore's planner is new and unproven on hardware. What SunCore adds is one + app with forecasts, plan, battery control, a safety layer, shadow mode and a reason for every + decision, set up through a wizard. evcc remains the better choice for charge points. + +See also: [Quick start](quick-start.md), [Surplus control](surplus-control.md), +[Contribute a device template](device-templates.md), [compatibility list](../compatibility.md). diff --git a/docs/user/en/quick-start.md b/docs/user/en/quick-start.md index f169a77..4ff8e94 100644 --- a/docs/user/en/quick-start.md +++ b/docs/user/en/quick-start.md @@ -1,10 +1,12 @@ # Quick start -SunCore is **pre-alpha** (Phase 3). This version helps you describe your -installation with a setup assistant, shows your energy flow live and can -control devices from your solar surplus. It starts in **shadow mode**: -nothing is switched and no set-point is written until you switch a device to -automatic yourself, see [Surplus control](surplus-control.md). The full app +SunCore is **pre-alpha** (Phase 4). This version helps you describe your +installation with a setup assistant, shows your energy flow live, controls +devices from your solar surplus, and plans the next 48 hours with forecasts, +prices and your battery. It starts in **shadow mode**: nothing is switched and +no limit or set-point is written until you switch a device or the battery to +automatic (or assisted) yourself, see [Surplus control](surplus-control.md) and +[Planning and battery control](planning-and-battery.md). The full app description is in [`addon/suncore/DOCS.md`](../../../addon/suncore/DOCS.md). ## 1. Install @@ -76,25 +78,50 @@ sign**. Idle at the moment? Check again when something clearly flows. ### Solar Add each solar array with its **Power sensor**, installed power in kWp, -tilt and orientation (azimuth: 0 = north, 180 = south). Optionally choose a -**Forecast source**, such as Solcast, if the integration is installed. +tilt and orientation (azimuth: 0 = north, 180 = south). Under **Forecast +sources** choose one or **several** solar forecasts (Solcast, Forecast.Solar, +Open-Meteo Solar Forecast or a generic template); SunCore offers the ones it +finds in Home Assistant and blends them by how well each has been right (the +**Weight in the blend** is automatic unless you set a fixed share). With +Forecast.Solar and several linked entries, choose the **Forecast.Solar entry** +of this plant. Optionally add a **Workday sensor** and a **Weather entity** +under **Load forecast inputs**: they improve the house load forecast. No +forecast source at all is allowed; the plan then assumes no solar power. See +[Forecasts](planning-and-battery.md#2-forecasts). ![Step Solar](../../assets/screenshots/wizard-pv-tablet-light-en.png) ### Battery Select the battery power sensor (positive = charging) and the state of -charge sensor, or choose **No battery**. Capacity and the minimum and -maximum charge are optional. SunCore only observes the battery for now. +charge sensor, or choose **No battery**. Capacity, the minimum and maximum +charge and the power limits are optional for observing, but the planner needs +them. Under **Control** choose a **Battery adapter**: the default **Observe +only (SunCore never writes)** leaves the battery to you; an adapter (generic +Home Assistant entities, Kostal Plenticore through the Home Assistant +integration or through Modbus) lets SunCore set limits later, and the battery +still starts in shadow mode. Then fill the **Battery model for the planner** +(capacity, power limits, reserve, BMS drift margin) and choose the +**Strategy** (self-consumption, keep the battery as full as possible, or reach +a target by a time), the **Risk level** (cautious is the default and the +targets are then met in about 9 of 10 cases), an optional **Minimum morning +buffer** and **Bridge into the next day**. Everything is explained in +[Planning and battery control](planning-and-battery.md#4-targets-and-strategies); +the adapters in [Adapters](planning-and-battery.md#7-adapters). ![Step Battery](../../assets/screenshots/wizard-battery-tablet-light-en.png) ### Tariff -Enter the **Import price** (**Fixed price** or **Dynamic price**) and the +Enter the **Import price** (**Fixed price**, **Fixed time-of-use (HT/NT)** or +**Dynamic price**) and the **Feed-in remuneration** (fixed, tiered by plant size, or none). A dynamic -price needs a price sensor or a tariff template such as Tibber. Prices are -stored for later versions; the planner does not use them yet. +price needs a price sensor or a tariff template (Tibber, Nord Pool, ENTSO-E, +EPEX Spot, Octopus Energy or a generic price list). If the source delivers +only the bare spot price, choose **Spot price only** under **What the price +contains** and enter your **Price formula** (grid fee, levies, margin, VAT); +without it the planner cannot optimise on prices. The planner uses these +prices; see [Tariffs](planning-and-battery.md#3-tariffs). ![Step Tariff](../../assets/screenshots/wizard-tariff-tablet-light-en.png) @@ -135,8 +162,12 @@ Drag devices by their handle, or use the arrow buttons or the arrow keys, to decide who gets surplus first. Position 1 is served first. Goals decide whether the battery's charging power counts as surplus for devices (target charge of the battery, climate before export); see -[Battery and goals](surplus-control.md#battery-and-goals). Grid charging at -night only is stored for a later version. +[Battery and goals](surplus-control.md#battery-and-goals). Under **Charging +from the grid** you can allow the battery to be charged from the grid, only +below a price level and inside a weekly schedule (off by default; see +[Grid charging](planning-and-battery.md#grid-charging)). The expert field +**Self-sufficiency weight per kWh** is a small tie-breaker for the planner +([explained here](planning-and-battery.md#the-self-sufficiency-weight)). ![Step Priorities and goals](../../assets/screenshots/wizard-priorities-tablet-light-en.png) @@ -156,7 +187,12 @@ for now. The **System check** looks at units, signs, the power balance and whether sensors deliver current values. Fix everything marked with a cross (open the step from the list), choose **Check again**, then **Finish setup**. -Warnings do not block you. +Warnings do not block you. A warning that the tariff delivers bare market +prices without a price formula means the plan cannot optimise on prices: +add the formula in the **Tariff** step. The summary also shows the **First +plan**: the expected solar energy, consumption, import and export of the next +hours and the battery's lowest, highest and final charge. **Update the +preview** recomputes it. ![Step Summary and check](../../assets/screenshots/wizard-summary-tablet-light-en.png) @@ -177,22 +213,30 @@ log and only then switch a single device: the step-by-step guide is ## 5. The Now view After **Finish setup** the **Now** page shows solar, grid, battery and house -with animated flows, the **Surplus** card and a card for every device with its -state, estimated power, mode switch and **Why?**. The red **Emergency stop** -button in the header hands every device back at once. +with animated flows, the **Surplus** card, a **Battery** card (state of charge, +power, the limits in force, the battery's mode switch and **Why?**), the +**Next planned actions** and a card for every device with its state, estimated +power, mode switch and **Why?**. The red **Emergency stop** button in the +header hands every device and the battery back at once. The **Plan** page +shows the 24 or 48 hour plan with the forecasts and their accuracy. ![Now view on a tablet, light theme](../../assets/screenshots/now-tablet-light-en.png) +![Battery card and next planned actions](../../assets/screenshots/now-battery-tablet-light-en.png) + The **Decision log** lists every decision with its reasons. How it all works, what happens when you change a device yourself and what SunCore does when -something fails is in [Surplus control](surplus-control.md). +something fails is in [Surplus control](surplus-control.md); the plan, the +forecasts and the battery are in +[Planning and battery control](planning-and-battery.md), including a +walk-through to take your first battery to assisted mode. ## 6. Change things later Open **Settings**. It lists every section of your setup (**Region**, -**Site (grid, solar, battery)**, **Tariff**, **PV forecast**, **Devices**, -**Goals**, **Operating mode**) with a short summary and an **Open** link to -the matching step. +**Site (grid, solar, battery)**, **Tariff**, **PV forecast**, **Battery +(control and planning)**, **Devices**, **Goals**, **Operating mode**) with a short +summary and an **Open** link to the matching step. ![Settings overview](../../assets/screenshots/settings-tablet-light-en.png) @@ -233,12 +277,17 @@ the matching step. ## What SunCore cannot do yet -Be aware before you rely on it. This version has no forecasts or planner -(your tariff and forecast choices are only stored), no history charts, no -battery control, no charge point (wallbox) control and no Home Assistant -entities. Its surplus control has never run against real hardware yet: that is -what your shadow-mode run is for. Compared with evcc (charge points and -heaters), EMHASS and Predbat (battery optimisation), SunCore currently -controls consumers from real surplus only. The list of open points is in -[Known limitations](surplus-control.md#known-limitations-and-unverified); the -[roadmap](../../roadmap.md) shows when each part arrives. +Be aware before you rely on it. SunCore now has forecasts, tariffs, a 48 hour +planner and battery control, but **none of it has ever run against real +hardware**: that is what your shadow-mode run is for. The battery starts in +shadow mode, and until the inverter's fallback timer has been measured on your +system a Kostal Modbus battery is capped at assisted mode. Kostal Plenticore +cannot be told to charge from the grid. There are no history charts or what-if +analysis yet (the plan view is minimal), no thermal models for air conditioners +and water heaters in the plan, no charge point (wallbox) control and no Home +Assistant entities. Compared with evcc (charge points and heaters), EMHASS and +Predbat (battery optimisation), SunCore's planner is new and unproven, while +its surplus control and safety layer are its strengths. The list of open points +is in [Known limitations](planning-and-battery.md#10-known-limitations-and-unverified) +and in [Surplus control](surplus-control.md#known-limitations-and-unverified); +the [roadmap](../../roadmap.md) shows when each part arrives. diff --git a/docs/user/en/surplus-control.md b/docs/user/en/surplus-control.md index 13de949..10d73ab 100644 --- a/docs/user/en/surplus-control.md +++ b/docs/user/en/surplus-control.md @@ -72,12 +72,13 @@ switch other devices off for it unless the controlled devices are the reason. ### Battery and goals -In this version SunCore does not control the battery; it only decides whether the -battery's **charging power** counts as surplus for devices: +Without a plan, this controller only decides whether the battery's **charging power** counts as +surplus for devices: - With the goal *Have the battery at a target charge by a time* and a charge below the target: the battery charges first, devices get no share of the battery's charging power. - The time of day is not evaluated yet, the target counts all day. + Without a plan the time of day is not evaluated and the target counts all day. **Your target is + a floor**: even with a plan, the battery stays first while it is below your target. - With *Run the air conditioner before exporting*, or when the target is reached: charging power is available to devices. - With **no goal at all**: the battery comes first, and devices only get what would be @@ -85,6 +86,16 @@ battery's **charging power** counts as surplus for devices: want; set one of the two goals if you want devices to use the power that would charge the battery. +**With a plan** (see [Planning and battery control](planning-and-battery.md)) the planner now sets +the bands the controller follows. **The battery comes first until the morning buffer** ("battery +first until X %"), which the plan computes from the forecast and your risk level; the controller +compares X with the **live** charge every few seconds. Above X the surplus goes to the devices +**while the plan says the evening target is still reachable**, and the plan caps a device at a maximum +power or blocks it when the target gets tight. A plan only ever **restricts** +devices compared with the plan-less controller. A stale plan (older than 2 hours) or none means the +behaviour above. The battery itself is controlled separately, through its own mode on the battery +card; see [Control](planning-and-battery.md#5-control-shadow-assisted-automatic). + ## 2. Operating modes There are three modes, per device and for the whole system (the **overall mode**). @@ -290,21 +301,24 @@ day with sun. The window of a few days is the point: you decide on evidence, not off. Whether a hung Plenticore shows unavailable or frozen values is `UNVERIFIED`. The default sensor cadences (power sensor 60 s, energy counter 300 s unless set) are assumptions. -- **No plan**: there are no forecasts, tariffs or planner in control yet. SunCore does not - shift load to cheaper hours, does not pre-heat for the weather and does not write to the - battery or the inverter. The goals *battery target* and *climate before export* only decide - whether the battery's charging power counts as surplus; the target's time is not evaluated. +- **The plan is new.** Forecasts, tariffs, the planner and battery control exist now + ([Planning and battery control](planning-and-battery.md)), but have never run against real + hardware either. SunCore does not shift device load to cheaper hours, does not pre-heat for the + weather and models no thermal behaviour of devices. Without a plan the goals *battery target* + and *climate before export* only decide whether the battery's charging power counts as surplus, + and the target's time is not evaluated. - **Time windows and quiet hours** are honoured by the controller but cannot be edited in the panel yet (templates and imported configuration only). - A removed or re-mapped device that cannot be given back (for example after a crash) is reported ("please check it by hand"), not retried forever. -- **Downgrade**: this version stores its data in database schema 3, which earlier versions cannot +- **Downgrade**: this version stores its data in database schema 4, which earlier versions cannot open. Export the configuration before updating. - **Compared with evcc, EMHASS and Predbat**: evcc is the better choice for charge points and has years of hardware experience; SunCore has no wallbox control yet. EMHASS and Predbat - optimise the battery over time, SunCore does not yet. What SunCore adds is one app with a - safety layer, shadow mode and a reason for every decision; see the - [roadmap](../../roadmap.md). + optimise the battery over time with years of field experience; SunCore's planner is new and + unproven on hardware. What SunCore adds is one app with a safety layer, shadow mode and a reason + for every decision; see the [roadmap](../../roadmap.md). -See also: [Quick start](quick-start.md), [Contribute a device template](device-templates.md), +See also: [Quick start](quick-start.md), [Planning and battery control](planning-and-battery.md), +[Contribute a device template](device-templates.md), [compatibility list](../compatibility.md). diff --git a/frontend/README.md b/frontend/README.md index f416c22..64da0d5 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -26,10 +26,20 @@ Demo backend: `SUNCORE_DEMO=1 SUNCORE_STATIC_DIR=frontend/dist uv run python -m - One WebSocket (`src/lib/stores/live.svelte.ts`) feeds all views; reconnect with jittered exponential back-off (`src/lib/api/ws.ts`). Flow lines use CSS animations on quantised speed levels, so a new value never restarts an animation unless the power class changes. -- Bundle budget: < 250 kB gzip (`npm run size`). +- Bundle budget (`npm run size`): everything except ECharts < 250 kB gzip, first paint < 125 kB, + the on-demand ECharts chunk (plan view only, never in the first paint) < 200 kB. - `.npmrc` sets `legacy-peer-deps=true`: npm 10.9 crashes (`edgesOut` of null in arborist) when resolving vitest's optional peer set. All peers we need are listed explicitly in `package.json`. +## Plan view and battery card (Phase 4) + +`#/plan` loads `PlanChart.svelte` (the only importer of ECharts) on demand. The option is a pure +function (`plan/chartOption.ts`), the data series, the next-actions list and the preview numbers +come from `plan/model.ts`. "Now" is the plan's hand-over time. The Now view shows the battery +card and the next planned actions; the wizard steps 4, 5, 6, 8 and 10 carry the Phase 4 forms +(`wizard/batteryForm.ts`, `tariffForm.ts`, `scheduleForm.ts`, `forecastForm.ts`). The demo battery +adapter for Playwright and screenshots is switched on with `SUNCORE_DEMO_BATTERY_CONTROL=1`. + ## Setup wizard (Phase 2) - Routes: `#/setup` resumes at the first step not in `wizard.completed_steps`; `#/setup/` diff --git a/frontend/e2e/battery.spec.ts b/frontend/e2e/battery.spec.ts new file mode 100644 index 0000000..25a3e25 --- /dev/null +++ b/frontend/e2e/battery.spec.ts @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: Apache-2.0 +import { expect, test } from '@playwright/test'; +import { expectNoAxeViolations, resetDemo } from './helpers'; + +test.describe.configure({ mode: 'serial' }); + +test.afterAll(async ({ request }) => { + await resetDemo(request); +}); + +test.describe('battery card on the Now view', () => { + test.beforeEach(async ({ request }) => { + await resetDemo(request); + }); + + test('shows state, limits and the next planned actions', async ({ page }) => { + await page.goto('/'); + const card = page.getByTestId('battery-card'); + await expect(card).toBeVisible(); + await expect(card.getByTestId('battery-effective-mode')).toHaveText('Shadow mode'); + await expect(card.getByTestId('battery-soc')).toContainText('%'); + await expect(card.getByTestId('battery-limits')).toContainText('Minimum state of charge'); + await expect(card.getByTestId('battery-control')).toContainText('own settings'); + const next = page.getByTestId('now-next-actions'); + await expect(next.getByTestId('planned-action').first()).toBeVisible(); + await next.getByText('Why?').first().click(); + await expect(next.getByRole('list').last()).toBeVisible(); + await expectNoAxeViolations(page); + }); + + test('hides the planned actions and says why when the plan is not followed', async ({ page }) => { + await page.route('**/api/v1/plan?*', async (route) => { + const res = await route.fetch(); + const body = await res.json(); + await route.fulfill({ response: res, json: { ...body, stale: true, in_use: false } }); + }); + await page.goto('/'); + await expect(page.getByTestId('now-plan-outdated')).toBeVisible(); + await expect(page.getByTestId('now-planned-actions')).toHaveCount(0); + }); + + test('switches to assisted after a confirmation with the battery identity', async ({ + page, + request, + }) => { + await page.goto('/'); + const card = page.getByTestId('battery-card'); + await card.getByTestId('battery-mode-assisted').click(); + const dialog = page.getByTestId('battery-dialog'); + await expect(dialog).toBeVisible(); + await expectNoAxeViolations(page); + // Cancel changes nothing. + await dialog.getByRole('button', { name: 'Cancel' }).click(); + await expect(card.getByTestId('battery-mode-shadow')).toHaveAttribute('aria-pressed', 'true'); + await card.getByTestId('battery-mode-assisted').click(); + await dialog.getByRole('button', { name: 'Switch to assisted' }).click(); + await expect(card.getByTestId('battery-mode-assisted')).toHaveAttribute('aria-pressed', 'true'); + // The overall mode is shadow and caps the battery's own mode. + await expect(card.getByTestId('battery-effective-mode')).toHaveText('Shadow mode'); + await expect(card.getByTestId('battery-mode-limited')).toBeVisible(); + const op = await (await request.get('/api/v1/config/operation')).json(); + expect(op.battery_mode).toBe('assisted'); + // Back to shadow needs no confirmation. + await card.getByTestId('battery-mode-shadow').click(); + await expect(card.getByTestId('battery-mode-shadow')).toHaveAttribute('aria-pressed', 'true'); + }); + + test('the server refuses a mode above shadow without or with a wrong identity', async ({ + request, + }) => { + const none = await request.put('/api/v1/operation/battery', { data: { mode: 'assisted' } }); + expect(none.ok()).toBe(false); + const wrong = await request.put('/api/v1/operation/battery', { + data: { mode: 'assisted', identity: 'not-the-token' }, + }); + expect(wrong.status()).toBe(409); + }); +}); diff --git a/frontend/e2e/plan.spec.ts b/frontend/e2e/plan.spec.ts new file mode 100644 index 0000000..db74f3b --- /dev/null +++ b/frontend/e2e/plan.spec.ts @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: Apache-2.0 +import { expect, test } from '@playwright/test'; +import { expectNoAxeViolations } from './helpers'; + +test.describe('Plan view', () => { + test('renders the plan with chart, badges, status and reasons', async ({ page }) => { + await page.goto('/#/plan'); + await expect(page.getByRole('heading', { name: 'Plan', level: 2 })).toBeVisible(); + await expect(page.getByTestId('plan-source')).toHaveText('Optimiser'); + await expect(page.getByTestId('plan-in-use')).toContainText('follows this plan'); + await expect(page.getByTestId('plan-last-run')).toContainText('successful'); + await expect(page.getByTestId('plan-next-run')).toBeVisible(); + const chart = page.getByTestId('plan-chart'); + await expect(chart).toBeVisible(); + await expect(chart).toHaveAttribute('role', 'img'); + await expect(chart.locator('canvas').first()).toBeVisible(); + // The text alternative: planned actions with "Why?" and the data table. + const actions = page.getByTestId('planned-actions').getByTestId('planned-action'); + await expect(actions.first()).toBeVisible(); + await actions.first().getByText('Why?').click(); + await expect(actions.first().locator('li').first()).not.toBeEmpty(); + await page.getByTestId('plan-table').getByText('Chart data as a table').click(); + await expect(page.getByTestId('plan-table').getByRole('row').nth(1)).toBeVisible(); + }); + + test('shows the reasons of an interval in the tooltip', async ({ page }) => { + await page.goto('/#/plan'); + const chart = page.getByTestId('plan-chart'); + await expect(chart.locator('canvas').first()).toBeVisible(); + const box = (await chart.boundingBox())!; + const x = box.width * 0.45; + await expect + .poll( + async () => { + // Hover on a desktop, tap on a phone: both end in a click on the same spot. + await chart.click({ position: { x, y: 150 } }); + return page.getByText('Why', { exact: true }).count(); + }, + { timeout: 15_000 }, + ) + .toBeGreaterThan(0); + }); + + test('switches between 24 and 48 hours', async ({ page }) => { + await page.goto('/#/plan'); + await expect(page.getByTestId('range-24')).toHaveAttribute('aria-pressed', 'true'); + const rows = () => page.getByTestId('planned-action').count(); + await page.getByTestId('range-48').click(); + await expect(page.getByTestId('range-48')).toHaveAttribute('aria-pressed', 'true'); + await expect(page.getByTestId('range-24')).toHaveAttribute('aria-pressed', 'false'); + expect(await rows()).toBeGreaterThan(0); + }); + + test('replan gives feedback and cannot be pressed twice at once', async ({ page }) => { + await page.goto('/#/plan'); + const replan = page.getByTestId('replan'); + await expect(replan).toBeEnabled(); + await replan.click(); + await expect(page.getByTestId('replan-feedback')).toContainText(/requested|moment ago/); + await expect(replan).toBeEnabled({ timeout: 10_000 }); + }); + + test('lists the forecast sources, accuracy, weights, calibration and the Open-Meteo credit', async ({ + page, + }) => { + await page.goto('/#/plan'); + const panel = page.getByTestId('forecast-panel'); + await expect(panel).toBeVisible(); + await expect(panel.getByTestId('fc-accuracy')).toBeVisible(); + await expect(panel.getByTestId('fc-weights')).toContainText('equal'); + await expect(panel.getByTestId('fc-calibration')).toContainText('No history yet'); + await expect(panel.getByTestId('fc-ml')).toContainText('Not available yet'); + const credit = panel.getByTestId('open-meteo-attribution'); + await expect(credit).toContainText('CC BY 4.0'); + await expect(credit.getByRole('link', { name: 'Open-Meteo.com' })).toHaveAttribute( + 'href', + 'https://open-meteo.com/', + ); + }); + + test('says so when the planner is not running', async ({ page }) => { + await page.route('**/api/v1/plan?*', (route) => + route.fulfill({ status: 409, json: { detail: 'api.error.planning_unavailable' } }), + ); + await page.route('**/api/v1/plan/status', (route) => + route.fulfill({ status: 409, json: { detail: 'api.error.planning_unavailable' } }), + ); + await page.goto('/#/plan'); + await expect(page.getByTestId('plan-unavailable')).toBeVisible(); + }); + + test('is in German for a German browser', async ({ browser }) => { + const ctx = await browser.newContext({ locale: 'de-DE' }); + const page = await ctx.newPage(); + await page.goto('/#/plan'); + await expect(page.getByTestId('plan-source')).toHaveText('Optimierer'); + await expect(page.getByRole('button', { name: 'Jetzt neu planen' })).toBeVisible(); + await expect(page.getByText('Nächste geplante Aktionen')).toBeVisible(); + await ctx.close(); + }); + + for (const scheme of ['light', 'dark'] as const) { + test(`has no axe violations (${scheme})`, async ({ browser }) => { + const ctx = await browser.newContext({ colorScheme: scheme }); + const page = await ctx.newPage(); + await page.goto('/#/plan'); + await expect(page.getByTestId('plan-chart').locator('canvas').first()).toBeVisible(); + await expect(page.getByTestId('fc-accuracy')).toBeVisible(); + await expectNoAxeViolations(page); + await ctx.close(); + }); + } +}); diff --git a/frontend/e2e/screenshots.spec.ts b/frontend/e2e/screenshots.spec.ts index 5e3b9ad..d54c0e7 100644 --- a/frontend/e2e/screenshots.spec.ts +++ b/frontend/e2e/screenshots.spec.ts @@ -15,6 +15,10 @@ const shots = [ { view: 'now', path: '/', scheme: 'dark', locale: 'de-DE' }, { view: 'settings', path: '/#/settings', scheme: 'light', locale: 'en-US' }, { view: 'settings', path: '/#/settings', scheme: 'light', locale: 'de-DE' }, + { view: 'plan', path: '/#/plan', scheme: 'light', locale: 'en-US' }, + { view: 'plan', path: '/#/plan', scheme: 'dark', locale: 'en-US' }, + { view: 'plan', path: '/#/plan', scheme: 'light', locale: 'de-DE' }, + { view: 'plan', path: '/#/plan', scheme: 'dark', locale: 'de-DE' }, ] as const; for (const shot of shots) { @@ -33,6 +37,10 @@ for (const shot of shots) { if (shot.view === 'settings') { await expect(page.getByTestId('overview')).toBeVisible(); } + if (shot.view === 'plan') { + await expect(page.getByTestId('plan-chart').locator('canvas').first()).toBeVisible(); + await expect(page.getByTestId('fc-accuracy')).toBeVisible(); + } // Let the live feed deliver a few updates before the capture. await page.waitForTimeout(1500); const name = `${shot.view}-${info.project.name}-${shot.scheme}-${shot.locale.slice(0, 2)}`; @@ -41,6 +49,50 @@ for (const shot of shots) { }); } +// The battery card and the next planned actions of the Now view (the demo runs the generic +// battery adapter, see playwright.config.ts). +for (const shot of [ + { scheme: 'light', locale: 'en-US' }, + { scheme: 'dark', locale: 'en-US' }, + { scheme: 'light', locale: 'de-DE' }, + { scheme: 'dark', locale: 'de-DE' }, +] as const) { + test(`now-battery ${shot.scheme} ${shot.locale}`, async ({ browser }, info) => { + test.skip(info.project.name === 'desktop', 'docs use phone and tablet'); + const ctx = await browser.newContext({ + colorScheme: shot.scheme, + locale: shot.locale, + viewport: info.project.use.viewport ?? { width: 1024, height: 768 }, + hasTouch: info.project.use.hasTouch, + }); + const page = await ctx.newPage(); + await page.goto('/'); + await expect(page.getByTestId('connection')).toHaveAttribute('data-status', 'live'); + const card = page.getByTestId('battery-card'); + await expect(card).toBeVisible(); + await expect( + page.getByTestId('now-next-actions').getByTestId('planned-action').first(), + ).toBeVisible(); + await page.waitForTimeout(1500); + const area = page.locator('main'); + const name = `now-battery-${info.project.name}-${shot.scheme}-${shot.locale.slice(0, 2)}`; + // From the battery card to the end of the planned actions. + const top = (await card.boundingBox())!; + const next = (await page.getByTestId('now-next-actions').boundingBox())!; + await page.screenshot({ + path: `${dir}/${name}.png`, + fullPage: true, + clip: { + x: 0, + y: Math.max(0, top.y - 8), + width: (await area.boundingBox())!.x * 2 + (await area.boundingBox())!.width, + height: next.y + next.height - top.y + 16, + }, + }); + await ctx.close(); + }); +} + // Decision log (rows appear a few ticks after the demo start) and the emergency stop: Now with // the stop active (banner, "Back to normal"). The stop is cleared again afterwards. const controlShots = [ @@ -95,13 +147,20 @@ const wizardShots = [ STEP_IDS.map((step) => ({ step, scheme: 'light' as const, locale })), ), ...(['en-US', 'de-DE'] as const).flatMap((locale) => - (['devices', 'summary'] as const).map((step) => ({ step, scheme: 'dark' as const, locale })), + (['devices', 'summary', 'battery'] as const).map((step) => ({ + step, + scheme: 'dark' as const, + locale, + })), ), ]; for (const { step, scheme, locale } of wizardShots) { test(`wizard ${step} ${scheme} ${locale}`, async ({ browser }, info) => { - test.skip(info.project.name !== 'tablet', 'wizard pages are long: tablet only'); + test.skip( + info.project.name === 'desktop' || (info.project.name === 'phone' && step !== 'battery'), + 'wizard pages are long: tablet only (the battery step also on the phone)', + ); const ctx = await browser.newContext({ colorScheme: scheme, locale, diff --git a/frontend/e2e/theme-a11y.spec.ts b/frontend/e2e/theme-a11y.spec.ts index 5632a9f..6764b1d 100644 --- a/frontend/e2e/theme-a11y.spec.ts +++ b/frontend/e2e/theme-a11y.spec.ts @@ -71,6 +71,8 @@ test('keyboard: skip link and navigation are reachable', async ({ page }) => { await page.keyboard.press('Tab'); await expect(page.getByRole('link', { name: 'Now' })).toBeFocused(); await page.keyboard.press('Tab'); + await expect(page.getByRole('link', { name: 'Plan', exact: true })).toBeFocused(); + await page.keyboard.press('Tab'); await expect(page.getByRole('link', { name: 'Decision log', exact: true })).toBeFocused(); await page.keyboard.press('Tab'); await page.keyboard.press('Enter'); diff --git a/frontend/e2e/wizard-phase4.spec.ts b/frontend/e2e/wizard-phase4.spec.ts new file mode 100644 index 0000000..70a8725 --- /dev/null +++ b/frontend/e2e/wizard-phase4.spec.ts @@ -0,0 +1,272 @@ +// SPDX-License-Identifier: Apache-2.0 +// The Phase 4 wizard steps against the demo: sources (4), battery (5), tariff (6), goals and +// grid charging (8), summary with the first plan (10). Each step is saved, read back from the API +// and shown again after a reload. +import { expect, test, type APIRequestContext } from '@playwright/test'; +import { expectNoAxeViolations, openStep, resetDemo } from './helpers'; + +test.describe.configure({ mode: 'serial' }); + +const next = (page: import('@playwright/test').Page) => page.getByTestId('wizard-next'); +const get = async (request: APIRequestContext, section: string) => + (await request.get(`/api/v1/config/${section}`)).json(); + +test.beforeEach(async ({ request }) => { + await resetDemo(request); +}); +test.afterAll(async ({ request }) => { + await resetDemo(request); +}); + +test('step 4: several sources, entry choice, fixed share and the load inputs', async ({ + page, + request, +}) => { + await openStep(page, 'pv'); + await expect(page.getByTestId('forecast-count')).toContainText('3 forecast sources'); + const entry = page.getByTestId('entry-field').getByRole('combobox'); + await expect(entry).toContainText('sim_entry_forecast_solar'); + await entry.selectOption('sim_entry_forecast_solar'); + const solcast = page.getByRole('group', { name: 'Weight in the blend' }).last(); + await solcast.getByRole('radio', { name: 'Fixed share' }).check(); + await solcast.getByLabel('Share (0–1)').fill('0.6'); + await expect(page.getByTestId('open-meteo-note')).toBeVisible(); + await expectNoAxeViolations(page); + await next(page).click(); + await expect(page).toHaveURL(/#\/setup\/battery$/); + const forecast = await get(request, 'forecast'); + const solar = forecast.sources.find( + (s: { template_id: string }) => s.template_id === 'forecast_solar.pv', + ); + expect(solar.config_entry_id).toBe('sim_entry_forecast_solar'); + const sol = forecast.sources.find((s: { template_id: string }) => s.template_id === 'solcast.pv'); + expect(sol).toMatchObject({ weight_mode: 'manual', weight: 0.6 }); + expect(forecast.load.workday.entity_id).toBe('binary_sensor.sim_workday_sensor'); + // Shown again after a reload. + await page.goto('/#/setup/pv'); + await page.reload(); + await expect( + page.getByRole('group', { name: 'Weight in the blend' }).last().getByLabel('Share (0–1)'), + ).toHaveValue('0.6'); +}); + +test('step 5: adapter, model, strategy and risk level round trip', async ({ page, request }) => { + await openStep(page, 'battery'); + const control = page.getByTestId('battery-control'); + await expect(control.getByRole('combobox', { name: 'Battery adapter' })).toContainText('generic'); + await control + .getByRole('combobox', { name: 'Battery adapter' }) + .selectOption('kostal.plenticore'); + await expect(page.getByTestId('hint-kostal-rest')).toContainText('Battery:MinSoc'); + await control + .getByRole('combobox', { name: 'Battery adapter' }) + .selectOption('kostal.plenticore_g3_modbus'); + await expect(page.getByTestId('hint-kostal-modbus')).toContainText('modbus hub'); + await expect(page.getByTestId('fallback-state')).toContainText('not been measured'); + // Observe only keeps the model. + await control.getByRole('combobox', { name: 'Battery adapter' }).selectOption(''); + await expect(page.getByTestId('observe-note')).toBeVisible(); + const model = page.getByTestId('battery-model'); + await model.getByLabel('Reserve (backup energy)').fill('15'); + await model.getByLabel('Maximum state of charge').fill('95'); + const strategy = page.getByTestId('battery-strategy'); + await strategy.getByRole('radio', { name: 'Keep the battery as full as possible' }).check(); + await strategy.getByRole('radio', { name: 'Balanced' }).check(); + await strategy.getByLabel('Minimum morning buffer').fill('25'); + await strategy.getByLabel('Bridge into the next day').uncheck(); + await expectNoAxeViolations(page); + await next(page).click(); + await expect(page).toHaveURL(/#\/setup\/tariff$/); + const battery = await get(request, 'battery'); + expect(battery).toMatchObject({ + adapter_template_id: null, + strategy: 'prefer_full', + risk: 'balanced', + morning_buffer_pct: 25, + bridge_next_day: false, + }); + expect(battery.model).toMatchObject({ reserve_pct: 15, max_soc_pct: 95, capacity_wh: 10000 }); + await page.goto('/#/setup/battery'); + await page.reload(); + await expect( + page.getByTestId('battery-strategy').getByRole('radio', { name: 'Balanced' }), + ).toBeChecked(); +}); + +test('step 5: the adapter with its entities is stored', async ({ page, request }) => { + await openStep(page, 'battery'); + const control = page.getByTestId('battery-control'); + await expect(control.getByLabel(/Minimum state of charge/)).toHaveValue( + 'number.sim_battery_min_soc', + ); + await next(page).click(); + await expect(page).toHaveURL(/#\/setup\/tariff$/); + const battery = await get(request, 'battery'); + expect(battery.adapter_template_id).toBe('generic.battery'); + expect(battery.entities.min_soc_number.entity_id).toBe('number.sim_battery_min_soc'); +}); + +test('step 6: HT/NT tariff editor round trip', async ({ page, request }) => { + await openStep(page, 'tariff'); + const imp = page.getByRole('group', { name: 'Import price' }); + await imp.getByRole('radio', { name: 'Fixed time-of-use (HT/NT)' }).check(); + const editor = page.getByTestId('tou-editor'); + await editor.getByLabel(/^Base price/).fill('0.34'); + await editor.getByTestId('tou-add').click(); + const period = editor.getByTestId('tou-period').first(); + await period.getByLabel(/^Price in this period/).fill('0.22'); + await period.getByLabel('Sat').uncheck(); + await period.getByLabel('Sun').uncheck(); + await expectNoAxeViolations(page); + await next(page).click(); + await expect(page).toHaveURL(/#\/setup\/devices$/); + const tariff = await get(request, 'tariff'); + expect(tariff.import.kind).toBe('tou'); + expect(tariff.import.tou.base_price).toBe(0.34); + expect(tariff.import.tou.periods[0]).toMatchObject({ + price: 0.22, + window: { days: [0, 1, 2, 3, 4], start: '22:00', end: '06:00' }, + }); + await page.goto('/#/setup/tariff'); + await expect(page.getByTestId('tou-editor').getByLabel(/^Base price/)).toHaveValue('0.34'); +}); + +test('step 6: a spot-only price gets its formula', async ({ page, request }) => { + await openStep(page, 'tariff'); + const imp = page.getByRole('group', { name: 'Import price' }); + await imp.getByRole('radio', { name: 'Dynamic price', exact: true }).check(); + await imp.getByRole('radio', { name: 'Only a price sensor' }).check(); + const picker = imp.getByRole('combobox', { name: 'Price sensor' }); + await picker.fill('sensor.sim_electricity_price'); + await page.keyboard.press('Escape'); + await page.getByTestId('price-includes').getByRole('combobox').selectOption('spot_only'); + const formula = page.getByTestId('formula-editor'); + await expect(formula).toBeVisible(); + await formula.getByRole('checkbox', { name: /Turn the spot price/ }).check(); + await formula.getByLabel(/^Grid fee per kWh/).fill('0.08'); + await formula.getByLabel('VAT').fill('19'); + await formula.getByText('Time-variable grid fees').click(); + await formula.getByRole('button', { name: 'Add a grid fee window' }).click(); + await formula.getByLabel(/^Grid fee in this window/).fill('0.12'); + await expectNoAxeViolations(page); + await next(page).click(); + await expect(page).toHaveURL(/#\/setup\/devices$/); + const tariff = await get(request, 'tariff'); + expect(tariff.import).toMatchObject({ + kind: 'dynamic', + price_includes: 'spot_only', + formula: { grid_fee: 0.08, vat_pct: 19 }, + }); + expect(tariff.import.formula.grid_fee_windows).toHaveLength(1); +}); + +test('step 8: grid-charge policy with price level and schedule, autarky weight', async ({ + page, + request, +}) => { + await openStep(page, 'priorities'); + const gc = page.getByTestId('grid-charge'); + await expect(gc.getByTestId('gc-enable')).not.toBeChecked(); + await gc.getByTestId('gc-enable').check(); + await gc.getByLabel(/^Charge only at or below/).fill('0.12'); + await gc.getByRole('button', { name: 'Fill with the night window 22:00–06:00' }).click(); + await expect( + gc.getByTestId('gc-schedule').getByRole('group', { name: 'Window 1' }), + ).toBeVisible(); + await gc.getByText('Self-sufficiency weight per kWh').first().click(); + await gc.getByLabel('Self-sufficiency weight per kWh').last().fill('0.02'); + await expectNoAxeViolations(page); + await next(page).click(); + await expect(page).toHaveURL(/#\/setup\/mode$/); + const battery = await get(request, 'battery'); + expect(battery.grid_charge).toMatchObject({ + enabled: true, + max_price: 0.12, + schedule: { windows: [{ days: [0, 1, 2, 3, 4, 5, 6], start: '22:00', end: '06:00' }] }, + }); + expect(battery.autarky_weight_per_kwh).toBe(0.02); +}); + +test('step 8: grid charging without a rule is refused by the step', async ({ page }) => { + await openStep(page, 'priorities'); + await page.getByTestId('gc-enable').check(); + await next(page).click(); + await expect(page.getByRole('alert')).toContainText('price level or a schedule'); + await expect(page).toHaveURL(/#\/setup\/priorities$/); +}); + +test('step 10: the first plan preview', async ({ page }) => { + await openStep(page, 'summary'); + const preview = page.getByTestId('plan-preview'); + await expect(preview.getByTestId('plan-preview-source')).toHaveText('Optimiser'); + await expect(preview.getByTestId('plan-preview-numbers')).toContainText('solar'); + await expect(preview.getByTestId('plan-preview-soc')).toContainText('Battery'); + await preview.getByRole('link', { name: 'Open the plan' }).click(); + await expect(page).toHaveURL(/#\/plan$/); +}); + +test('settings link to the steps and show the new summaries', async ({ page }) => { + await page.goto('/#/settings'); + const overview = page.getByTestId('overview'); + await expect(overview).toContainText('forecast source'); + await expect(overview).toContainText('Control:'); +}); + +test('German labels of the new steps', async ({ browser }) => { + const ctx = await browser.newContext({ locale: 'de-DE' }); + const page = await ctx.newPage(); + await page.goto('/#/setup/battery'); + await expect(page.getByTestId('battery-strategy')).toContainText('Risikostufe'); + await page.goto('/#/setup/priorities'); + await expect(page.getByTestId('grid-charge')).toContainText('Laden aus dem Netz'); + await ctx.close(); +}); + +test('step 6: a stored price formula survives saving at once, before the template has loaded', async ({ + page, + request, +}) => { + const formula = { + spot_multiplier: 1, + grid_fee: 0.08, + levies: 0.03, + margin: 0.01, + vat_pct: 19, + grid_fee_windows: [], + }; + const put = await request.put('/api/v1/config/tariff', { + data: { + schema_version: 3, + import: { + kind: 'dynamic', + template_id: 'entsoe.price', + price_entity: { entity_id: 'sensor.sim_electricity_price', invert_sign: false }, + formula, + }, + export: { kind: 'fixed', fixed_price: 0.08, tiers: [] }, + }, + }); + expect(put.ok()).toBe(true); + // Slow template answers: the step cannot know the source yet when "save" is pressed. + await page.route('**/api/v1/templates/entsoe.price', async (route) => { + await new Promise((r) => setTimeout(r, 1500)); + await route.continue(); + }); + await openStep(page, 'tariff'); + await next(page).click(); + await expect(page).toHaveURL(/#\/setup\/devices$/); + const tariff = await get(request, 'tariff'); + expect(tariff.import.formula).toMatchObject({ grid_fee: 0.08, vat_pct: 19 }); +}); + +test('step 6: a period without a price blocks saving', async ({ page }) => { + await openStep(page, 'tariff'); + const imp = page.getByRole('group', { name: 'Import price' }); + await imp.getByRole('radio', { name: 'Fixed time-of-use (HT/NT)' }).check(); + const editor = page.getByTestId('tou-editor'); + await editor.getByLabel(/^Base price/).fill('0.34'); + await editor.getByTestId('tou-add').click(); + await next(page).click(); + await expect(page.getByRole('alert')).toBeVisible(); + await expect(page).toHaveURL(/#\/setup\/tariff$/); +}); diff --git a/frontend/e2e/wizard.spec.ts b/frontend/e2e/wizard.spec.ts index f36d1e5..80d03e7 100644 --- a/frontend/e2e/wizard.spec.ts +++ b/frontend/e2e/wizard.spec.ts @@ -62,8 +62,12 @@ test.describe('setup wizard', () => { // 5 battery await expect(page).toHaveURL(/#\/setup\/battery$/); await expect(page.getByTestId('sign-question')).toContainText(/battery is/i); + await page.getByRole('combobox', { name: 'Battery adapter' }).selectOption(''); await expect(page.getByTestId('observe-note')).toBeVisible(); - await page.getByLabel('Usable capacity').fill('10'); + await page + .getByRole('group', { name: 'Capacity and limits' }) + .getByLabel('Usable capacity') + .fill('10'); await expectNoAxeViolations(page); await next(page).click(); @@ -122,7 +126,7 @@ test.describe('setup wizard', () => { await expect(page).toHaveURL(/#\/setup\/summary$/); await expect(page.getByTestId('check-items')).toBeVisible(); await expect(page.getByTestId('check-overall')).toHaveAttribute('data-severity', /ok|warn/); - await expect(page.getByTestId('plan-note')).toContainText('later version'); + await expect(page.getByTestId('plan-preview')).toBeVisible(); await expectNoAxeViolations(page); await next(page).click(); await expect(page).toHaveURL(/#\/$/); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index d262718..3733928 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.0", "license": "Apache-2.0", "dependencies": { + "echarts": "5.6.0", "intl-messageformat": "12.1.2" }, "devDependencies": { @@ -1784,6 +1785,16 @@ "dev": true, "license": "MIT" }, + "node_modules/echarts": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/echarts/-/echarts-5.6.0.tgz", + "integrity": "sha512-oTbVTsXfKuEhxftHqL5xprgLoc0k7uScAwtryCgWF6hPYFLRwOUHiFmHGCBKP5NPFNkDVopOieyUqYGH8Fa3kA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "2.3.0", + "zrender": "5.6.1" + } + }, "node_modules/entities": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz", @@ -3666,6 +3677,12 @@ "typescript": ">=4.8.4" } }, + "node_modules/tslib": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", + "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==", + "license": "0BSD" + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -4107,6 +4124,15 @@ "integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==", "dev": true, "license": "MIT" + }, + "node_modules/zrender": { + "version": "5.6.1", + "resolved": "https://registry.npmjs.org/zrender/-/zrender-5.6.1.tgz", + "integrity": "sha512-OFXkDJKcrlx5su2XbzJvj/34Q3m6PvyCZkVPHGYpcCJ52ek4U/ymZyfuV1nKE23AyBJ51E/6Yr0mhZ7xGTO4ag==", + "license": "BSD-3-Clause", + "dependencies": { + "tslib": "2.3.0" + } } } } diff --git a/frontend/package.json b/frontend/package.json index 7f14f30..32f3234 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -23,6 +23,7 @@ "verify": "npm run gen:api:check && npm run lint && npm run format:check && npm run check && npm run test && npm run build && npm run size" }, "dependencies": { + "echarts": "5.6.0", "intl-messageformat": "12.1.2" }, "devDependencies": { diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 81396c1..f3728dc 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -21,7 +21,7 @@ export default defineConfig({ locale: 'en-US', }, webServer: { - command: `npm run build && cd .. && SUNCORE_PORT=${PORT} SUNCORE_DEMO=1 SUNCORE_DEMO_START_TIME=09:30 SUNCORE_STATIC_DIR=frontend/dist uv run python -m suncore`, + command: `npm run build && cd .. && SUNCORE_PORT=${PORT} SUNCORE_DEMO=1 SUNCORE_DEMO_BATTERY_CONTROL=1 SUNCORE_DEMO_START_TIME=09:30 SUNCORE_STATIC_DIR=frontend/dist uv run python -m suncore`, url: `http://127.0.0.1:${PORT}/health`, reuseExistingServer: !process.env.CI, timeout: 180_000, diff --git a/frontend/scripts/bundle-size.mjs b/frontend/scripts/bundle-size.mjs index e0699d2..9668f96 100644 --- a/frontend/scripts/bundle-size.mjs +++ b/frontend/scripts/bundle-size.mjs @@ -1,10 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 -// Reports the gzip size of dist/ and fails above the budget (Phase 1: 250 kB). +// Reports the gzip size of dist/ and fails above the budgets: +// * everything except the ECharts chunk: 250 kB (Phase 1 budget, unchanged), +// * first paint (index.html plus its static import graph): 125 kB, +// * the ECharts chunk (Phase 4: loaded on demand with the plan view only): 200 kB, +// * ECharts must not be reachable from index.html through static imports. import { readdirSync, readFileSync, statSync } from 'node:fs'; -import { join, relative } from 'node:path'; +import { dirname, join, relative, resolve } from 'node:path'; import { gzipSync } from 'node:zlib'; const BUDGET_BYTES = 250 * 1000; +const FIRST_PAINT_BYTES = 125 * 1000; +const ECHARTS_BYTES = 200 * 1000; const dist = new URL('../dist/', import.meta.url).pathname; function* walk(dir) { @@ -15,17 +21,56 @@ function* walk(dir) { } } +const gz = (file) => gzipSync(readFileSync(file), { level: 9 }).length; +const isEcharts = (file) => /(^|\/)echarts-[^/]*\.js$/.test(file); + let total = 0; +let echarts = 0; for (const file of walk(dist)) { if (!/\.(js|css|html|json|svg)$/.test(file)) continue; - const gz = gzipSync(readFileSync(file), { level: 9 }).length; - total += gz; - console.log(`${(gz / 1000).toFixed(1).padStart(8)} kB ${relative(dist, file)}`); + const size = gz(file); + if (isEcharts(file)) echarts += size; + else total += size; + console.log( + `${(size / 1000).toFixed(1).padStart(8)} kB ${relative(dist, file)}${isEcharts(file) ? ' (on demand)' : ''}`, + ); +} + +// First paint: the files index.html loads and their static imports (dynamic import() excluded). +const firstPaint = new Set(); +function visit(file) { + if (firstPaint.has(file)) return; + firstPaint.add(file); + if (!file.endsWith('.js')) return; + const code = readFileSync(file, 'utf8'); + for (const m of code.matchAll(/(?:\bfrom|\bimport)\s*["'](\.{1,2}\/[^"']+\.js)["']/g)) { + visit(resolve(dirname(file), m[1])); + } } +const html = readFileSync(join(dist, 'index.html'), 'utf8'); +firstPaint.add(join(dist, 'index.html')); +for (const m of html.matchAll(/(?:src|href)="\.\/([^"]+\.(?:js|css))"/g)) visit(join(dist, m[1])); +let paint = 0; +for (const file of firstPaint) paint += gz(file); + +const kb = (n) => `${(n / 1000).toFixed(1)} kB`; console.log( - `${(total / 1000).toFixed(1).padStart(8)} kB total gzip (budget ${BUDGET_BYTES / 1000} kB)`, + `${kb(paint).padStart(8)} first paint (index.html + static imports; budget ${FIRST_PAINT_BYTES / 1000} kB)`, ); -if (total > BUDGET_BYTES) { - console.error('Bundle size budget exceeded.'); - process.exit(1); -} +console.log( + `${kb(echarts).padStart(8)} ECharts chunk, on demand (budget ${ECHARTS_BYTES / 1000} kB)`, +); +console.log( + `${kb(total).padStart(8)} total gzip without ECharts (budget ${BUDGET_BYTES / 1000} kB)`, +); + +let failed = false; +const fail = (msg) => { + console.error(msg); + failed = true; +}; +if ([...firstPaint].some(isEcharts)) fail('ECharts is part of the first paint.'); +if (paint > FIRST_PAINT_BYTES) fail('First paint budget exceeded.'); +if (echarts > ECHARTS_BYTES) fail('ECharts chunk budget exceeded.'); +if (total > BUDGET_BYTES) fail('Bundle size budget exceeded.'); +if (failed) process.exit(1); diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte index ff7bec7..e5ca83a 100644 --- a/frontend/src/App.svelte +++ b/frontend/src/App.svelte @@ -82,6 +82,7 @@

{t('app.title')}