Repository navigation
feat(cloud): report installations, configured capacity and hourly energy #1693
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b05efd4
feat(cloud): add separately consented hourly project statistics
frahlg 34e234b
Merge remote-tracking branch 'origin/master' into feat/usage-energy-s…
frahlg 2757af6
feat(stats): wait for the service to approve the consent policy
frahlg fdd0196
docs(cloud): keep collection off until C8 review
frahlg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| "ftw": minor | ||
| --- | ||
|
|
||
| Add a separate, versioned Cloud statistics path for reporting installations, | ||
| configured capacity and recorded hourly energy. Older consents stay inactive | ||
| for these fields; the owner must accept the new policy. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "context" | ||
| "math" | ||
| "net/http" | ||
| "time" | ||
|
|
||
| "github.com/srcfl/ftw/go/internal/state" | ||
| "github.com/srcfl/ftw/go/protocol/cloudwire" | ||
| ) | ||
|
|
||
| // CloudStatistics contains only the fields named by the separate statistics | ||
| // consent. Configuration and ledger ids never cross this boundary. | ||
| func (s *Server) CloudStatistics(ctx context.Context, now time.Time) (cloudwire.Stats, bool) { | ||
| hour := now.UTC().Truncate(time.Hour).Add(-time.Hour) | ||
| out := cloudwire.Stats{HourMS: hour.UnixMilli(), Metrics: map[string]int64{}} | ||
| if s.deps == nil || s.deps.Cfg == nil || s.deps.CfgMu == nil { | ||
| return out, false | ||
| } | ||
| s.deps.CfgMu.RLock() | ||
| cfg := s.deps.Cfg | ||
| // A partner-controlled site's contract must allow statistics first. | ||
| if cfg.Nova != nil && cfg.Nova.Enabled { | ||
| s.deps.CfgMu.RUnlock() | ||
| return out, false | ||
| } | ||
| put := func(key string, value float64) { | ||
| if !math.IsNaN(value) && !math.IsInf(value, 0) && value >= 0 && value <= 1_000_000 { | ||
| out.Metrics[key] = int64(math.Round(value/10)) * 10 | ||
| } | ||
| } | ||
| batteryWh, flexibleW, powerKnown := 0.0, 0.0, true | ||
| groups := map[string]float64{} | ||
| drivers := map[string]bool{} | ||
| for _, d := range cfg.Drivers { | ||
| if d.Disabled { | ||
| continue | ||
| } | ||
| drivers[d.Name] = !d.ObserveOnly && !d.BatteryTelemetryOnly | ||
| if d.BatteryCapacityWh > 0 { | ||
| batteryWh += d.BatteryCapacityWh | ||
| if !drivers[d.Name] { | ||
| continue | ||
| } | ||
| cap := math.Max(d.MaxChargeW, d.MaxDischargeW) | ||
| if cap <= 0 || math.IsNaN(cap) || math.IsInf(cap, 0) { | ||
| powerKnown = false | ||
| continue | ||
| } | ||
| group := d.InverterGroup | ||
| if group == "" { | ||
| group = d.Name | ||
| } | ||
| groups[group] = math.Max(groups[group], cap) | ||
| } | ||
| } | ||
| for _, cap := range groups { | ||
| flexibleW += cap | ||
| } | ||
| chargers := map[string]float64{} | ||
| for _, lp := range cfg.Loadpoints { | ||
| if !drivers[lp.DriverName] { | ||
| continue | ||
| } | ||
| if lp.MaxChargeW <= 0 || math.IsNaN(lp.MaxChargeW) || math.IsInf(lp.MaxChargeW, 0) { | ||
| powerKnown = false | ||
| continue | ||
| } | ||
| chargers[lp.DriverName] = math.Max(chargers[lp.DriverName], lp.MaxChargeW) | ||
| } | ||
| for _, cap := range chargers { | ||
| flexibleW += cap | ||
| } | ||
| put("battery_capacity_wh", batteryWh) | ||
| if powerKnown { | ||
| put("flexible_power_w", flexibleW) | ||
| } | ||
| if cfg.Weather != nil { | ||
| rated := cfg.Weather.PVRatedW | ||
| if len(cfg.Weather.PVArrays) > 0 { | ||
| rated = 0 | ||
| for _, array := range cfg.Weather.PVArrays { | ||
| rated += array.RatedWatts() | ||
| } | ||
| } | ||
| if rated > 0 { | ||
| put("pv_rated_w", rated) | ||
| } | ||
| } | ||
| s.deps.CfgMu.RUnlock() | ||
| if s.deps.State == nil { | ||
| return out, true | ||
| } | ||
| points, truncated, err := s.deps.State.LoadEnergyHistoryContext(ctx, state.EnergyHistoryQuery{ | ||
| SinceMS: hour.UnixMilli(), UntilMS: hour.Add(time.Hour).UnixMilli(), BucketMS: cloudwire.StatsHourMS, Limit: 1, | ||
| }) | ||
| if err != nil || truncated { | ||
| return out, true | ||
| } | ||
| totals := map[string]float64{} | ||
| for _, point := range points { | ||
| if point.BucketStartMS != hour.UnixMilli() || point.BucketLenMS != cloudwire.StatsHourMS || | ||
| (point.Quality != "measured" && point.Quality != "estimated" && point.Quality != "recovered") { | ||
| continue | ||
| } | ||
| key := string(point.Flow) + "_wh" | ||
| for _, allowed := range cloudwire.StatsMetricKeys { | ||
| if key == allowed { | ||
| if point.EnergyWh >= 0 && !math.IsNaN(point.EnergyWh) && !math.IsInf(point.EnergyWh, 0) { | ||
| totals[key] += point.EnergyWh | ||
| } | ||
| } | ||
| } | ||
| } | ||
| for key, value := range totals { | ||
| put(key, value) | ||
| } | ||
| return out, true | ||
| } | ||
|
|
||
| // The owner reads this before POST /api/cloud/stats with this policy id. | ||
| func (s *Server) handleCloudStatsPolicy(w http.ResponseWriter, r *http.Request) { | ||
| if !s.cloudGate(w, r, false) { | ||
| return | ||
| } | ||
| available := s.deps != nil && s.deps.Cloud != nil && s.deps.Cloud.Status().StatisticsReady | ||
| writeJSON(w, http.StatusOK, map[string]any{ | ||
| "available": available, | ||
| "policy": cloudwire.StatsPolicy, | ||
| "purpose": "Publish group totals for FTW use and energy; improve planning. No ads or household decisions.", | ||
| "fields": cloudwire.StatsMetricKeys, | ||
| "meaning": "One opted-in installation, configured flexible power and solar ratings, battery capacity, and recorded closed-hour energy. Configured limits do not prove physical control. Missing readings are unknown.", | ||
| "resolution": "Closed UTC hours, energy rounded to 10 Wh, capacities and limits rounded to 10 Wh or W. No names, addresses, device ids or location.", | ||
| "retention": "13 months. Switching statistics off deletes unpublished household rows; published group totals remain.", | ||
| "publication_minimum_homes": cloudwire.StatsMinimumHomes, | ||
| "publication_max_home_share": 0.3, | ||
| "controller": "sourceful", "default": "off", "optional": true, | ||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "context" | ||
| "github.com/srcfl/ftw/go/internal/config" | ||
| "github.com/srcfl/ftw/go/internal/state" | ||
| "path/filepath" | ||
| "sync" | ||
| "testing" | ||
| "time" | ||
| ) | ||
|
|
||
| func TestCloudStatisticsConfiguredLimitsReadOnlyUnknownAndPartner(t *testing.T) { | ||
| cfg := &config.Config{Drivers: []config.Driver{ | ||
| {Name: "bat1", BatteryCapacityWh: 10000, MaxChargeW: 3000, MaxDischargeW: 5000, InverterGroup: "shared"}, | ||
| {Name: "bat2", BatteryCapacityWh: 5000, MaxChargeW: 4000, InverterGroup: "shared"}, | ||
| {Name: "observed", BatteryCapacityWh: 20000, MaxChargeW: 10000, ObserveOnly: true}, | ||
| {Name: "disabled", BatteryCapacityWh: 99999, Disabled: true}, {Name: "ev"}, | ||
| }, Loadpoints: []config.Loadpoint{{DriverName: "ev", MaxChargeW: 11000}, {DriverName: "ev", MaxChargeW: 7000}}, Weather: &config.Weather{PVRatedW: 12345}} | ||
| s := &Server{deps: &Deps{Cfg: cfg, CfgMu: &sync.RWMutex{}}} | ||
| report, ok := s.CloudStatistics(context.Background(), time.Now()) | ||
| if !ok { | ||
| t.Fatal("no report") | ||
| } | ||
| if report.Metrics["battery_capacity_wh"] != 35000 || report.Metrics["flexible_power_w"] != 16000 || report.Metrics["pv_rated_w"] != 12350 { | ||
| t.Fatalf("wrong totals %+v", report.Metrics) | ||
| } | ||
| if _, ok := report.Metrics["pv_generation_wh"]; ok { | ||
| t.Fatal("missing energy became zero") | ||
| } | ||
| cfg.Drivers[0].MaxChargeW = 0 | ||
| cfg.Drivers[0].MaxDischargeW = 0 | ||
| report, _ = s.CloudStatistics(context.Background(), time.Now()) | ||
| if _, ok := report.Metrics["flexible_power_w"]; ok { | ||
| t.Fatal("unknown limit invented") | ||
| } | ||
| cfg.Nova = &config.Nova{Enabled: true} | ||
| if _, ok := s.CloudStatistics(context.Background(), time.Now()); ok { | ||
| t.Fatal("partner site sent statistics") | ||
| } | ||
| } | ||
|
|
||
| func TestCloudStatisticsReadsClosedLedgerHourAndRoundsEnergy(t *testing.T) { | ||
| st, err := state.Open(filepath.Join(t.TempDir(), "state.db")) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| defer st.Close() | ||
| now := time.Date(2026, 10, 17, 12, 30, 0, 0, time.UTC) | ||
| base := now.Truncate(time.Hour).Add(-time.Hour) | ||
| for i, value := range []float64{1000, 1123} { | ||
| at := base.Add(time.Duration(i+1) * time.Minute).UnixMilli() | ||
| err := st.RecordTickWithEnergy(state.HistoryPoint{TsMs: at, JSON: "{}"}, nil, []state.EnergyObservation{{AssetID: "private-hardware", DeviceID: "private-serial", AssetKind: state.AssetGridMeter, Flow: state.FlowGridImport, AtMs: at, CounterWh: &value}}) | ||
| if err != nil { | ||
| t.Fatal(err) | ||
| } | ||
| } | ||
| s := &Server{deps: &Deps{Cfg: &config.Config{}, CfgMu: &sync.RWMutex{}, State: st}} | ||
| report, ok := s.CloudStatistics(context.Background(), now) | ||
| if !ok || report.Metrics["grid_import_wh"] != 120 { | ||
| t.Fatalf("ledger energy %+v", report) | ||
| } | ||
| if _, ok := report.Metrics["pv_generation_wh"]; ok { | ||
| t.Fatal("unknown solar became zero") | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When an EV or vehicle driver carries the legacy
battery_capacity_whsetting, this loop adds the vehicle's capacity tobattery_capacity_whstatistics. The existingdriverCapacitiesFromlogic ingo/cmd/ftw/main.go:3482-3494explicitly excludes drivers referenced by loadpoints and drivers whose catalog capability isevorvehicle, because that value is vehicle capacity rather than installed site-battery capacity. Without equivalent filtering here, affected installations permanently publish inflated battery-capacity results under their consented statistics ID.Useful? React with 👍 / 👎.