batpred icon indicating copy to clipboard operation
batpred copied to clipboard

Joint cost-aware EV and home-battery scheduling under a site import limit

Open arturonaredo opened this issue 1 month ago • 8 comments

Feature request

Joint cost-aware scheduling of a fixed-rate EV and home battery under a site import limit

This is a request for one native Predbat plan which jointly decides when the EV charges and when the home battery charges, holds or discharges, using household and heating demand, PV forecasts, actual import/export prices and physical limits. It is not a request for a second Home Assistant optimiser or a fast protective loop.

I am developing an opt-in implementation in my personal fork. This issue describes the intended behaviour and acceptance criteria, not a claim that the feature is complete or deployed. Diagnostic draft PR #5486 remains separate and does not close this request.

Problem

The current Predbat-led car planner selects low-import-price windows before the household battery optimisation. It does not jointly search EV placement, battery preparation and whole-site import feasibility. A fixed-rate charger cannot follow whatever PV surplus happens to remain: when enabled, its real full demand must be accounted for, with the balance supplied by an executable combination of battery and grid.

Avoiding expensive hours alone can miss a better overall outcome. Charging a car with PV plus some battery now can be cheaper when later sunlight will replenish the battery anyway. Conversely, buying cheap electricity overnight for the car and/or home battery may preserve valuable stored energy for household demand later. There should be no unconditional rule to fill the home battery before the EV, use the battery at all costs, or avoid grid charging altogether.

Plain-language use case

Think of this as one coordinator for the house, home battery and fixed-rate EV, not three independent timers. Ordinary Predbat already supports batteries and EV planning; the requested change is to choose their schedules together and only dispatch combinations supported by the installed inverter and EV executor.

Example: the car needs more power than the grid allowance

Using deliberately rounded, illustrative values:

  • The house needs 2 kW.
  • The fixed-rate EV charger needs 7 kW whenever it is ON; it cannot turn down.
  • Whole-site grid import is limited to 6 kW.
  • Total demand is therefore 9 kW, not 6 kW.

With no PV, a feasible candidate may draw 6 kW from the grid and 3 kW from the home battery, provided the actual inverter mode can do this and battery power, energy, losses, reserve and restart thresholds all permit it. If they do not, the planner must prepare the battery earlier or move the EV slot. It must not invent a lower charger power, silently exceed the import allowance, or count energy that the battery does not have.

Compare the cost of the complete household outcome, not just the EV's tariff: charging the car now with some stored energy can be worthwhile if later PV will replenish the battery; buying inexpensive energy overnight may instead preserve that battery for household demand. Household supply remains the priority.

Four different user intentions

Priority Expected behaviour
cost Choose a low-cost feasible combined schedule before departure; split EV runs can be appropriate.
asap Use the next useful opportunity, including nearby solar or a cheaper tariff, while preserving the departure requirement.
now Attempt a validated start in the current control interval; report why it cannot start rather than silently substituting a later slot.
solar Require sufficient conservative and observed household PV surplus for the fixed EV demand; do not silently fall back to grid or battery support for the EV.

If the cheapest hours are insufficient, the cost-aware policy should consider the next eligible price bands before departure. A legacy car-planner price setting must not silently masquerade as a limit on a different joint policy. Any hard price cap would need an explicit contract explaining that it can leave the departure target unmet.

A plan is not evidence that the car charged

An applied household command and future EV windows do not prove EV delivery. The current EV interval needs a separate unexpired authorisation, real relay and power observations, and cumulative energy evidence. Replanning should not keep moving a promised start forward indefinitely without making the changed plan and any deadline shortfall accountable. Departure completion must be reported separately from an estimate or a successful software replay.

For a standing daily policy, use a trustworthy connection and permission gate; GPS may be an optional additional input, not a universal prerequisite. A brief telemetry outage must withdraw live authority without automatically inventing a physical unplug or discarding the original cumulative-meter baseline. Late meter batches still belong to the physical charging interval that delivered them. Explicit disconnections, meter resets and contradictory evidence remain distinct and must not be hidden.

