Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/planner-hourly-import-limit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ftw": patch
---

The plan now keeps each clock hour under the hourly import limit. The planner used to see only the fuse. With a 4.5 kW limit it could plan the car at 4.8 kW for four hours, import 5.5 kWh in an hour and show a charging goal as met that FTW could not deliver. Each plan now gets every clock hour in the box's local time and what the hour in progress has used, and FTW rejects a plan that imports more in an hour than it may. A planned hour keeps a little under the limit, because the car charges in whole amps and FTW raises it only with a step to spare; the plan then promises about what the car gets. When the limit puts a goal out of reach, the plan says how much is missing. The home battery covers the house so the car gets more of the hour. The bundled Energyplan worker does not take the hours yet: when its plan breaks them, FTW uses its own plan. Where FTW cannot plan the site itself, it keeps the worker's plan, says the plan may break the limit, and still holds each hour to it live. A new limit replans at once.
45 changes: 36 additions & 9 deletions docs/energyplan-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,11 @@ whose I/O exceeds the call deadline; a later call may start a fresh process.
The handshake identifies the worker, its version, protocol range and features.
Protocol compatibility and supported features govern use, not matching Core
and Energyplan release numbers. Current features are `champion`,
`forecast_reset`, `partial_slots`, `demand_charges`, `ev_duty` and
`charging_periods` and `published_prices`; the worker also reports
`forecast_protocol_version`.
Core negotiates `charging_periods` before sending its optional fields.
`forecast_reset`, `partial_slots`, `demand_charges`, `ev_duty`,
`charging_periods`, `published_prices` and `hourly_import_caps`; the worker
also reports `forecast_protocol_version`.
Core negotiates `charging_periods` before sending its optional fields, and
`hourly_import_caps` before sending `hourly_import_caps`.

New optional request fields need capability negotiation or a paired update
that preserves deployed clients. Unknown optimizer request fields are errors.
Expand Down Expand Up @@ -92,6 +93,31 @@ charge/discharge direction in each slot. Demand-charge windows use explicit
UTC intervals and elapsed import from Core; Core owns local calendar and
daylight-saving conversion.

`hourly_import_caps` carries the owner's hourly import limit as a hard
limit. Each entry is `{start_ms, end_ms, max_mean_w, elapsed_import_wh}`:
one local clock hour as UTC milliseconds, the mean import the hour may hold
in W, and the import in Wh the hour has already used before the plan starts
(0 for later hours). Core sends one entry per clock hour that overlaps the
plan, from the first slot's execution start to the horizon end; a
daylight-saving day has 23 or 25. The hour in progress may start before the
first slot and the last may end after the horizon; an entry outside the plan
is ignored. Entries must not overlap, last 1 minute to 25 hours, and number
at most 512. Import is `max(0, grid)` per pulse state: a duty slot imports
`duty * max(0, grid on)` plus `(1 - duty) * max(0, grid off)`, at the cut
points between the cars' duties. In every scenario, the plan's import inside
an hour from execution start must not exceed
`max_mean_w * hours - elapsed_import_wh`. In an hour where every car is off
it may instead reach what the house alone imports there,
`max(0, load_w + pv_w)` per slot with the battery idle, if that is more: Core
cannot cut the house, but its live limit stops a car before the house.
`max_mean_w` may be 0: the hour then has room for the house alone. The worker
is stricter in one case: while a car pulses into solar surplus and the
battery charges, it counts the car's on-step import plus the whole charge.
The cap wins over EV goals, whose miss shows in
`flex_shortfall_wh`. The plan reports each hour in
`plan.hourly_import_caps` as `{start_ms, end_ms, import_wh, max_wh}` on the
published forecast, `import_wh` including the elapsed part.

Thermal, commercial and recourse inputs are unsupported. Protocol v1 has no
per-phase electrical model, future connection windows or phase-switch schedule.
Total watts cannot certify phase safety. Those extensions need an explicit
Expand Down Expand Up @@ -169,11 +195,12 @@ objective. Unknown bounds and gaps remain null. When executed pulse cost and
the optimized cost model differ, report `feasible` and omit the cost bound.
Core validates physical execution; it does not independently prove optimality.

Current Core allows 500 ms for small plans and 5 s for larger plans or demand
charges, with a 7 s transport timeout. It reduces the budget near the first
slot's end and leaves 50 ms for validation/publication. These are compute and
call budgets, not a proven wall-time SLA. Measure queueing, startup, decoding,
solving, replay, encoding and Core validation separately when changing them.
Current Core allows 500 ms for small plans and 5 s for larger plans, demand
charges or hourly import caps, with a 7 s transport timeout. It reduces the
budget near the first slot's end and leaves 50 ms for validation/publication.
These are compute and call budgets, not a proven wall-time SLA. Measure
queueing, startup, decoding, solving, replay, encoding and Core validation
separately when changing them.

