Skip to content
Open
24 changes: 24 additions & 0 deletions .changeset/heat-shadow-plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
"ftw": minor
---

Heat zones can now be planned. A new `heat` section names each zone's
sensor, control, boundary, heat output, target and hard band, and the owner's
own rules: price comfort, peak relief and a least saving per day for all
zones together. No number has a default. Core plans every quarter from the
thermal twins, the stored prices and the weather forecast, and shows the plan
and what it would save at `GET /api/heat/plan`. Nothing is written unless
`heat.write` is on; then a zone's setpoint is held through the same control
holds as an operator's request, only while its twin is trusted, the least
saving is reached and the site meter is fresh, and the device is handed back
to its own default otherwise. A device that drops a written value by itself is
written again before it does.

A zone can name its heat input (`heat_input: "<driver>/<metric>"`), so a room
sensor on one device, such as an underfloor gateway, learns against the heat
of another, such as a heat pump's estimated space heat. A sensor named in
`heat.zones` is learned even when its driver does not declare it.

A zone can be heated by a heat pump (`source: heat_pump`) with the owner's
efficiency and heat curve, and planned through a declared curve offset with
the owner's figures for what one unit does.
12 changes: 12 additions & 0 deletions .changeset/heatplan-owner-rules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"ftw": patch
---

The heat planner no longer stops and starts for a sliver of price: a change
of value must earn a share of what one slot at full output costs, so a price
that wobbles by a couple of percent gives 11 changes a day instead of 74 at
about 0.4 % higher planned cost. Two rules the owner sets are added to the
planner, both off at zero and with no default: a least saving a day's plans
must reach together before they are acted on, and a short price peak a zone
may sit through at the bottom of its band. Nothing calls them yet; the
planner still only proposes.
37 changes: 37 additions & 0 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,43 @@ fleet_ping:
# soc_min: 0.10
# soc_max: 0.95

# Heat control (docs/adr/0012). Every number is the owner's and none has a
# default. Without write: true the plan is shadow: GET /api/heat/plan shows
# it and what it would save, and nothing is written. Prices are the stored
# total price (öre/kWh); min_per_day is in öre for all zones together.
# heat:
# write: false
# savings: { min_per_day: 500, keep_share: 0.8 }
# zones:
# - name: bathroom_floor
# sensor: wiser_7/floor_temp_c # the twin that judges this zone
# control: wiser_7/set_setpoint # a declared setpoint control
# # heat_input: ctc/space_heat_w # when the heat comes from another device
# boundary: wiser_7/room_temp_c # or "outdoor"
# source: direct_electric
# heat_kw: 0.6
# target_c: 24.5
# min_c: 20
# max_c: 27
# comfort_weight: 2
# price_comfort: { cheap_price: 150, normal_price: 260, dear_price: 400, raise_k: 1, lower_k: 0 }
# peak_relief: { min_price: 200, factor: 3, window_h: 12, max_hours: 3 }
# # A house heated by a hydronic heat pump, its rooms read elsewhere.
# - name: house
# sensor: LK/zone_2_temp_c
# heat_input: CTC/space_heat_w # the pump's estimated space heat
# boundary: outdoor
# source: heat_pump
# heat_kw: 6
# target_c: 21
# min_c: 20
# max_c: 22.5
# heat_pump: # zero or absent: the planner's start point
# carnot_fraction: 0.5
# supply: { cold_outdoor_c: -20, cold_supply_c: 45, mild_outdoor_c: 15, mild_supply_c: 24 }
# # control: CTC/set_heat_curve_offset # once the driver declares one
# # curve_effect: { zone_k_per_unit: 0.5, supply_k_per_unit: 1 }