Vehicle connection codes, explicitly tolerated warning codes, optional telemetry quality attributes and charger power/efficiency must come from configuration. The engine must not assign one installation's numeric error code or vehicle vendor's quality field to every car. A configured warning is logged, not promoted to an execution permission that bypasses the remaining checks.

Planning remains separate from fast electrical protection. This example is a behaviour contract, not a deployment configuration or a claim of completed physical commissioning.

Representative configurable example

The following is a synthetic acceptance profile, not a deployment configuration:

Quantity Example
Whole-site grid import ceiling 6,000 W
Fixed EV charging demand 6,770 W, on/off only
Home battery capacity approximately 32 kWh
Home battery charge/discharge limits 3,000 / 8,000 W
Minimum domestic SoC 10%
EV pause/restart domestic SoC 15% / 25%
EV target / departure 100% / 07:30, subject to physical feasibility
Import bands 8.1 / 11.2 / 19.1 currency cents per kWh
Export compensation zero in this example, configurable elsewhere

Grid import, battery power, inverter conversion and AC load/passthrough limits are distinct constraints. A 6 kW import ceiling is not a 6 kW household-load ceiling: PV and battery can supply additional load within the verified topology. An inverter's nominal rating alone is not proof of available power at every SoC.

Use cases and expected behaviour

1. Charge on solar now, recover the home battery later

Given 5 kW usable PV, 1 kW household demand and a 6.77 kW fixed EV, a candidate may use approximately 2.77 kW of battery support, subject to losses and limits. If later PV can replenish the home battery after the EV finishes, compare this with delaying the EV or buying overnight. Do not reject the daytime candidate merely because PV alone cannot cover the EV, and do not pretend the charger has reduced itself to the available surplus.

2. Prepare the home battery during cheap hours

When PV is insufficient, the planner may buy cheap energy for the home battery before an EV slot. Include charging power, charging/discharging losses, SoC, household consumption and the time available. Grid-charge preparation and EV charging must be co-scheduled, not assumed to fit simultaneously under the cap. Do not assume an ECO inverter supplies only the amount above the import limit; simulate its actual battery-first/hold/charge behaviour.

3. Use the next more expensive eligible hours automatically

If the lowest-price windows cannot meet the target, include the next cheapest eligible windows before departure, rather than reporting a shortfall merely because cheap time ran out. Compare the full system cost, including solar and storage opportunity cost, not only the import-price label on an EV slot. Only a genuine absence of a physically feasible plan should remain unmet. A bounded search must distinguish "no plan found" from a proof of impossibility.

4. Heating and household demand remain the priority

When heating or other household demand rises, re-plan the flexible EV/battery schedule. Do not silently shed household demand, move heating without permission, increase electrical limits or invent a reduced EV charging rate. Include actual EV restart hysteresis and minimum switching intervals to avoid a plan the executor will repeatedly pause.

5. Anticipate arrival without inventing a connection

An expected return time and a recent EV SoC may establish a future energy need, even while the car is away. No EV energy may be assigned before its availability window. Expected availability is not permission to energise an absent/unplugged charger: actual execution needs a separate trustworthy connection/session gate. Re-plan on delayed arrival, cancellation, stale/unknown SoC or disconnection.

6. Do not use tomorrow's sun to satisfy an earlier deadline

PV arriving after a 07:30 departure cannot count towards that departure's EV energy. It can affect the value of energy left in the house battery afterwards. Price changes on weekdays must be respected from the supplied tariff series.

7. Respect power and energy at every step

With no PV, a battery already at reserve, a 1.2 kW house and a fixed 6.77 kW EV, the demand is 7.97 kW. A 6 kW import ceiling cannot be satisfied by clipping the graph or debiting an empty battery. Move the EV or prepare energy earlier. Preserve raw energy balance, efficiencies, charge/discharge limits and SoC bounds. Curtailing grid-funded battery charging must not unnecessarily curtail usable PV.

8. Compare equivalent end conditions and handle forecast changes