A warm worker may keep one previous plan as a candidate. Before reuse it must
match asset identities, advance time, rebuild energy from current measurements,
Expand Down
7 changes: 7 additions & 0 deletions go/cmd/ftw/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1670,6 +1670,13 @@ func main() {
defer ctrlMu.Unlock()
return control.PhaseImbalanceW(tel, ctrl, timeout, time.Now())
}
// The planner keeps each clock hour under the owner's import
// ceiling, from the budget Core's live limit counts.
mpcSvc.ImportCeiling = func() mpc.ImportCeiling {
ctrlMu.Lock()
defer ctrlMu.Unlock()
return control.PlanningImportCeiling(ctrl)
}
// Cap planned export below the fuse when the operator set a site
// export ceiling, so the DP never schedules a discharge that would
// over-export and trip an inverter (the Ferroamp 0x8030 fault).
Expand Down
5 changes: 5 additions & 0 deletions go/internal/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -1934,6 +1934,11 @@ func (s *Server) handleSetPeakImportCeiling(w http.ResponseWriter, r *http.Reque
s.deps.CtrlMu.Lock()
s.deps.Ctrl.PeakImportCeilingW = req.PeakImportCeilingW
s.deps.CtrlMu.Unlock()
// The plan spreads each hour's import under the ceiling; a new ceiling
// changes what the plan may deliver.
if s.deps.MPC != nil && req.PeakImportCeilingW != prevW {
s.deps.MPC.RequestReplan("import_ceiling_changed")
}
writeJSON(w, 200, map[string]any{"status": "ok", "peak_import_ceiling_w": req.PeakImportCeilingW})
}

Expand Down
19 changes: 19 additions & 0 deletions go/internal/api/api_peak_import_ceiling_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,22 @@ func TestPeakImportCeilingNotAppliedWhenTheSaveFails(t *testing.T) {
t.Fatalf("ceiling = %.0f W after a failed save, want 6,000", ctrl.PeakImportCeilingW)
}
}

// A new ceiling changes what the plan may deliver, so the plan follows it at
// once instead of at the next quarter.
func TestPeakImportCeilingChangeReplans(t *testing.T) {
_, _, svc := newScheduleServer(t)
st, err := state.Open(filepath.Join(t.TempDir(), "state.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = st.Close() })
srv := newCeilingServer(t, st, &control.State{})
srv.deps.MPC = svc

postCeiling(t, srv, "4500")
waitForSchedulePlan(t, svc)
if _, reason := svc.LastReplanInfo(); reason != "import_ceiling_changed" {
t.Fatalf("replan reason = %q, want import_ceiling_changed", reason)
}
}
27 changes: 27 additions & 0 deletions go/internal/control/import_hour.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"math"
"time"

"github.com/srcfl/ftw/go/internal/mpc"
"github.com/srcfl/ftw/go/internal/telemetry"
)

Expand Down Expand Up @@ -218,6 +219,32 @@ func (s *State) importRiseCeilingW(fuseMaxW float64) float64 {
return eff
}

// PlanningImportCeiling is the ceiling as the planner gets it, from the hour
// the live limit counts: the clock hour in progress and what it has used.
// Time with no record counts at the ceiling. Until a reading measures the
// hour against this ceiling, the rest of the hour may hold the ceiling, so
// the time before counts as used. A planned hour holds the ceiling less half
// a rise step: the car runs in whole steps and a rise keeps a step in hand,
// so a car under the ceiling ends each hour 0.4-0.6 kWh short of it. Planned
// at the ceiling the plan promised the car 8-15 % more than it got; at half
// a step less the car gets as much, within 1 % of the promise with the
// battery covering the house and 6 % without
// (TestSiteSimPlanUnderImportCeiling). Zero while the ceiling is off.
// Callers hold the control lock.
func PlanningImportCeiling(s *State) mpc.ImportCeiling {
if s == nil || !(s.PeakImportCeilingW > 0) {
return mpc.ImportCeiling{}
}
now, ceiling := s.now(), s.PeakImportCeilingW
start := s.importHourStart(now)
elapsedWh := ceiling * now.Sub(start).Hours()
if h := &s.importHour; s.importHourMeasured() {
elapsedWh = h.importedWh + ceiling*h.unknown.Hours()
}
step := evPhaseMarginA * s.SiteFuseVoltage * float64(s.SiteFusePhases)
return mpc.ImportCeiling{W: ceiling, MeanW: max(0, ceiling-step/2), HourStart: start, ElapsedWh: elapsedWh}
}

// ImportHourStatus is the clock hour's import budget left, negative once it
// is overrun, and the import limit in force. ok is false while the ceiling is
// off. Callers hold the control lock or a copy of State.
Expand Down
80 changes: 80 additions & 0 deletions go/internal/control/import_hour_planning_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package control

import (
"math"
"testing"
"time"

"github.com/srcfl/ftw/go/internal/mpc"
)

// The planner gets the clock hour Core's live limit counts and what it has
// used. On 25 October 2026 02:00 comes twice in Stockholm, and each of the
// two hours counts its own import.
func TestPlanningImportCeilingOnTheLongDay(t *testing.T) {
zone, err := time.LoadLocation("Europe/Stockholm")
if err != nil {
t.Fatal(err)
}
var now time.Time
st, store := newImportHourState(&now)
st.PeakImportCeilingW, st.importHourZone = 4500, zone
first := time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC) // 02:00 CEST
for _, hour := range []time.Time{first, first.Add(time.Hour)} {
for at := hour; !at.After(hour.Add(20 * time.Minute)); at = at.Add(2 * time.Second) {
feedMeter(st, store, &now, at, 3000)
}
got := PlanningImportCeiling(st)
if !got.HourStart.Equal(hour) || got.HourStart.In(zone).Hour() != 2 || got.W != 4500 {
t.Fatalf("at %s: hour from %s, ceiling %.0f W", now.In(zone).Format("15:04 MST"), got.HourStart.In(zone).Format("15:04 MST"), got.W)
}
if want := 3000 * 20 / 60.; math.Abs(got.ElapsedWh-want) > 1 {
t.Fatalf("at %s: %.1f Wh used, want %.1f Wh", now.In(zone).Format("15:04 MST"), got.ElapsedWh, want)
}
}
st.PeakImportCeilingW = 0
if got := PlanningImportCeiling(st); got != (mpc.ImportCeiling{}) {
t.Fatalf("ceiling off gave %+v", got)
}
}