# Peak-power tariff (weekday 06–20 local time). Same minor units as
# grid_tariff_ore_kwh, per kW, excluding VAT. 0 disables it.
# price:
Expand Down
23 changes: 23 additions & 0 deletions docs/adr/0012-heat-control.md
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,29 @@ Fredrik answered on comfort that follows the day's price on 15 November 2026:
the day's mean against the owner's fixed levels. Whether a longer
reference, such as the month, serves better is open until it has run in
more than one house.
- **A least saving, as the owner's own number.** Decision 9 did not take
one, on the evidence that in the one house that ran it the plans saved
0.1–4.9 kr a day against a limit of 5 kr and the limit never opened. That
figure was one room's saving read against a limit that is the household's.
Summed over the three rooms, as the limit is, the same house's log reached
5 kr on 15 and 16 November and held it open for 84 % and 41 % of the
time. Part of that was a room model that overstated what a preheat saves;
with the model corrected the sum is 2–4 kr a day and the limit is mostly
closed, which is the effect decision 9 describes. The question left is what
the limit is for. Proposed: not a switch that turns the planner off, but the
owner's own answer to "what must a day's saving be worth to me before I
accept a change of comfort or a write to my devices". It is off at zero,
has no default, and the shadow run's saving per day is what the owner sets
it against. `heatplan.SavingsGate` carries the rule so the owner's number
has somewhere to go if the decision is revisited; nothing calls it yet.
- **Sitting out a short price peak.** The same house keeps a second rule of
its own: a slot is a peak when it costs at least 200 öre and three times
the lowest price of the next 12 hours, and a zone may sit at the bottom of
its band for at most 3 hours of one. On a dear but flat day nothing is a
peak and the rule does nothing, which is why it cannot replace the
planner. `heatplan.PeakRelief` carries it as the owner's numbers, with no
default, applied to a zone's target after `PriceComfort`; the band is not
moved.
- **Holding off a reheat needs a control.** Many heat pumps start a
hot-water charge by themselves at their own start temperature. The planner
can only delay a reheat on a device whose driver declares a control that
Expand Down
111 changes: 111 additions & 0 deletions go/cmd/ftw/heat_control.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package main

import (
"sync"
"time"

"github.com/srcfl/ftw/go/internal/config"
"github.com/srcfl/ftw/go/internal/drivers"
"github.com/srcfl/ftw/go/internal/heatrun"
"github.com/srcfl/ftw/go/internal/state"
)

// heatCatalog is the driver catalog as the heat control reads it. The
// reload path replaces it; the heat tick reads it from another goroutine.
type heatCatalog struct {
mu sync.Mutex
drivers []config.Driver
catalog []drivers.CatalogEntry
}

func (h *heatCatalog) set(cfgDrivers []config.Driver, catalog []drivers.CatalogEntry) {
h.mu.Lock()
defer h.mu.Unlock()
h.drivers = append([]config.Driver(nil), cfgDrivers...)
h.catalog = catalog
}

// control is the declared control behind a driver instance's name. A driver
// that is disabled, observe-only or unknown has none.
func (h *heatCatalog) control(driver, control string) (drivers.CatalogControl, bool) {
h.mu.Lock()
defer h.mu.Unlock()
for _, d := range h.drivers {
if d.Name != driver || d.Disabled || d.ObserveOnly {
continue
}
entry := drivers.EntryForDriver(h.catalog, d.Lua)
if entry == nil {
return drivers.CatalogControl{}, false
}
for _, c := range entry.Controls {
if c.ID == control {
return c, true
}
}
}
return drivers.CatalogControl{}, false
}

// heatPrices reads the stored total price, the one the owner's limits are
// written in.
func heatPrices(st *state.Store, zone func() string) func(from, to time.Time) []heatrun.Price {
return func(from, to time.Time) []heatrun.Price {
z := zone()
if st == nil || z == "" {
return nil
}
rows, err := st.LoadPrices(z, from.Add(-time.Hour).UnixMilli(), to.UnixMilli())
if err != nil {
return nil
}
out := make([]heatrun.Price, 0, len(rows))
for _, r := range rows {
if r.SlotLenMin <= 0 {
continue
}
out = append(out, heatrun.Price{
Start: time.UnixMilli(r.SlotTsMs),
Len: time.Duration(r.SlotLenMin) * time.Minute,
Value: r.TotalOreKwh,
})
}
return out
}
}