Account for terminal stored energy or an explicit terminal target, so an emptier battery does not masquerade as a saving. Include uncertainty/re-planning when PV underperforms or household load increases. A safe forecast is not a guarantee against every instantaneous unforecast load spike.

Integration and acceptance criteria

  • Opt-in; disabled behaviour remains unchanged.
  • Native Predbat owns the plan; existing inverter mappings and one existing EV executor remain authoritative. No competing controller or external service.
  • Real fixed-rate EV energy, battery losses, source accounting and terminal energy are covered by synthetic regression tests for the use cases above.
  • Candidate selection treats physical feasibility and the departure requirement separately from monetary cost; no arbitrary large monetary penalty presented as a hard constraint.
  • Any candidate applied to native control must match executable inverter modes, window resolution/count and rates. Unsupported configurations must be explicit, not silently run an idealised dispatch model against different hardware.
  • Python, native-kernel, cache and final HA publication paths must agree, or an unsupported accelerated path must be explicitly disabled for the feature.
  • Planning is not electrical protection. Hardware protection and a verified fast control path are still needed; a five-minute optimisation loop cannot enforce an instantaneous whole-site ceiling by itself.

Relation to existing work

  • #5486: truthful site-import diagnostics; retained as the first foundation, not relabelled as joint optimisation or enforcement.
  • #2449: site import modelling. This request adds the coupled EV/battery scheduling objective and concrete fixed-rate departure/availability cases.
  • #5384: solar opportunity cost when choosing EV slots. The same economics also matter with zero export compensation and limited storage.
  • #5195: solar-led charging/availability/deadlines. Its current solar path assumes a charger that modulates to surplus; this request must also support fixed on/off EV charging with battery/grid support, without that assumption.
  • #3293: concurrent EV and battery charging. A blanket ban is not required when PV and the verified topology make concurrency feasible.
  • #1199: rolling capacity tariffs are related but remain a separate billing feature, not interchangeable with this per-step import constraint.

The new issue is intentionally an integration-level behaviour contract linking those pieces, not a duplicate request for another import-limit setting. No issue above should be closed merely by publishing diagnostics or this proposal.

arturonaredo avatar Oct 11 '26 20:10 arturonaredo

šŸ¤– Automated first-pass triage — a maintainer will review this before any action is taken.

Classification: enhancement (feature request, so no priority label).

Verified against current main (v9.3.7-6-gd6985b6d) — the gap the issue describes is real:

  • EV slots are placed by plan_car_charging() (apps/predbat/plan.py:5969), called from fetch_sensor_data_car_planning() (apps/predbat/fetch.py:1424, slot creation at fetch.py:1454) before the battery optimisation runs. It sorts the handed-over low-rate windows cheapest-first (car_charging_plan_smart only reorders them) and fills to car_charging_limit by the ready time; PV, battery SoC and any import cap never enter that search, and when the handed windows can't reach the target the plan just ends up short — there is no expansion into other windows. The battery solver then runs with the placed car slots as fixed load, so the plan's cost is car-aware, but EV placement itself is never co-searched. That is exactly the joint-scheduling gap the issue names.
  • There is no whole-site import limit today: import_limit appears only as per-inverter discovery ratings (sunsynk.py:1605, fox.py:2614 — device-reported caps) and never as a planner setting. The shipped precedent it would mirror is the export-side export_limit clamp inside the per-minute prediction loop (prediction.py:664).
  • The kernel/Python-parity acceptance criterion is a real constraint: run_prediction() dispatches to the native kernel when available (prediction.py:538), and the kernel source lives in prediction_kernel.cpp. A new constraint must be mirrored in both engines or the accelerated path disabled while the feature is on, which is what the issue asks for and which draft PR #5486's change list (prediction.py, prediction_kernel.py, tests) already anticipates.