// A planned hour holds the ceiling less half a rise step, the margin
// TestSiteSimPlanUnderImportCeiling measures.
func TestPlanningImportCeilingKeepsHalfARiseStep(t *testing.T) {
now := time.Date(2026, 10, 26, 9, 0, 0, 0, hourTestZone)
st, _ := newImportHourState(&now)
st.PeakImportCeilingW = 4500
// Half of 1 A on each of three 230 V phases.
if got := PlanningImportCeiling(st); got.MeanW != 4155 {
t.Fatalf("planned mean %.0f W, want 4155 W", got.MeanW)
}
st.PeakImportCeilingW = 300
if got := PlanningImportCeiling(st); got.W != 300 || got.MeanW != 0 {
t.Fatalf("a ceiling under half a step: %+v, want it on with no room", got)
}
}

// Before a reading measures the hour, as after a restart or a new ceiling,
// the live limit lets the rest of the hour hold the ceiling: the time before
// counts as used. A restart that seeds the hour from state.db counts what
// the record covers, and the time it misses at the ceiling.
func TestPlanningImportCeilingAfterARestart(t *testing.T) {
now := time.Date(2026, 10, 26, 9, 40, 0, 0, hourTestZone)
st, store := newImportHourState(&now)
st.PeakImportCeilingW = 4500
if got := PlanningImportCeiling(st); math.Abs(got.ElapsedWh-3000) > 1e-6 || got.HourStart.Minute() != 0 {
t.Fatalf("at boot: %.1f Wh used in the hour from %s; want 3000 Wh from 09:00", got.ElapsedWh, got.HourStart.Format("15:04"))
}
// state.db covered 30 of the 40 minutes with 1.2 kWh.
st.SeedHourImport(now, 1200, 30*time.Minute)
feedMeter(st, store, &now, now.Add(time.Second), 2000)
if got := PlanningImportCeiling(st); math.Abs(got.ElapsedWh-(1200+4500/6.+2000/3600.)) > 1 {
t.Fatalf("seeded: %.1f Wh used, want 1200 Wh plus 10 unseen minutes at the ceiling", got.ElapsedWh)
}
now = now.Add(10 * time.Minute)
feedMeter(st, store, &now, now, 2000)
st.PeakImportCeilingW = 3000 // set during the hour, not yet seen by a reading
if got := PlanningImportCeiling(st); math.Abs(got.ElapsedWh-2500) > 1 {
t.Fatalf("new ceiling: %.1f Wh used, want 50 minutes at 3 kW", got.ElapsedWh)
}
}
Loading
Loading