// heatOutdoor is the outdoor forecast for n quarters from start, from rows
// fetched within the last 12 hours, or false when any quarter is missing.
func heatOutdoor(st *state.Store, since func() int64) func(start time.Time, n int) ([]float64, bool) {
return func(start time.Time, n int) ([]float64, bool) {
if st == nil || n <= 0 {
return nil, false
}
end := start.Add(time.Duration(n) * 15 * time.Minute)
rows, err := st.LoadForecasts(start.Add(-2*time.Hour).UnixMilli(), end.UnixMilli())
if err != nil {
return nil, false
}
now := time.Now()
out := make([]float64, n)
for k := 0; k < n; k++ {
t := start.Add(time.Duration(k)*15*time.Minute + 7*time.Minute).UnixMilli()
found := false
for _, r := range rows {
slotLen := r.SlotLenMin
if slotLen <= 0 {
slotLen = 60
}
if t >= r.SlotTsMs && t < r.SlotTsMs+int64(slotLen)*60*1000 && r.TempC != nil &&
usableTrainingWeather(r, now) && r.FetchedAtMs >= since() {
out[k], found = *r.TempC, true
break
}
}
if !found {
return nil, false
}
}
return out, true
}
}
82 changes: 82 additions & 0 deletions go/cmd/ftw/heat_holds_wiring_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package main

import (
"go/ast"
"go/parser"
"go/token"
"testing"
)

// The heat control and the API must hold devices through one
// drivercontrol.Holds. If main handed the API none, the API would build its
// own, and an operator's hold and a planned value would sit on two locks:
// each would think the driver free and could expire into a default that
// undoes the other. main.go is read rather than run because building the
// whole process here would test everything but this.
func TestMainHandsTheHeatControlAndTheAPIOneSetOfHolds(t *testing.T) {
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, "main.go", nil, 0)
if err != nil {
t.Fatal(err)
}

var made []string // identifiers assigned from drivercontrol.New
heatHolds, apiHolds := "", ""
ast.Inspect(file, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.AssignStmt:
for i, rhs := range n.Rhs {
call, ok := rhs.(*ast.CallExpr)
if !ok || !isSelector(call.Fun, "drivercontrol", "New") || i >= len(n.Lhs) {
continue
}
if id, ok := n.Lhs[i].(*ast.Ident); ok {
made = append(made, id.Name)
}
}
case *ast.CompositeLit:
switch {
case isSelector(n.Type, "heatrun", "HoldsWriter"):
heatHolds = fieldIdent(n, "Holds")
case isSelector(n.Type, "api", "Deps"):
apiHolds = fieldIdent(n, "ControlHolds")
}
}
return true
})

if len(made) != 1 {
t.Fatalf("main.go makes %d sets of control holds (%v), want 1", len(made), made)
}
if heatHolds != made[0] {
t.Errorf("heatrun.HoldsWriter{Holds: %q}, want %q", heatHolds, made[0])
}
if apiHolds != made[0] {
t.Errorf("api.Deps{ControlHolds: %q}, want %q; without it the API builds its own", apiHolds, made[0])
}
}

func isSelector(e ast.Expr, pkg, name string) bool {
sel, ok := e.(*ast.SelectorExpr)
if !ok || sel.Sel.Name != name {
return false
}
id, ok := sel.X.(*ast.Ident)
return ok && id.Name == pkg
}

// fieldIdent is the identifier a keyed composite literal sets field to, or "".
func fieldIdent(lit *ast.CompositeLit, field string) string {
for _, elt := range lit.Elts {
kv, ok := elt.(*ast.KeyValueExpr)
if !ok {
continue
}
if key, ok := kv.Key.(*ast.Ident); ok && key.Name == field {
if v, ok := kv.Value.(*ast.Ident); ok {
return v.Name
}
}
}
return ""
}
Loading
Loading