Not a duplicate — none of the linked pieces asks for the joint objective; each covers a subset:

  • #2449 / #1199 — the import-cap setting itself. A design note recorded on #1199 suggests a staged approach: a flat, solar-blind import_limit mirroring export_limit as a first cut, a reactive external-target throttle (projected 15-minute average) as follow-up, Predbat publishing state while user automations keep billing policy — and it flags the measurement gap, that a load not on the total-import reading can't be clamped.
  • #5384 — PV-export opportunity cost in car slot ranking.
  • PR #5195 — solar-led charging with surplus-sized slots. Not merged, and car_charging_solar doesn't exist anywhere in main, so use case 5's "solar path" describes a proposal, not shipped behaviour.
  • #3293 — capacity-tariff request to block EV + battery grid-charging simultaneity.
  • PR #5486 (draft, same reporter) — the diagnostics foundation (import_limit scalar + predbat.best_import_limit sensor, no enforcement, no candidate ordering change) — i.e. the first stage of the #1199 note's staging.

Shape for maintainer review: this is one umbrella request whose pieces could land in the recorded order above (cap → diagnostics → ranking cost → joint search), and the maintainer may equally decide the joint EV+battery search shouldn't live inside the 5-minute-loop planner at all — the issue's own acceptance criteria treat that loop as not-electrical-protection and leave hardware protection explicitly out of scope. Both the scope decision and where the joint search lives (car planner vs main solver) are maintainer calls on a change this wide.

Nothing further is needed for triage — as a feature request it doesn't require a debug yaml or log.

springfall2008 avatar Oct 11 '26 20:10 springfall2008

Personal-fork progress, not an installation recommendation or a claim that this issue is solved:

Published commit: 11f3d385, signature verified by GitHub.

  • Development branch: joint-site-energy-planner, with scope and limitations. The separate diagnostic PR #5486 remains unchanged.
  • The experimental bounded search jointly chooses fixed-rate EV on/off and domestic-battery demand/hold/charge across the horizon. It accounts for losses, curtailment, terminal battery value, domestic-battery EV hysteresis/cooldown, expected availability, departure and more-expensive eligible slots.
  • Native integration is shadow-only: each candidate is independently replayed with fresh native central/PV10 predictions. It never replaces executable inverter/EV windows, the active prediction/cache, or the actuator-facing EV-slot signal. execution_enabled and enforced remain false.
  • Offline validation: independent energy-conservation tests and a separate tiny exhaustive reference; real calculate_plan → solver → native replay tests; full quick suite with the native kernel required; both committed golden debug replays; pre-commit and documentation build. Four slow suites remain excluded. No change to either native prediction engine's dispatch semantics.

This is a bounded approximation, not proof of a global optimum or infeasibility when no plan is found. Executable window mapping (including adjacent unequal targets), reliable real connection/session permission, and hardware validation are still unresolved. No live deployment, forced charging, hardware-limit change, or new upstream implementation PR has been made. Maintainer scope/design approval is still separate from automated triage.

arturonaredo avatar Oct 11 '26 21:10 arturonaredo

Adding a use case that I think falls under this, plus a couple of questions.

