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/app-history-measured-power.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"ftw": patch
---

The app's history for solar, grid and battery now shows the measured power, the same as the box's own charts. Before, it came from the energy counters, which on a Sungrow move in 0.1 kWh steps, so each five minutes read 0 or 1.2 kW while the sun gave 0.4 kW. Home use is unchanged. Five minutes in which a flow went unmeasured for more than half the time is now a gap for that flow, not a lower value.
123 changes: 123 additions & 0 deletions go/cmd/ftw/app_history_power_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package main

import (
"context"
"math"
"path/filepath"
"testing"
"time"

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

// The app's tiles draw what was measured. A Sungrow's energy counters move in
// 0.1 kWh steps, so a ledger bucket read 0 or 1.2 kW while the sun shone at
// 0.4 kW (Fredrik's box, 25 October 2026). Grid, PV and battery now come from
// the power rows /api/history draws; a flow that fell silent is a hole there,
// never a mean of the rows that were left.
func TestAppHistoryDrawsMeasuredPower(t *testing.T) {
st, err := state.Open(filepath.Join(t.TempDir(), "state.db"))
if err != nil {
t.Fatal(err)
}
defer st.Close()
if err := st.EnableHistoryAggregation(); err != nil {
t.Fatal(err)
}
tel := telemetry.NewStore()
tel.Update("grid", telemetry.DerMeter, 300, nil, nil)
tel.RecordDriverSuccess("grid")
tel.Update("sungrow", telemetry.DerPV, -400, nil, nil)
tel.Update("sungrow", telemetry.DerBattery, 500, nil, nil)
tel.RecordDriverSuccess("sungrow")
const step = int64(300_000)
base := time.Now().Add(-20 * time.Minute).Truncate(5 * time.Minute).UnixMilli()
for i := int64(0); i < 60; i++ {
// The inverter falls silent six minutes in.
if i == 36 {
tel.Get("sungrow", telemetry.DerPV).UpdatedAt = time.Now().Add(-10 * time.Minute)
}
p, _ := buildHistoryPoint(tel, tickPersistControl{SiteMeterDriver: "grid"}, base+i*10_000, 90*time.Second)
p.Sources.AtMS = base + i*10_000
if err := st.RecordTickWithEnergy(p, nil, nil); err != nil {
t.Fatal(err)
}
}
if err := st.FlushHistory(context.Background()); err != nil {
t.Fatal(err)
}
got, err := (&appHistory{st: st}).Window(context.Background(), []string{"pv_w", "grid_w", "battery_w"}, step, base, base+2*step)
if err != nil {
t.Fatal(err)
}
pv := map[int64]float64{}
for _, s := range got["pv_w"] {
pv[s.StartMs] = s.W
}
grid := map[int64]float64{}
for _, s := range got["grid_w"] {
grid[s.StartMs] = s.W
}
if w, ok := pv[base]; !ok || math.Abs(w+400) > 0.5 {
t.Fatalf("first five minutes: pv %v (present %v), want -400 W measured", w, ok)
}
if w, ok := pv[base+step]; ok {
t.Fatalf("a silent inverter's five minutes read %v W, want a hole", w)
}
for _, at := range []int64{base, base + step} {
if w, ok := grid[at]; !ok || math.Abs(w-300) > 0.5 {
t.Fatalf("grid at %d: %v (present %v), want 300 W", at, w, ok)
}
}
// Charging is power into the site: positive, as the ledger had it.
battery := map[int64]float64{}
for _, s := range got["battery_w"] {
battery[s.StartMs] = s.W
}
if w, ok := battery[base]; !ok || math.Abs(w-500) > 0.5 {
t.Fatalf("battery: %v (present %v), want +500 W charging in the first five minutes", w, ok)
}
}

// One stale reading in five minutes is not a hole: the mean is over the
// readings that measured the sun, as long as they cover 90 % of them.
func TestAppHistoryKeepsAFiveMinutesWithOneMissedReading(t *testing.T) {
st, err := state.Open(filepath.Join(t.TempDir(), "state.db"))
if err != nil {
t.Fatal(err)
}
defer st.Close()
if err := st.EnableHistoryAggregation(); err != nil {
t.Fatal(err)
}
tel := telemetry.NewStore()
tel.Update("grid", telemetry.DerMeter, 300, nil, nil)
tel.RecordDriverSuccess("grid")
tel.Update("sungrow", telemetry.DerPV, -400, nil, nil)
tel.RecordDriverSuccess("sungrow")
const step = int64(300_000)
base := time.Now().Add(-20 * time.Minute).Truncate(5 * time.Minute).UnixMilli()
for i := int64(0); i < 30; i++ {
pv := tel.Get("sungrow", telemetry.DerPV)
pv.UpdatedAt = time.Now()
if i == 12 {
pv.UpdatedAt = time.Now().Add(-10 * time.Minute)
}
p, _ := buildHistoryPoint(tel, tickPersistControl{SiteMeterDriver: "grid"}, base+i*10_000, 90*time.Second)
p.Sources.AtMS = base + i*10_000
if err := st.RecordTickWithEnergy(p, nil, nil); err != nil {
t.Fatal(err)
}
}
if err := st.FlushHistory(context.Background()); err != nil {
t.Fatal(err)
}
got, err := (&appHistory{st: st}).Window(context.Background(), []string{"pv_w"}, step, base, base+step)
if err != nil {
t.Fatal(err)
}
if pv := got["pv_w"]; len(pv) != 1 || math.Abs(pv[0].W+400) > 0.5 {
t.Fatalf("pv: %+v, want -400 W over the readings that measured it", pv)
}
}
76 changes: 56 additions & 20 deletions go/cmd/ftw/app_link.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,12 +285,14 @@ func (a *appModes) ObservedMode() (control.Mode, bool) {
return a.ctrl.Mode, true
}

// appHistory serves the app's history tiles from the energy ledger.
// appHistory serves the app's history tiles: mean power per bucket, signed
// as the site convention says (positive watts flow into the site).
//
// The ledger stores energy per flow per bucket; the wire wants mean power per
// signed series. The mapping below is the site convention and nothing else:
// positive watts flow into the site, so import minus export is the grid, and
// PV is generation negated. W = Wh × 3 600 000 / bucket, no other arithmetic.
// Grid, PV and battery are the measured power rows /api/history draws,
// averaged over each bucket. Their energy counters may move in 0.1 kWh steps
// (Sungrow), so a ledger bucket held 0 or 1.2 kW while the sun shone at
// 0.4 kW. Load is the ledger's consumer use, which the source accounting
// already balances from power: W = Wh × 3 600 000 / bucket.
type appHistory struct {
st *state.Store
}
Expand All @@ -303,31 +305,65 @@ func (a *appHistory) Window(
sign float64
}
termsByName := map[string][]term{
"grid_w": {{state.FlowGridImport, 1}, {state.FlowGridExport, -1}},
"pv_w": {{state.FlowPVGeneration, -1}},
"battery_w": {{state.FlowBatteryCharge, 1}, {state.FlowBatteryDischarge, -1}},
"load_w": {{state.FlowConsumerUse, 1}},
}

points, _, err := a.st.LoadEnergyHistoryContext(ctx, state.EnergyHistoryQuery{
SinceMS: fromMs,
UntilMS: toMs,
BucketMS: stepMs,
// One tile is at most 168 buckets; the ledger's own cap is 2000.
Limit: 2000,
})
if err != nil {
return nil, err
"load_w": {{state.FlowConsumerUse, 1}},
}
type measured struct {
missing state.HistoryMissing
w func(state.PowerBucket) float64
}
powerByName := map[string]measured{
"grid_w": {state.MissingGrid, func(b state.PowerBucket) float64 { return b.GridW }},
"pv_w": {state.MissingPV, func(b state.PowerBucket) float64 { return b.PVW }},
"battery_w": {state.MissingBattery, func(b state.PowerBucket) float64 { return b.BatW }},
}

wantLedger := false
for _, name := range names {
wantLedger = wantLedger || termsByName[name] != nil
}
var points []state.EnergyLedgerPoint
var err error
if wantLedger {
points, _, err = a.st.LoadEnergyHistoryContext(ctx, state.EnergyHistoryQuery{
SinceMS: fromMs,
UntilMS: toMs,
BucketMS: stepMs,
// One tile is at most 168 buckets; the ledger's own cap is 2000.
Limit: 2000,
})
if err != nil {
return nil, err
}
}

// A bucket exists on the wire only if some term reported it. A bucket
// where nothing was metered stays absent and becomes MISSING, which is
// the honest answer — zero would claim the house used no power at all.
byName := make(map[string]map[int64]float64, len(names))
wantPower := false
for _, name := range names {
if termsByName[name] != nil {
byName[name] = map[int64]float64{}
}
if _, ok := powerByName[name]; ok {
byName[name] = map[int64]float64{}
wantPower = true
}
}
if wantPower {
buckets, err := a.st.LoadPowerBuckets(ctx, fromMs, toMs, stepMs)
if err != nil {
return nil, err
}
for _, b := range buckets {
for _, name := range names {
// A flow some row did not measure has no mean here: the
// rows that did would read as the whole bucket.
if m, ok := powerByName[name]; ok && b.Missing&m.missing == 0 {
byName[name][b.StartMS] = m.w(b)
}
}
}
}
for _, p := range points {
for _, name := range names {
Expand Down
6 changes: 3 additions & 3 deletions go/cmd/ftw/cloud_link.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ type cloudSite struct {
// With it, the link sends the car class, and a charger's level and
// goal fields are views of its session's car.
cars *cars.Runtime
// history is the energy ledger, read as the app's history over Noise
// reads it, so a closed tile is the same bytes either way.
// history is the app's history, read as the app over Noise reads it,
// so a closed tile is the same bytes either way.
history *appHistory

sessMu sync.Mutex
Expand All @@ -71,7 +71,7 @@ var _ cloudlink.HistorySite = (*cloudSite)(nil)
// HistoryWindow serves the tiles class.
func (c *cloudSite) HistoryWindow(ctx context.Context, names []string, stepMs, fromMs, toMs int64) (map[string][]protocol.HistorySample, error) {
if c.history == nil {
return nil, errors.New("no energy ledger")
return nil, errors.New("no history")
}
return c.history.Window(ctx, names, stepMs, fromMs, toMs)
}
Expand Down
9 changes: 5 additions & 4 deletions go/internal/appproto/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ import (
// in package protocol, because FTW Cloud must compute the same tiles. This
// file plans which tiles answer a query and reads them from the store.
//
// Power series are derived from the energy ledger: a bucket's mean power is
// its energy divided by its width. That is an average, and it is presented as
// one — the chunk carries its step, and the app labels it. Sub-bucket wiggles
// are gone, which is the correct price for history that survives a restart.
// A series holds a bucket's mean power: measured power for grid, PV and
// battery, the energy ledger's consumer use for load (see appHistory in
// cmd/ftw). That is an average, and it is presented as one — the chunk
// carries its step, and the app labels it. Sub-bucket wiggles are gone,
// which is the correct price for history that survives a restart.

// HistoryProvider answers windows of stored series.
//
Expand Down
97 changes: 97 additions & 0 deletions go/internal/state/history_power_buckets.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package state

import (
"context"
"database/sql"
"errors"
"strconv"
"strings"
"time"
)

// PowerBucket is the measured mean power over one fixed bucket, site-signed,
// from the same stored rows /api/history draws. Each flow's mean is over the
// rows that measured it. Missing marks a flow left unmeasured in more than
// maxPowerBucketUnknownShare of the bucket's rows, or in all of them: its
// mean is not a value then.
type PowerBucket struct {
StartMS int64
GridW float64
PVW float64
BatW float64
Missing HistoryMissing
}

// LoadPowerBuckets returns the mean measured power in each bucketMs bucket of
// [fromMs, toMs), the buckets laid from fromMs. A bucket with no stored row is
// absent. Unlike an energy counter, which may move in 0.1 kWh steps, the
// power rows give each bucket its own shape. Load is not here: it comes from
// the source accounting, which the energy ledger keeps.
func (s *Store) LoadPowerBuckets(ctx context.Context, fromMs, toMs, bucketMs int64) ([]PowerBucket, error) {
if bucketMs <= 0 || toMs <= fromMs {
return nil, errors.New("power buckets need a positive width and range")
}
if (toMs-fromMs+bucketMs-1)/bucketMs > maxSeriesBuckets {
return nil, ErrHistoryQueryLimit
}
if s.history == nil {
return nil, nil
}
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Per flow: the mean over the rows that measured it, and how many rows
// did not.
flow := func(column string, bit HistoryMissing) string {
b := strconv.Itoa(int(bit))
return `SUM(CASE WHEN missing&` + b + `=0 THEN COALESCE(` + column + `,0)*n END)/SUM(CASE WHEN missing&` + b + `=0 THEN n END),
SUM(CASE WHEN missing&` + b + `<>0 THEN n ELSE 0 END)`
}
rows, err := s.history.QueryContext(ctx, halfOpenHistoryRange(historyTierUnion)+`
SELECT (ts_ms - ?) / ? AS bucket, SUM(n),
`+flow("grid_w", MissingGrid)+`,
`+flow("pv_w", MissingPV)+`,
`+flow("bat_w", MissingBattery)+`
FROM deduped GROUP BY bucket ORDER BY bucket`,
fromMs, toMs, fromMs, toMs, fromMs, toMs, fromMs, toMs, fromMs, toMs, fromMs, bucketMs)
if err != nil {
return nil, err
}
defer rows.Close()
var out []PowerBucket
for rows.Next() {
var b PowerBucket
var index, total int64
var grid, pv, bat sql.NullFloat64
var gridOff, pvOff, batOff int64
if err := rows.Scan(&index, &total, &grid, &gridOff, &pv, &pvOff, &bat, &batOff); err != nil {
return nil, err
}
b.StartMS = fromMs + index*bucketMs
take := func(mean sql.NullFloat64, off int64, bit HistoryMissing) float64 {
if !mean.Valid || off*100 > total*maxPowerBucketUnknownShare {
b.Missing |= bit
return 0
}
return mean.Float64
}
b.GridW = take(grid, gridOff, MissingGrid)
b.PVW = take(pv, pvOff, MissingPV)
b.BatW = take(bat, batOff, MissingBattery)
out = append(out, b)
}
return out, rows.Err()
}

// maxPowerBucketUnknownShare is the share of a bucket's rows, by weight, a
// flow may miss and still have a mean. Rows roll up after a day into minutes
// that carry any tick's flag, so one stale reading in five minutes grows
// from 3 % of the rows to 20 %. A majority rule keeps a closed bucket the
// same before and after; a tenth would turn it into a hole a day later.
const maxPowerBucketUnknownShare = 50 // percent

// halfOpenHistoryRange turns historyTierUnion's closed ranges into [from, to),
// so a row on a bucket boundary belongs to one bucket only.
func halfOpenHistoryRange(union string) string {
union = strings.ReplaceAll(union, "ts_ms BETWEEN ? AND ?", "ts_ms >= ? AND ts_ms < ?")
return strings.ReplaceAll(union, "last_ms BETWEEN ? AND ?", "last_ms >= ? AND last_ms < ?")
}
Loading
Loading