Setup (UK, being installed now)

  • Hanchu HESS-HY-S-10.0K hybrid, 48 kWh of battery, 23 kWp PV, heat pump. Export limit 7.5 kW, exporting on Agile Outgoing.
  • One EV (Porsche Macan, 95 kWh usable) on fixed-rate 7.4 kW chargers. They are Hanchu HC-EV-AC-07K, controllable through the Hanchu cloud: charging on/off, plus a "disable battery discharge to EV" toggle that blocks battery-to-EV while the battery keeps supplying the house (details in #6044 / upton68/hanchu-ess-ha#55).
  • Import on Intelligent Octopus Go, Octopus-led through the car integration. The house is cheap 23:30-05:30. The car gets at most 6 h a day of cheap dispatches (midday to midday). Car charging over the cap, or boosts, is billed at the EV peak rate, even at night (EV and home are separate lines on the bill since the 2026 change).

What I need the plan to do

  • The car can charge for up to 12 h between 20:00 and 08:00.
  • Up to 6 h comes from the grid in Octopus dispatches, with battery-to-EV blocked.
  • The rest comes from the home battery outside dispatches, with no grid for the car outside dispatches, because that is billed at peak.
  • Meanwhile the battery still fills 23:30-05:30 and exports on Agile Outgoing when that pays.

So the planner has to reserve battery energy for the battery-fed car hours, and treat car-from-battery as allowed outside dispatches but blocked inside them. Per the #6044 triage, today IOG cars are Octopus-led, so plan_car_charging() is skipped and car_charging_from_battery is global. That means it currently needs HA glue (manual_load_adjust plus flipping the switch by automation).

Questions

  1. Does your joint planner cover the Octopus-led case (the dispatches decide the grid-fed EV slots, and the planner only adds battery-fed EV time around them)? Or only Predbat-led fixed-rate tariffs?
  2. Is it heading towards a PR, and is there anything blocking it, e.g. waiting on maintainer review or the native-kernel parity work?

I'm happy to test your branch on real hardware once the batteries and IOG are live (soon), and to share logs.

Jon2263 avatar Nov 08 '26 00:11 Jon2263

Title: Feature Request: Respect total Grid Import Limit (Main Fuse Cap) when co-scheduling EV(s) and Home Battery

Problem Description On a typical European/Dutch 3-phase 3x25A residential grid connection, the maximum total site import power is strictly capped at 17.25 kW (3 x 25A x 230V), enforced by hardware dynamic load balancers (such as Blue Current Wattson / P1 CT clamps).

Currently, Predbat plans EV charging (plan_car_charging()) and home battery charging independently without enforcing a site-wide grid import limit:

  1. When two 11 kW EVs are plugged in, Predbat schedules 22 kWh per hour in the Car column (e.g., from 02:00 to 04:00) while simultaneously scheduling home battery charging (Chrg from 21% to 95%) and ~1.2 kW house load in the exact same slots.
  2. This assumes a combined grid import of ~28–30 kW on a 17.25 kW main connection.
  3. Because Predbat assumes the EVs will receive the full 22 kW, it only allocates 3 hours of cheap night slots (02:00–05:00 at 38p–39p) and skips adjacent cheap slots (00:00–02:00 at 40p).
  4. In reality, the hardware load balancer throttles the two EV chargers down to ~6.9 kW each (~13.8 kW total, or less while the home battery charges). As a result, the EVs are not finished by 05:00 and are forced to continue charging during expensive morning peak hours (06:00–07:30 at 44p–49p).

Requested Enhancement (relates to #5490)

  • Introduce a configurable site_import_limit_kw (e.g., 17.25 kW) in apps.yaml / HA UI.
  • Ensure that in any planned slot, Home Load + Home Battery Charge Power + Total EV Charging Power <= site_import_limit_kw.
  • If simultaneous EV(s) + Home Battery charging exceeds site_import_limit_kw, Predbat should automatically:
    1. Cap the combined EV charging rate per slot to the remaining available import capacity (expanding EV charging into adjacent cheap slots like 00:00–02:00 so the target SoC is still met on time), and/or
    2. Stagger home battery charging and EV charging into separate cheap slots when possible.

Gammaed avatar Nov 11 '26 10:11 Gammaed

Adding a UK use case where the inverter can enforce the import cap itself, so Predbat would only need to model it.

Setup

  • SigenStor EC 10.0 SP (10 kW inverter), 34.2 kWh battery, inverter_type: SIG
  • Sigen AC charger, about 7 kW fixed rate, with car charging tracked through car_charging_energy
  • Octopus Go, with cheap import 00:30–05:30. The DNO limit is on export only (10 kW). There is no contractual import limit.

Problem On Go nights the car (7 kW), battery grid charging and evening loads overlap. Import has reached 18–19 kW. At that load the supply voltage sags enough that the AC charger has faulted and the car didn't charge.

My workaround is to cap battery charging at 7 kW during 00:30–05:30 only. Five hours at 7 kW is 35 kWh, which is still enough to fill the battery from empty. The rest of the day the battery charges at full rate from PV.

In Predbat, the nearest setting is inverter_limit_charge, but it applies all day. So it also caps PV charging, which is the same issue raised in #2449.

What would help, in order of preference:

  1. A site import_limit (W) that Predbat models in the plan, with house load + EV + battery charge <= limit in each slot. Enforcement can stay with the inverter: Sigen has a grid import limitation setting (number.sigen_plant_grid_import_limitation in the Sigenergy-Local-Modbus integration). Predbat just needs to plan with it, the same way export_limit works today. This seems to fit the "model it, don't enforce it" scope discussed above.
  2. Failing that, a time window for inverter_limit_charge, or a separate grid-charge rate limit, so the cap applies only to AC charging in the cheap window and leaves PV charging alone.

Happy to test either on a SIG setup.

garethparris avatar Nov 12 '26 15:11 garethparris

Point 1 is the aim of this feature request, agreed that is the best long term solution.

  1. Failing that, a time window for inverter_limit_charge, or a separate grid-charge rate limit, so the cap applies only to AC charging in the cheap window and leaves PV charging alone.

You can do this already in predbat, just use an automation to change inverter_limit_charge at the times you want using select.predbat_manual_api

https://springfall2008.github.io/batpred/manual-api/

gcoan avatar Nov 12 '26 17:11 gcoan

Thanks @gcoan, that's helpful.

I've gone with a slightly different workaround, for anyone else on SIG with a Sigen AC charger. A timed inverter_limit_charge override via select.predbat_manual_api would also cap the battery on nights the car isn't charging. So I clamp the battery only while the car is actually drawing power.

The HA automation that maps Predbat's input_number.charge_rate to number.sigen_plant_ess_max_charging_limit now also triggers on sensor.sigen_ac_charger_charging_power. While the charger draws more than 1 kW, it writes min(Predbat rate, 7 kW); otherwise it writes the Predbat rate unchanged. The car is never throttled, only the battery, and PV charging is unaffected unless the car is also charging.

Known gap: Predbat still models full-rate battery charging during car slots, so on car nights the plan is a bit optimistic until it replans. A modelled site import_limit (this issue) would close that. I'll report back once it's running under Predbat control.

garethparris avatar Nov 13 '26 12:11 garethparris

+1 on this feature request — want to add a real-world use case that makes the gap very concrete.

My setup: SolaX X3-IES-P hybrid inverter/battery, ground-source heat pump with resistive backup heating, two Tesla EVs on separate chargers (Zaptec + Easee), all behind a single site connection with a fixed main fuse rating. With resistive heating, the heat pump, and both EVs potentially drawing at once, total load can spike well above what the connection is rated for — and Predbat has no concept of this at all. It happily plans car charging and battery charging/discharging independently of each other and of the other loads, based purely on price, with zero awareness that the sum could trip the main fuse.

Worth noting this cuts both ways. It's not just that Predbat is unaware of the risk of exceeding the import limit — it's equally unaware of how to make full use of the capacity that IS available. A joint scheduler could intentionally pack battery charging and EV charging together into the cheapest slots to use the available headroom efficiently, instead of planning them independently where they might needlessly spread out, undershoot the available capacity, or clash unpredictably.

As a stopgap, I've had to build this myself entirely outside Predbat: a pair of Home Assistant automations that watch total house load and force input_number.predbat_set_reserve_min to 100% (effectively "hands off the battery") whenever load crosses my fuse-safe threshold for a sustained period, then release it back down once load drops again. It works, but it's crude — it only protects the battery side, has no visibility into what Predbat's planner is actually trying to do at that moment, and does nothing for coordinating the EV chargers themselves or for actively using spare capacity.

A native site-import-aware plan — as described in this issue — covering battery charge/discharge AND EV charging rate/on-off together against one shared import ceiling would be hugely valuable for anyone with a hybrid inverter + heat pump + multi-EV household on a limited connection, which feels like an increasingly common setup. Happy to help test an opt-in version if one becomes available.

janipoussu-ui avatar Nov 20 '26 05:11 janipoussu-ui