diff --git a/changelog/highlights/295.json b/changelog/highlights/295.json new file mode 100644 index 00000000..5cf482b8 --- /dev/null +++ b/changelog/highlights/295.json @@ -0,0 +1,8 @@ +{ + "de": { + "*": "Automationsvorschläge für Überschuss und Lastverschiebung werden an deinen Daten geprüft" + }, + "en": { + "*": "Automation suggestions for surplus and load shifts are checked against your data" + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index b9c827e9..d0d66c47 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.11.22-pre.32 (2026-11-06) +## v0.11.22-pre.33 (2026-11-06) ### Features @@ -32,6 +32,37 @@ - **automations:** Learning knows device cycles, the PV reserve and the remaining surplus of the day (#289) (5d86b6b) - **monitoring:** A Monitoring tab with notices, acknowledgement and all learned values (#291) (7ae50a9) - **autolearn:** The rule check finds feedback, competition for the surplus, a rising base load and battery problems (#292) (142387b) +- **autolearn:** The node records minute values and keeps every regulator step as a base for learning (#293) (19e65e7) +- **autolearn:** parse the learned_value condition (da541e8) +- **automations:** edit the learned_value condition (672ca29) +- **automations:** edit the learned_value fields in the rule card (ae0c8e1) +- **autolearn:** replay energy rules minute by minute in a closed loop (20ece0f) +- **learnrec:** add the replay threshold steps to the limits (e733d17) +- **autolearn:** build replay days from minutes or stretched quarters (f76647f) +- **autolearn:** wire the minute reader into the learning input and borrow minute shape (3d1e2a4) +- **autolearn:** check energy suggestions by replay before showing them (488eacd) +- **automations:** add the shift start and battery full templates (2d4a899) +- **autolearn:** suggest switching loads into the typical surplus window (860a4e5) +- **autolearn:** register the surplus window detector (47ad596) +- **autolearn:** rate surplus thresholds by replaying them (a78819a) +- **autolearn:** register the threshold rating (a39d13e) +- **autolearn:** suggest moving cycles from grid into surplus (af6f920) +- **autolearn:** register the load shift detector (a1b6eca) +- **autolearn:** offer loads after the battery is full (cbe1805) +- **autolearn:** give the learning input the steps and the regulator tuning (b2fba9d) +- **autolearn:** tune the zero feed-in regulator from its own steps (d434abd) +- **autolearn:** register the regulator quality check (4091025) +- **autolearn:** give the rule checker the replay input (5b25c1b) +- **autolearn:** use minute noise and the condition signal in the rule checks (0215f5e) +- **autolearn:** word the cooldown fix and the signal feature (96b1a20) +- **autolearn:** seed energy suggestions in the demo (99970b7) +- **autolearn:** seed a pendulating regulator in the demo (06cd9e3) +- **autolearn:** seed a surplus window for the demo dryer (3f47e5a) +- **autolearn:** seed a load shift for the demo dishwasher (e7f86ce) +- **automations:** build the shift start as one scenario (4b75e8f) +- **automations:** show findings on scenario cards (054b01a) +- **automations:** ease the target curve and the scale bars into the evidence (0134794) +- **autolearn:** Automation suggestions for surplus and load shifts are checked against your data (#295) - **learnrec:** resolve where the minute recording lives (972c4aa) - **learnrec:** add the binary day format of the minute recording (f0e0eec) - **learnrec:** keep minute values in RAM and append them to the chosen drive (64aff34) @@ -43,7 +74,6 @@ - **settings:** add the texts for the minute recording card (81d9b09) - **settings:** choose where minute values are kept (d6e14c7) - **autolearn:** seed minute values and regulator steps in the demo (956b559) -- **autolearn:** The node records minute values and keeps every regulator step as a base for learning (#293) - **autolearn:** let a fix change several rules and estimate signal noise (80c444e) - **autolearn:** flag rules whose own load flips their condition (67cbc32) - **autolearn:** name feedback as the cause of flapping rules (f6ea384) @@ -299,10 +329,29 @@ - **storage:** offer sticks with several partitions as a group and format single partitions (#243) (c4e6d33) - **storage:** wipe old file system signatures before formatting a stick (#245) (aeafa63) - **storage:** set up, back up and replug the additional drive reliably (#247) (b668394) +- **autolearn:** harden the replay against unsupported fields and absent keys (f762aae) +- **automations:** prefill the surplus templates from a suggestion (d977098) +- **automations:** prefill the shift start template from a suggestion (d1b835a) +- **automations:** prefill the battery full template from a suggestion (747fa07) +- **autolearn:** cache the replay input and keep scenario findings visible (f0ec18a) +- **automations:** apply a regulator fix to the scenario draft (d6df277) +- **autolearn:** show one scale bar per regulator parameter and drop the unsafe entity (1b7c79a) +- **demo:** keep the pendulating regulator off the live output topic (f5e993c) +- **automations:** style the parameter name above each regulator scale bar (e98a332) +- **demo:** feed the demo regulator its own load profile (78ec0a9) +- **autolearn:** give the surplus window its curve and target block (4b1c051) +- **automations:** load the shift suggestion for the dishwasher into the assistant (a716e0d) +- **automations:** show the shift start time as a clock in the suggestion (56b157e) +- **monitoring:** list the regulator quality finding with its facts (8c50b41) +- **automations:** show the replayed triggers instead of the burst span in the frequent evidence (0010fc8) +- **automations:** draw the replayed triggers of the events evidence (3c44aa1) +- **autolearn:** read the regulator steps from the files after a start (0edcbe0) +- **automations:** open the scenario finding with its own key (5116883) +- **automations:** keep the target bar at its own opacity after the entrance (2bb3b06) +- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **autolearn:** write step files per scenario and day, drop deadband from figures (8f2a75a) - **dashboard:** bound the step ring by the RAM days and log slow flushes (0046eee) - **settings:** format the drive free space in GB (2c55808) -- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **autolearn:** drop findings whose fix is saved and show an early full battery in Monitoring (cb2d65b) - **automations:** keep learned findings while a fix sits in the draft (715cbfd) - **automations:** preselect the switch of night off and quiet off suggestions (e3a0952) @@ -411,6 +460,7 @@ ### Documentation +- **automations:** describe replay based energy suggestions (fa34bb8) - **monitoring:** document the monitoring page and add the smoke check (9802fe9) - **storage:** describe the system disk breakdown (b2222d8) - **storage:** explain sticks with several partitions and extend the smoke check (7e75f7a) @@ -438,6 +488,8 @@ ### Chores +- **dashboard:** bump the cache-bust marks for energy suggestions (5e08c00) +- **dashboard:** bump the cache-bust marks for the evidence animation (a185d8b) - **dashboard:** bump the cache-bust marks for the minute recording (604eb49) - **dashboard:** bump the cache-bust mark of the settings page (84aa771) - **dashboard:** bump the cache-bust marks for energy findings (85a44b4) diff --git a/dashboard/VERSION b/dashboard/VERSION index 68462daf..3db6093a 100644 --- a/dashboard/VERSION +++ b/dashboard/VERSION @@ -1 +1 @@ -v0.11.22-pre.32 +v0.11.22-pre.33 diff --git a/dashboard/cmd/dashboard/learn_engine.go b/dashboard/cmd/dashboard/learn_engine.go index 939b9454..57a81824 100644 --- a/dashboard/cmd/dashboard/learn_engine.go +++ b/dashboard/cmd/dashboard/learn_engine.go @@ -227,6 +227,10 @@ func registerEnergyDetectors(e *autolearn.Engine, reserve func() (float64, bool, e.Register(autolearn.PVReserveDetector(reserve)) e.Register(autolearn.LearnCyclesDetector) e.Register(autolearn.NewLearnSurplusDetector(check)) + e.Register(autolearn.SurplusDetector) + e.Register(autolearn.ShiftDetector) + e.Register(autolearn.ThresholdDetector) + e.Register(autolearn.RegulatorDetector) } // learnOutdoor finds the outdoor temperature entity by its unique id among the diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 6481f343..6f471cc2 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -623,6 +623,10 @@ func main() { }) // Die Regelpruefung prueft PV-Schwellen gegen dieselbe Bestkurve wie die Engine. automationChecker.SetPV(pvSource) + // Die Regelpruefung liest fuer Nachspiel und Minutenrauschen dieselben Daten wie die Engine. + automationChecker.SetReplaySource(func() *autolearn.Input { + return automationEngine.ReplayInput(time.Now()) + }) // Herabstufung: nur bei automatischer Stufe rueckt die gemerkte Stufe eine // nach unten. Eine feste Stufe der Einstellungen bleibt unberuehrt. engineDowngrade := func() { @@ -786,6 +790,10 @@ func main() { }) learnHub.AddMinute("minutes", minutes.store) var minuteReader learnrec.Reader = minutes.store + // Die Minutenaufzeichnung fuer das Nachspielen der Engine. + automationEngine.SetMinutes(func() learnrec.Reader { return minuteReader }) + // Die Reglerschritte fuer die Regelguete der Nulleinspeisung. + automationEngine.SetSteps(minutes.steps.Steps) go runStorageResume(ctx, storageService) // Die Belegung der Systemplatte: in der Demo feste Werte, sonst eine Messung // im Hintergrund, die alle zehn Minuten erneuert wird. diff --git a/dashboard/internal/autolearn/applied.go b/dashboard/internal/autolearn/applied.go index d8299b1a..4ffdf40d 100644 --- a/dashboard/internal/autolearn/applied.go +++ b/dashboard/internal/autolearn/applied.go @@ -106,12 +106,23 @@ func OpsApplied(fix Fix, doc Doc) bool { } seen := false for _, g := range groups { - rule := ruleNamed(doc, g.RuleID) - if rule == nil { + // A regulator fix names a scenario by its ID, a rule fix names a rule. + if rule := ruleNamed(doc, g.RuleID); rule != nil { + for _, op := range g.Ops { + got, ok := ruleValueAt(*rule, op.Path) + if !ok || !sameValue(got, op.Value) { + return false + } + seen = true + } + continue + } + sc := scenarioNamed(doc, g.RuleID) + if sc == nil { return false } for _, op := range g.Ops { - got, ok := ruleValueAt(*rule, op.Path) + got, ok := scenarioValueAt(*sc, op.Path) if !ok || !sameValue(got, op.Value) { return false } @@ -131,6 +142,38 @@ func ruleNamed(doc Doc, id string) *Rule { return nil } +// scenarioNamed returns the scenario with the given ID, nil without one. +func scenarioNamed(doc Doc, id string) *Scenario { + for i := range doc.Scenarios { + if doc.Scenarios[i].ID == id { + return &doc.Scenarios[i] + } + } + return nil +} + +// scenarioValueAt reads the regulator fields that the regulator fixes write: +// while.regulator.gain, deadband_w and max_change_w. A scenario without a +// regulator and any other path report false. Without a max_change_w limit the +// value is nil, which no fix writes. +func scenarioValueAt(sc Scenario, path []any) (any, bool) { + if sc.Regulator == nil || len(path) != 3 || path[0] != "while" || path[1] != "regulator" { + return nil, false + } + switch path[2] { + case "gain": + return sc.Regulator.Gain, true + case "deadband_w": + return sc.Regulator.DeadbandW, true + case "max_change_w": + if sc.Regulator.MaxChangeW == nil { + return nil, true + } + return *sc.Regulator.MaxChangeW, true + } + return nil, false +} + // ruleValueAt reads a rule field or a field of one condition, the paths the // fixes write. Any other path reports false. func ruleValueAt(rule Rule, path []any) (any, bool) { diff --git a/dashboard/internal/autolearn/applied_test.go b/dashboard/internal/autolearn/applied_test.go index 12cd6aae..63590f83 100644 --- a/dashboard/internal/autolearn/applied_test.go +++ b/dashboard/internal/autolearn/applied_test.go @@ -116,3 +116,65 @@ func TestOpsAppliedSingleRuleAndOddCases(t *testing.T) { t.Fatal("index out of range, want not applied") } } + +// regulatorDoc is a document with one regulator scenario "reg" of gain 0.8, deadband 20 W +// and no max_change_w limit. +func regulatorDoc() Doc { + return Doc{Scenarios: []Scenario{{ID: "reg", Enabled: true, Regulator: &RegulatorSpec{Gain: 0.8, DeadbandW: 20}}}} +} + +func regulatorFix(path string, value any) Fix { + return Fix{Code: "set_regulator", RuleID: "reg", Ops: []Op{{Path: []any{"while", "regulator", path}, Value: value}}} +} + +func TestOpsAppliedReadsScenarioRegulator(t *testing.T) { + doc := regulatorDoc() + if !OpsApplied(regulatorFix("gain", 0.8), doc) { + t.Fatal("gain already at 0.8, want applied") + } + if OpsApplied(regulatorFix("gain", 0.6), doc) { + t.Fatal("gain 0.8 against 0.6, want not applied") + } + if !OpsApplied(regulatorFix("deadband_w", 20.0), doc) { + t.Fatal("deadband 20 W, want applied") + } + if OpsApplied(regulatorFix("max_change_w", 300.0), doc) { + t.Fatal("no max_change_w limit, want not applied") + } + limited := regulatorDoc() + limit := 300.0 + limited.Scenarios[0].Regulator.MaxChangeW = &limit + if !OpsApplied(regulatorFix("max_change_w", 300.0), limited) { + t.Fatal("max_change_w 300, want applied") + } +} + +func TestOpsAppliedScenarioNeedsRegulatorAndKnownPath(t *testing.T) { + doc := regulatorDoc() + if OpsApplied(Fix{Code: "set_regulator", RuleID: "gibt_es_nicht", Ops: []Op{{Path: []any{"while", "regulator", "gain"}, Value: 0.8}}}, doc) { + t.Fatal("unknown scenario id, want not applied") + } + if OpsApplied(Fix{Code: "set_regulator", RuleID: "reg", Ops: []Op{{Path: []any{"while", "regulator", "output"}, Value: 0.8}}}, doc) { + t.Fatal("unknown regulator field, want not applied") + } + noReg := Doc{Scenarios: []Scenario{{ID: "reg", Enabled: true}}} + if OpsApplied(regulatorFix("gain", 0.8), noReg) { + t.Fatal("scenario without a regulator, want not applied") + } +} + +func TestOpsAppliedMixesRuleAndScenarioGroups(t *testing.T) { + doc := appliedDoc(t, `{"type":"balance_threshold","field":"battery_soc","comparison":"above","threshold":96,"hysteresis":0,"hold_seconds":0}`) + doc.Scenarios = regulatorDoc().Scenarios + fix := Fix{Code: "mixed", Rules: []RuleOps{ + {RuleID: "r1", Ops: []Op{{Path: []any{"conditions", 0, "threshold"}, Value: 96.0}}}, + {RuleID: "reg", Ops: []Op{{Path: []any{"while", "regulator", "gain"}, Value: 0.8}}}, + }} + if !OpsApplied(fix, doc) { + t.Fatal("rule and scenario both applied, want applied") + } + fix.Rules[1].Ops[0].Value = 0.5 + if OpsApplied(fix, doc) { + t.Fatal("scenario not applied, the group as a whole is not applied") + } +} diff --git a/dashboard/internal/autolearn/check_feedback.go b/dashboard/internal/autolearn/check_feedback.go index 76cd14d0..bebdcbf3 100644 --- a/dashboard/internal/autolearn/check_feedback.go +++ b/dashboard/internal/autolearn/check_feedback.go @@ -28,6 +28,8 @@ const ( feedbackConfirmShare = 0.3 // feedbackMinChanges is the number of switch-ons needed to observe the step. feedbackMinChanges = 3 + // feedbackMinuteDays is the number of minute days the noise is taken from the minutes. + feedbackMinuteDays = 3 ) // feedbackRun lists the feedback findings as candidates. The check is static, so @@ -55,8 +57,6 @@ func FeedbackFindings(in *Input) []Finding { if in == nil || len(in.Doc.Rules) == 0 { return nil } - noise := feedbackNoise(in.Days) - reserve := 2 * noise rules := ruleByID(in.Doc) var out []Finding seen := map[string]bool{} @@ -76,7 +76,12 @@ func FeedbackFindings(in *Input) []Finding { continue } off, offIdx, xAus, ok := feedbackOffRule(in.Doc, info, on.ID, rules) - if !ok || x-pAnlauf-noise > xAus { + if !ok { + continue + } + noise := feedbackNoiseAt(in, x) + reserve := 2 * noise + if x-pAnlauf-noise > xAus { continue } seen[on.ID] = true @@ -220,6 +225,19 @@ func feedbackNoise(days []DayFile) float64 { return QuarterNoise(series) } +// feedbackNoiseAt is the noise of the export at the switch-on threshold x. From +// feedbackMinuteDays minute days on it is the minute noise near x, otherwise +// the quarter noise of the days. The quarter noise also stays when no minute +// lies near x. +func feedbackNoiseAt(in *Input, x float64) float64 { + if minuteDayCount(in) >= feedbackMinuteDays { + if n, ok := MinuteNoise(in.Minutes, "b:"+feedbackField, x, in.Now.AddDate(0, 0, -engineHistoryDays), in.Now); ok { + return n + } + } + return feedbackNoise(in.Days) +} + // feedbackInrush is the median start peak of the device over its cycles, or the // operating power when no cycle has a peak. func feedbackInrush(days []DayFile, device string, p float64) float64 { diff --git a/dashboard/internal/autolearn/check_feedback_test.go b/dashboard/internal/autolearn/check_feedback_test.go index 1417df12..8cc793cb 100644 --- a/dashboard/internal/autolearn/check_feedback_test.go +++ b/dashboard/internal/autolearn/check_feedback_test.go @@ -142,3 +142,54 @@ func TestFeedbackDetectorWrapsFindingsAsCandidates(t *testing.T) { t.Fatalf("candidates = %+v, want one listed feedback candidate", got) } } + +// fbNoiseFact returns the noise_w fact of the first feedback finding, false without one. +func fbNoiseFact(got []Finding) (float64, bool) { + if len(got) != 1 { + return 0, false + } + for _, f := range got[0].Facts { + if f.Code == "noise_w" { + v, ok := f.Value.(float64) + return v, ok + } + } + return 0, false +} + +// TestFeedbackNoiseIsMinuteNoiseWithThreeMinuteDays: with three minute days the +// noise near the switch-on threshold comes from the minutes, with fewer it +// stays the quarter noise of the days. +func TestFeedbackNoiseIsMinuteNoiseWithThreeMinuteDays(t *testing.T) { + loc := berlinLoc(t) + spikes := make([]float32, 1440) + for m := range spikes { + spikes[m] = 1500 + if m%10 == 5 { + spikes[m] = 1580 + } + } + days := []DayFile{relDay(fbDay(loc, 15)), relDay(fbDay(loc, 16)), relDay(fbDay(loc, 17))} + minutes := func(n int) fakeMinutes { + fm := fakeMinutes{loc: loc, days: map[string]map[string][]float32{}} + for _, d := range days[:n] { + fm.days[d.Day] = map[string][]float32{"b:grid_export": spikes} + } + return fm + } + run := func(fm fakeMinutes) []Finding { + in := relInput(loc, days, fbDevice(), fbRule("on", "above", 1500), fbRule("off", "below", 500)) + in.Learned = fbLearned(2000) + in.Minutes = fm + return FeedbackFindings(in) + } + + noise, ok := fbNoiseFact(run(minutes(3))) + if !ok || noise != 80 { + t.Fatalf("noise with three minute days = %v (found %v), want the minute noise 80", noise, ok) + } + noise, ok = fbNoiseFact(run(minutes(2))) + if !ok || noise != 0 { + t.Fatalf("noise with two minute days = %v (found %v), want the quarter noise 0", noise, ok) + } +} diff --git a/dashboard/internal/autolearn/checker.go b/dashboard/internal/autolearn/checker.go index 5ed0fc77..a5901b45 100644 --- a/dashboard/internal/autolearn/checker.go +++ b/dashboard/internal/autolearn/checker.go @@ -20,6 +20,8 @@ const ( checkerDocEvery = time.Minute // checkerMaxFindings caps the findings the check reports. checkerMaxFindings = 20 + // checkerReplayEvery is how long the replay input is kept before it is built again. + checkerReplayEvery = 10 * time.Minute ) // Checker runs the static and observed checks on the rule document and keeps @@ -39,6 +41,13 @@ type Checker struct { reliabilityOn func() bool // pv gives the roof model for the PV thresholds, nil until SetPV is called. pv PVSource + // replay gives the input of the replay checks, nil until SetReplaySource is called. + replay func() *Input + // replayIn is the input built at replayAt, kept for checkerReplayEvery. + // replayBuilt is false until the first build. + replayIn *Input + replayAt time.Time + replayBuilt bool mu sync.Mutex // doc is the last rule document that parsed. docOK is false when the last @@ -101,6 +110,41 @@ func (c *Checker) SetEngineSource(candidates func() []Candidate, reliabilityOn f c.reliabilityOn = reliabilityOn } +// SetReplaySource gives the checker the input the replay evidence and the +// minute noise are read from, the same data the engine reads. Without it the +// frequent check keeps its fallback hysteresis and no replay evidence. +func (c *Checker) SetReplaySource(replay func() *Input) { + c.mu.Lock() + defer c.mu.Unlock() + c.replay = replay +} + +// replayInputLocked returns the replay input for the observed checks. It is +// built only when the document has an enabled rule, and kept for +// checkerReplayEvery after its build time. A nil result is kept as well. +func (c *Checker) replayInputLocked(now time.Time) *Input { + if c.replay == nil || !c.docOK || !hasEnabledRule(c.doc) { + return nil + } + if c.replayBuilt { + if age := now.Sub(c.replayAt); age >= 0 && age < checkerReplayEvery { + return c.replayIn + } + } + c.replayIn, c.replayAt, c.replayBuilt = c.replay(), now, true + return c.replayIn +} + +// hasEnabledRule reports whether the document has a rule that is switched on. +func hasEnabledRule(doc Doc) bool { + for _, r := range doc.Rules { + if r.Enabled { + return true + } + } + return false +} + // Findings returns the static, observed and reliability findings without the // ignored ones, ordered by severity and ID, at most 20. Ignored IDs of rules that no longer // exist are removed from the ignored file here. @@ -112,7 +156,7 @@ func (c *Checker) Findings(now time.Time) []Finding { // must follow at once, not up to checkerDocEvery later. c.refreshLocked(now, true) all := StaticFindings(c.doc, c.entityExists) - all = append(all, ObservedFindingsWithPV(c.doc, c.obs.Snapshot(), c.season, c.pv, now, c.thresholds)...) + all = append(all, ObservedFindingsWithPV(c.doc, c.obs.Snapshot(), c.season, c.pv, c.replayInputLocked(now), now, c.thresholds)...) all = append(all, c.reliabilityLocked()...) sort.SliceStable(all, func(i, j int) bool { ri, rj := severityRank[all[i].Severity], severityRank[all[j].Severity] @@ -287,10 +331,14 @@ func (c *Checker) reliabilityLocked() []Finding { if c.engineCandidates == nil || c.reliabilityOn == nil || !c.docOK || !c.reliabilityOn() { return nil } - current := make(map[string]bool, len(c.doc.Rules)) + // Scenario findings (regulator quality) name a scenario, which is a current target too. + current := make(map[string]bool, len(c.doc.Rules)+len(c.doc.Scenarios)) for _, rule := range c.doc.Rules { current[rule.ID] = true } + for _, sc := range c.doc.Scenarios { + current[sc.ID] = true + } var out []Finding for _, cand := range c.engineCandidates() { f := cand.Finding diff --git a/dashboard/internal/autolearn/checker_test.go b/dashboard/internal/autolearn/checker_test.go index 01a04ea1..926a939c 100644 --- a/dashboard/internal/autolearn/checker_test.go +++ b/dashboard/internal/autolearn/checker_test.go @@ -393,3 +393,60 @@ func TestCheckerDropsReliabilityFindingWhoseFixIsSaved(t *testing.T) { t.Fatalf("finding with an open fix = %d findings, want 1", len(got)) } } + +func TestCheckerReadsReplaySourceOnFindings(t *testing.T) { + c := NewChecker(NewObserver(time.UTC), nil, staticRead(unsatisfiableDoc), nil, "", t.Logf) + calls := 0 + c.SetReplaySource(func() *Input { + calls++ + return &Input{Now: testBase} + }) + c.Findings(testBase) + if calls != 1 { + t.Fatalf("replay source calls = %d, want 1", calls) + } +} + +// regulatorScenarioDoc has one scenario with a regulator and no rule. +const regulatorScenarioDoc = `{"rules":[],"scenarios":[{"id":"heater","name":"Heizstab","enabled":true,"while":{"regulator":{"output":{"topic":"heater/power/set"}}}}]}` + +func TestCheckerKeepsRegulatorFindingOfScenario(t *testing.T) { + on := true + reg := reliabilityCandidate("regulator", "heater") + c := checkerWithEngine(t, regulatorScenarioDoc, []Candidate{reg}, &on, "") + got := c.Findings(testBase) + if len(got) != 1 || got[0].ID != "regulator:heater" { + t.Fatalf("findings = %+v, want the regulator:heater finding of the scenario", got) + } +} + +func TestCheckerReplayInputIsKeptTenMinutes(t *testing.T) { + c := NewChecker(NewObserver(time.UTC), nil, staticRead(unsatisfiableDoc), nil, "", t.Logf) + calls := 0 + c.SetReplaySource(func() *Input { + calls++ + return &Input{Now: testBase} + }) + c.Findings(testBase) + c.Findings(testBase.Add(5 * time.Minute)) + if calls != 1 { + t.Fatalf("source calls after 5 minutes = %d, want 1", calls) + } + c.Findings(testBase.Add(11 * time.Minute)) + if calls != 2 { + t.Fatalf("source calls after 11 minutes = %d, want 2", calls) + } +} + +func TestCheckerReplayInputNotBuiltWithoutEnabledRule(t *testing.T) { + c := NewChecker(NewObserver(time.UTC), nil, staticRead(emptyRuleDoc), nil, "", t.Logf) + calls := 0 + c.SetReplaySource(func() *Input { + calls++ + return &Input{Now: testBase} + }) + c.Findings(testBase) + if calls != 0 { + t.Fatalf("source calls without rules = %d, want 0", calls) + } +} diff --git a/dashboard/internal/autolearn/demo.go b/dashboard/internal/autolearn/demo.go index d41859b1..04f91437 100644 --- a/dashboard/internal/autolearn/demo.go +++ b/dashboard/internal/autolearn/demo.go @@ -27,6 +27,10 @@ const ( demoPlugDry = "plug_entfeuchter" // demoRelais ist das Kellerrelais, das die Balkonsteckdose mitschaltet. demoRelais = "relais_keller" + // demoDryer ist der Wäschetrockner, der mittags aus der Sonne läuft, ohne Regel. + demoDryer = "waeschetrockner" + // demoDishwasher ist die Spülmaschine, die abends aus dem Netz läuft. + demoDishwasher = "spuelmaschine" // demoHeatPump ist die Wärmepumpe, deren Modus die Demo-Regel schaltet. demoHeatPump = "waermepumpe" // demoRuleID ist die Regel „Akku leer, WP aus“ der Demo. Sie schaltet die @@ -111,10 +115,12 @@ var demoEntities = map[string]string{ demoRelais: "relais_keller_switch_1", demoHeatPump: "waermepumpe_mode", demoWasherDevice: "waschmaschine_steckdose", + demoDryer: "waeschetrockner_steckdose", + demoDishwasher: "spuelmaschine_steckdose", } // demoWatts ist die Leistung der Demo-Geräte, wenn sie laufen. -var demoWatts = map[string]float64{demoPlugBalkon: 60, demoPlugDry: 300, demoRelais: 500, demoHeatPump: 1500, demoWasherDevice: 2000} +var demoWatts = map[string]float64{demoPlugBalkon: 60, demoPlugDry: 300, demoRelais: 500, demoHeatPump: 1500, demoWasherDevice: 2000, demoDryer: 500, demoDishwasher: 500} // SeedDemo schreibt die Tagesdateien der letzten 21 Tage vor now in dir, für die // Geräte der Demo. Jede Datei trägt "fake": true, die Konsole der Demo entfernt @@ -165,6 +171,10 @@ func demoDaysWith(now time.Time, loc *time.Location, rise bool) []DayFile { wash := rand.New(rand.NewSource(demoSeed + 1)) // Die Wärmepumpenzyklen haben einen eigenen Zufallsstrom aus demselben Grund. heat := rand.New(rand.NewSource(demoSeed + 3)) + // Der Trockner hat einen eigenen Zufallsstrom. + dry := rand.New(rand.NewSource(demoSeed + 5)) + // Die Spülmaschine hat einen eigenen Zufallsstrom. + dish := rand.New(rand.NewSource(demoSeed + 7)) today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc) out := make([]DayFile, 0, demoSeedDays) for i := 0; i < demoSeedDays; i++ { @@ -265,6 +275,8 @@ func demoDaysWith(now time.Time, loc *time.Location, rise bool) []DayFile { b.battery() if i < demoAwayFrom || i > demoAwayTo { b.heatCycle(heat) + b.dryer(dry) + b.dishwasher(dish) } if demoCompetitionDays[i] { b.competition() @@ -282,7 +294,7 @@ func demoDaysWith(now time.Time, loc *time.Location, rise bool) []DayFile { // ist gedrosselt, ein Schatten liegt im Westen über dem Horizont. Der // Wetterfaktor k ist 0,9 an klaren Tagen und 0,4 an bedeckten. const ( - demoPVPeakW = 5000.0 + demoPVPeakW = 6500.0 demoPVTiltDeg = 30.0 demoPVAzDeg = 180.0 demoPVAzCellDeg = 5.0 @@ -388,6 +400,43 @@ func (b *demoBuilder) heatCycle(rng *rand.Rand) { b.f.Cycles = append(b.f.Cycles, rec) } +// dryer schreibt den Lauf des Wäschetrockners: zwei Stunden um Mittag, 1000 Wh +// bei 500 W, aus der Sonne. Der Lauf ist eine Messung, keine Schaltung, deshalb +// entstehen dafür keine Ereignisse und keine Befunde der Gewohnheiten. +func (b *demoBuilder) dryer(rng *rand.Rand) { + wh := 1000 + 30*rng.NormFloat64() + opW := 500 + 10*rng.NormFloat64() + start := 720 + 60*rng.Float64() - 30 + rec := CycleRec{Device: demoDryer, Wh: float32(wh), OpW: float32(opW), PV: 1} + rec.Start = b.at(start).Unix() + rec.DurS = int(wh / opW * 3600) + rec.End = "self" + b.f.Cycles = append(b.f.Cycles, rec) + on := int(math.Round(start)) + b.changes[demoDryer] = append(b.changes[demoDryer], + demoChange{minute: on, on: true}, + demoChange{minute: on + rec.DurS/60, on: false}) +} + +// dishwasher schreibt den Lauf der Spülmaschine: eine Stunde, 500 Wh bei 500 W, +// aus dem Netz. Der Start streut am Abend zwischen 17:30 und 21:30, so weit, dass +// der robuste Streuungswert des Erkenners über 60 Minuten liegt. Auch hier +// entstehen keine Ereignisse. +func (b *demoBuilder) dishwasher(rng *rand.Rand) { + wh := 500 + 15*rng.NormFloat64() + opW := 500 + 10*rng.NormFloat64() + start := 1050 + 240*rng.Float64() + rec := CycleRec{Device: demoDishwasher, Wh: float32(wh), OpW: float32(opW), Grid: 1} + rec.Start = b.at(start).Unix() + rec.DurS = int(wh / opW * 3600) + rec.End = "self" + b.f.Cycles = append(b.f.Cycles, rec) + on := int(math.Round(start)) + b.changes[demoDishwasher] = append(b.changes[demoDishwasher], + demoChange{minute: on, on: true}, + demoChange{minute: on + rec.DurS/60, on: false}) +} + // competition schreibt die Konkurrenz des Tages: die Regel der Wärmepumpe und die // Regel der Waschmaschine schalten um elf Uhr im selben Viertel ein, die // Waschmaschine läuft dann eine Stunde. @@ -671,6 +720,7 @@ func (b *demoBuilder) fill(rng *rand.Rand) { b.f.Site.Seen[q] = dayCounterMax b.f.Site.LoadTotal[q] = float32(300 + load[q] + 10*rng.NormFloat64()) b.f.Site.GridImport[q] = b.f.Site.LoadTotal[q] + b.f.Site.GridExport[q] = float32(math.Max(0, float64(b.f.Site.PV[q]-b.f.Site.LoadTotal[q]))) } } @@ -781,6 +831,15 @@ func SeedDemoMinutes(dataDir string, now time.Time, loc *time.Location) error { } days := demoDays(now.In(loc), loc) rng := rand.New(rand.NewSource(demoSeed + 4)) + // Der Regler mit dem letzten Wert als Basis hat einen eigenen Zufallsstrom. + rngLast := rand.New(rand.NewSource(demoSeed + 6)) + // Die Schritte des zweiten Reglers gibt es an allen Demo-Tagen, damit die + // Zahl der Stellwertänderungen im Fenster des Erkenners reicht. + for i := 0; i < demoSeedDays; i++ { + if err := seedDemoStepsLast(dataDir, days[i], loc, rngLast); err != nil { + return fmt.Errorf("autolearn: demo steps: %w", err) + } + } for i := demoSeedDays - demoMinuteDays; i < demoSeedDays; i++ { f := days[i] path := minuteFileName(dataDir, f.Day) @@ -898,6 +957,73 @@ func seedDemoSteps(dataDir string, f DayFile, loc *time.Location, rng *rand.Rand return writeNewFile(path, buf) } +// demoStepScenarioLast ist das zweite Szenario der Demo mit Regler, dessen +// Basis der letzte Wert ist. Seine Strecke folgt dem Stellwert mit K = 1 und +// Totzeit 1, so wie der nächtliche Erkenner sie messen kann. +const demoStepScenarioLast = "nulleinspeisung_last" + +// demoStepBaseLoadW ist die feste Grundlast der Regler-Schritte in W. Sie hängt +// nicht am Lastprofil der Tage, damit Geräte der Demo die Schritte nicht ändern. +const demoStepBaseLoadW = 300.0 + +// demoStepJumpW ist der Sprung der Last je Viertelstunde in W. +const demoStepJumpW = 15.0 + +// seedDemoStepsLast schreibt die Reglerschritte des Szenarios mit der Basis +// „last“ am Tag f, wenn die Datei fehlt. Die Schritte liegen von 09:00 bis 14:00, +// dort liegt die PV über der Last, der Stellwert bestimmt also das Netz. Das Netz +// ist das kleinere von PV und dem Stellwert des vorigen Schritts, abzüglich der +// festen Grundlast und einer langsam driftenden Last. So folgt die Netzänderung der +// Stellwertänderung im nächsten Schritt, K = 1 und Totzeit 1. +func seedDemoStepsLast(dataDir string, f DayFile, loc *time.Location, rng *rand.Rand) error { + path := stepFileName(dataDir, f.Day, demoStepScenarioLast) + if demoFileExists(path) { + return nil + } + day, err := time.ParseInLocation(dayLayout, f.Day, loc) + if err != nil { + return err + } + var buf []byte + prev := demoStepLimitMax + drift := 0.0 + load := demoStepBaseLoadW + for m := 9 * 60; m < 14*60; m++ { + q := m / 15 + if m%15 == 0 { + // Die Last springt je Viertelstunde, wie die Verbraucher des Hauses. + load = demoStepBaseLoadW + demoStepJumpW*rng.NormFloat64() + } + // Die Last driftet langsam, so ändert der Regler den Stellwert regelmäßig. + drift += 4 * rng.NormFloat64() + net := math.Min(float64(f.Site.PV[q]), prev) - load - drift + errW := net - demoStepTargetW + to, why := prev, StepUnchanged + switch { + case math.Abs(errW) <= demoStepDeadbandW: + why = StepDeadband + default: + raw := prev - demoStepGain*errW + switch { + case raw > demoStepLimitMax || raw < demoStepLimitMin: + to = math.Max(demoStepLimitMin, math.Min(demoStepLimitMax, math.Round(raw/10)*10)) + why = StepLimit + default: + to = math.Round(raw/10) * 10 + if to != prev { + why = StepSent + } + } + } + from32, to32 := float32(prev), float32(to) + at := time.Date(day.Year(), day.Month(), day.Day(), m/60, m%60, 0, 0, loc) + buf = append(buf, encodeStep(Step{At: at.Unix(), Err: float32(errW), Net: float32(net), + From: &from32, To: &to32, Why: why})...) + prev = to + } + return writeNewFile(path, buf) +} + // demoFileExists meldet, ob path existiert. func demoFileExists(path string) bool { _, err := os.Stat(path) diff --git a/dashboard/internal/autolearn/demo_test.go b/dashboard/internal/autolearn/demo_test.go index 32e15dc9..0bc9bb13 100644 --- a/dashboard/internal/autolearn/demo_test.go +++ b/dashboard/internal/autolearn/demo_test.go @@ -195,7 +195,8 @@ func demoEngineRun(t *testing.T, dir string, now time.Time, loc *time.Location) loc) for _, d := range []Detector{SwitchTimeDetector, RuntimeDetector, CouplingDetector, OverriddenDetector, AwayStandbyDetector, TemperatureDetector, LearnSwitchTimeDetector, LearnRuntimeDetector, LearnDayBoundsDetector, LearnHouseStateDetector, - LearnCyclesDetector, FeedbackDetector, CompetitionDetector, BatteryDetector, BaseLoadDetector} { + LearnCyclesDetector, FeedbackDetector, CompetitionDetector, BatteryDetector, BaseLoadDetector, + ThresholdDetector, RegulatorDetector, SurplusDetector, ShiftDetector} { e.Register(d) } // The energy checks read the operating powers the engine learned before them. @@ -205,6 +206,19 @@ func demoEngineRun(t *testing.T, dir string, now time.Time, loc *time.Location) season.Put(w) } e.SetSeason(season) + pvRaster := DemoPVRasterYear(now, demoLat, demoLon) + pvModel := DemoPVModel(pvRaster) + e.SetPV(func() (PVModel, *Raster, bool) { return pvModel, pvRaster, true }) + if err := SeedDemoMinutes(dir, now, loc); err != nil { + t.Fatalf("SeedDemoMinutes: %v", err) + } + minutes := learnrec.NewMinuteStore(loc, + func() learnrec.MinutePlan { return learnrec.MinutePlan{On: true, Days: demoSeedDays} }, + func() learnrec.MinuteDirs { return learnrec.MinuteDirs{Drive: dir} }, + func() bool { return true }, func() learnrec.Limits { return learnrec.Limits{} }, nil) + e.SetMinutes(func() learnrec.Reader { return minutes }) + steps := NewStepLog(func() int { return demoSeedDays }, func() string { return dir }).WithRingDays(func() int { return 0 }) + e.SetSteps(steps.Steps) e.SetOutdoor(func() OutdoorSource { return OutdoorSource{EntityID: demoOutdoorEntity, Topic: "outstation/outdoor/state", ValueTemplate: "{{ value_json.temp }}"} }) @@ -717,6 +731,110 @@ func TestDemoSeedYieldsEnergyFindings(t *testing.T) { } } +// TestDemoSeedYieldsThresholdFinding checks that the demo holds a surplus rule +// whose threshold is too high for the heat pump, so the threshold rating +// suggests a lower one. +func TestDemoSeedYieldsThresholdFinding(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 20, 9, 0, 0, 0, loc) + ids := map[string]Candidate{} + for _, c := range demoEngineRun(t, t.TempDir(), now, loc).Candidates() { + ids[c.Finding.ID] = c + } + const id = "threshold:regel_wp_ueberschuss_hoch" + c, ok := ids[id] + if !ok { + t.Fatalf("no %s in the demo pipeline, ids %v", id, candidateIDs(ids)) + } + if c.Finding.Summary.Code != "threshold.too_high" { + t.Errorf("%s code = %q, want threshold.too_high", id, c.Finding.Summary.Code) + } +} + +// candidateIDs lists the finding IDs for failure messages. +func candidateIDs(m map[string]Candidate) []string { + out := make([]string, 0, len(m)) + for id := range m { + out = append(out, id) + } + sort.Strings(out) + return out +} + +// TestDemoSeedYieldsRegulatorFinding checks that the demo regulator with the +// last value as base, which follows the output with K = 1 and dead time 1, +// gets a gain suggestion about 0,2 below its configured 0,8. +func TestDemoSeedYieldsRegulatorFinding(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 20, 9, 0, 0, 0, loc) + ids := map[string]Candidate{} + for _, c := range demoEngineRun(t, t.TempDir(), now, loc).Candidates() { + ids[c.Finding.ID] = c + } + const id = "regulator:nulleinspeisung_last" + c, ok := ids[id] + if !ok { + t.Fatalf("no %s in the demo pipeline, ids %v", id, candidateIDs(ids)) + } + soll := c.Finding.Evidence.SollValue + if soll == nil || math.Abs(*soll-0.2) > 0.1 { + t.Errorf("%s gain soll = %v, want about 0.2", id, soll) + } +} + +// TestDemoRegulatorScenariosShareNoOutputTopic checks that the demo scenarios +// with a regulator never drive the same output topic, so the demo does not +// fight over the live limit of the PV inverter. +func TestDemoRegulatorScenariosShareNoOutputTopic(t *testing.T) { + doc, err := ParseDoc(demoRulesRaw(t)) + if err != nil { + t.Fatalf("parse demo rules: %v", err) + } + seen := map[string]string{} + for _, sc := range doc.Scenarios { + if sc.Regulator == nil { + continue + } + if other, ok := seen[sc.RegulatorTopic]; ok { + t.Errorf("scenarios %s and %s both drive %s", other, sc.ID, sc.RegulatorTopic) + } + seen[sc.RegulatorTopic] = sc.ID + } + if len(seen) < 2 { + t.Fatalf("demo regulator scenarios = %v, want two", seen) + } +} + +// TestDemoSeedYieldsSurplusFinding checks that the demo dryer, which runs at +// midday on solar power and no rule switches on surplus, gets a surplus window. +func TestDemoSeedYieldsSurplusFinding(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 20, 9, 0, 0, 0, loc) + ids := map[string]Candidate{} + for _, c := range demoEngineRun(t, t.TempDir(), now, loc).Candidates() { + ids[c.Finding.ID] = c + } + const id = "surplus:" + demoDryer + if _, ok := ids[id]; !ok { + t.Errorf("no %s in the demo pipeline, ids %v", id, candidateIDs(ids)) + } +} + +// TestDemoSeedYieldsShiftFinding checks that the demo dishwasher, which runs in +// the evening from the grid, gets a load shift to the midday surplus. +func TestDemoSeedYieldsShiftFinding(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 20, 9, 0, 0, 0, loc) + ids := map[string]Candidate{} + for _, c := range demoEngineRun(t, t.TempDir(), now, loc).Candidates() { + ids[c.Finding.ID] = c + } + const id = "shift:" + demoDishwasher + if _, ok := ids[id]; !ok { + t.Errorf("no %s in the demo pipeline, ids %v", id, candidateIDs(ids)) + } +} + // TestDemoSeedKeepsTheHabitSuggestions checks the suggestions the demo had // before the energy findings: run time of the dehumidifier and the away standby. func TestDemoSeedKeepsTheHabitSuggestions(t *testing.T) { @@ -752,7 +870,7 @@ func TestDemoPVYearRestsTheFeedInRule(t *testing.T) { st.Rules["regel_einspeisung_entfeuchter"] = RuleStats{FirstSeen: now.Add(-40 * 24 * time.Hour), Hours: map[int64]int{}} src := func() (PVModel, *Raster, bool) { return m, r, true } var got *Finding - for _, f := range ObservedFindingsWithPV(doc, st, nil, src, now, DefaultThresholds()) { + for _, f := range ObservedFindingsWithPV(doc, st, nil, src, nil, now, DefaultThresholds()) { if f.ID == FindingID("never_fired", "regel_einspeisung_entfeuchter") { f := f got = &f diff --git a/dashboard/internal/autolearn/detect_battery.go b/dashboard/internal/autolearn/detect_battery.go index b07f3e6f..a8f94790 100644 --- a/dashboard/internal/autolearn/detect_battery.go +++ b/dashboard/internal/autolearn/detect_battery.go @@ -2,6 +2,7 @@ package autolearn import ( "context" + "encoding/json" "math" "sort" "strings" @@ -43,6 +44,17 @@ const ( batteryWeekDays = 7.0 // batteryLearnRoundWh rounds the learned night energy. batteryLearnRoundWh = 100.0 + // batteryMaxOffers is the number of loads offered after "full". + batteryMaxOffers = 2 + // batteryReplayDays is the number of days the replay of an offer reads. + batteryReplayDays = 14 + // batteryAfterSoC, batteryAfterExportW, batteryAfterImportW and + // batteryAfterHoldS are the conditions of the after_battery_full scenario, + // as its template sets them. + batteryAfterSoC = 96.0 + batteryAfterExportW = 100.0 + batteryAfterImportW = 100.0 + batteryAfterHoldS = 120 ) // batteryDay is one day file with a charge. The sun values are local minutes @@ -76,7 +88,7 @@ func batteryRun(ctx context.Context, in *Input, _ string) []Candidate { return nil } var out []Candidate - out = append(out, batteryFull(days)...) + out = append(out, batteryFull(ctx, in, days)...) out = append(out, batteryEmpty(in, days)...) out = append(out, batteryLearned(in, days)...) return out @@ -275,8 +287,12 @@ func batteryMinSoC(f *DayFile) float64 { // batteryFull looks for a battery that is full before solar noon on most days. // Days without sun are left out. The finding carries the median time of the -// first full quarter and the export after it. -func batteryFull(days []*batteryDay) []Candidate { +// first full quarter and the export after it. Up to batteryMaxOffers switchable +// loads whose power fits that export are offered with the after_battery_full +// template, each one replayed. A replay that adds more grid energy than the +// export it saves drops the offer (replayAddsGrid, the gate rule). Without a +// replay the offer stays and carries no benefit. +func batteryFull(ctx context.Context, in *Input, days []*batteryDay) []Candidate { var flags []bool var hits []*batteryDay for _, d := range days { @@ -306,8 +322,8 @@ func batteryFull(days []*batteryDay) []Candidate { } kwh = append(kwh, wh/1000) } - // The finding has no rule and no fix. In the group check it reaches the - // rule check and from there the Monitoring page as a notice, like shade. + // The finding reaches the rule check and from there the Monitoring page as + // a notice, like shade. Its offers are the only fixes. finding := Finding{ ID: "battery:full", Kind: "battery", @@ -320,6 +336,13 @@ func batteryFull(days []*batteryDay) []Candidate { }}, Evidence: batteryFullEvidence(hits[len(hits)-1]), } + offers := batteryOffers(ctx, in, days, hits) + if len(offers.apply) > 0 { + finding.Apply = offers.apply + } + if offers.replayed { + finding.Benefit = &offers.benefit + } return []Candidate{{ Finding: finding, Detector: "battery", @@ -328,9 +351,158 @@ func batteryFull(days []*batteryDay) []Candidate { Lower: lower, Limit: batteryShare, HalvesAgree: batteryHalves(flags), + Benefit: offers.benefit, }} } +// batteryOfferSet is what batteryOffers returns: the fixes, and the largest +// benefit of an offer that was replayed. replayed is false when no offer was +// replayed, then no benefit is set. +type batteryOfferSet struct { + apply []Fix + benefit Benefit + replayed bool +} + +// batteryOffers offers the switchable loads whose power fits the export after +// "full", the largest first, up to batteryMaxOffers. An offer whose replay adds +// grid energy is dropped and does not take a slot. +func batteryOffers(ctx context.Context, in *Input, days []*batteryDay, hits []*batteryDay) batteryOfferSet { + var set batteryOfferSet + if len(hits) == 0 { + return set + } + exportW := batteryExportAfterFull(hits) + type load struct { + id string + w float64 + } + var fit []load + for id, info := range in.Devices { + if !info.Switchable || len(info.Entities) == 0 { + continue + } + w := batteryDevicePower(in, id, days) + if w > 0 && w <= exportW { + fit = append(fit, load{id: id, w: w}) + } + } + sort.SliceStable(fit, func(a, b int) bool { + if fit[a].w != fit[b].w { + return fit[a].w > fit[b].w + } + return fit[a].id < fit[b].id + }) + for _, l := range fit { + if len(set.apply) >= batteryMaxOffers || ctx.Err() != nil { + break + } + info := in.Devices[l.id] + minRun := minRunForRole(info) + fix := Fix{Code: "after_battery_full", Template: "after_battery_full", + Prefill: withEntity(map[string]any{"device": l.id, "min_run_s": minRun}, "entity", switchEntityOf(in, l.id))} + verdict, benefit, err := batteryReplay(ctx, in, l.id, l.w, minRun) + if err == nil && verdict != nil { + if replayAddsGrid(*verdict) { + continue + } + if !set.replayed || benefit.Value > set.benefit.Value { + set.benefit = benefit + } + set.replayed = true + } + set.apply = append(set.apply, fix) + } + return set +} + +// batteryExportAfterFull is the median over the days of the mean export in W +// from the first full quarter to the end of the day, over the quarters the day +// has a measurement for. +func batteryExportAfterFull(hits []*batteryDay) float64 { + var per []float64 + for _, d := range hits { + var sum float64 + n := 0 + for q := d.fullQ; q < dayQuarters; q++ { + if d.f.Site.Seen[q] == 0 { + continue + } + sum += float64(d.f.Site.GridExport[q]) + n++ + } + if n > 0 { + per = append(per, sum/float64(n)) + } + } + return Median(per) +} + +// batteryDevicePower is the operating power of a device in W, the learned value +// when there is one, else the median of its positive mean power in the days. +func batteryDevicePower(in *Input, device string, days []*batteryDay) float64 { + if p, ok := learnedOperatingPower(in.Learned, device); ok { + return p + } + var vals []float64 + for _, d := range days { + dd := d.f.Devices[device] + if dd == nil { + continue + } + for q := 0; q < dayQuarters; q++ { + if dd.Seen[q] != 0 && dd.AvgW[q] > 0 { + vals = append(vals, float64(dd.AvgW[q])) + } + } + } + return Median(vals) +} + +// batteryReplay replays the after_battery_full scenario for one load over the +// last batteryReplayDays days. It returns a nil verdict when there are no +// minutes, and an error when the scenario cannot be replayed. +func batteryReplay(ctx context.Context, in *Input, device string, opW float64, minRun float64) (*ReplayVerdict, Benefit, error) { + if in.Doc.Location == nil { + return nil, Benefit{}, nil + } + id := "battery-full:" + device + scenario := map[string]any{ + "id": id, + "enabled": true, + "min_run_s": minRun, + "when": map[string]any{"conditions": []map[string]any{ + {"type": "balance_threshold", "field": "battery_soc", "comparison": "above", "threshold": batteryAfterSoC}, + {"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": batteryAfterExportW}, + }}, + "until": map[string]any{"conditions": []map[string]any{ + {"type": "balance_threshold", "field": "grid_import", "comparison": "above", "threshold": batteryAfterImportW, "hold_seconds": batteryAfterHoldS}, + }}, + } + raw, err := json.Marshal(scenario) + if err != nil { + return nil, Benefit{}, err + } + loc := in.Loc + if loc == nil { + loc = time.Local + } + chk := ReplayCheck{ + Rule: json.RawMessage(raw), + Target: ReplayTarget{ScenarioID: id, Device: device, OpW: opW, + PeakW: feedbackInrush(in.Days, device, opW), MinRunS: minRun}, + Benefit: func(alt, base ReplayResult) Benefit { + // The energy the load takes from the export, per week. + return Benefit{Unit: "kwh_week", Value: (base.ExportWh - alt.ExportWh) / 1000 * 7 / batteryReplayDays} + }, + } + verdict, benefit, err := EvaluateReplay(ctx, in, chk, batteryReplayDays, loc, *in.Doc.Location) + if ctx.Err() != nil { + return nil, Benefit{}, ctx.Err() + } + return verdict, benefit, err +} + // batteryEmpty looks for a battery that is empty before sunrise on most days, // when the same weeks of the year before were empty on less than half of their // days. Without a record of the year before no finding is made. The fix is a diff --git a/dashboard/internal/autolearn/detect_battery_test.go b/dashboard/internal/autolearn/detect_battery_test.go index 25d3fa24..1c3aa190 100644 --- a/dashboard/internal/autolearn/detect_battery_test.go +++ b/dashboard/internal/autolearn/detect_battery_test.go @@ -325,3 +325,77 @@ func TestBatteryEmptyEvidenceKeepsTheFloorUntilSunrise(t *testing.T) { t.Errorf("Soll after the charge rose = %v, want the Ist %v", ev.SollQ[50], ev.Quarters[50]) } } + +// btFullAt1120 is a battery that is full from 11:20 on, the quarters before stay at 40 %. +func btFullAt1120(i, q int) (float32, bool) { + if float64(q)*baseQuarterMin >= 11*60+20 { + return 98, true + } + return 40, true +} + +// btAfterFull sets the export after 11:15 and the heater power on every day. +func btAfterFull(in *Input, exportW, heaterW float32) { + for i := range in.Days { + f := &in.Days[i] + for q := 0; q < dayQuarters; q++ { + if float64(q)*baseQuarterMin >= 11*60+15 { + f.Site.GridExport[q] = exportW + } + f.Devices["plug.heater"].AvgW[q] = heaterW + } + } +} + +// TestBatteryFullOffersHeaterThatFitsTheExport: 3 kW export after "voll", a +// 2 kW heater is offered with the after_battery_full template and the role +// minimum run time of a device without role (300 s). +func TestBatteryFullOffersHeaterThatFitsTheExport(t *testing.T) { + in := btInput(14, btNovStart, btFullAt1120, 1000, nil) + btAfterFull(in, 3000, 2000) + findings, _ := btSplit(in) + f, ok := btFindingByID(findings, "battery:full") + if !ok { + t.Fatalf("want a battery:full finding, got %d findings", len(findings)) + } + if len(f.Apply) != 1 { + t.Fatalf("Apply = %+v, want one offer for the heater", f.Apply) + } + fix := f.Apply[0] + if fix.Code != "after_battery_full" || fix.Template != "after_battery_full" { + t.Errorf("Apply code %q template %q, want after_battery_full", fix.Code, fix.Template) + } + if fix.Prefill["device"] != "plug.heater" || fix.Prefill["min_run_s"] != float64(300) { + t.Errorf("Prefill = %+v, want plug.heater with min_run_s 300", fix.Prefill) + } + if f.Benefit == nil || f.Benefit.Unit != "kwh_week" || f.Benefit.Value <= 0 { + t.Errorf("Benefit = %+v, want kwh_week above zero from the replay", f.Benefit) + } +} + +// TestBatteryFullNoOfferForLoadAboveExport: a 4 kW heater does not fit 3 kW export. +func TestBatteryFullNoOfferForLoadAboveExport(t *testing.T) { + in := btInput(14, btNovStart, btFullAt1120, 1000, nil) + btAfterFull(in, 3000, 4000) + findings, _ := btSplit(in) + f, ok := btFindingByID(findings, "battery:full") + if !ok { + t.Fatalf("want a battery:full finding, got %d findings", len(findings)) + } + if len(f.Apply) != 0 { + t.Errorf("Apply = %+v, want none for a 4 kW load and 3 kW export", f.Apply) + } +} + +// TestBatteryReplayRejectsMoreGridImport: a replay that adds more grid energy +// than the export it saves takes the offer away, a small extra import does not. +func TestBatteryReplayRejectsMoreGridImport(t *testing.T) { + more := ReplayVerdict{Base: ReplayResult{GridWh: 100, ExportWh: 1000}, Alt: ReplayResult{GridWh: 500, ExportWh: 900}} + if !replayAddsGrid(more) { + t.Errorf("extra 400 Wh grid over 100 Wh export saved: want the offer dropped") + } + small := ReplayVerdict{Base: ReplayResult{GridWh: 0, ExportWh: 500000}, Alt: ReplayResult{GridWh: 1700, ExportWh: 185000}} + if replayAddsGrid(small) { + t.Errorf("1.7 kWh grid over 315 kWh export saved: want the offer kept") + } +} diff --git a/dashboard/internal/autolearn/detect_overridden.go b/dashboard/internal/autolearn/detect_overridden.go index 8507787b..2af9fadc 100644 --- a/dashboard/internal/autolearn/detect_overridden.go +++ b/dashboard/internal/autolearn/detect_overridden.go @@ -52,6 +52,7 @@ const ( overriddenSurplus = "surplus" overriddenToSunset = "to_sunset" overriddenElevation = "sun_elevation" + overriddenSignal = "signal" ) // overriddenSunSearchMin is the half width in minutes of the search for the @@ -91,6 +92,10 @@ type overrideCase struct { toSunset float64 sunset time.Time elevation float64 + // hasSignal is set when the rule has a balance condition and its value at + // the switch is known. signal is that value in W. + hasSignal bool + signal float64 } // overridePoint is one case of a numeric feature. @@ -241,6 +246,11 @@ func overriddenCandidate(device string, in *Input, rule Rule, sw []overrideSwitc cases := make([]overrideCase, n) hits := 0 + signalField, hasField := overriddenSignalField(rule) + days := make(map[string]*DayFile, len(in.Days)) + for i := range in.Days { + days[in.Days[i].Day] = &in.Days[i] + } for j, i := range idx { s := sw[i] c := overrideCase{at: s.at, on: s.on, house: s.house, surplus: s.surplus} @@ -254,6 +264,9 @@ func overriddenCandidate(device string, in *Input, rule Rule, sw []overrideSwitc c.reverseMin = minuteOfDay(rev, loc) hits++ } + if hasField { + c.signal, c.hasSignal = overrideSignal(in, signalField, at, loc, days) + } if in.Doc.Location != nil { if m, set, e, ok := overrideSunState(at, in.Doc.Location); ok { c.sunOK, c.toSunset, c.sunset, c.elevation = true, m, set, e @@ -293,7 +306,7 @@ func overriddenCandidate(device string, in *Input, rule Rule, sw []overrideSwitc var sollSpans [][2]int64 if split, ok := overriddenSplit(cases, in.Base); ok { // A split the rule already holds is not offered again. - if fix, spans, ok := overriddenAddFix(rule, in.Base, split, cases, in.Doc.Location); ok && !FixApplied(fix, in.Doc) { + if fix, spans, ok := overriddenAddFix(rule, in.Base, split, cases, in.Doc.Location); ok && !overriddenFixHeld(split.feature, fix, in.Doc) { feature = split.feature apply = []Fix{fix} sollSpans = spans @@ -416,6 +429,7 @@ func overriddenSplit(cases []overrideCase, base Base) (overrideSplit, bool) { considerNumeric(overriddenSurplus, overridePoints(cases, func(c overrideCase) float64 { return c.surplus })) considerNumeric(overriddenToSunset, overrideSunPoints(cases, func(c overrideCase) float64 { return c.toSunset })) considerNumeric(overriddenElevation, overrideSunPoints(cases, func(c overrideCase) float64 { return c.elevation })) + considerNumeric(overriddenSignal, overrideSignalPoints(cases)) return best, found } @@ -446,6 +460,48 @@ func overridePoints(cases []overrideCase, value func(overrideCase) float64) []ov return out } +// overrideSignalPoints returns the cases whose condition signal is known with +// its value in W. +func overrideSignalPoints(cases []overrideCase) []overridePoint { + out := make([]overridePoint, 0, len(cases)) + for _, c := range cases { + if c.hasSignal { + out = append(out, overridePoint{x: c.signal, ov: c.reversed}) + } + } + return out +} + +// overriddenSignalField is the field of the first balance condition of the +// rule, the signal the rule switches on. It reports false without one. +func overriddenSignalField(rule Rule) (string, bool) { + for _, c := range rule.Conditions { + if c.Type == "balance_threshold" && c.Field != "" { + return c.Field, true + } + } + return "", false +} + +// overrideSignal is the value of the signal field at the minute of the switch, +// read from the minute record and otherwise from the quarter hour of the day +// file. ok is false when neither holds the value. +func overrideSignal(in *Input, field string, at time.Time, loc *time.Location, days map[string]*DayFile) (float64, bool) { + if in.Minutes != nil { + m := at.Truncate(time.Minute) + if vals := in.Minutes.Range("b:"+field, m, m.Add(time.Minute)).Values; len(vals) > 0 && !math.IsNaN(float64(vals[0])) { + return float64(vals[0]), true + } + } + local := at.In(loc) + f := days[local.Format(dayLayout)] + if f == nil { + return 0, false + } + v := quarterValue(f, field, quarterOf(local)) + return v, !math.IsNaN(v) +} + // overrideSunPoints returns the cases that have a sun state with their value of // one sun feature. Without a location no case has one, and the feature is skipped. func overrideSunPoints(cases []overrideCase, value func(overrideCase) float64) []overridePoint { @@ -659,10 +715,17 @@ func overriddenAddFix(rule Rule, base Base, s overrideSplit, cases []overrideCas } else { cond = map[string]any{"type": "sun_window", "from": "sunrise", "to": "sunset", "from_offset_min": 0, "to_offset_min": off} } - case overriddenHouseLoad, overriddenSurplus: + case overriddenHouseLoad, overriddenSurplus, overriddenSignal: field, threshold := "load_total", math.Round(s.cut/overriddenRoundW)*overriddenRoundW - if s.feature == overriddenSurplus { + switch s.feature { + case overriddenSurplus: field = "grid_export" + case overriddenSignal: + f, ok := overriddenSignalField(rule) + if !ok { + return Fix{}, nil, false + } + field = f } comparison := "above" if s.acceptedLeft { @@ -676,6 +739,34 @@ func overriddenAddFix(rule Rule, base Base, s overrideSplit, cases []overrideCas Ops: []Op{{Path: []any{"conditions", at}, Value: cond}}}, spans, true } +// overriddenFixHeld reports whether the rule already holds the condition of an +// add_condition fix. A signal threshold is held only with the same value, since +// FixApplied would take the rule's own export condition for it whatever its +// threshold. Every other feature uses FixApplied. +func overriddenFixHeld(feature string, fix Fix, doc Doc) bool { + if feature != overriddenSignal { + return FixApplied(fix, doc) + } + if len(fix.Ops) != 1 { + return false + } + want, ok := normalizedCondition(fix.Ops[0].Value) + if !ok { + return false + } + for _, r := range doc.Rules { + if r.ID != fix.RuleID { + continue + } + for _, c := range r.Conditions { + if c.Type == want["type"] && c.Field == want["field"] && c.Comparison == want["comparison"] && c.Threshold == want["threshold"] { + return true + } + } + } + return false +} + // overriddenShiftFix moves the start of the rule's time window to the median // switch-back time, when the reversals cluster at a similar clock time. It also // returns the median in minutes of the day. diff --git a/dashboard/internal/autolearn/detect_overridden_test.go b/dashboard/internal/autolearn/detect_overridden_test.go index 52202945..e3b82f51 100644 --- a/dashboard/internal/autolearn/detect_overridden_test.go +++ b/dashboard/internal/autolearn/detect_overridden_test.go @@ -384,3 +384,43 @@ func TestOverriddenSunFixDropsOffsetOutOfRange(t *testing.T) { } } } + +// TestOverriddenSignalSplitGivesThresholdCondition: the reversals happen when +// the export at the switch was under 600 W, so the split is the signal and the +// fix adds the export threshold as a condition. +func TestOverriddenSignalSplitGivesThresholdCondition(t *testing.T) { + loc := berlinLoc(t) + start := time.Date(2026, 11, 2, 0, 0, 0, 0, loc) + n := 20 + reversed := make([]bool, n) + for i := 0; i < 14; i++ { + reversed[i] = true + } + days := ovDays(t, loc, start, reversed, func(int) float64 { return 300 }) + for i := range days { + exp := float32(900) + if reversed[i] { + exp = 300 + } + days[i].Site.Seen[72] = 1 // quarter hour of 18:00 + days[i].Site.GridExport[72] = exp + } + got := ovRun(loc, days, Base{}, relRule("heat", "Heizung")) + if len(got) != 1 { + t.Fatalf("candidates = %d, want 1: %+v", len(got), got) + } + f := got[0].Finding + if f.Facts[1].Value != overriddenSignal { + t.Fatalf("feature = %v, want %q", f.Facts[1].Value, overriddenSignal) + } + if len(f.Apply) != 1 || f.Apply[0].Code != "add_condition" { + t.Fatalf("apply = %+v, want add_condition", f.Apply) + } + cond, ok := f.Apply[0].Ops[0].Value.(map[string]any) + if !ok || cond["type"] != "balance_threshold" || cond["field"] != "grid_export" { + t.Fatalf("condition = %+v, want balance_threshold grid_export", f.Apply[0].Ops[0].Value) + } + if cond["threshold"] != 600.0 { + t.Errorf("threshold = %v, want 600 between 300 and 900 W", cond["threshold"]) + } +} diff --git a/dashboard/internal/autolearn/detect_regulator.go b/dashboard/internal/autolearn/detect_regulator.go new file mode 100644 index 00000000..88d32935 --- /dev/null +++ b/dashboard/internal/autolearn/detect_regulator.go @@ -0,0 +1,484 @@ +package autolearn + +import ( + "context" + "math" + "sort" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// RegulatorDetector rates the tuning of a zero feed-in regulator from its own +// steps (spec 15.6 "Regelgüte Nulleinspeisung"). The dead time d is the shift +// of the largest correlation between output and net, 0 to 5 steps. K is the +// median of the net change per output change, and gain_grenze is +// d^d / ((d+1)^(d+1) * K). A gain above 1.25 times 0.8 * gain_grenze swings. +// The deadband and the largest change per step are rated against the noise of +// the net, one output stage times K, and the largest usual load jump settled +// in three steps. Each PV band below and above 40 % of the best curve is rated +// on its own. Without a PV model, minutes or steps the detector finds nothing. +var RegulatorDetector = Detector{ + Name: "regulator_quality", + Group: "reliability", + Light: false, + PerDevice: false, + Run: regulatorRun, +} + +const ( + // regulatorWindow is the span of steps the rating reads. + regulatorWindow = 14 * 24 * time.Hour + // regulatorMinChanges is the number of steps with an output change needed. + regulatorMinChanges = 200 + // regulatorMinBand is the number of changes a PV band needs to be rated alone. + regulatorMinBand = 30 + // regulatorMaxDead is the largest dead time searched, in steps. + regulatorMaxDead = 5 + // regulatorBandShare is the share of the best curve that splits the PV bands. + regulatorBandShare = 0.4 + // regulatorKSpread is the largest relative spread of K that counts as safe. + regulatorKSpread = 0.25 + // regulatorKDiff is the relative difference of K between the bands that + // makes the cautious value count. + regulatorKDiff = 0.3 + // regulatorSwingShare is the factor above the target gain that counts as swinging. + regulatorSwingShare = 1.25 + // regulatorDeadFactor is the factor by which the deadband or the change + // limit may differ from the target before it is reported. + regulatorDeadFactor = 2.0 + // regulatorGainTarget is the share of gain_grenze the target gain takes. + regulatorGainTarget = 0.8 + // regulatorGainMin and regulatorGainMax bound the gain (schema). + regulatorGainMin = 0.1 + regulatorGainMax = 1.0 + // regulatorJumpSteps is the number of steps a usual load jump may take to settle. + regulatorJumpSteps = 3.0 + // regulatorDefaultGain is the gain of a regulator without a gain field. + regulatorDefaultGain = 0.8 +) + +// regulatorResult is the rating of one regulator. Measured is set when the +// regulator works on a measured base: only the dead time is rated then. +type regulatorResult struct { + Measured bool + Dead int + K float64 + Spread float64 + Changes int + GainSoll float64 + DeadbandSoll float64 + // MaxChangeSoll is 0 when no usual load jump was seen. + MaxChangeSoll float64 + SettleS float64 + FlipsH float64 + Days float64 +} + +// regulatorPair is one output change with the net change d steps later. +type regulatorPair struct { + i int // index of the output change + x float64 // output change in W + k float64 // net change over output change, signed +} + +// regulatorRun rates the regulators of the enabled scenarios. +func regulatorRun(ctx context.Context, in *Input, _ string) []Candidate { + if ctx.Err() != nil || in == nil || in.Steps == nil || in.PV == nil || in.Minutes == nil || in.Doc.Location == nil { + return nil + } + var out []Candidate + for _, sc := range in.Doc.Scenarios { + if ctx.Err() != nil { + return nil + } + if !sc.Enabled || sc.Regulator == nil { + continue + } + steps := in.Steps(sc.ID, in.Now.Add(-regulatorWindow), in.Now) + res, ok := regulatorEval(in, sc, steps) + if !ok || res.Measured { + continue + } + if cand, ok := regulatorCandidate(sc, res); ok { + out = append(out, cand) + } + } + return out +} + +// regulatorEval rates the steps of one scenario. It returns false when the +// steps are too few, the dead time or K cannot be found, or K scatters. +func regulatorEval(in *Input, sc Scenario, steps []Step) (regulatorResult, bool) { + if sc.Regulator == nil || in.Doc.Location == nil || in.PV == nil || in.Minutes == nil { + return regulatorResult{}, false + } + model, raster, ok := in.PV() + if !ok { + return regulatorResult{}, false + } + pts := make([]Step, 0, len(steps)) + for _, st := range steps { + if st.To != nil { + pts = append(pts, st) + } + } + sort.SliceStable(pts, func(a, b int) bool { return pts[a].At < pts[b].At }) + n := len(pts) + if n < 3 { + return regulatorResult{}, false + } + x, y, valid := regulatorDeltas(pts) + changes := 0 + for i := 1; i < n; i++ { + if valid[i] && x[i] != 0 { + changes++ + } + } + if changes < regulatorMinChanges { + return regulatorResult{}, false + } + d, ok := regulatorDeadTime(x, y, valid) + if !ok { + return regulatorResult{}, false + } + res := regulatorResult{Dead: d, Changes: changes, Measured: sc.Regulator.BaseSource != "last"} + res.Days = float64(pts[n-1].At-pts[0].At) / 86400 + res.FlipsH = regulatorFlips(x, valid) / math.Max(float64(pts[n-1].At-pts[0].At)/3600, 1e-9) + res.SettleS = float64(d+3) * regulatorMedianGap(pts) + if res.Measured { + return res, true + } + + pairs := regulatorPairs(x, y, valid, d) + ks := make([]float64, 0, len(pairs)) + for _, p := range pairs { + ks = append(ks, math.Abs(p.k)) + } + if len(ks) == 0 { + return regulatorResult{}, false + } + k := Median(ks) + if k <= 0 { + return regulatorResult{}, false + } + res.Spread = MADScale(ks) / k + if res.Spread >= regulatorKSpread { + return regulatorResult{}, false + } + + bands := regulatorBands(in, pts, pairs, model, raster) + var lo, hi []regulatorPair + for j, p := range pairs { + switch bands[j] { + case 0: + lo = append(lo, p) + case 1: + hi = append(hi, p) + } + } + if len(lo) >= regulatorMinBand && len(hi) >= regulatorMinBand { + kLo, kHi := regulatorMedianK(lo), regulatorMedianK(hi) + if math.Abs(kHi-kLo)/math.Max(kLo, kHi) > regulatorKDiff { + res = regulatorCautious(res, x, y, valid, d, lo, hi) + res.K = k + return res, true + } + } + gain, dead, maxChange, _ := regulatorBandParams(x, y, valid, pairs, k, d) + res.K = k + res.GainSoll = gain + res.DeadbandSoll = dead + res.MaxChangeSoll = maxChange + return res, true +} + +// regulatorBandParams returns the targets of the pairs with K as given. +func regulatorBandParams(x, y []float64, valid []bool, pairs []regulatorPair, k float64, d int) (gain, dead, maxChange, stage float64) { + noise, jump := regulatorNoise(x, y, valid) + stage = regulatorStage(pairs) + limit := math.Pow(float64(d), float64(d)) / (math.Pow(float64(d+1), float64(d+1)) * k) + gain = math.Min(regulatorGainMax, math.Max(regulatorGainMin, regulatorGainTarget*limit)) + dead = math.Max(2*noise, k*stage) + if jump > 0 { + maxChange = math.Max(jump/(regulatorJumpSteps*k), stage) + } + return gain, dead, maxChange, stage +} + +// regulatorCautious rates both PV bands with their own K and keeps the more +// cautious value of each parameter: the smaller gain and change limit, the +// larger deadband. +func regulatorCautious(res regulatorResult, x, y []float64, valid []bool, d int, lo, hi []regulatorPair) regulatorResult { + gLo, dLo, mLo, _ := regulatorBandParams(x, y, valid, lo, regulatorMedianK(lo), d) + gHi, dHi, mHi, _ := regulatorBandParams(x, y, valid, hi, regulatorMedianK(hi), d) + res.GainSoll = math.Min(gLo, gHi) + res.DeadbandSoll = math.Max(dLo, dHi) + switch { + case mLo > 0 && mHi > 0: + res.MaxChangeSoll = math.Min(mLo, mHi) + case mLo > 0: + res.MaxChangeSoll = mLo + default: + res.MaxChangeSoll = mHi + } + return res +} + +// regulatorDeltas returns the output change and the net change of every step +// against the step before. A pair with a gap above the step gap cap is not valid. +func regulatorDeltas(pts []Step) (x, y []float64, valid []bool) { + n := len(pts) + x = make([]float64, n) + y = make([]float64, n) + valid = make([]bool, n) + for i := 1; i < n; i++ { + if pts[i].At-pts[i-1].At > stepGapCap { + continue + } + x[i] = float64(*pts[i].To - *pts[i-1].To) + y[i] = float64(pts[i].Net - pts[i-1].Net) + valid[i] = true + } + return x, y, valid +} + +// regulatorDeadTime returns the shift from 0 to regulatorMaxDead steps with +// the largest correlation between the output change and the later net change. +func regulatorDeadTime(x, y []float64, valid []bool) (int, bool) { + n := len(x) + best, bestR, found := 0, math.Inf(-1), false + for lag := 0; lag <= regulatorMaxDead; lag++ { + var xs, ys []float64 + for i := 1; i+lag < n; i++ { + if valid[i] && valid[i+lag] { + xs = append(xs, x[i]) + ys = append(ys, y[i+lag]) + } + } + r, ok := regulatorCorrelation(xs, ys) + if ok && r > bestR { + best, bestR, found = lag, r, true + } + } + return best, found +} + +// regulatorCorrelation returns the Pearson correlation, false without variance. +func regulatorCorrelation(xs, ys []float64) (float64, bool) { + n := float64(len(xs)) + if n < 2 { + return 0, false + } + var sx, sy float64 + for i := range xs { + sx += xs[i] + sy += ys[i] + } + mx, my := sx/n, sy/n + var cxy, cxx, cyy float64 + for i := range xs { + dx, dy := xs[i]-mx, ys[i]-my + cxy += dx * dy + cxx += dx * dx + cyy += dy * dy + } + if cxx == 0 || cyy == 0 { + return 0, false + } + return cxy / math.Sqrt(cxx*cyy), true +} + +// regulatorPairs returns the output changes whose net change d steps later is valid. +func regulatorPairs(x, y []float64, valid []bool, d int) []regulatorPair { + var out []regulatorPair + n := len(x) + for i := 1; i < n; i++ { + j := i + d + if !valid[i] || x[i] == 0 || j >= n || !valid[j] { + continue + } + out = append(out, regulatorPair{i: i, x: x[i], k: y[j] / x[i]}) + } + return out +} + +// regulatorBands returns per pair 0 for the lower PV band, 1 for the upper +// band and -1 when the PV or the best curve is unknown. +func regulatorBands(in *Input, pts []Step, pairs []regulatorPair, model PVModel, raster *Raster) []int { + bands := make([]int, len(pairs)) + for j := range bands { + bands[j] = -1 + } + if len(pts) == 0 { + return bands + } + site := in.Doc.Location + from := time.Unix(pts[0].At, 0).UTC().Truncate(time.Minute) + to := time.Unix(pts[len(pts)-1].At, 0).UTC().Add(time.Minute) + pv := in.Minutes.Range("b:pv", from, to) + for j, p := range pairs { + at := pts[p.i].At + m := int((at - pv.From.Unix()) / 60) + if m < 0 || m >= len(pv.Values) { + continue + } + val := float64(pv.Values[m]) + if math.IsNaN(val) { + continue + } + az, el := sun.Position(time.Unix(at, 0).UTC(), site.Lat, site.Lon) + best := model.Best(az, el, raster) + if best <= 0 { + continue + } + if val/best < regulatorBandShare { + bands[j] = 0 + } else { + bands[j] = 1 + } + } + return bands +} + +// regulatorNoise returns the noise of the net and the largest usual load +// jump: both are the 95th percentile of the net change without an output change, +// the noise halved. +func regulatorNoise(x, y []float64, valid []bool) (noise, jump float64) { + var diffs []float64 + for i := 1; i < len(x); i++ { + if valid[i] && x[i] == 0 { + diffs = append(diffs, math.Abs(y[i])) + } + } + jump = pvQuantile(diffs, 0.95) + return jump / 2, jump +} + +// regulatorStage returns the smallest output change in W of the pairs. +func regulatorStage(pairs []regulatorPair) float64 { + stage := math.Inf(1) + for _, p := range pairs { + stage = math.Min(stage, math.Abs(p.x)) + } + if math.IsInf(stage, 1) { + return 0 + } + return stage +} + +// regulatorMedianK returns the median of the absolute K of the pairs. +func regulatorMedianK(pairs []regulatorPair) float64 { + ks := make([]float64, 0, len(pairs)) + for _, p := range pairs { + ks = append(ks, math.Abs(p.k)) + } + return Median(ks) +} + +// regulatorFlips counts the sign changes of the output between valid changes. +func regulatorFlips(x []float64, valid []bool) float64 { + flips := 0.0 + prev := 0.0 + for i := 1; i < len(x); i++ { + if !valid[i] || x[i] == 0 { + continue + } + if prev != 0 && (x[i] > 0) != (prev > 0) { + flips++ + } + prev = x[i] + } + return flips +} + +// regulatorMedianGap returns the median gap between the steps in seconds. +func regulatorMedianGap(pts []Step) float64 { + gaps := make([]float64, 0, len(pts)) + for i := 1; i < len(pts); i++ { + if g := pts[i].At - pts[i-1].At; g > 0 { + gaps = append(gaps, float64(g)) + } + } + return Median(gaps) +} + +// regulatorCandidate builds the finding of a regulator whose gain swings or +// whose deadband or change limit differs from the target by more than the factor. +func regulatorCandidate(sc Scenario, res regulatorResult) (Candidate, bool) { + r := sc.Regulator + gain := r.Gain + if gain == 0 { + gain = regulatorDefaultGain + } + gainIst, gainSoll := gain, roundTo(res.GainSoll, 2) + var ops []Op + var bars []ScaleBar + if gain > regulatorSwingShare*res.GainSoll { + ops = append(ops, Op{Path: []any{"while", "regulator", "gain"}, Value: gainSoll}) + bars = append(bars, ScaleBar{Name: "gain", Ist: gainIst, Soll: gainSoll}) + } + if r.DeadbandW > regulatorDeadFactor*res.DeadbandSoll || r.DeadbandW < res.DeadbandSoll/regulatorDeadFactor { + soll := math.Round(res.DeadbandSoll) + ops = append(ops, Op{Path: []any{"while", "regulator", "deadband_w"}, Value: soll}) + bars = append(bars, ScaleBar{Name: "deadband_w", Ist: r.DeadbandW, Soll: soll, Unit: "W"}) + } + if res.MaxChangeSoll > 0 { + off := r.MaxChangeW == nil || *r.MaxChangeW > regulatorDeadFactor*res.MaxChangeSoll || *r.MaxChangeW < res.MaxChangeSoll/regulatorDeadFactor + if off { + soll := math.Max(1, math.Round(res.MaxChangeSoll)) + ops = append(ops, Op{Path: []any{"while", "regulator", "max_change_w"}, Value: soll}) + // Ist 0 stands for no change limit. + ist := 0.0 + if r.MaxChangeW != nil { + ist = *r.MaxChangeW + } + bars = append(bars, ScaleBar{Name: "max_change_w", Ist: ist, Soll: soll, Unit: "W"}) + } + } + if len(ops) == 0 { + return Candidate{}, false + } + name := sc.Name + if name == "" { + name = sc.ID + } + benefit := Benefit{} + finding := Finding{ + ID: FindingID("regulator", sc.ID), + Kind: "regulator", + Group: "check", + RuleIDs: []string{sc.ID}, + Severity: "info", + Confidence: "high", + Summary: Text{Code: "regulator.quality", Params: map[string]any{ + "scenario": name, "gain": gainIst, "gain_soll": gainSoll}}, + Evidence: Evidence{Shape: "scale", IstValue: &gainIst, SollValue: &gainSoll, Scales: bars}, + Facts: []Fact{ + {Code: "k", Value: roundTo(res.K, 2)}, + {Code: "dead_steps", Value: res.Dead}, + {Code: "flips_h", Value: roundTo(res.FlipsH, 1)}, + {Code: "settle_s", Value: math.Round(res.SettleS)}, + }, + Apply: []Fix{{Code: "set_regulator", RuleID: sc.ID, Ops: ops}}, + } + return Candidate{ + Finding: finding, + Detector: "regulator_quality", + NEff: res.Days, + MinNEff: 0, + Lower: 1, + Limit: 1, + HalvesAgree: true, + Benefit: benefit, + Values: map[string]float64{ + "gain": gainIst, "gain_soll": gainSoll, "k": res.K, "dead_steps": float64(res.Dead), + }, + }, true +} + +// roundTo rounds v to the given number of decimals. +func roundTo(v float64, decimals int) float64 { + p := math.Pow(10, float64(decimals)) + return math.Round(v*p) / p +} diff --git a/dashboard/internal/autolearn/detect_regulator_test.go b/dashboard/internal/autolearn/detect_regulator_test.go new file mode 100644 index 00000000..63a83e17 --- /dev/null +++ b/dashboard/internal/autolearn/detect_regulator_test.go @@ -0,0 +1,233 @@ +package autolearn + +import ( + "context" + "math" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// regTestSite is the site of the regulator tests, in daylight on the test day. +var regTestSite = sun.Location{Lat: 52.52, Lon: 13.405} + +// regTestModel is a roof model with one south facing surface. +func regTestModel() PVModel { + return PVModel{Surfaces: []Surface{{PMax: 6000, TiltDeg: 30, AzimuthDeg: 180}}, CapW: 6000, Safe: true} +} + +// regTestMinutes returns a minute record whose b:pv equals the best curve of +// the model on the test day, so every step sits in the upper PV band. +func regTestMinutes(model PVModel, day time.Time) fakeMinutes { + vals := make([]float32, 1440) + for m := range vals { + t := day.Add(time.Duration(m) * time.Minute) + az, el := sun.Position(t, regTestSite.Lat, regTestSite.Lon) + vals[m] = float32(model.Best(az, el, nil)) + } + return fakeMinutes{loc: time.UTC, days: map[string]map[string][]float32{ + day.Format(dayLayout): {"b:pv": vals}, + }} +} + +// regTestSteps builds n regulator steps 10 s apart. The output To moves by +// pseudo random steps of 10 or 20 W. The net changes by kOf(i-d) times the +// output change of step i-d, so the dead time of the plant is d steps. +func regTestSteps(start time.Time, n, d int, kOf func(i int) float64) []Step { + to := make([]float64, n) + seed := uint32(7) + cur := 500.0 + for i := range to { + seed = seed*1103515245 + 12345 + step := []float64{-20, -10, 10, 20}[(seed>>16)%4] + if i > 0 { + cur += step + } + to[i] = cur + } + net := make([]float64, n) + net[0] = 1000 + for i := 1; i < n; i++ { + dNet := 0.0 + if j := i - d; j >= 1 { + dNet = kOf(j) * (to[j] - to[j-1]) + } + net[i] = net[i-1] + dNet + } + out := make([]Step, n) + for i := range out { + v := float32(to[i]) + out[i] = Step{At: start.Add(time.Duration(i) * 10 * time.Second).Unix(), Net: float32(net[i]), To: &v, Why: StepSent} + } + return out +} + +// regTestInput wires the steps of one scenario, the minutes and the model. +func regTestInput(steps []Step, now time.Time, reg *RegulatorSpec) *Input { + model := regTestModel() + day := time.Date(2026, 11, 22, 0, 0, 0, 0, time.UTC) + site := regTestSite + return &Input{ + Now: now, + Loc: time.UTC, + Doc: Doc{Location: &site, Scenarios: []Scenario{{ID: "reg", Name: "Regler", Enabled: true, Regulator: reg}}}, + PV: func() (PVModel, *Raster, bool) { + return model, nil, true + }, + Minutes: regTestMinutes(model, day), + Steps: func(scenario string, from, to time.Time) []Step { + if scenario != "reg" { + return nil + } + return steps + }, + } +} + +// regTestNow is the end of the test steps, in daylight on the test day. +func regTestNow(n int) time.Time { + return time.Date(2026, 11, 22, 9, 0, 0, 0, time.UTC).Add(time.Duration(n) * 10 * time.Second) +} + +func regTestStart(n int) time.Time { + return regTestNow(n).Add(-time.Duration(n) * 10 * time.Second) +} + +func regTestOne(t *testing.T, in *Input) []Candidate { + t.Helper() + return regulatorRun(context.Background(), in, "") +} + +func constK(k float64) func(int) float64 { + return func(int) float64 { return k } +} + +func TestRegulatorDetectsOscillation(t *testing.T) { + const n = 400 + steps := regTestSteps(regTestStart(n), n, 1, constK(1)) + in := regTestInput(steps, regTestNow(n), &RegulatorSpec{DeadbandW: 20, Gain: 0.8, BaseSource: "last"}) + cands := regTestOne(t, in) + if len(cands) != 1 { + t.Fatalf("candidates = %d, want 1 for a gain of 0.8 with a dead time of one step", len(cands)) + } + f := cands[0].Finding + if f.ID != "regulator:reg" || f.Group != "check" || f.Severity != "info" { + t.Fatalf("finding = %+v, want regulator:reg in group check with severity info", f) + } + var gain *float64 + for _, op := range f.Apply[0].Ops { + if len(op.Path) == 3 && op.Path[2] == "gain" { + v := op.Value.(float64) + gain = &v + } + } + if gain == nil || math.Abs(*gain-0.2) > 1e-9 { + t.Fatalf("gain op = %v, want 0.2 (0.8 * 1/4 * 1)", gain) + } +} + +func TestRegulatorWithoutDeadTimeKeepsTheGain(t *testing.T) { + const n = 400 + steps := regTestSteps(regTestStart(n), n, 0, constK(1)) + in := regTestInput(steps, regTestNow(n), &RegulatorSpec{DeadbandW: 20, Gain: 0.8, BaseSource: "last"}) + res, ok := regulatorEval(in, in.Doc.Scenarios[0], steps) + if !ok { + t.Fatal("no evaluation for a clean plant with 400 steps") + } + if math.Abs(res.GainSoll-0.8) > 1e-9 { + t.Fatalf("gain soll = %v, want 0.8 for a dead time of zero", res.GainSoll) + } + if len(regTestOne(t, in)) != 0 { + t.Fatal("a gain of 0.8 at the limit must not be reported") + } +} + +func TestRegulatorNeedsTwoHundredChanges(t *testing.T) { + const n = 150 + steps := regTestSteps(regTestStart(n), n, 1, constK(1)) + in := regTestInput(steps, regTestNow(n), &RegulatorSpec{DeadbandW: 20, Gain: 0.8, BaseSource: "last"}) + if got := regTestOne(t, in); len(got) != 0 { + t.Fatalf("candidates = %d, want 0 with 150 steps", len(got)) + } +} + +func TestRegulatorSkipsScatteredGain(t *testing.T) { + const n = 400 + alt := func(i int) float64 { + if i%2 == 0 { + return 1.0 + } + return 1.5 + } + steps := regTestSteps(regTestStart(n), n, 1, alt) + in := regTestInput(steps, regTestNow(n), &RegulatorSpec{DeadbandW: 20, Gain: 0.8, BaseSource: "last"}) + if got := regTestOne(t, in); len(got) != 0 { + t.Fatalf("candidates = %d, want 0 when K scatters by 40 %%", len(got)) + } +} + +func TestRegulatorMeasuredBaseOnlyRatesDeadTime(t *testing.T) { + const n = 400 + steps := regTestSteps(regTestStart(n), n, 1, constK(1)) + in := regTestInput(steps, regTestNow(n), &RegulatorSpec{DeadbandW: 20, Gain: 0.8, BaseSource: "balance"}) + res, ok := regulatorEval(in, in.Doc.Scenarios[0], steps) + if !ok || !res.Measured { + t.Fatalf("eval = %+v, ok %v, want a measured result", res, ok) + } + if res.Dead != 1 { + t.Fatalf("dead steps = %d, want 1", res.Dead) + } + if res.GainSoll != 0 { + t.Fatalf("gain soll = %v, want none for a measured base", res.GainSoll) + } + if len(regTestOne(t, in)) != 0 { + t.Fatal("a measured base must not produce a gain finding") + } +} + +func TestRegulatorSkipsWithoutPVModel(t *testing.T) { + const n = 400 + steps := regTestSteps(regTestStart(n), n, 1, constK(1)) + in := regTestInput(steps, regTestNow(n), &RegulatorSpec{DeadbandW: 20, Gain: 0.8, BaseSource: "last"}) + in.PV = nil + if got := regTestOne(t, in); len(got) != 0 { + t.Fatalf("candidates = %d, want 0 without a PV model", len(got)) + } +} + +func TestRegulatorScaleBarsOnlyForChangedParameters(t *testing.T) { + maxChange := 100.0 + res := regulatorResult{GainSoll: 0.2, DeadbandSoll: 10, MaxChangeSoll: 5, K: 1, Dead: 1, Days: 3} + reg := &RegulatorSpec{DeadbandW: 50, Gain: 0.8, MaxChangeW: &maxChange, BaseSource: "last"} + cand, ok := regulatorCandidate(Scenario{ID: "reg", Name: "Regler", Regulator: reg}, res) + if !ok { + t.Fatal("no candidate for a swinging gain, a wide deadband and a loose change limit") + } + bars := cand.Finding.Evidence.Scales + if len(bars) != 3 { + t.Fatalf("bars = %+v, want gain, deadband_w and max_change_w", bars) + } + if bars[0].Name != "gain" || bars[0].Ist != 0.8 || math.Abs(bars[0].Soll-0.2) > 1e-9 { + t.Errorf("gain bar = %+v, want ist 0.8 soll 0.2", bars[0]) + } + if bars[1].Name != "deadband_w" || bars[1].Ist != 50 || bars[1].Soll != 10 || bars[1].Unit != "W" { + t.Errorf("deadband bar = %+v, want ist 50 soll 10 W", bars[1]) + } + if bars[2].Name != "max_change_w" || bars[2].Ist != 100 || bars[2].Soll != 5 { + t.Errorf("change bar = %+v, want ist 100 soll 5", bars[2]) + } +} + +func TestRegulatorScaleBarsSkipUnchangedGain(t *testing.T) { + res := regulatorResult{GainSoll: 0.8, DeadbandSoll: 20, K: 1, Dead: 0, Days: 3} + reg := &RegulatorSpec{DeadbandW: 50, Gain: 0.8, BaseSource: "last"} + cand, ok := regulatorCandidate(Scenario{ID: "reg", Regulator: reg}, res) + if !ok { + t.Fatal("no candidate for a wide deadband") + } + bars := cand.Finding.Evidence.Scales + if len(bars) != 1 || bars[0].Name != "deadband_w" { + t.Fatalf("bars = %+v, want only the deadband bar", bars) + } +} diff --git a/dashboard/internal/autolearn/detect_shift.go b/dashboard/internal/autolearn/detect_shift.go new file mode 100644 index 00000000..8b619590 --- /dev/null +++ b/dashboard/internal/autolearn/detect_shift.go @@ -0,0 +1,411 @@ +package autolearn + +import ( + "context" + "encoding/json" + "fmt" + "math" + "sort" + "time" +) + +// ShiftDetector suggests starting a switchable load in the surplus of the day +// when it runs from the grid (spec 15.6 "Lastverschiebung"). A run counts when +// more than half of its energy came from the grid. It is movable when the +// surplus of the same day held its power for its whole run, after the runs +// that already took surplus. Surplus is shared by the switchable devices in +// the order of their grid energy, so a stretch counts once. The device is only +// proposed when its start times spread, a device that always starts at the same +// minute is a habit and not a shiftable load. +var ShiftDetector = Detector{ + Name: "load_shift", + Group: "energy", + Light: false, + PerDevice: true, + Run: shiftRunFor, +} + +const ( + // shiftMinRuns is the number of grid runs from which a suggestion is safe. + shiftMinRuns = 8 + // shiftLimit is the Wilson lower bound of the movable share. + shiftLimit = 0.5 + // shiftGridShare is the share of a run's energy from the grid that makes it a grid run. + shiftGridShare = 0.5 + // shiftSpreadMin is the spread of the start times in minutes above which a device is movable. + shiftSpreadMin = 60.0 + // shiftLatestPct is the percentile of the start times that sets the latest start. + // The plan gives the value 75, read as the percentile. + shiftLatestPct = 0.75 + // shiftLatestStepMin rounds the latest start. + shiftLatestStepMin = 15 + // shiftRoundW rounds the surplus threshold. + shiftRoundW = 100.0 + // shiftHoldS is the hold of the surplus condition in seconds, as the template sets it. + shiftHoldS = 120 + // shiftQuarterS is the length of a quarter hour in seconds. + shiftQuarterS = 900 + // shiftReplayDays is the number of days the replay check reads. + shiftReplayDays = 14 +) + +// shiftScopeDay is one day the detector reads: the surplus per quarter hour and +// the quarters the day has a measurement for. +type shiftScopeDay struct { + date string + seen [dayQuarters]bool + surplus [dayQuarters]float64 +} + +// shiftRun is one finished cycle of a device on a day of the scope. +type shiftRun struct { + device string + day int + q0, dur int + startMin float64 + durS int + grid float64 + heavy bool + claimant bool + opW float64 + claimed bool +} + +// shiftRunFor returns the shift suggestion of one device, if it is movable and +// safe. The other switchable devices decide on the same surplus, so the run is +// allocated for all of them first. +func shiftRunFor(ctx context.Context, in *Input, device string) []Candidate { + if ctx.Err() != nil { + return nil + } + info, ok := in.Devices[device] + if !ok || !info.Switchable || len(info.Entities) == 0 { + return nil + } + loc := in.Loc + if loc == nil { + loc = time.Local + } + days, runs := shiftAllocate(in, loc) + + var starts, opW, runDur, claimedDur []float64 + n, k := 0, 0 + heavyDay := make([]int, len(days)) + claimedDay := make([]int, len(days)) + for i := range runs { + r := &runs[i] + if r.device != device { + continue + } + starts = append(starts, r.startMin) + opW = append(opW, r.opW) + runDur = append(runDur, float64(r.durS)) + if r.heavy { + n++ + heavyDay[r.day]++ + } + if r.claimed { + k++ + claimedDay[r.day]++ + claimedDur = append(claimedDur, float64(r.durS)) + } + } + if n < shiftMinRuns { + return nil + } + center := CircMedian(starts) + spread := CircSpread(starts, center) + if spread <= shiftSpreadMin { + return nil + } + lower := WilsonLower(k, n) + if lower < shiftLimit { + return nil + } + agree := shiftHalvesAgree(heavyDay, claimedDay) + + var claimedWh float64 + for i := range runs { + if runs[i].device == device && runs[i].claimed { + claimedWh += runs[i].grid + } + } + weeks := math.Max(1, float64(len(days))/7) + benefit := Benefit{Unit: "kwh_week", Value: claimedWh / 1000 / weeks} + + p := Median(opW) + if p <= 0 { + return nil + } + onW := math.Max(shiftRoundW, math.Round(p/shiftRoundW)*shiftRoundW) + runS := int(Median(claimedDur)) + if len(claimedDur) == 0 { + runS = int(Median(runDur)) + } + latest := shiftLatest(starts) + latestClock := shiftClock(latest) + peak := Median(shiftPeaks(in, device)) + if peak <= 0 { + peak = p + } + cycleWhMed := Median(shiftWh(in, device)) + + conf := "estimate" + if agree { + conf = "high" + } + id := "shift:" + device + finding := Finding{ + ID: id, + Kind: "load_shift", + Group: "energy", + Severity: "info", + Confidence: conf, + Summary: Text{Code: "shift.load", Params: map[string]any{ + "device": device, "kwh": math.Round(benefit.Value*10) / 10, "latest": latestClock, "runs": n}}, + Evidence: Evidence{Shape: "curve", From: 0, To: int64(minutesPerDay), Quarters: shiftTypicalDay(days)}, + Facts: []Fact{ + {Code: "spread_min", Value: math.Round(spread)}, + {Code: "hit_rate", Value: float64(k) / float64(n)}, + }, + Apply: []Fix{{Code: "shift_start", Template: "shift_start", Prefill: map[string]any{ + "device": device, "on_w": onW, "latest": latestClock, "min_run_s": runS}}}, + Device: device, + Benefit: &benefit, + } + cand := Candidate{ + Finding: finding, + Detector: "load_shift", + NEff: float64(n), + MinNEff: shiftMinRuns, + Lower: lower, + Limit: shiftLimit, + HalvesAgree: agree, + Benefit: benefit, + Values: map[string]float64{"hit_rate": float64(k) / float64(n), "latest": float64(latest)}, + } + if verdict, err := shiftReplay(ctx, in, device, id, onW, latest, p, peak, cycleWhMed, runS); err == nil && verdict != nil { + cand.Replay = verdict + } + return []Candidate{cand} +} + +// shiftAllocate reads the scope days and the cycles of all devices. Runs that +// took the surplus on their own are taken off the surplus first. Then the grid +// runs of the switchable devices claim a stretch of their length in the day, by +// grid energy in descending order. A claimed stretch counts once. +func shiftAllocate(in *Input, loc *time.Location) ([]shiftScopeDay, []shiftRun) { + files := make([]*DayFile, 0, len(in.Days)) + for i := range in.Days { + if !in.Base.Away[in.Days[i].Day] { + files = append(files, &in.Days[i]) + } + } + sort.SliceStable(files, func(a, b int) bool { return files[a].Day < files[b].Day }) + + opByDevice := map[string][]float64{} + for _, f := range files { + for _, c := range f.Cycles { + if c.Wh > 0 && c.OpW > 0 { + opByDevice[c.Device] = append(opByDevice[c.Device], float64(c.OpW)) + } + } + } + var days []shiftScopeDay + var runs []shiftRun + for _, f := range files { + t, err := time.ParseInLocation(dayLayout, f.Day, loc) + if err != nil { + continue + } + d := shiftScopeDay{date: f.Day} + _, without := surWinSeries(in, f, t) + for q := 0; q < dayQuarters; q++ { + d.seen[q] = f.Site.Seen[q] != 0 + if d.seen[q] { + d.surplus[q] = without[q] + } + } + days = append(days, d) + dayIdx := len(days) - 1 + + var taken [dayQuarters]float64 + var claimants []int + for _, c := range f.Cycles { + if c.Wh <= 0 || c.DurS <= 0 { + continue + } + at := time.Unix(c.Start, 0).In(loc) + r := shiftRun{ + device: c.Device, + day: dayIdx, + q0: at.Hour()*4 + at.Minute()/15, + dur: max(1, int(math.Ceil(float64(c.DurS)/shiftQuarterS))), + startMin: float64(at.Hour()*60 + at.Minute()), + durS: c.DurS, + grid: float64(c.Wh) * float64(c.Grid), + heavy: float64(c.Grid) > shiftGridShare, + opW: float64(c.OpW), + } + r.claimant = r.heavy && in.Devices[c.Device].Switchable + runs = append(runs, r) + idx := len(runs) - 1 + if r.claimant { + claimants = append(claimants, idx) + } else { + shiftMark(&taken, r.q0, r.dur, r.opW) + } + } + + sort.SliceStable(claimants, func(a, b int) bool { + ra, rb := runs[claimants[a]], runs[claimants[b]] + if ra.grid != rb.grid { + return ra.grid > rb.grid + } + if ra.startMin != rb.startMin { + return ra.startMin < rb.startMin + } + return ra.device < rb.device + }) + for _, idx := range claimants { + r := &runs[idx] + pw := Median(opByDevice[r.device]) + if pw <= 0 { + continue + } + for s := 0; s+r.dur <= dayQuarters; s++ { + if !shiftFree(&d.surplus, &taken, s, r.dur, pw) { + continue + } + shiftMark(&taken, s, r.dur, pw) + r.claimed = true + break + } + } + } + return days, runs +} + +// shiftFree reports whether the surplus minus what is taken holds pw for the +// quarters from s up to s + dur. +func shiftFree(surplus, taken *[dayQuarters]float64, s, dur int, pw float64) bool { + for q := s; q < s+dur; q++ { + if surplus[q]-taken[q] < pw { + return false + } + } + return true +} + +// shiftMark adds w to the taken power of the quarters from q0 up to q0 + dur. +func shiftMark(taken *[dayQuarters]float64, q0, dur int, w float64) { + for q := q0; q < q0+dur && q < dayQuarters; q++ { + taken[q] += w + } +} + +// shiftHalvesAgree reports whether the first and the second half of the days +// both have grid runs, and in each the claimed share is at least one half. +func shiftHalvesAgree(heavy, claimed []int) bool { + half := len(heavy) / 2 + agree := true + for _, part := range [][2]int{{0, half}, {half, len(heavy)}} { + n, k := 0, 0 + for d := part[0]; d < part[1]; d++ { + n += heavy[d] + k += claimed[d] + } + if n == 0 || 2*k < n { + agree = false + } + } + return agree +} + +// shiftLatest returns the latest start in minutes of the day: the percentile of +// the start times, rounded to shiftLatestStepMin. +func shiftLatest(starts []float64) int { + s := append([]float64(nil), starts...) + sort.Float64s(s) + idx := int(math.Ceil(shiftLatestPct*float64(len(s)))) - 1 + idx = min(max(idx, 0), len(s)-1) + m := int(math.Round(s[idx]/shiftLatestStepMin)) * shiftLatestStepMin + return min(max(m, 0), dayQuarters*15-shiftLatestStepMin) +} + +// shiftClock formats minutes of the day as HH:MM. +func shiftClock(m int) string { + return fmt.Sprintf("%02d:%02d", m/60%24, m%60) +} + +// shiftTypicalDay is the median surplus per quarter over the days that have the +// quarter, the curve of a typical day. +func shiftTypicalDay(days []shiftScopeDay) []float32 { + out := make([]float32, dayQuarters) + for q := 0; q < dayQuarters; q++ { + var xs []float64 + for i := range days { + if days[i].seen[q] { + xs = append(xs, days[i].surplus[q]) + } + } + out[q] = float32(Median(xs)) + } + return out +} + +// shiftPeaks returns the start peaks of the device cycles in the scope. +func shiftPeaks(in *Input, device string) []float64 { + var out []float64 + for i := range in.Days { + for _, c := range in.Days[i].Cycles { + if c.Device == device && c.PeakW > 0 { + out = append(out, float64(c.PeakW)) + } + } + } + return out +} + +// shiftWh returns the energy of the device cycles in Wh. +func shiftWh(in *Input, device string) []float64 { + var out []float64 + for i := range in.Days { + for _, c := range in.Days[i].Cycles { + if c.Device == device && c.Wh > 0 { + out = append(out, float64(c.Wh)) + } + } + } + return out +} + +// shiftReplay checks the proposed rule by replay: the surplus starts the device +// before the latest start. A rule that cannot be replayed, or a replay without +// minutes, leaves the candidate without a replay. +func shiftReplay(ctx context.Context, in *Input, device, id string, onW float64, latest int, p, peak, cycleWh float64, runS int) (*ReplayVerdict, error) { + if in.Doc.Location == nil { + return nil, nil + } + rule := map[string]any{"id": id, "enabled": true, "conditions": []map[string]any{ + {"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": onW, "hold_seconds": shiftHoldS}, + {"type": "time_window", "start": "00:00", "end": shiftClock(latest), "weekdays": []int{}}, + }} + loc := in.Loc + if loc == nil { + loc = time.Local + } + raw, err := json.Marshal(rule) + if err != nil { + return nil, err + } + chk := ReplayCheck{ + Rule: json.RawMessage(raw), + Target: ReplayTarget{RuleID: id, Device: device, OpW: p, PeakW: peak, CycleWh: cycleWh, MinRunS: float64(runS)}, + } + verdict, _, err := EvaluateReplay(ctx, in, chk, shiftReplayDays, loc, *in.Doc.Location) + if ctx.Err() != nil { + return nil, ctx.Err() + } + return verdict, err +} diff --git a/dashboard/internal/autolearn/detect_shift_test.go b/dashboard/internal/autolearn/detect_shift_test.go new file mode 100644 index 00000000..31c4fcef --- /dev/null +++ b/dashboard/internal/autolearn/detect_shift_test.go @@ -0,0 +1,163 @@ +package autolearn + +import ( + "context" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/energy" +) + +// shiftTDay builds a day with every quarter seen. The grid export is surW in the +// quarters from fromQ up to toQ, zero elsewhere. +func shiftTDay(day string, fromQ, toQ int, surW float32, cycles []CycleRec) DayFile { + f := DayFile{V: 1, Day: day, Cycles: cycles} + for q := 0; q < dayQuarters; q++ { + f.Site.Seen[q] = 1 + if q >= fromQ && q < toQ { + f.Site.GridExport[q] = surW + } + } + return f +} + +// shiftTCycle is a finished cycle that started at minute of the day of the file. +func shiftTCycle(t *testing.T, loc *time.Location, day string, minute int, device string, durMin int, wh, opW, grid float32) CycleRec { + t.Helper() + d, err := time.ParseInLocation(dayLayout, day, loc) + if err != nil { + t.Fatal(err) + } + at := d.Add(time.Duration(minute) * time.Minute) + return CycleRec{Device: device, Start: at.Unix(), DurS: durMin * 60, Wh: wh, OpW: opW, PeakW: opW * 1.2, Grid: grid} +} + +// shiftTDays returns n days from 2026-11-08 on, built by fn(i, day). +func shiftTDays(n int, loc *time.Location, fn func(i int, day string) DayFile) []DayFile { + first := time.Date(2026, 11, 8, 0, 0, 0, 0, loc) + var out []DayFile + for i := 0; i < n; i++ { + out = append(out, fn(i, first.AddDate(0, 0, i).Format(dayLayout))) + } + return out +} + +// shiftTInput builds the input with the given days and switchable devices. +func shiftTInput(t *testing.T, days []DayFile, devices ...string) *Input { + t.Helper() + loc := berlinLoc(t) + devs := map[string]DeviceInfo{} + for _, id := range devices { + devs[id] = DeviceInfo{ID: id, Role: energy.RoleSwitch, Switchable: true, Entities: []string{"switch." + id}} + } + return &Input{ + Now: time.Date(2026, 11, 22, 8, 0, 0, 0, loc), + Loc: loc, + Days: days, + Doc: Doc{Location: shadeSite}, + Devices: devs, + } +} + +// shiftTWash gives a washing machine that runs in the evening from the grid, +// with its start spread over about four hours. The surplus of 3000 W lies at +// noon for four hours. +func shiftTWash(t *testing.T, loc *time.Location, n int) []DayFile { + return shiftTDays(n, loc, func(i int, day string) DayFile { + c := shiftTCycle(t, loc, day, 1020+24*(i%10), "wash", 120, 1000, 2000, 0.9) + return shiftTDay(day, 44, 60, 3000, []CycleRec{c}) + }) +} + +// TestShiftSuggestsGridCyclesMovableToSurplus: the washing machine runs in the +// evening from the grid while the surplus is there at noon. +func TestShiftSuggestsGridCyclesMovableToSurplus(t *testing.T) { + loc := berlinLoc(t) + in := shiftTInput(t, shiftTWash(t, loc, 10), "wash") + cands := ShiftDetector.Run(context.Background(), in, "wash") + if len(cands) != 1 { + t.Fatalf("want one suggestion, got %d", len(cands)) + } + c := cands[0] + if c.Finding.ID != "shift:wash" { + t.Fatalf("ID = %q, want shift:wash", c.Finding.ID) + } + if len(c.Finding.Apply) != 1 || c.Finding.Apply[0].Template != "shift_start" { + t.Fatalf("apply = %+v, want the shift_start template", c.Finding.Apply) + } + p := c.Finding.Apply[0].Prefill + if p["device"] != "wash" { + t.Errorf("prefill device = %v, want wash", p["device"]) + } + if _, ok := p["entity"]; ok { + t.Errorf("prefill carries an entity %v, want none: the first entity is not a safe switch", p["entity"]) + } + if p["on_w"] != 2000.0 { + t.Errorf("prefill on_w = %v, want 2000", p["on_w"]) + } + if p["latest"] != "19:45" { + t.Errorf("prefill latest = %v, want 19:45", p["latest"]) + } + if c.Finding.Benefit == nil || c.Finding.Benefit.Unit != "kwh_week" || c.Finding.Benefit.Value <= 0 { + t.Errorf("benefit = %+v, want a positive kwh_week", c.Finding.Benefit) + } + if c.Replay == nil { + t.Errorf("replay = nil, want a replay verdict") + } +} + +// TestShiftFixedStartNoSuggestion: a device that always starts at 07:00 has no +// spread of start times, so it is a habit and not a shiftable load. +func TestShiftFixedStartNoSuggestion(t *testing.T) { + loc := berlinLoc(t) + days := shiftTDays(10, loc, func(i int, day string) DayFile { + c := shiftTCycle(t, loc, day, 420, "wash", 120, 1000, 2000, 0.9) + return shiftTDay(day, 44, 60, 3000, []CycleRec{c}) + }) + in := shiftTInput(t, days, "wash") + if cands := ShiftDetector.Run(context.Background(), in, "wash"); len(cands) != 0 { + t.Fatalf("fixed start: want no suggestion, got %d", len(cands)) + } +} + +// TestShiftCompetitionGoesToMoreGridEnergy: one surplus window of one hour fits +// only one of two devices. The dryer takes more grid energy and gets it. +func TestShiftCompetitionGoesToMoreGridEnergy(t *testing.T) { + loc := berlinLoc(t) + days := shiftTDays(10, loc, func(i int, day string) DayFile { + start := 1020 + 24*(i%10) + dryer := shiftTCycle(t, loc, day, start, "dryer", 60, 2000, 2000, 1.0) + wash := shiftTCycle(t, loc, day, start, "wash", 30, 1000, 2000, 0.9) + return shiftTDay(day, 48, 52, 3000, []CycleRec{dryer, wash}) + }) + in := shiftTInput(t, days, "dryer", "wash") + if cands := ShiftDetector.Run(context.Background(), in, "wash"); len(cands) != 0 { + t.Fatalf("wash: want no suggestion, got %d", len(cands)) + } + cands := ShiftDetector.Run(context.Background(), in, "dryer") + if len(cands) != 1 || cands[0].Finding.ID != "shift:dryer" { + t.Fatalf("dryer: want shift:dryer, got %d candidates", len(cands)) + } +} + +// TestShiftNeedsEightRuns: six runs are not enough for a safe suggestion. +func TestShiftNeedsEightRuns(t *testing.T) { + loc := berlinLoc(t) + in := shiftTInput(t, shiftTWash(t, loc, 6), "wash") + if cands := ShiftDetector.Run(context.Background(), in, "wash"); len(cands) != 0 { + t.Fatalf("6 runs: want no suggestion, got %d", len(cands)) + } +} + +// TestShiftNoSurplusNoSuggestion: without surplus on the day the runs cannot move. +func TestShiftNoSurplusNoSuggestion(t *testing.T) { + loc := berlinLoc(t) + days := shiftTDays(10, loc, func(i int, day string) DayFile { + c := shiftTCycle(t, loc, day, 1020+24*(i%10), "wash", 120, 1000, 2000, 0.9) + return shiftTDay(day, 0, 0, 0, []CycleRec{c}) + }) + in := shiftTInput(t, days, "wash") + if cands := ShiftDetector.Run(context.Background(), in, "wash"); len(cands) != 0 { + t.Fatalf("no surplus: want no suggestion, got %d", len(cands)) + } +} diff --git a/dashboard/internal/autolearn/detect_surplus.go b/dashboard/internal/autolearn/detect_surplus.go new file mode 100644 index 00000000..639565a0 --- /dev/null +++ b/dashboard/internal/autolearn/detect_surplus.go @@ -0,0 +1,448 @@ +package autolearn + +import ( + "context" + "encoding/json" + "fmt" + "math" + "sort" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/energy" + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// SurplusDetector suggests running a load in the typical surplus window of the +// day (spec 15.6 "Ueberschussfenster"). The surplus of a quarter hour is grid +// export plus PV reserve plus battery charge above 200 W. The window is the +// longest run of quarter hours in which the surplus reaches the operating +// power plus the reserve on at least half of the days by the Wilson bound. +var SurplusDetector = Detector{ + Name: "surplus_window", + Group: "energy", + Light: false, + PerDevice: true, + Run: surWinWindowRun, +} + +const ( + // surWinWindowDays is the number of recent days the window reads. + surWinWindowDays = 14 + // surWinWindowLimit is the Wilson lower bound a quarter hour needs. + surWinWindowLimit = 0.5 + // surWinWindowMinNEff is the minimum effective number of days. + surWinWindowMinNEff = 10.0 + // surWinWindowMinReserveDays is the number of days the reserve must make + // the window, from the last surWinWindowDays days. + surWinWindowMinReserveDays = 5 + // surWinReserveMarginW is the reserve added to the start peak and the + // operating power. The spec gives no number, the value is an assumption. + surWinReserveMarginW = 200.0 + // surWinBatteryFloorW is the battery charge that counts as surplus. + surWinBatteryFloorW = 200.0 + // surWinRoundW rounds the proposed threshold. + surWinRoundW = 100.0 + // surWinHoldS is the hold of the on condition in seconds, as the templates set it. + surWinHoldS = 120 + // surWinReserveKey is the learned key of the PV reserve. + surWinReserveKey = "site/pv_reserve_w" +) + +// surWinDay is one day the window reads: the surplus per quarter hour with +// and without the PV reserve, and the quarters the day has a measurement for. +type surWinDay struct { + date string + weight float64 + seen [dayQuarters]bool + with [dayQuarters]float64 + without [dayQuarters]float64 +} + +// surWinWindowRun finds the surplus window of one device and proposes a rule +// that switches it on there. It needs the learned operating power and the +// cycle energy of the device, and it stays silent when a rule already switches +// the device on surplus. +func surWinWindowRun(ctx context.Context, in *Input, device string) []Candidate { + if ctx.Err() != nil { + return nil + } + p, ok := learnedOperatingPower(in.Learned, device) + if !ok { + return nil + } + cycle, ok := surWinLearnedNumber(in.Learned, "device/"+device+"/cycle_wh") + if !ok || cycle <= 0 { + return nil + } + if surWinHasRule(in, device) { + return nil + } + days := surWinDays(in) + if len(days) == 0 { + return nil + } + weights := make([]float64, 0, len(days)) + for _, d := range days { + weights = append(weights, d.weight) + } + neff := NEff(weights) + if neff < surWinWindowMinNEff { + return nil + } + need := int(math.Ceil(cycle / p * 4)) + if need < 1 { + return nil + } + threshold := p + surWinReserveMarginW + + pickExport := func(d *surWinDay) *[dayQuarters]float64 { return &d.without } + pickReserve := func(d *surWinDay) *[dayQuarters]float64 { return &d.with } + source := "export" + pick := pickExport + start, n, lower, rate := surWinLongestWindow(days, threshold, pickExport) + if n < need { + start2, n2, lower2, rate2 := surWinLongestWindow(days, threshold, pickReserve) + if n2 < need || !surWinReserveHelps(days, threshold, need) { + return nil + } + source = "reserve" + pick = pickReserve + start, n, lower, rate = start2, n2, lower2, rate2 + } + return []Candidate{surWinCandidate(ctx, in, device, p, cycle, source, start, n, lower, rate, days, neff, pick)} +} + +// surWinCurve is the typical surplus per quarter hour of the day in W: the +// median over the days that have the quarter, computed on the same series that +// found the window. Quarters without data stay 0. +func surWinCurve(days []surWinDay, pick func(*surWinDay) *[dayQuarters]float64) []float32 { + out := make([]float32, dayQuarters) + for q := 0; q < dayQuarters; q++ { + var xs []float64 + for i := range days { + if days[i].seen[q] { + xs = append(xs, pick(&days[i])[q]) + } + } + out[q] = float32(Median(xs)) + } + return out +} + +// surWinTarget is the switch on power per quarter hour: on_w inside the window, +// 0 outside, so the target block shows the window as a step. +func surWinTarget(start, n int, onW float64) []float32 { + out := make([]float32, dayQuarters) + for q := start; q < start+n && q < dayQuarters; q++ { + out[q] = float32(onW) + } + return out +} + +// surWinCandidate builds the finding for the window and checks it by replay. +func surWinCandidate(ctx context.Context, in *Input, device string, p, cycle float64, source string, start, n int, lower, rate float64, days []surWinDay, neff float64, pick func(*surWinDay) *[dayQuarters]float64) Candidate { + peak := feedbackInrush(in.Days, device, p) + onW := math.Round((peak+surWinReserveMarginW)/surWinRoundW) * surWinRoundW + runS := int(cycle / p * 3600) + code := "surplus_switch" + if in.Devices[device].Role == energy.RoleWallbox { + code = "surplus_wallbox" + } + id := "surplus:" + device + clockFrom, clockTo := surWinClock(start), surWinClock(start+n) + + benefit := Benefit{Unit: "kwh_week", Value: cycle / 1000 * rate * 7} + conf := "high" + if len(days) < surWinWindowDays { + conf = "estimate" + } + prefill := map[string]any{"device": device, "on_w": onW, "source": source, "min_run_s": runS} + finding := Finding{ + ID: id, + Kind: "surplus_window", + Group: "energy", + Severity: "info", + Confidence: conf, + Summary: Text{Code: "surplus.window", Params: map[string]any{ + "device": device, "on_w": onW, "from": clockFrom, "to": clockTo, "days": len(days)}}, + Evidence: Evidence{Shape: "curve", From: int64(start * 15), To: int64((start + n) * 15), Soll: []int64{int64(onW)}, + Quarters: surWinCurve(days, pick), SollQ: surWinTarget(start, n, onW)}, + Facts: []Fact{ + {Code: "window_min", Value: n * 15}, + {Code: "run_min", Value: runS / 60}, + {Code: "source", Value: source}, + }, + Apply: []Fix{{Code: code, Template: code, Prefill: prefill}}, + Device: device, + Benefit: &benefit, + } + if source == "reserve" { + finding.Summary.Code = "surplus.reserve" + } + cand := Candidate{ + Finding: finding, + Detector: "surplus_window", + NEff: neff, + MinNEff: surWinWindowMinNEff, + Lower: lower, + Limit: surWinWindowLimit, + HalvesAgree: true, + Benefit: benefit, + Values: map[string]float64{"window_quarters": float64(n), "on_w": onW}, + } + if verdict, b, err := surWinReplay(ctx, in, device, id, onW, source, p, peak, cycle, runS); err == nil && verdict != nil { + cand.Replay = verdict + cand.Benefit = b + finding.Benefit = &b + cand.Finding = finding + } + return cand +} + +// surWinReplay checks the proposed rule by replay. A rule that cannot be +// replayed, or a replay without minutes, leaves the candidate without a replay. +func surWinReplay(ctx context.Context, in *Input, device, id string, onW float64, source string, p, peak, cycle float64, runS int) (*ReplayVerdict, Benefit, error) { + if in.Doc.Location == nil { + return nil, Benefit{}, nil + } + rule := map[string]any{"id": id, "enabled": true} + if source == "reserve" { + rule["conditions"] = []map[string]any{{"type": "learned_value", "learned": surWinReserveKey, + "comparison": "above", "threshold": onW, "fallback": 0, "hysteresis": 100, + "max_age_s": 1800, "hold_seconds": surWinHoldS}} + } else { + rule["conditions"] = []map[string]any{{"type": "balance_threshold", "field": "grid_export", + "comparison": "above", "threshold": onW, "hold_seconds": surWinHoldS}} + } + raw, err := json.Marshal(rule) + if err != nil { + return nil, Benefit{}, err + } + loc := in.Loc + if loc == nil { + loc = time.Local + } + chk := ReplayCheck{ + Rule: json.RawMessage(raw), + Target: ReplayTarget{RuleID: id, Device: device, OpW: p, PeakW: peak, CycleWh: cycle, MinRunS: float64(runS)}, + Benefit: func(alt, base ReplayResult) Benefit { + // The energy the load takes from the export, per week. + return Benefit{Unit: "kwh_week", Value: (base.ExportWh - alt.ExportWh) / 1000 * 7 / surWinWindowDays} + }, + } + verdict, b, err := EvaluateReplay(ctx, in, chk, surWinWindowDays, loc, *in.Doc.Location) + if ctx.Err() != nil { + return nil, Benefit{}, ctx.Err() + } + return verdict, b, err +} + +// surWinDays returns the last surWinWindowDays day files with a measurement, +// oldest first. Days the house was away are left out. +func surWinDays(in *Input) []surWinDay { + loc := in.Loc + if loc == nil { + loc = time.Local + } + files := make([]*DayFile, 0, len(in.Days)) + for i := range in.Days { + files = append(files, &in.Days[i]) + } + sort.SliceStable(files, func(a, b int) bool { return files[a].Day > files[b].Day }) + + var out []surWinDay + for _, f := range files { + if len(out) == surWinWindowDays { + break + } + if in.Base.Away[f.Day] { + continue + } + t, err := time.ParseInLocation(dayLayout, f.Day, loc) + if err != nil { + continue + } + d := surWinDay{date: f.Day, weight: DayWeight(math.Max(0, in.Now.Sub(t).Hours()/24))} + hasData := false + d.with, d.without = surWinSeries(in, f, t) + for q := 0; q < dayQuarters; q++ { + d.seen[q] = f.Site.Seen[q] != 0 + hasData = hasData || d.seen[q] + } + if hasData { + out = append(out, d) + } + } + // The days are read newest first above, the window reads them oldest first. + for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 { + out[i], out[j] = out[j], out[i] + } + return out +} + +// surWinSeries returns the surplus per quarter hour of one day, with and +// without the PV reserve. The reserve is max(0, Best * k - PV) with the +// weather factor k of the quarter, as the rest surplus does it. Without a PV +// model or a site the reserve is 0. +func surWinSeries(in *Input, f *DayFile, midnight time.Time) (with, without [dayQuarters]float64) { + var model PVModel + var raster *Raster + haveModel := false + if in.PV != nil { + model, raster, haveModel = in.PV() + } + site := in.Doc.Location + haveModel = haveModel && site != nil + for q := 0; q < dayQuarters; q++ { + exp := float64(f.Site.GridExport[q]) + bat := math.Max(0, float64(f.Site.BatteryCharge[q])-surWinBatteryFloorW) + without[q] = exp + bat + res := 0.0 + if haveModel { + az, el := sun.Position(shadeQuarterTime(midnight, q), site.Lat, site.Lon) + k := 0.0 + if kv := f.Site.K[q]; kv != nil { + k = float64(*kv) + } + res = math.Max(0, model.Best(az, el, raster)*k-float64(f.Site.PV[q])) + } + with[q] = without[q] + res + } + return with, without +} + +// surWinLongestWindow returns the longest run of quarter hours whose Wilson +// lower bound of "surplus reaches the threshold" is at least +// surWinWindowLimit, the first quarter of the run, its length, the lowest +// bound in it and the mean share of days in it. +func surWinLongestWindow(days []surWinDay, threshold float64, pick func(*surWinDay) *[dayQuarters]float64) (start, n int, lower, rate float64) { + var good [dayQuarters]bool + var low, share [dayQuarters]float64 + for q := 0; q < dayQuarters; q++ { + hits, seen := 0, 0 + for i := range days { + if !days[i].seen[q] { + continue + } + seen++ + if pick(&days[i])[q] >= threshold { + hits++ + } + } + if seen == 0 { + continue + } + low[q] = WilsonLower(hits, seen) + share[q] = float64(hits) / float64(seen) + good[q] = low[q] >= surWinWindowLimit + } + bestStart, bestN := 0, 0 + for q := 0; q < dayQuarters; { + if !good[q] { + q++ + continue + } + s := q + for q < dayQuarters && good[q] { + q++ + } + if q-s > bestN { + bestStart, bestN = s, q-s + } + } + if bestN == 0 { + return 0, 0, 0, 0 + } + lower = 1 + for q := bestStart; q < bestStart+bestN; q++ { + lower = math.Min(lower, low[q]) + rate += share[q] + } + return bestStart, bestN, lower, rate / float64(bestN) +} + +// surWinReserveHelps reports whether the reserve makes the window on at least +// surWinWindowMinReserveDays days, where the surplus without the reserve is +// shorter than the run. +func surWinReserveHelps(days []surWinDay, threshold float64, need int) bool { + count := 0 + for i := range days { + with := longestRun(&days[i].with, threshold) + without := longestRun(&days[i].without, threshold) + if with >= need && without < need { + count++ + } + } + return count >= surWinWindowMinReserveDays +} + +// longestRun is the longest run of quarter hours at or above threshold. +func longestRun(xs *[dayQuarters]float64, threshold float64) int { + best, cur := 0, 0 + for _, x := range xs { + if x >= threshold { + cur++ + best = max(best, cur) + } else { + cur = 0 + } + } + return best +} + +// surWinHasRule reports whether an enabled rule already switches the device on +// surplus: a grid export or PV reserve condition and an action on one of the +// device entities. +func surWinHasRule(in *Input, device string) bool { + entities := in.Devices[device].Entities + if len(entities) == 0 { + return false + } + own := make(map[string]bool, len(entities)) + for _, e := range entities { + own[e] = true + } + for _, r := range in.Doc.Rules { + if !r.Enabled || !surWinRuleOnSurplus(r) { + continue + } + for _, a := range r.Actions { + if own[a.EntityID] { + return true + } + } + } + return false +} + +// surWinRuleOnSurplus reports whether a rule has a surplus condition. +func surWinRuleOnSurplus(r Rule) bool { + for _, c := range r.Conditions { + if c.Type == "balance_threshold" && c.Field == "grid_export" { + return true + } + if c.Type == "learned_value" { + for _, ref := range c.Learned { + if ref.Key == surWinReserveKey { + return true + } + } + } + } + return false +} + +// surWinLearnedNumber reads a learned number, false when it is missing. +func surWinLearnedNumber(learned map[string]LearnedEntry, key string) (float64, bool) { + e, ok := learned[key] + if !ok { + return 0, false + } + return asFloat(e.Value) +} + +// surWinClock formats a quarter hour index as HH:MM. +func surWinClock(q int) string { + m := q * 15 + return fmt.Sprintf("%02d:%02d", m/60%24, m%60) +} diff --git a/dashboard/internal/autolearn/detect_surplus_test.go b/dashboard/internal/autolearn/detect_surplus_test.go new file mode 100644 index 00000000..1bbdc5f1 --- /dev/null +++ b/dashboard/internal/autolearn/detect_surplus_test.go @@ -0,0 +1,208 @@ +package autolearn + +import ( + "context" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// surplusWinNow is the clock of the surplus window tests. +func surplusWinNow(t *testing.T) time.Time { + t.Helper() + return time.Date(2026, 11, 22, 8, 0, 0, 0, berlinLoc(t)) +} + +// surplusWinDay builds a day with every quarter seen. grid returns the grid +// export in W of a quarter, pv the measured PV in W and k the weather factor. +func surplusWinDay(day string, grid func(q int) float32, pv func(q int) float32) DayFile { + f := DayFile{V: 1, Day: day} + for q := 0; q < dayQuarters; q++ { + f.Site.Seen[q] = 1 + f.Site.LoadTotal[q] = 400 + f.Site.GridExport[q] = grid(q) + f.Site.PV[q] = pv(q) + k := float32(1) + f.Site.K[q] = &k + } + return f +} + +// surplusWinDays returns the 14 days before 2026-11-22. Day i is built by fn. +func surplusWinDays(loc *time.Location, fn func(i int, q int) (grid, pv float32)) []DayFile { + first := time.Date(2026, 11, 8, 0, 0, 0, 0, loc) + var out []DayFile + for i := 0; i < surWinWindowDays; i++ { + i := i + day := first.AddDate(0, 0, i).Format(dayLayout) + out = append(out, surplusWinDay(day, + func(q int) float32 { g, _ := fn(i, q); return g }, + func(q int) float32 { _, p := fn(i, q); return p })) + } + return out +} + +// surplusWinInput builds the input of a 1500 W device with a 2 h run. +func surplusWinInput(t *testing.T, days []DayFile) *Input { + t.Helper() + loc := berlinLoc(t) + return &Input{ + Now: surplusWinNow(t), + Loc: loc, + Days: days, + Doc: Doc{Location: shadeSite}, + Devices: map[string]DeviceInfo{ + "plug": {ID: "plug", Switchable: true, Entities: []string{"switch.plug"}}, + }, + Learned: map[string]LearnedEntry{ + "device/plug/op_power_w": {Key: "device/plug/op_power_w", Value: 1500.0}, + "device/plug/cycle_wh": {Key: "device/plug/cycle_wh", Value: 3000.0}, + }, + } +} + +// surplusWinExport is 2500 W of export from 11 to 15 o'clock on the first twelve days. +func surplusWinExport(i, q int) (float32, float32) { + if i < 12 && q >= 44 && q < 60 { + return 2500, 0 + } + return 0, 0 +} + +func surplusWinRun(t *testing.T, in *Input) []Candidate { + t.Helper() + return SurplusDetector.Run(context.Background(), in, "plug") +} + +func TestSurplusWindowSuggestsSwitchOnWindow(t *testing.T) { + loc := berlinLoc(t) + in := surplusWinInput(t, surplusWinDays(loc, surplusWinExport)) + got := surplusWinRun(t, in) + if len(got) != 1 { + t.Fatalf("candidates = %d, want 1", len(got)) + } + c := got[0] + if c.Finding.Summary.Code != "surplus.window" { + t.Errorf("summary = %q, want surplus.window", c.Finding.Summary.Code) + } + if c.Finding.ID != "surplus:plug" { + t.Errorf("id = %q, want surplus:plug", c.Finding.ID) + } + if len(c.Finding.Apply) != 1 { + t.Fatalf("apply = %d fixes, want 1", len(c.Finding.Apply)) + } + fix := c.Finding.Apply[0] + if fix.Template != "surplus_switch" { + t.Errorf("template = %q, want surplus_switch", fix.Template) + } + if on, _ := fix.Prefill["on_w"].(float64); on != 1700 { + t.Errorf("on_w = %v, want 1700", fix.Prefill["on_w"]) + } + if src := fix.Prefill["source"]; src != "export" { + t.Errorf("source = %v, want export", src) + } + if c.Finding.Benefit == nil || c.Finding.Benefit.Unit != "kwh_week" || c.Finding.Benefit.Value <= 0 { + t.Errorf("benefit = %+v, want a positive kwh_week", c.Finding.Benefit) + } + if c.Finding.Evidence.Shape != "curve" { + t.Errorf("evidence shape = %q, want curve", c.Finding.Evidence.Shape) + } + ev := c.Finding.Evidence + if len(ev.Quarters) != dayQuarters || len(ev.SollQ) != dayQuarters { + t.Fatalf("curve lengths = %d, %d, want %d each", len(ev.Quarters), len(ev.SollQ), dayQuarters) + } + for q := 0; q < dayQuarters; q++ { + inWindow := q >= 44 && q < 60 + if inWindow && ev.SollQ[q] != 1700 { + t.Errorf("SollQ[%d] = %v in window, want 1700", q, ev.SollQ[q]) + } + if !inWindow && ev.SollQ[q] != 0 { + t.Errorf("SollQ[%d] = %v outside window, want 0", q, ev.SollQ[q]) + } + if inWindow && ev.Quarters[q] < 1700 { + t.Errorf("Quarters[%d] = %v in window, want >= 1700", q, ev.Quarters[q]) + } + } +} + +func TestSurplusWindowReserveSource(t *testing.T) { + loc := berlinLoc(t) + // No export, the feed-in is throttled to 2000 W. The reserve is the PV that + // the roof would make beyond the throttle. + model := PVModel{Surfaces: []Surface{{PMax: 20000, TiltDeg: 30, AzimuthDeg: 180}}, CapW: 20000, Safe: true} + days := surplusWinDays(loc, func(i, q int) (float32, float32) { + if i >= 12 { + return 0, 0 + } + day := time.Date(2026, 11, 8, 0, 0, 0, 0, loc).AddDate(0, 0, i) + az, el := sunPosForTest(day, q) + best := model.Best(az, el, nil) + return 0, float32(min(best, 2000)) + }) + in := surplusWinInput(t, days) + in.PV = func() (PVModel, *Raster, bool) { return model, nil, true } + got := surplusWinRun(t, in) + if len(got) != 1 { + t.Fatalf("candidates = %d, want 1", len(got)) + } + c := got[0] + if c.Finding.Summary.Code != "surplus.reserve" { + t.Errorf("summary = %q, want surplus.reserve", c.Finding.Summary.Code) + } + if src := c.Finding.Apply[0].Prefill["source"]; src != "reserve" { + t.Errorf("source = %v, want reserve", src) + } +} + +func TestSurplusWindowShortWindowNoSuggestion(t *testing.T) { + loc := berlinLoc(t) + short := func(i, q int) (float32, float32) { + if i < 12 && q >= 44 && q < 48 { // 1 h of export, the run needs 2 h + return 2500, 0 + } + return 0, 0 + } + if got := surplusWinRun(t, surplusWinInput(t, surplusWinDays(loc, short))); len(got) != 0 { + t.Errorf("candidates = %d, want 0 for a 1 h window", len(got)) + } +} + +func TestSurplusWindowExistingSurplusRuleNoSuggestion(t *testing.T) { + loc := berlinLoc(t) + in := surplusWinInput(t, surplusWinDays(loc, surplusWinExport)) + in.Doc.Rules = []Rule{{ + ID: "zero-feed", + Enabled: true, + Conditions: []Condition{{Type: "balance_threshold", Field: "grid_export", + Comparison: "above", Threshold: 1000}}, + Actions: []Action{{Type: "switch", EntityID: "switch.plug"}}, + }} + if got := surplusWinRun(t, in); len(got) != 0 { + t.Errorf("candidates = %d, want 0 with an existing surplus rule", len(got)) + } +} + +func TestSurplusWindowNoisePatternNoSuggestion(t *testing.T) { + loc := berlinLoc(t) + noise := func(i, q int) (float32, float32) { + return float32(300 + (q*37+i*11)%500), 0 + } + if got := surplusWinRun(t, surplusWinInput(t, surplusWinDays(loc, noise))); len(got) != 0 { + t.Errorf("candidates = %d, want 0 without a pattern", len(got)) + } +} + +func TestSurplusWindowNeedsLearnedPower(t *testing.T) { + loc := berlinLoc(t) + in := surplusWinInput(t, surplusWinDays(loc, surplusWinExport)) + in.Learned = nil + if got := surplusWinRun(t, in); len(got) != 0 { + t.Errorf("candidates = %d, want 0 without learned operating power", len(got)) + } +} + +// sunPosForTest is the sun position of quarter q of the day, as the surplus detector reads it. +func sunPosForTest(day time.Time, q int) (float64, float64) { + return sun.Position(shadeQuarterTime(day, q), shadeSite.Lat, shadeSite.Lon) +} diff --git a/dashboard/internal/autolearn/detect_threshold.go b/dashboard/internal/autolearn/detect_threshold.go new file mode 100644 index 00000000..ae90f2fd --- /dev/null +++ b/dashboard/internal/autolearn/detect_threshold.go @@ -0,0 +1,448 @@ +package autolearn + +import ( + "context" + "encoding/json" + "math" + "sort" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// ThresholdDetector rates the threshold of a surplus rule by replaying it with +// other thresholds (spec 15.6 "Schwellenbewertung"). Every replayable surplus +// rule is tried with Limits.ThresholdSteps values between 0.3 and 2 times its +// threshold. The value J = E_pv - 1.5 * E_netz - 0.02 kWh * N is maximised +// over the grid, and the middle of the widest run near the maximum is taken. +// Rules that are not replayable are skipped silently. +var ThresholdDetector = Detector{ + Name: "threshold_rating", + Group: "energy", + Light: false, + PerDevice: false, + Run: thresholdRun, +} + +const ( + // thresholdReplayDays is the number of days the rating replays. + thresholdReplayDays = 14 + // thresholdLowFactor and thresholdHighFactor bound the grid. + thresholdLowFactor = 0.3 + thresholdHighFactor = 2.0 + // thresholdGridPenalty is the weight of grid import in J. + thresholdGridPenalty = 1.5 + // thresholdSwitchKWh is the cost of one switch in J. + thresholdSwitchKWh = 0.02 + // thresholdPlateau is the share of the maximum a point needs to count as near it. + thresholdPlateau = 0.95 + // thresholdMinGainKWhWeek is the gain per week a rating must exceed. + thresholdMinGainKWhWeek = 0.5 + // thresholdRoundW rounds the proposed threshold. + thresholdRoundW = 10.0 +) + +// thresholdJointHysteresisW and thresholdJointMinRunS are the grid of the +// joint variation (ReplayJointHold, full level only). +var ( + thresholdJointHysteresisW = []float64{0, 100, 200} + thresholdJointMinRunS = []float64{0, 300, 600} +) + +// thresholdPoint is one replayed point of the grid. +type thresholdPoint struct { + x, h, m float64 + j float64 +} + +// thresholdRun rates the surplus rules of the document. +func thresholdRun(ctx context.Context, in *Input, _ string) []Candidate { + if ctx.Err() != nil || in == nil || in.Limits.ThresholdSteps < 2 { + return nil + } + minutes, estimate := ReplayDays(in, thresholdReplayDays) + loc := replayLoc(in) + days := thresholdDays(minutes, loc) + if len(days) < 2 { + return nil + } + var site sun.Location + if in.Doc.Location != nil { + site = *in.Doc.Location + } + var out []Candidate + for _, r := range in.Doc.Rules { + if ctx.Err() != nil { + return nil + } + if !r.Enabled { + continue + } + cand, ok := thresholdRule(ctx, in, r, minutes, days, estimate, loc, site) + if ok { + out = append(out, cand) + } + } + return out +} + +// thresholdRule rates one rule. It returns false when the rule is not a +// replayable surplus rule, has no operating power, or gives no finding. +func thresholdRule(ctx context.Context, in *Input, r Rule, minutes []ReplayMinute, days []string, estimate bool, loc *time.Location, site sun.Location) (Candidate, bool) { + idx, ok := thresholdCondition(r) + if !ok || Replayable(r) != nil { + return Candidate{}, false + } + device, info, ok := thresholdDevice(in, r) + if !ok { + return Candidate{}, false + } + p, ok := learnedOperatingPower(in.Learned, device) + if !ok { + return Candidate{}, false + } + cycle := 0.0 + if v, ok := surWinLearnedNumber(in.Learned, "device/"+device+"/cycle_wh"); ok { + cycle = v + } + today := r.Conditions[idx].Threshold + if today <= 0 { + return Candidate{}, false + } + hyst0 := r.Conditions[idx].Hysteresis + run0 := reliabilityMinRuntime(info) + base := thresholdTarget{rule: r.ID, device: device, opW: p, peakW: feedbackInrush(in.Days, device, p), cycleWh: cycle} + real := RealState(in, device, minutes) + + hysts := []float64{hyst0} + runs := []float64{run0} + if in.Limits.ReplayJointHold { + hysts = thresholdJointHysteresisW + runs = thresholdJointMinRunS + } + grid := thresholdGrid(today, in.Limits.ThresholdSteps) + + // Rate every point of the grid and keep the (hysteresis, minimum run) pair + // with the best point. The pair is fixed before the plateau is read. + var rows [][]thresholdPoint + bestRow, bestJ := -1, math.Inf(-1) + for _, h := range hysts { + for _, m := range runs { + row, err := thresholdRow(ctx, in, r, idx, base, m, h, grid, minutes, real, loc, site) + if err != nil { + return Candidate{}, false + } + rows = append(rows, row) + for _, pt := range row { + if pt.j > bestJ { + bestJ = pt.j + bestRow = len(rows) - 1 + } + } + } + } + if bestRow < 0 { + return Candidate{}, false + } + row := rows[bestRow] + chosen := thresholdWidest(row) + soll := math.Round(chosen.x/thresholdRoundW) * thresholdRoundW + if soll == today || soll <= 0 { + return Candidate{}, false + } + + // Gain against today's rule, per week, and the halves of the days. + nDays := float64(len(days)) + todayPt := thresholdEval(ctx, in, r, idx, base, run0, hyst0, today, minutes, real, loc, site) + if todayPt.err != nil { + return Candidate{}, false + } + chosenEval := thresholdEval(ctx, in, r, idx, base, chosen.m, chosen.h, soll, minutes, real, loc, site) + if chosenEval.err != nil { + return Candidate{}, false + } + gainWeek := (chosenEval.j - todayPt.j) * 7 / nDays + if !(gainWeek > thresholdMinGainKWhWeek) { + return Candidate{}, false + } + if !thresholdHalvesAgree(ctx, in, r, idx, base, minutes, real, loc, site, days, today, hyst0, run0, soll, chosen.h, chosen.m) { + return Candidate{}, false + } + + code := "threshold.too_low" + kwh := (todayPt.eNetz - chosenEval.eNetz) * 7 / nDays + if soll < today { + code = "threshold.too_high" + kwh = (chosenEval.ePV - todayPt.ePV) * 7 / nDays + } + joint := in.Limits.ReplayJointHold + return thresholdCandidate(in, r, device, p, code, kwh, gainWeek, today, soll, chosen, joint, estimate, nDays, chosenEval), true +} + +// thresholdTarget holds what does not change over the grid of one rule. +type thresholdTarget struct { + rule string + device string + opW float64 + peakW float64 + cycleWh float64 +} + +// thresholdEvalResult is the replay of one point with its terms. +type thresholdEvalResult struct { + alt, base ReplayResult + j float64 + ePV float64 + eNetz float64 + err error +} + +// thresholdEval replays one point of the grid on the given minutes: the rule +// with threshold x, hysteresis h and minimum run m. It returns J with its terms. +func thresholdEval(ctx context.Context, in *Input, r Rule, idx int, t thresholdTarget, m, h, x float64, minutes []ReplayMinute, real []bool, loc *time.Location, site sun.Location) thresholdEvalResult { + target := ReplayTarget{RuleID: t.rule, Device: t.device, OpW: t.opW, PeakW: t.peakW, CycleWh: t.cycleWh, MinRunS: m} + raw, err := thresholdRuleJSON(r, idx, x, h) + if err != nil { + return thresholdEvalResult{err: err} + } + base, err := Replay(ctx, replayBaseRule, target, minutes, real, loc, site) + if err != nil { + return thresholdEvalResult{err: err} + } + alt, err := Replay(ctx, raw, target, minutes, real, loc, site) + if err != nil { + return thresholdEvalResult{err: err} + } + j, ePV, eNetz := thresholdJ(alt, base) + return thresholdEvalResult{alt: alt, base: base, j: j, ePV: ePV, eNetz: eNetz} +} + +// thresholdRow rates the whole grid for one hysteresis and minimum run. +func thresholdRow(ctx context.Context, in *Input, r Rule, idx int, t thresholdTarget, m, h float64, grid []float64, minutes []ReplayMinute, real []bool, loc *time.Location, site sun.Location) ([]thresholdPoint, error) { + row := make([]thresholdPoint, 0, len(grid)) + for _, x := range grid { + if err := ctx.Err(); err != nil { + return nil, err + } + ev := thresholdEval(ctx, in, r, idx, t, m, h, x, minutes, real, loc, site) + if ev.err != nil { + return nil, ev.err + } + row = append(row, thresholdPoint{x: x, h: h, m: m, j: ev.j}) + } + return row, nil +} + +// thresholdWidest returns the middle of the widest run of points whose J is +// at least thresholdPlateau of the maximum of the row. Ties keep the first run. +func thresholdWidest(row []thresholdPoint) thresholdPoint { + maxJ := math.Inf(-1) + for _, pt := range row { + maxJ = math.Max(maxJ, pt.j) + } + bestStart, bestEnd := -1, -1 + for i := 0; i < len(row); { + if row[i].j < thresholdPlateau*maxJ { + i++ + continue + } + s := i + for i < len(row) && row[i].j >= thresholdPlateau*maxJ { + i++ + } + e := i - 1 + if bestStart < 0 || row[e].x-row[s].x > row[bestEnd].x-row[bestStart].x { + bestStart, bestEnd = s, e + } + } + if bestStart < 0 { + bestStart, bestEnd = 0, 0 + } + mid := (row[bestStart].x + row[bestEnd].x) / 2 + out := row[bestStart] + out.x = mid + return out +} + +// thresholdHalvesAgree reports whether the proposal beats today's rule on the +// first and on the second half of the days. +func thresholdHalvesAgree(ctx context.Context, in *Input, r Rule, idx int, t thresholdTarget, minutes []ReplayMinute, real []bool, loc *time.Location, site sun.Location, days []string, today, hyst0, run0, soll, h, m float64) bool { + split := thresholdSplit(minutes, loc, days) + parts := [][2]int{{0, split}, {split, len(minutes)}} + for _, part := range parts { + lo, hi := part[0], part[1] + if hi <= lo { + return false + } + mins := minutes[lo:hi] + rl := real[lo:hi] + prop := thresholdEval(ctx, in, r, idx, t, m, h, soll, mins, rl, loc, site) + now := thresholdEval(ctx, in, r, idx, t, run0, hyst0, today, mins, rl, loc, site) + if prop.err != nil || now.err != nil { + return false + } + if !(prop.j-now.j > 0) { + return false + } + } + return true +} + +// thresholdCandidate builds the finding and the candidate of a rated rule. +func thresholdCandidate(in *Input, r Rule, device string, p float64, code string, kwh, gainWeek, today, soll float64, chosen thresholdPoint, joint, estimate bool, nDays float64, chosenEval thresholdEvalResult) Candidate { + rules := ruleByID(in.Doc) + conf := "high" + if estimate { + conf = "estimate" + } + name := ruleName(rules, r.ID) + idx, _ := thresholdCondition(r) + fixes := []Fix{{Code: "set_threshold", RuleID: r.ID, Ops: []Op{{ + Path: []any{"conditions", idx, "threshold"}, Value: soll}}}} + fixes = append(fixes, Fix{Code: "learned_threshold", RuleID: r.ID, Ops: []Op{{ + Path: []any{"conditions", idx, "threshold"}, + Value: map[string]any{"learned": "device/" + device + "/op_power_w", "offset": soll - p}}}}) + var facts []Fact + if joint { + facts = []Fact{{Code: "hysteresis", Value: chosen.h}, {Code: "min_run_s", Value: chosen.m}} + } + benefit := Benefit{Unit: "kwh_week", Value: gainWeek} + finding := Finding{ + ID: "threshold:" + r.ID, + Kind: "threshold", + Group: "check", + RuleIDs: []string{r.ID}, + Severity: "info", + Confidence: conf, + Summary: Text{Code: code, Params: map[string]any{ + "rule": name, "kwh": kwh, "threshold": today, "soll": soll}}, + Evidence: Evidence{Shape: "scale", Unit: "W", IstValue: &today, SollValue: &soll}, + Facts: facts, + Apply: fixes, + Device: device, + Benefit: &benefit, + } + replay := &ReplayVerdict{Base: chosenEval.base, Alt: chosenEval.alt, Estimate: estimate} + return Candidate{ + Finding: finding, + Detector: "threshold_rating", + NEff: nDays, + MinNEff: 0, + Lower: 1, + Limit: 1, + HalvesAgree: true, + Benefit: benefit, + Values: map[string]float64{"today": today, "soll": soll, "gain_week": gainWeek}, + Replay: replay, + } +} + +// thresholdCondition returns the index of the surplus condition of a rule: a +// grid export or PV reserve condition with a numeric threshold, above it. +func thresholdCondition(r Rule) (int, bool) { + for i, c := range r.Conditions { + if _, ref := c.Learned["threshold"]; ref { + continue + } + if c.Comparison != "above" { + continue + } + if c.Type == "balance_threshold" && c.Field == "grid_export" { + return i, true + } + if c.Type == "learned_value" { + if ref, ok := c.Learned["learned"]; ok && ref.Key == surWinReserveKey { + return i, true + } + } + } + return 0, false +} + +// thresholdDevice returns the device the rule switches, by its entity. +func thresholdDevice(in *Input, r Rule) (string, DeviceInfo, bool) { + ids := make([]string, 0, len(in.Devices)) + for id := range in.Devices { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + info := in.Devices[id] + if actsOnDevice(r, info) { + return id, info, true + } + } + return "", DeviceInfo{}, false +} + +// thresholdGrid returns steps values between 0.3 and 2 times the threshold. +func thresholdGrid(today float64, steps int) []float64 { + lo, hi := thresholdLowFactor*today, thresholdHighFactor*today + out := make([]float64, steps) + for i := range out { + out[i] = lo + (hi-lo)*float64(i)/float64(steps-1) + } + return out +} + +// thresholdJ is J = E_pv - 1.5 * E_netz - 0.02 kWh * N in kWh. E_pv is the +// extra surplus the proposal uses, E_netz the extra grid import it causes. +func thresholdJ(alt, base ReplayResult) (j, ePV, eNetz float64) { + ePV = math.Max(0, base.ExportWh-alt.ExportWh) / 1000 + eNetz = math.Max(0, alt.GridWh-base.GridWh) / 1000 + j = ePV - thresholdGridPenalty*eNetz - thresholdSwitchKWh*float64(alt.Switches) + return j, ePV, eNetz +} + +// thresholdRuleJSON returns the rule with the threshold x and the hysteresis +// h on condition idx, the other conditions unchanged. +func thresholdRuleJSON(r Rule, idx int, x, h float64) (json.RawMessage, error) { + conds := make([]json.RawMessage, len(r.Conditions)) + for i, c := range r.Conditions { + if i != idx { + conds[i] = c.Raw + continue + } + var m map[string]any + if err := json.Unmarshal(c.Raw, &m); err != nil { + return nil, err + } + m["threshold"] = x + m["hysteresis"] = h + b, err := json.Marshal(m) + if err != nil { + return nil, err + } + conds[i] = b + } + return json.Marshal(map[string]any{ + "id": r.ID, "enabled": true, + "cooldown_seconds": r.CooldownSeconds, "repeat_seconds": r.RepeatSeconds, + "conditions": conds, + }) +} + +// thresholdDays returns the distinct days of the minutes, oldest first. +func thresholdDays(minutes []ReplayMinute, loc *time.Location) []string { + var out []string + seen := map[string]bool{} + for _, m := range minutes { + d := m.At.In(loc).Format(dayLayout) + if !seen[d] { + seen[d] = true + out = append(out, d) + } + } + return out +} + +// thresholdSplit returns the index of the first minute of the second half of the days. +func thresholdSplit(minutes []ReplayMinute, loc *time.Location, days []string) int { + boundary := days[len(days)/2] + for i, m := range minutes { + if m.At.In(loc).Format(dayLayout) >= boundary { + return i + } + } + return len(minutes) +} diff --git a/dashboard/internal/autolearn/detect_threshold_test.go b/dashboard/internal/autolearn/detect_threshold_test.go new file mode 100644 index 00000000..6507b712 --- /dev/null +++ b/dashboard/internal/autolearn/detect_threshold_test.go @@ -0,0 +1,179 @@ +package autolearn + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" +) + +// thresholdDoc builds the rule document of one surplus rule switching the plug. +func thresholdDoc(t *testing.T, threshold float64, extra string) Doc { + t.Helper() + raw := fmt.Sprintf(`{"rules":[{"id":"heat","name":"Heizstab","enabled":true, + "conditions":[{"type":"balance_threshold","field":"grid_export","comparison":"above","threshold":%v,"hold_seconds":120%s}], + "actions":[{"type":"publish","topic":"plug/set","payload":"ON","entity_id":"switch.plug"}]}]}`, threshold, extra) + doc, err := ParseDoc([]byte(raw)) + if err != nil { + t.Fatalf("parse doc: %v", err) + } + return doc +} + +// thresholdInput builds a 1500 W plug with a 3000 Wh cycle and 14 days. +func thresholdInput(t *testing.T, doc Doc, days []DayFile) *Input { + t.Helper() + return &Input{ + Now: surplusWinNow(t), + Loc: berlinLoc(t), + Days: days, + Doc: doc, + Devices: map[string]DeviceInfo{ + "plug": {ID: "plug", Switchable: true, Entities: []string{"switch.plug"}}, + }, + Learned: map[string]LearnedEntry{ + "device/plug/op_power_w": {Key: "device/plug/op_power_w", Value: 1500.0}, + "device/plug/cycle_wh": {Key: "device/plug/cycle_wh", Value: 3000.0}, + }, + Limits: learnrec.LimitsFor(learnrec.LevelBalanced, 1), + } +} + +// thresholdFixtureDays builds the 14 days before today. grid and imp return the grid +// export and grid import in W of a quarter of day i. +func thresholdFixtureDays(t *testing.T, fn func(i, q int) (exp, imp float32)) []DayFile { + t.Helper() + loc := berlinLoc(t) + first := time.Date(2026, 11, 8, 0, 0, 0, 0, loc) + var out []DayFile + for i := 0; i < thresholdReplayDays; i++ { + i := i + f := DayFile{V: 1, Day: first.AddDate(0, 0, i).Format(dayLayout)} + for q := 0; q < dayQuarters; q++ { + exp, imp := fn(i, q) + f.Site.Seen[q] = 1 + f.Site.LoadTotal[q] = 400 + f.Site.GridExport[q] = exp + f.Site.GridImport[q] = imp + k := float32(1) + f.Site.K[q] = &k + } + out = append(out, f) + } + return out +} + +// thresholdRunOn runs the rating on the plug. +func thresholdRunOn(t *testing.T, in *Input) []Candidate { + t.Helper() + return ThresholdDetector.Run(context.Background(), in, "") +} + +// surplus2500 is 2500 W export from 11 to 15 o'clock. +func surplus2500(i, q int) (float32, float32) { + if q >= 44 && q < 60 { + return 2500, 0 + } + return 0, 0 +} + +func TestThresholdTooHighLowersToPlateau(t *testing.T) { + in := thresholdInput(t, thresholdDoc(t, 3000, ""), thresholdFixtureDays(t, surplus2500)) + got := thresholdRunOn(t, in) + if len(got) != 1 { + t.Fatalf("candidates = %d, want 1", len(got)) + } + f := got[0].Finding + if f.Summary.Code != "threshold.too_high" { + t.Fatalf("code = %s, want threshold.too_high", f.Summary.Code) + } + soll := f.Evidence.SollValue + if soll == nil || *soll < 1500 || *soll > 1900 { + t.Fatalf("soll = %v, want about 1700", soll) + } + if len(f.Apply) != 2 || f.Apply[0].Code != "set_threshold" || f.Apply[1].Code != "learned_threshold" { + t.Fatalf("fixes = %+v", f.Apply) + } + if got[0].Replay == nil { + t.Fatal("candidate without replay verdict") + } +} + +func TestThresholdTooLowRaisesWithGridImport(t *testing.T) { + // 600 W export from 12 to 14 o'clock. The rule at 500 W takes it, and the + // load draws the rest from the grid. + day := func(i, q int) (float32, float32) { + if q >= 48 && q < 56 { + return 600, 0 + } + return 0, 0 + } + in := thresholdInput(t, thresholdDoc(t, 500, ""), thresholdFixtureDays(t, day)) + got := thresholdRunOn(t, in) + if len(got) != 1 { + t.Fatalf("candidates = %d, want 1", len(got)) + } + if code := got[0].Finding.Summary.Code; code != "threshold.too_low" { + t.Fatalf("code = %s, want threshold.too_low", code) + } + if soll := got[0].Finding.Evidence.SollValue; soll == nil || *soll <= 500 { + t.Fatalf("soll = %v, want above 500", soll) + } +} + +func TestThresholdHalvesDisagreeNoFinding(t *testing.T) { + // Surplus only on the first seven days: the second half gains nothing. + day := func(i, q int) (float32, float32) { + if i < 7 { + return surplus2500(i, q) + } + return 0, 0 + } + in := thresholdInput(t, thresholdDoc(t, 3000, ""), thresholdFixtureDays(t, day)) + if got := thresholdRunOn(t, in); len(got) != 0 { + t.Fatalf("candidates = %d, want 0", len(got)) + } +} + +func TestThresholdNotReplayableRuleSilent(t *testing.T) { + doc := thresholdDoc(t, 3000, `},{"type":"chain_value","comparison":"above","threshold":1,"hold_seconds":0`) + in := thresholdInput(t, doc, thresholdFixtureDays(t, surplus2500)) + if got := thresholdRunOn(t, in); len(got) != 0 { + t.Fatalf("candidates = %d, want 0", len(got)) + } +} + +func TestThresholdWidestPlateauMiddle(t *testing.T) { + var row []thresholdPoint + for x := 1000.0; x <= 2400; x += 100 { + j := 0.0 + switch { + case x == 1000: + j = 10 + case x >= 1600 && x <= 2000: + j = 9.6 + } + row = append(row, thresholdPoint{x: x, j: j}) + } + if mid := thresholdWidest(row).x; mid != 1800 { + t.Fatalf("mid = %v, want 1800", mid) + } +} + +func TestThresholdJointHoldAddsFactsOnly(t *testing.T) { + in := thresholdInput(t, thresholdDoc(t, 3000, ""), thresholdFixtureDays(t, surplus2500)) + in.Limits = learnrec.LimitsFor(learnrec.LevelFull, 4) + got := thresholdRunOn(t, in) + if len(got) != 1 { + t.Fatalf("candidates = %d, want 1", len(got)) + } + f := got[0].Finding + if len(f.Facts) != 2 || f.Facts[0].Code != "hysteresis" || f.Facts[1].Code != "min_run_s" { + t.Fatalf("facts = %+v, want hysteresis and min_run_s", f.Facts) + } + if len(f.Apply) != 2 || len(f.Apply[0].Ops) != 1 { + t.Fatalf("joint hold must set only the threshold, fixes = %+v", f.Apply) + } +} diff --git a/dashboard/internal/autolearn/engine.go b/dashboard/internal/autolearn/engine.go index de029a02..8c9c9e40 100644 --- a/dashboard/internal/autolearn/engine.go +++ b/dashboard/internal/autolearn/engine.go @@ -70,6 +70,8 @@ type Engine struct { outdoor func() OutdoorSource pv func() (PVModel, *Raster, bool) learned func() map[string]LearnedEntry + minutes func() learnrec.Reader + steps func(scenario string, from, to time.Time) []Step // recentC is the mean outdoor temperature of the last three days as the // last round read it, nil when unknown. recentC *float64 @@ -422,7 +424,15 @@ func (e *Engine) input(now time.Time, limits learnrec.Limits, devices map[string outdoor := e.outdoor in.PV = e.pv learned := e.learned + minutes := e.minutes + steps := e.steps e.mu.Unlock() + if minutes != nil { + in.Minutes = minutes() + } + if steps != nil { + in.Steps = steps + } if learned != nil { in.Learned = learned() } @@ -432,6 +442,12 @@ func (e *Engine) input(now time.Time, limits learnrec.Limits, devices map[string return in } +// ReplayInput builds the input of a round at now for the checks that replay a +// rule. It reads the same days, learned values and minutes as a round does. +func (e *Engine) ReplayInput(now time.Time) *Input { + return e.input(now, e.limits(), e.devices()) +} + // SetPV gives the engine the roof model and the sky raster. A round reads them // through Input.PV. The function is called by the detectors that need the // model, so it should return a copy of the raster. Without it no model exists. @@ -449,6 +465,22 @@ func (e *Engine) SetLearned(f func() map[string]LearnedEntry) { e.learned = f } +// SetMinutes gives the engine the minute record. A round reads it into +// Input.Minutes. Without it the replay works from the quarter hours. +func (e *Engine) SetMinutes(f func() learnrec.Reader) { + e.mu.Lock() + defer e.mu.Unlock() + e.minutes = f +} + +// SetSteps gives the engine the regulator steps. A round passes the reader +// into Input.Steps. Without it the detectors that need the steps find nothing. +func (e *Engine) SetSteps(f func(scenario string, from, to time.Time) []Step) { + e.mu.Lock() + defer e.mu.Unlock() + e.steps = f +} + // SetOutdoor gives the engine the outdoor temperature entity. It is read on // every round into Input.Outdoor. Without it the round has no entity. func (e *Engine) SetOutdoor(f func() OutdoorSource) { diff --git a/dashboard/internal/autolearn/finding.go b/dashboard/internal/autolearn/finding.go index fd37d879..6f3581c6 100644 --- a/dashboard/internal/autolearn/finding.go +++ b/dashboard/internal/autolearn/finding.go @@ -101,6 +101,18 @@ type Evidence struct { Missing bool `json:"missing,omitempty"` // Marks holds the steps of a scale, such as the stages of staggered thresholds. Marks []Mark `json:"marks,omitempty"` + // Scales holds one Ist and Soll bar per parameter of a scale evidence. When + // it is set the scale draws these bars and ignores IstValue and SollValue. + Scales []ScaleBar `json:"scales,omitempty"` +} + +// ScaleBar is one parameter of a scale evidence: its Ist and Soll value in +// its unit. Name is the parameter name, the catalog key is automations.learn.param.. +type ScaleBar struct { + Name string `json:"name"` + Ist float64 `json:"ist"` + Soll float64 `json:"soll"` + Unit string `json:"unit,omitempty"` } // Mark is one step on the scale of a finding. Dormant marks a step that the diff --git a/dashboard/internal/autolearn/gates.go b/dashboard/internal/autolearn/gates.go index de5eed3b..25ee988c 100644 --- a/dashboard/internal/autolearn/gates.go +++ b/dashboard/internal/autolearn/gates.go @@ -56,6 +56,10 @@ func Gate(cands []Candidate, doc Doc, prev map[string]Shown) (out []Finding, sho continue } + if c.Replay != nil && replayAddsGrid(*c.Replay) { + continue + } + conf := f.Confidence var score float64 if f.Group != "check" { @@ -71,6 +75,9 @@ func Gate(cands []Candidate, doc Doc, prev map[string]Shown) (out []Finding, sho if !pass || !compatible(f, doc) { continue } + if c.Replay != nil && c.Replay.Estimate && conf == "high" { + conf = "estimate" + } score = kwh * confidenceWeight(conf) } f.Confidence = conf @@ -137,7 +144,7 @@ func Gate(cands []Candidate, doc Doc, prev map[string]Shown) (out []Finding, sho // displayFinding returns f with the stabilised values in its summary params // and in the prefills of its fixes. Only keys that exist in those maps change, -// the key "time" is shown as HH:MM. f and its maps are not modified. +// the keys "time" and "latest" are shown as HH:MM. f and its maps are not modified. func displayFinding(f Finding, values map[string]float64) Finding { if len(values) == 0 { return f @@ -177,7 +184,7 @@ func displayFinding(f Finding, values map[string]float64) Finding { // displayValue formats a stabilised value for display. Times are minutes of // the day and shown as HH:MM, like the detectors do. func displayValue(key string, v float64) any { - if key == "time" { + if key == "time" || key == "latest" { return switchTimeClock(v) } return v @@ -212,6 +219,14 @@ var benefitMinimum = map[string]float64{ "switches_day": 10, } +// replayAddsGrid reports whether the suggestion draws more extra grid import +// than the export it uses. Such a suggestion is dropped. +func replayAddsGrid(v ReplayVerdict) bool { + extraGrid := v.Alt.GridWh - v.Base.GridWh + usedExport := v.Base.ExportWh - v.Alt.ExportWh + return extraGrid > usedExport +} + // benefitKWh converts a benefit to kWh per week with the fixed rates of spec // 15.8: 1 kWh = 5 handgriffe = 20 switches. It reports false for an unknown // unit or a benefit below its minimum. diff --git a/dashboard/internal/autolearn/gates_test.go b/dashboard/internal/autolearn/gates_test.go index ad7e811e..6b822ee7 100644 --- a/dashboard/internal/autolearn/gates_test.go +++ b/dashboard/internal/autolearn/gates_test.go @@ -261,3 +261,27 @@ func TestBenefitKWhDropsNaN(t *testing.T) { t.Error("benefit at the minimum was dropped") } } + +// TestGateShowsStabilisedLatestAsClock checks the shift suggestion: its latest +// start is a minute of the day in Values, and the summary and the prefill show +// it as HH:MM, not as a number the assistant cannot read. +func TestGateShowsStabilisedLatestAsClock(t *testing.T) { + cand := gateCand("shift:spuelmaschine", "shift", 1, 2, 2, true) + cand.Finding.Summary = Text{Code: "shift.load", Params: map[string]any{"device": "spuelmaschine", "latest": "20:45"}} + cand.Finding.Apply = []Fix{{Code: "shift_start", Template: "shift_start", + Prefill: map[string]any{"device": "spuelmaschine", "latest": "20:45", "on_w": 500.0}}} + cand.Values = map[string]float64{"latest": 1245} + cand.Spread = map[string]float64{"latest": 8} + prev := map[string]Shown{"shift:spuelmaschine": {Lower: 2, Values: map[string]float64{"latest": 1245}}} + + out, _ := Gate([]Candidate{cand}, Doc{}, prev) + if len(out) != 1 { + t.Fatalf("got %v, want one finding", gateIDs(out)) + } + if got := out[0].Summary.Params["latest"]; got != "20:45" { + t.Errorf("summary latest = %v, want 20:45", got) + } + if got := out[0].Apply[0].Prefill["latest"]; got != "20:45" { + t.Errorf("prefill latest = %v, want 20:45", got) + } +} diff --git a/dashboard/internal/autolearn/input.go b/dashboard/internal/autolearn/input.go index 4a33909d..4f475fbd 100644 --- a/dashboard/internal/autolearn/input.go +++ b/dashboard/internal/autolearn/input.go @@ -44,6 +44,13 @@ type Input struct { // before that were empty before sunrise, and whether a record of that week // exists. Nil, or a week without a record, means the empty finding is not made. PriorEmptyShare func(week int) (float64, bool) + // Minutes reads the minute record. Nil when none is wired, and the replay + // then works from the quarter hours of the day files. + Minutes learnrec.Reader + // Steps reads the regulator steps of a scenario from and to, both ends + // included. Nil when no step log is wired, and the detectors that need the + // steps then find nothing. + Steps func(scenario string, from, to time.Time) []Step } // OutdoorSource names the outdoor temperature entity: its unique id, its state @@ -91,6 +98,9 @@ type Candidate struct { Benefit Benefit Values map[string]float64 Spread map[string]float64 + // Replay is the replay check of an energy suggestion, nil when the + // suggestion is not replayed. + Replay *ReplayVerdict // Value is set on a learned value. Such a candidate is no finding and // reaches the engine through Values, not Candidates. Value *Value diff --git a/dashboard/internal/autolearn/minrun.go b/dashboard/internal/autolearn/minrun.go new file mode 100644 index 00000000..01f95fed --- /dev/null +++ b/dashboard/internal/autolearn/minrun.go @@ -0,0 +1,21 @@ +package autolearn + +import "github.com/Developer-Simon/energy-node-dashboard/internal/energy" + +// minRunForRole is the minimum run time in seconds a device tolerates before it +// may switch off (spec 15.4 "Takten", as a table in Go). A heat pump takes +// 600 s, a wallbox 180 s, a light nothing. Every other switchable load, a heater +// included, takes 300 s, because the device has no heater role in the energy +// model. The longer value is the safe side for a heater. +func minRunForRole(info DeviceInfo) float64 { + switch { + case info.Light: + return 0 + case info.Role == energy.RoleHeatPump: + return 600 + case info.Role == energy.RoleWallbox: + return 180 + default: + return 300 + } +} diff --git a/dashboard/internal/autolearn/minrun_test.go b/dashboard/internal/autolearn/minrun_test.go new file mode 100644 index 00000000..58eb08e4 --- /dev/null +++ b/dashboard/internal/autolearn/minrun_test.go @@ -0,0 +1,26 @@ +package autolearn + +import ( + "testing" + + "github.com/Developer-Simon/energy-node-dashboard/internal/energy" +) + +func TestMinRunForRole(t *testing.T) { + cases := []struct { + name string + info DeviceInfo + want float64 + }{ + {"heat pump", DeviceInfo{Role: energy.RoleHeatPump}, 600}, + {"wallbox", DeviceInfo{Role: energy.RoleWallbox}, 180}, + {"light", DeviceInfo{Light: true}, 0}, + {"heater without role", DeviceInfo{Switchable: true}, 300}, + {"other role", DeviceInfo{Role: energy.RoleLoad}, 300}, + } + for _, c := range cases { + if got := minRunForRole(c.info); got != c.want { + t.Errorf("%s: minRunForRole = %v, want %v", c.name, got, c.want) + } + } +} diff --git a/dashboard/internal/autolearn/observed.go b/dashboard/internal/autolearn/observed.go index e19d4a2c..8527883a 100644 --- a/dashboard/internal/autolearn/observed.go +++ b/dashboard/internal/autolearn/observed.go @@ -1,6 +1,7 @@ package autolearn import ( + "context" "math" "os" "sort" @@ -15,6 +16,12 @@ const ( frequentWindow = 24 * time.Hour // seasonWindow is the period the seasonal maximum is taken from. seasonWindow = 365 * 24 * time.Hour + // frequentReplayDays is how many days the replay of the frequent check covers. + frequentReplayDays = 14 + // hysteresisStepW is the step the minute hysteresis is rounded up to. + hysteresisStepW = 50.0 + // cooldownFloorS is the shortest cooldown the frequent check proposes. + cooldownFloorS = 300 ) // PVSource returns the stored roof model, the sky raster and whether a model @@ -63,7 +70,7 @@ func ObservedFindings(doc Doc, st ObserverState, season SeasonalSource, now time // ObservedFindingsWith is ObservedFindingsWithPV without a PV source. func ObservedFindingsWith(doc Doc, st ObserverState, season SeasonalSource, now time.Time, th Thresholds) []Finding { - return ObservedFindingsWithPV(doc, st, season, nil, now, th) + return ObservedFindingsWithPV(doc, st, season, nil, nil, now, th) } // ObservedFindingsWithPV checks the rules against what was observed. A rule that @@ -74,8 +81,10 @@ func ObservedFindingsWith(doc Doc, st ObserverState, season SeasonalSource, now // reported as a seasonal rest when the season had a higher maximum. season may // be nil, which skips the seasonal check. pv may be nil. With a safe PV model // and the site location, a PV or grid export threshold is checked against the -// clear-sky curve instead of the seasonal maximum. -func ObservedFindingsWithPV(doc Doc, st ObserverState, season SeasonalSource, pv PVSource, now time.Time, th Thresholds) []Finding { +// clear-sky curve instead of the seasonal maximum. in may be nil, which keeps +// the hysteresis of the frequent check to its fallback and leaves out the +// replay evidence. +func ObservedFindingsWithPV(doc Doc, st ObserverState, season SeasonalSource, pv PVSource, in *Input, now time.Time, th Thresholds) []Finding { var findings []Finding for _, rule := range doc.Rules { if !rule.Enabled { @@ -85,7 +94,7 @@ func ObservedFindingsWithPV(doc Doc, st ObserverState, season SeasonalSource, pv if !seen { continue } - if f, ok := frequentFinding(rule, stats, now, th.FrequentMinCount); ok { + if f, ok := frequentFinding(rule, stats, in, now, th.FrequentMinCount); ok { findings = append(findings, f) } if f, ok := neverFiredFinding(rule, stats, st, season, pv, doc.Location, now, th); ok { @@ -103,8 +112,10 @@ func ObservedFindingsWithPV(doc Doc, st ObserverState, season SeasonalSource, pv } // frequentFinding reports the busiest hour of the last 24 h if it reached the -// frequent count. The evidence covers the 4 h around that hour. -func frequentFinding(rule Rule, stats RuleStats, now time.Time, minCount int) (Finding, bool) { +// frequent count. The evidence covers the 4 h around that hour. With in, the +// hysteresis comes from the minute noise and the replay of the rule with it +// gives the events that are left as the proposed times. +func frequentFinding(rule Rule, stats RuleStats, in *Input, now time.Time, minCount int) (Finding, bool) { first := now.Add(-frequentWindow).Unix() / 3600 last := now.Unix() / 3600 var peak int64 @@ -132,19 +143,39 @@ func frequentFinding(rule Rule, stats RuleStats, now time.Time, minCount int) (F } var fixes []Fix + confidence := "high" + hystIdx := -1 + hyst := 0 for i, c := range rule.Conditions { // A learned threshold has no fixed number to derive a hysteresis from. if _, learned := c.Learned["threshold"]; learned { continue } if c.Type == "balance_threshold" && c.Hysteresis == 0 { - fixes = append(fixes, Fix{Code: "set_hysteresis", RuleID: rule.ID, Ops: []Op{ - {Path: []any{"conditions", i, "hysteresis"}, Value: hysteresisFor(c.Threshold)}}}) + hystIdx, hyst = i, hysteresisFor(c.Threshold) + if v, ok := minuteHysteresis(in, rule, c, now); ok { + hyst = v + } break } } + if hystIdx >= 0 { + fixes = append(fixes, Fix{Code: "set_hysteresis", RuleID: rule.ID, Ops: []Op{ + {Path: []any{"conditions", hystIdx, "hysteresis"}, Value: hyst}}}) + if in != nil { + if soll, est, ok := frequentSoll(in, rule, hystIdx, hyst, from, to); ok { + // The replayed triggers are the Soll. The span of the Ist triggers + // would stand in for it, so it is dropped. + ev.Soll = soll + ev.SollSpans = nil + if est { + confidence = "estimate" + } + } + } + } fixes = append(fixes, Fix{Code: "set_cooldown", RuleID: rule.ID, Ops: []Op{ - {Path: []any{"cooldown_seconds"}, Value: 600}}}) + {Path: []any{"cooldown_seconds"}, Value: frequentCooldown(ist)}}}) return Finding{ ID: FindingID("frequent", rule.ID), @@ -152,7 +183,7 @@ func frequentFinding(rule Rule, stats RuleStats, now time.Time, minCount int) (F Group: "check", RuleIDs: []string{rule.ID}, Severity: "warn", - Confidence: "high", + Confidence: confidence, Summary: Text{Code: "check.frequent", Params: map[string]any{ "rule": rule.Name, "count": peakCount}}, Evidence: ev, @@ -161,6 +192,81 @@ func frequentFinding(rule Rule, stats RuleStats, now time.Time, minCount int) (F }, true } +// minuteHysteresis is 2 times the minute noise of the condition signal plus +// the load step, the operating power of the device, rounded up to 50 W. It +// reports false without minute days near the threshold or without an operating +// power, and then the fallback of hysteresisFor applies. +func minuteHysteresis(in *Input, rule Rule, c Condition, now time.Time) (int, bool) { + if in == nil || in.Minutes == nil { + return 0, false + } + device, _, ok := thresholdDevice(in, rule) + if !ok { + return 0, false + } + p, ok := learnedOperatingPower(in.Learned, device) + if !ok { + return 0, false + } + noise, ok := MinuteNoise(in.Minutes, "b:"+c.Field, c.Threshold, now.AddDate(0, 0, -engineHistoryDays), now) + if !ok { + return 0, false + } + return int(math.Ceil((2*noise+p)/hysteresisStepW) * hysteresisStepW), true +} + +// frequentSoll replays the rule with hysteresis h over the last frequentReplayDays +// days and returns the trigger times left in [from, to), in Unix seconds. est +// is set when stretched quarter hours took part. ok is false when the rule +// cannot be replayed or no minutes exist. +func frequentSoll(in *Input, rule Rule, idx, h int, from, to int64) (soll []int64, est, ok bool) { + device, info, ok := thresholdDevice(in, rule) + if !ok { + return nil, false, false + } + p, ok := learnedOperatingPower(in.Learned, device) + if !ok { + return nil, false, false + } + raw, err := thresholdRuleJSON(rule, idx, rule.Conditions[idx].Threshold, float64(h)) + if err != nil { + return nil, false, false + } + cycle, _ := surWinLearnedNumber(in.Learned, "device/"+device+"/cycle_wh") + minutes, est := ReplayDays(in, frequentReplayDays) + if len(minutes) == 0 { + return nil, false, false + } + var site sun.Location + if in.Doc.Location != nil { + site = *in.Doc.Location + } + target := ReplayTarget{RuleID: rule.ID, Device: device, OpW: p, + PeakW: feedbackInrush(in.Days, device, p), CycleWh: cycle, MinRunS: reliabilityMinRuntime(info)} + res, err := Replay(context.Background(), raw, target, minutes, RealState(in, device, minutes), replayLoc(in), site) + if err != nil { + return nil, false, false + } + first := minutes[0].At.Unix() + soll = []int64{} + for _, f := range res.Fires { + if t := first + f; t >= from && t < to { + soll = append(soll, t) + } + } + return soll, est, true +} + +// frequentCooldown is 3 times the mean distance of the triggers in the burst, +// at least cooldownFloorS, rounded up to whole seconds. +func frequentCooldown(ist []int64) int { + if len(ist) < 2 { + return cooldownFloorS + } + mean := float64(ist[len(ist)-1]-ist[0]) / float64(len(ist)-1) + return max(cooldownFloorS, int(math.Ceil(3*mean))) +} + // hysteresisFor is 10 % of the threshold, rounded to 50 W, at least 100 W. func hysteresisFor(threshold float64) int { h := int(math.Round(threshold*0.1/50) * 50) diff --git a/dashboard/internal/autolearn/observed_test.go b/dashboard/internal/autolearn/observed_test.go index 612a5b10..1b3771d0 100644 --- a/dashboard/internal/autolearn/observed_test.go +++ b/dashboard/internal/autolearn/observed_test.go @@ -95,8 +95,8 @@ func TestObservedFrequentWithBothFixes(t *testing.T) { } cool := f.Apply[1] - if cool.Code != "set_cooldown" || len(cool.Ops) != 1 || cool.Ops[0].Path[0] != "cooldown_seconds" || cool.Ops[0].Value != 600 { - t.Errorf("second fix = %+v, want set_cooldown to 600", cool) + if cool.Code != "set_cooldown" || len(cool.Ops) != 1 || cool.Ops[0].Path[0] != "cooldown_seconds" || cool.Ops[0].Value != 300 { + t.Errorf("second fix = %+v, want set_cooldown to 300", cool) } if len(f.Facts) != 1 || f.Facts[0].Code != "per_hour_max" || f.Facts[0].Value != 15 { @@ -327,7 +327,7 @@ func TestObservedNeverFiredPVSeasonalWeekIsInfo(t *testing.T) { t.Fatal("SeasonWeekFor(3000) from testNow: not ok, want a week") } - findings := ObservedFindingsWithPV(doc, st, fakeSeason{ok: false}, pvSource(pvRoof(), true), testNow, DefaultThresholds()) + findings := ObservedFindingsWithPV(doc, st, fakeSeason{ok: false}, pvSource(pvRoof(), true), nil, testNow, DefaultThresholds()) got := findKind(findings, "never_fired") if len(got) != 1 { t.Fatalf("never_fired findings = %d, want 1: %+v", len(got), findings) @@ -349,7 +349,7 @@ func TestObservedNeverFiredPVAboveRoofIsWarnWithFix(t *testing.T) { st := neverFiredStateFor("pv", testNow.Add(-40*24*time.Hour), 1850) findings := ObservedFindingsWithPV(doc, st, fakeSeason{maxW: 5000, months: []int{6}, days: 300, ok: true}, - pvSourceWith(pvRoof(), rasterAt(180, 61, 5000)), testNow, DefaultThresholds()) + pvSourceWith(pvRoof(), rasterAt(180, 61, 5000)), nil, testNow, DefaultThresholds()) got := findKind(findings, "never_fired") if len(got) != 1 { t.Fatalf("never_fired findings = %d, want 1: %+v", len(got), findings) @@ -373,7 +373,7 @@ func TestObservedNeverFiredPVWithoutModelUsesSeasonMax(t *testing.T) { "no model": pvSource(PVModel{}, false), "not safe": pvSource(PVModel{Surfaces: pvRoof().Surfaces, CapW: 5250}, true), } { - findings := ObservedFindingsWithPV(doc, st, season, src, testNow, DefaultThresholds()) + findings := ObservedFindingsWithPV(doc, st, season, src, nil, testNow, DefaultThresholds()) got := findKind(findings, "never_fired") if len(got) != 1 || got[0].Summary.Code != "check.seasonal_rest" { t.Errorf("%s: findings = %+v, want check.seasonal_rest", name, got) @@ -389,15 +389,125 @@ func TestObservedNeverFiredPVWinterRasterFallsBack(t *testing.T) { winter := rasterAt(180, 14, 1800) findings := ObservedFindingsWithPV(doc, st, fakeSeason{maxW: 5000, months: []int{6}, days: 300, ok: true}, - pvSourceWith(pvRoof(), winter), testNow, DefaultThresholds()) + pvSourceWith(pvRoof(), winter), nil, testNow, DefaultThresholds()) if got := findKind(findings, "never_fired"); len(got) != 0 { t.Fatalf("never_fired with a winter raster = %+v, want none", got) } findings = ObservedFindingsWithPV(doc, st, fakeSeason{maxW: 6500, months: []int{6}, days: 300, ok: true}, - pvSourceWith(pvRoof(), winter), testNow, DefaultThresholds()) + pvSourceWith(pvRoof(), winter), nil, testNow, DefaultThresholds()) got := findKind(findings, "never_fired") if len(got) != 1 || got[0].Summary.Code != "check.seasonal_rest" { t.Fatalf("findings = %+v, want check.seasonal_rest from the seasonal maximum", got) } } + +// spikeDays returns the balance keys of the given days: the export is 1000 W +// with every tenth minute at 1080 W, the load total is 1000 W. +func spikeDays(days ...string) map[string]map[string][]float32 { + out := make(map[string]map[string][]float32, len(days)) + for _, d := range days { + grid := make([]float32, 1440) + load := make([]float32, 1440) + for m := range grid { + grid[m], load[m] = 1000, 1000 + if m%10 == 5 { + grid[m] = 1080 + } + } + out[d] = map[string][]float32{"b:grid_export": grid, "b:load_total": load} + } + return out +} + +// frequentInputFor is an input with a 1000 W heater on switch.heater and the +// given minute days. +func frequentInputFor(t *testing.T, now time.Time, days map[string]map[string][]float32) *Input { + t.Helper() + doc := staticDoc(t, `{"rules": [{"id": "heat", "name": "Heater", "enabled": true, + "conditions": [{"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 1000}], + "actions": [{"type": "publish", "topic": "heater/set", "payload": "ON", "entity_id": "switch.heater"}]}]}`) + in := &Input{ + Now: now, + Loc: time.UTC, + Doc: doc, + Devices: map[string]DeviceInfo{"heater": {ID: "heater", Switchable: true, Entities: []string{"switch.heater"}}}, + Learned: map[string]LearnedEntry{"device/heater/op_power_w": {Key: "device/heater/op_power_w", Value: 1000.0}}, + } + if days != nil { + in.Minutes = fakeMinutes{loc: time.UTC, days: days} + } + return in +} + +func TestObservedFrequentHysteresisFromMinuteNoise(t *testing.T) { + in := frequentInputFor(t, testNow, spikeDays("2026-11-18", "2026-11-17", "2026-11-16")) + doc := in.Doc + findings := ObservedFindingsWithPV(doc, frequentState(15), nil, nil, in, testNow, DefaultThresholds()) + got := findKind(findings, "frequent") + if len(got) != 1 { + t.Fatalf("frequent findings = %d, want 1", len(got)) + } + hyst := got[0].Apply[0] + if hyst.Code != "set_hysteresis" || hyst.Ops[0].Value != 1200 { + t.Fatalf("hysteresis fix = %+v, want 1200 (2 x 80 W noise + 1000 W load, up to 50 W)", hyst) + } +} + +func TestObservedFrequentHysteresisFallsBackWithoutMinutes(t *testing.T) { + in := frequentInputFor(t, testNow, nil) + findings := ObservedFindingsWithPV(in.Doc, frequentState(15), nil, nil, in, testNow, DefaultThresholds()) + got := findKind(findings, "frequent") + if len(got) != 1 { + t.Fatalf("frequent findings = %d, want 1", len(got)) + } + if v := got[0].Apply[0].Ops[0].Value; v != hysteresisFor(1000) { + t.Fatalf("hysteresis = %v, want the fallback %d", v, hysteresisFor(1000)) + } +} + +func TestObservedFrequentEvidenceSollFromReplay(t *testing.T) { + // The burst sits on 19 Nov at 09:00, the replay runs on the days before 20 Nov. + now := time.Date(2026, 11, 20, 8, 0, 0, 0, time.UTC) + in := frequentInputFor(t, now, spikeDays("2026-11-19", "2026-11-18")) + findings := ObservedFindingsWithPV(in.Doc, frequentState(15), nil, nil, in, now, DefaultThresholds()) + got := findKind(findings, "frequent") + if len(got) != 1 { + t.Fatalf("frequent findings = %d, want 1", len(got)) + } + if got[0].Evidence.Soll == nil { + t.Fatalf("Soll = nil, want the replayed triggers with the hysteresis") + } + for _, s := range got[0].Evidence.Soll { + if s < got[0].Evidence.From || s >= got[0].Evidence.To { + t.Errorf("Soll %d outside the evidence window", s) + } + } +} + +func TestObservedFrequentCooldownFromBurstGap(t *testing.T) { + if got := frequentCooldown([]int64{0, 60, 120}); got != 300 { + t.Errorf("cooldown for 60 s gaps = %d, want the floor 300", got) + } + if got := frequentCooldown([]int64{0, 200, 400}); got != 600 { + t.Errorf("cooldown for 200 s gaps = %d, want 600", got) + } +} + +// With a replay the Soll lane shows the replayed triggers, not the span of the +// burst, so the span of the Ist triggers is dropped. +func TestObservedFrequentReplayReplacesIstSpan(t *testing.T) { + now := time.Date(2026, 11, 20, 8, 0, 0, 0, time.UTC) + in := frequentInputFor(t, now, spikeDays("2026-11-19", "2026-11-18")) + findings := ObservedFindingsWithPV(in.Doc, frequentState(15), nil, nil, in, now, DefaultThresholds()) + got := findKind(findings, "frequent") + if len(got) != 1 { + t.Fatalf("frequent findings = %d, want 1", len(got)) + } + if got[0].Evidence.Soll == nil { + t.Fatalf("Soll = nil, want the replay") + } + if len(got[0].Evidence.SollSpans) != 0 { + t.Errorf("SollSpans = %v, want none beside the replayed Soll", got[0].Evidence.SollSpans) + } +} diff --git a/dashboard/internal/autolearn/replay.go b/dashboard/internal/autolearn/replay.go new file mode 100644 index 00000000..341186e8 --- /dev/null +++ b/dashboard/internal/autolearn/replay.go @@ -0,0 +1,378 @@ +package autolearn + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "math" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// ErrNotReplayable marks a rule or scenario whose conditions reach outside the +// energy core, so the replay cannot judge it. +var ErrNotReplayable = errors.New("not replayable") + +// ReplayMinute is one tick of the replay: the balance and the learned values +// that hold at At. A nil Balance means the balance is stale at that tick. +type ReplayMinute struct { + At time.Time + Balance map[string]float64 + Learned map[string]float64 +} + +// ReplayTarget is the device the replay switches. OpW is the operating power, PeakW +// the start peak added during the first two minutes after switching on, +// CycleWh the energy of one cycle (0 for a device without cycle) and MinRunS +// the minimum run time before a device without cycle may switch off. +type ReplayTarget struct { + RuleID, ScenarioID, Device string + OpW, PeakW, CycleWh, MinRunS float64 +} + +// ReplayResult is the outcome of one replay. Fires are the seconds since the +// first tick at which the rule fired or the scenario started. Phases holds the +// result of every tick, On the simulated state of the target at every tick. +type ReplayResult struct { + Fires []int64 + On []bool + Phases []string + PVWh float64 + GridWh float64 + ExportWh float64 + Switches int + Estimate bool +} + +// replaySubject is the parsed rule or scenario that a replay runs. +type replaySubject struct { + rule *replayRule + scenario *replayScenario +} + +// Replayable reports ErrNotReplayable, wrapped, when a condition of the rule +// reaches outside the energy core. It is nil otherwise. +func Replayable(r Rule) error { + _, err := ruleFromStruct(r) + return err +} + +// ReplayableScenario checks a scenario given as its raw JSON object, since the +// Scenario type does not keep its conditions. It wraps ErrNotReplayable when +// the scenario is not replayable. +func ReplayableScenario(raw json.RawMessage) error { + _, err := parseReplayScenario(raw) + return err +} + +// Replay runs a rule or a scenario minute by minute in a closed loop. rule is +// a Rule or the raw JSON object of a rule or a scenario. real holds the real +// switch state of the target per minute, site the location for sun windows +// (the zero value means no location). +func Replay(ctx context.Context, rule any, target ReplayTarget, minutes []ReplayMinute, real []bool, loc *time.Location, site sun.Location) (ReplayResult, error) { + return replayCore(ctx, rule, target, minutes, real, time.Minute, loc, site) +} + +// replayCore runs the replay with a tick of step. Hold, cooldown, repeat and +// minimum run times count real seconds with step. +// +// settling_seconds of the service is deliberately not modelled. It only blocks +// the first moments after a service start, while a replay over up to 56 days +// describes the settled operation. +func replayCore(ctx context.Context, rule any, target ReplayTarget, ticks []ReplayMinute, real []bool, step time.Duration, loc *time.Location, site sun.Location) (ReplayResult, error) { + subject, err := parseSubject(rule) + if err != nil { + return ReplayResult{}, err + } + if loc == nil { + loc = time.UTC + } + env := replayEnv{loc: loc, site: site, hasSite: site != (sun.Location{})} + res := ReplayResult{On: make([]bool, len(ticks)), Phases: make([]string, len(ticks))} + if len(ticks) == 0 { + return res, nil + } + start := ticks[0].At + hours := step.Hours() + + var rm *ruleMachine + var sm *scenarioMachine + if subject.rule != nil { + rm = newRuleMachine(*subject.rule) + } else { + sm = newScenarioMachine(*subject.scenario) + } + + on := false + var onSince time.Time + cycleUsed := 0.0 + for i, tick := range ticks { + if err := ctx.Err(); err != nil { + return ReplayResult{}, err + } + now := tick.At + realOn := i < len(real) && real[i] + + // Closed loop: the balance of this tick carries the difference between + // the simulated and the real switch state of the target. + delta := loopDelta(target, on, realOn, onSince, now) + balance, learned := applyDelta(tick.Balance, tick.Learned, delta) + ec := evalCtx{now: now, env: env, balance: balance, learned: learned} + + var startEvent, wanted bool + if rm != nil { + phase, fired := rm.tick(ec) + res.Phases[i] = phase + startEvent, wanted = fired, rm.fired + if fired { + res.Fires = append(res.Fires, secondsSince(start, now)) + } + } else { + phase, started := sm.tick(ec) + res.Phases[i] = phase + startEvent, wanted = started, phase == "active" + if started { + res.Fires = append(res.Fires, secondsSince(start, now)) + } + } + + prevOn := on + switch { + case startEvent: + on, onSince, cycleUsed = true, now, 0 + case on && target.CycleWh > 0 && cycleUsed >= target.CycleWh: + on = false + case on && target.CycleWh <= 0 && !wanted && now.Sub(onSince).Seconds() >= target.MinRunS: + on = false + } + if on { + cycleUsed += target.OpW * hours + } + if on != prevOn { + res.Switches++ + } + res.On[i] = on + + if balance != nil { + res.PVWh += balance["pv"] * hours + res.GridWh += balance["grid_import"] * hours + res.ExportWh += balance["grid_export"] * hours + } + } + return res, nil +} + +// loopDelta is the extra load, in watts, that the simulated switch state adds +// to the real balance of this tick. Positive values are consumption the real +// data does not show, negative values are consumption it still shows. +func loopDelta(t ReplayTarget, simOn, realOn bool, onSince, now time.Time) float64 { + switch { + case simOn && !realOn: + delta := t.OpW + if now.Sub(onSince) <= 2*time.Minute { + delta += t.PeakW + } + return delta + case realOn && !simOn: + return -t.OpW + } + return 0 +} + +// applyDelta returns the balance and the learned values of one tick after the +// load delta. A positive delta takes grid export first, then the PV reserve, +// then grid import. A negative delta lowers grid import first and raises grid +// export with the rest. The inputs are not changed. +func applyDelta(balance, learned map[string]float64, delta float64) (map[string]float64, map[string]float64) { + if balance == nil || delta == 0 { + return balance, learned + } + b := make(map[string]float64, len(balance)+1) + for k, v := range balance { + b[k] = v + } + // add changes a key only when it exists or the change is not zero, so a + // missing key is not created by a zero amount. + add := func(key string, inc float64) { + if _, ok := b[key]; ok || inc != 0 { + b[key] += inc + } + } + add("load_total", delta) + if delta > 0 { + take := math.Min(math.Max(b["grid_export"], 0), delta) + add("grid_export", -take) + rest := delta - take + if reserve, ok := learned[reserveKey]; ok && rest > 0 { + used := math.Min(math.Max(reserve, 0), rest) + learned = copyLearned(learned) + learned[reserveKey] = reserve - used + rest -= used + } + add("grid_import", rest) + return b, learned + } + cut := -delta + take := math.Min(math.Max(b["grid_import"], 0), cut) + add("grid_import", -take) + add("grid_export", cut-take) + return b, learned +} + +const reserveKey = "site/pv_reserve_w" + +func copyLearned(in map[string]float64) map[string]float64 { + out := make(map[string]float64, len(in)) + for k, v := range in { + out[k] = v + } + return out +} + +func secondsSince(start, now time.Time) int64 { + return int64(now.Sub(start) / time.Second) +} + +// parseSubject turns the rule argument of Replay into a rule or a scenario. +func parseSubject(rule any) (replaySubject, error) { + switch v := rule.(type) { + case Rule: + r, err := ruleFromStruct(v) + if err != nil { + return replaySubject{}, err + } + return replaySubject{rule: r}, nil + case json.RawMessage: + return parseRawSubject(v) + case []byte: + return parseRawSubject(v) + case Scenario: + return replaySubject{}, fmt.Errorf("%w: a Scenario keeps no conditions, pass its raw JSON", ErrNotReplayable) + default: + return replaySubject{}, fmt.Errorf("replay: unsupported rule type %T", rule) + } +} + +func parseRawSubject(raw json.RawMessage) (replaySubject, error) { + var probe map[string]json.RawMessage + if err := json.Unmarshal(raw, &probe); err != nil { + return replaySubject{}, fmt.Errorf("replay: %w", err) + } + if _, ok := probe["when"]; ok { + s, err := parseReplayScenario(raw) + if err != nil { + return replaySubject{}, err + } + return replaySubject{scenario: s}, nil + } + r, err := parseReplayRule(raw) + if err != nil { + return replaySubject{}, err + } + return replaySubject{rule: r}, nil +} + +// replayRule is a rule as far as the replay needs it. +type replayRule struct { + id string + enabled bool + conds []replayCond + cooldownS float64 + repeatS float64 +} + +func ruleFromStruct(r Rule) (*replayRule, error) { + conds := make([]replayCond, 0, len(r.Conditions)) + for _, c := range r.Conditions { + parsed, err := parseReplayCond(c.Raw) + if err != nil { + return nil, err + } + conds = append(conds, parsed) + } + return &replayRule{id: r.ID, enabled: r.Enabled, conds: conds, + cooldownS: r.CooldownSeconds, repeatS: r.RepeatSeconds}, nil +} + +func parseReplayRule(raw json.RawMessage) (*replayRule, error) { + var wire struct { + ID string `json:"id"` + Enabled bool `json:"enabled"` + CooldownSeconds float64 `json:"cooldown_seconds"` + RepeatSeconds float64 `json:"repeat_seconds"` + Conditions []json.RawMessage `json:"conditions"` + } + if err := json.Unmarshal(raw, &wire); err != nil { + return nil, fmt.Errorf("replay: %w", err) + } + conds := make([]replayCond, 0, len(wire.Conditions)) + for _, c := range wire.Conditions { + parsed, err := parseReplayCond(c) + if err != nil { + return nil, err + } + conds = append(conds, parsed) + } + return &replayRule{id: wire.ID, enabled: wire.Enabled, conds: conds, + cooldownS: wire.CooldownSeconds, repeatS: wire.RepeatSeconds}, nil +} + +// parseReplayScenario reads a scenario. Only the modes none and hold are +// replayable, a regulator is not. +func parseReplayScenario(raw json.RawMessage) (*replayScenario, error) { + var wire struct { + ID string `json:"id"` + Enabled bool `json:"enabled"` + When *struct { + Conditions []json.RawMessage `json:"conditions"` + } `json:"when"` + Until *struct { + Conditions []json.RawMessage `json:"conditions"` + } `json:"until"` + MinRunS float64 `json:"min_run_s"` + MaxDurationS *float64 `json:"max_duration_s"` + CooldownS float64 `json:"cooldown_s"` + While *struct { + Mode string `json:"mode"` + } `json:"while"` + } + if err := json.Unmarshal(raw, &wire); err != nil { + return nil, fmt.Errorf("replay: %w", err) + } + if wire.When == nil { + return nil, fmt.Errorf("replay: scenario %q has no when block", wire.ID) + } + if wire.While != nil && wire.While.Mode != "" && wire.While.Mode != "none" && wire.While.Mode != "hold" { + return nil, fmt.Errorf("%w: while mode %q", ErrNotReplayable, wire.While.Mode) + } + s := &replayScenario{id: wire.ID, enabled: wire.Enabled, minRunS: wire.MinRunS, cooldownS: wire.CooldownS} + var err error + if s.when, err = parseConditionList(wire.When.Conditions); err != nil { + return nil, err + } + if wire.Until != nil { + s.hasUntil = true + if s.until, err = parseConditionList(wire.Until.Conditions); err != nil { + return nil, err + } + } + if wire.MaxDurationS != nil { + s.hasMaxDuration = true + s.maxDurationS = *wire.MaxDurationS + } + return s, nil +} + +func parseConditionList(raws []json.RawMessage) ([]replayCond, error) { + out := make([]replayCond, 0, len(raws)) + for _, c := range raws { + parsed, err := parseReplayCond(c) + if err != nil { + return nil, err + } + out = append(out, parsed) + } + return out, nil +} diff --git a/dashboard/internal/autolearn/replay_rules.go b/dashboard/internal/autolearn/replay_rules.go new file mode 100644 index 00000000..ef354295 --- /dev/null +++ b/dashboard/internal/autolearn/replay_rules.go @@ -0,0 +1,476 @@ +package autolearn + +import ( + "bytes" + "encoding/json" + "fmt" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// replayEnv is the fixed context of a replay: the local time zone and the +// site location for sun windows. +type replayEnv struct { + loc *time.Location + site sun.Location + hasSite bool +} + +// evalCtx is the input of one tick. balance is nil when it is stale. +type evalCtx struct { + now time.Time + env replayEnv + balance map[string]float64 + learned map[string]float64 +} + +// replayRef is a number that a learned value sets, read as in the service: +// clamped to min and max, the offset is added, a missing value means fallback. +type replayRef struct { + key string + min, max, fallback, off float64 +} + +// replayCond is one condition as far as the replay evaluates it. +type replayCond struct { + typ string + field string + comparison string + threshold float64 + thresholdRef *replayRef + hysteresis float64 + hold float64 + holdRef *replayRef + learned string + fallback float64 + startH int + startM int + endH int + endM int + weekdays []int + monthDays []int + from, to string + fromOffset float64 + toOffset float64 +} + +// replayCondRT is the runtime of one condition: since is the start of the +// current raw episode, latched the hysteresis state. +type replayCondRT struct { + since time.Time + hasSince bool + latched bool +} + +// ruleMachine runs the state machine of one rule, as the service does. fired +// is the episode flag: true from the first fire until the conditions break. +type ruleMachine struct { + rule replayRule + rts []replayCondRT + fired bool + hasLast bool + last time.Time +} + +func newRuleMachine(r replayRule) *ruleMachine { + return &ruleMachine{rule: r, rts: make([]replayCondRT, len(r.conds))} +} + +// tick evaluates the rule at ec.now. It returns the result phase of the tick +// and whether the rule fired in it. +func (m *ruleMachine) tick(ec evalCtx) (string, bool) { + if !m.rule.enabled { + m.fired = false + return "disabled", false + } + allRaw, allHeld, stale := evalConditions(m.rule.conds, m.rts, ec) + if !allRaw { + m.fired = false + } + inCooldown := false + if m.hasLast { + inCooldown = m.rule.cooldownS-ec.now.Sub(m.last).Seconds() > 0 + } + switch { + case stale: + return "balance_stale", false + case !allRaw: + return "conditions_not_met", false + case m.fired: + if m.rule.repeatS > 0 && allHeld && m.hasLast && ec.now.Sub(m.last).Seconds() >= m.rule.repeatS { + m.fire(ec.now) + return "fired", true + } + return "fired", false + case inCooldown: + return "cooldown", false + case !allHeld: + return "hold_pending", false + } + m.fire(ec.now) + return "fired", true +} + +func (m *ruleMachine) fire(now time.Time) { + m.fired = true + m.hasLast = true + m.last = now +} + +// evalConditions evaluates every condition, as the service does, and reports +// whether all are met raw, all are held and whether a balance condition saw a +// stale balance. +func evalConditions(conds []replayCond, rts []replayCondRT, ec evalCtx) (allRaw, allHeld, stale bool) { + allRaw, allHeld = true, true + for i, c := range conds { + raw, held, staleHere := evalCond(c, &rts[i], ec) + allRaw = allRaw && raw + allHeld = allHeld && held + stale = stale || staleHere + } + return allRaw, allHeld, stale +} + +// evalCond returns the raw state, the held state (raw for hold_seconds) and +// whether the condition saw a stale balance. +func evalCond(c replayCond, rt *replayCondRT, ec evalCtx) (raw, held, stale bool) { + switch c.typ { + case "balance_threshold": + if ec.balance == nil { + stale = true + break + } + value, ok := ec.balance[c.field] + if !ok { + break + } + threshold := c.threshold + if c.thresholdRef != nil { + threshold = resolveRef(*c.thresholdRef, ec.learned) + } + if c.hysteresis > 0 { + raw = thresholdMet(c.comparison, value, threshold, c.hysteresis, rt.latched) + rt.latched = raw + } else { + raw = thresholdMet(c.comparison, value, threshold, 0, false) + } + case "learned_value": + value, ok := ec.learned[c.learned] + if !ok { + value = c.fallback + } + threshold := c.threshold + if c.thresholdRef != nil { + threshold = resolveRef(*c.thresholdRef, ec.learned) + } + if c.hysteresis > 0 { + raw = thresholdMet(c.comparison, value, threshold, c.hysteresis, rt.latched) + rt.latched = raw + } else { + raw = thresholdMet(c.comparison, value, threshold, 0, false) + } + case "time_window", "sun_window": + raw = windowActive(c, ec) + } + if !raw { + rt.hasSince = false + return false, false, stale + } + if !rt.hasSince { + rt.since = ec.now + rt.hasSince = true + } + hold := c.hold + if c.holdRef != nil { + hold = resolveRef(*c.holdRef, ec.learned) + } + return true, ec.now.Sub(rt.since).Seconds() >= hold, stale +} + +// thresholdMet compares value with threshold. With a hysteresis and a latched +// state, the state holds until the value leaves the band. +func thresholdMet(comparison string, value, threshold, hysteresis float64, latched bool) bool { + held := latched && hysteresis > 0 + switch comparison { + case "above": + if held { + return value >= threshold-hysteresis + } + return value > threshold + case "below": + if held { + return value <= threshold+hysteresis + } + return value < threshold + } + return false +} + +// resolveRef reads a learned number. A missing value means fallback, a value +// outside min and max is clamped. The offset is added in both cases. +func resolveRef(ref replayRef, learned map[string]float64) float64 { + value, ok := learned[ref.key] + if !ok { + return ref.fallback + ref.off + } + if value < ref.min { + return ref.min + ref.off + } + if value > ref.max { + return ref.max + ref.off + } + return value + ref.off +} + +// windowActive reports whether a time or sun window holds at ec.now. It looks +// at today's window and yesterday's, and a window belongs to its start day +// for the weekday and month day filters. +func windowActive(c replayCond, ec evalCtx) bool { + now := ec.now.In(ec.env.loc) + y, m, d := now.Date() + for _, back := range []int{0, -1} { + day := time.Date(y, m, d+back, 0, 0, 0, 0, ec.env.loc) + start, end, ok := windowBounds(c, day, ec) + if !ok || ec.now.Before(start) || !ec.now.Before(end) { + continue + } + if len(c.weekdays) > 0 && !containsInt(c.weekdays, pyWeekday(day)) { + continue + } + if len(c.monthDays) > 0 && !containsInt(c.monthDays, day.Day()) { + continue + } + return true + } + return false +} + +func windowBounds(c replayCond, day time.Time, ec evalCtx) (time.Time, time.Time, bool) { + y, m, d := day.Date() + loc := ec.env.loc + if c.typ == "time_window" { + start := time.Date(y, m, d, c.startH, c.startM, 0, 0, loc) + end := time.Date(y, m, d, c.endH, c.endM, 0, 0, loc) + if !end.After(start) { + end = time.Date(y, m, d+1, c.endH, c.endM, 0, 0, loc) + } + return start, end, true + } + if !ec.env.hasSite { + return time.Time{}, time.Time{}, false + } + startEvent, ok := sunEvent(day, c.from, ec.env.site) + if !ok { + return time.Time{}, time.Time{}, false + } + endEvent, ok := sunEvent(day, c.to, ec.env.site) + if !ok { + return time.Time{}, time.Time{}, false + } + start := startEvent.Add(offsetDuration(c.fromOffset)) + end := endEvent.Add(offsetDuration(c.toOffset)) + if end.Before(start) { + next, ok := sunEvent(day.AddDate(0, 0, 1), c.to, ec.env.site) + if !ok { + return time.Time{}, time.Time{}, false + } + end = next.Add(offsetDuration(c.toOffset)) + } + return start, end, true +} + +// sunEvent returns sunrise or sunset of the calendar day of day. +func sunEvent(day time.Time, event string, site sun.Location) (time.Time, bool) { + rise, set, ok := sun.Times(day, site.Lat, site.Lon) + if !ok { + return time.Time{}, false + } + if event == "sunrise" { + return rise, true + } + return set, true +} + +func offsetDuration(minutes float64) time.Duration { + return time.Duration(minutes * float64(time.Minute)) +} + +// pyWeekday numbers the days as the service does, Monday is 0. +func pyWeekday(day time.Time) int { + return (int(day.Weekday()) + 6) % 7 +} + +func containsInt(values []int, want int) bool { + for _, v := range values { + if v == want { + return true + } + } + return false +} + +// parseReplayCond reads one condition. A condition outside the energy core +// wraps ErrNotReplayable. +func parseReplayCond(raw json.RawMessage) (replayCond, error) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil { + return replayCond{}, fmt.Errorf("%w: %v", ErrNotReplayable, err) + } + var head struct { + Type string `json:"type"` + } + if err := json.Unmarshal(raw, &head); err != nil { + return replayCond{}, fmt.Errorf("%w: %v", ErrNotReplayable, err) + } + c := replayCond{typ: head.Type} + var err error + if c.hold, c.holdRef, err = numberOrRef(fields["hold_seconds"]); err != nil { + return replayCond{}, err + } + switch head.Type { + case "balance_threshold", "learned_value": + if err := decodeString(fields["comparison"], &c.comparison); err != nil { + return replayCond{}, err + } + if c.comparison != "above" && c.comparison != "below" { + return replayCond{}, fmt.Errorf("%w: comparison %q", ErrNotReplayable, c.comparison) + } + if len(bytes.TrimSpace(fields["threshold"])) == 0 { + return replayCond{}, fmt.Errorf("%w: threshold missing", ErrNotReplayable) + } + if c.threshold, c.thresholdRef, err = numberOrRef(fields["threshold"]); err != nil { + return replayCond{}, err + } + if c.hysteresis, err = optionalNumber(fields["hysteresis"]); err != nil { + return replayCond{}, err + } + if head.Type == "balance_threshold" { + if err := decodeString(fields["field"], &c.field); err != nil || !balanceFields[c.field] { + return replayCond{}, fmt.Errorf("%w: balance field %q", ErrNotReplayable, c.field) + } + return c, nil + } + if err := decodeString(fields["learned"], &c.learned); err != nil || c.learned == "" { + return replayCond{}, fmt.Errorf("%w: learned", ErrNotReplayable) + } + if c.fallback, err = optionalNumber(fields["fallback"]); err != nil { + return replayCond{}, err + } + return c, nil + case "time_window": + var start, end string + if err := decodeString(fields["start"], &start); err != nil { + return replayCond{}, err + } + if err := decodeString(fields["end"], &end); err != nil { + return replayCond{}, err + } + if c.startH, c.startM, err = parseClock(start); err != nil { + return replayCond{}, err + } + if c.endH, c.endM, err = parseClock(end); err != nil { + return replayCond{}, err + } + if err := decodeInts(fields["weekdays"], &c.weekdays); err != nil { + return replayCond{}, err + } + if err := decodeInts(fields["month_days"], &c.monthDays); err != nil { + return replayCond{}, err + } + return c, nil + case "sun_window": + if err := decodeString(fields["from"], &c.from); err != nil { + return replayCond{}, err + } + if err := decodeString(fields["to"], &c.to); err != nil { + return replayCond{}, err + } + if (c.from != "sunrise" && c.from != "sunset") || (c.to != "sunrise" && c.to != "sunset") { + return replayCond{}, fmt.Errorf("%w: sun event", ErrNotReplayable) + } + if c.fromOffset, err = optionalNumber(fields["from_offset_min"]); err != nil { + return replayCond{}, err + } + if c.toOffset, err = optionalNumber(fields["to_offset_min"]); err != nil { + return replayCond{}, err + } + return c, nil + } + return replayCond{}, fmt.Errorf("%w: condition type %q", ErrNotReplayable, head.Type) +} + +// numberOrRef reads a number or a learned reference. An absent or null value +// is 0 and no reference. +func numberOrRef(raw json.RawMessage) (float64, *replayRef, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || string(trimmed) == "null" { + return 0, nil, nil + } + var n float64 + if err := json.Unmarshal(trimmed, &n); err == nil { + return n, nil, nil + } + var ref struct { + Learned string `json:"learned"` + Min *float64 `json:"min"` + Max *float64 `json:"max"` + Fallback *float64 `json:"fallback"` + Offset float64 `json:"offset"` + } + if err := json.Unmarshal(trimmed, &ref); err != nil || ref.Learned == "" || + ref.Min == nil || ref.Max == nil || ref.Fallback == nil { + return 0, nil, fmt.Errorf("%w: reference", ErrNotReplayable) + } + return 0, &replayRef{key: ref.Learned, min: *ref.Min, max: *ref.Max, + fallback: *ref.Fallback, off: ref.Offset}, nil +} + +func optionalNumber(raw json.RawMessage) (float64, error) { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || string(trimmed) == "null" { + return 0, nil + } + var n float64 + if err := json.Unmarshal(trimmed, &n); err != nil { + return 0, fmt.Errorf("%w: number expected", ErrNotReplayable) + } + return n, nil +} + +func decodeString(raw json.RawMessage, out *string) error { + if err := json.Unmarshal(raw, out); err != nil { + return fmt.Errorf("%w: text expected", ErrNotReplayable) + } + return nil +} + +func decodeInts(raw json.RawMessage, out *[]int) error { + trimmed := bytes.TrimSpace(raw) + if len(trimmed) == 0 || string(trimmed) == "null" { + return nil + } + if err := json.Unmarshal(trimmed, out); err != nil { + return fmt.Errorf("%w: list of numbers expected", ErrNotReplayable) + } + return nil +} + +// balanceFields are the balance fields of the service (BALANCE_FIELDS). Custom +// categories (custom:) and unknown names are not replayable. +var balanceFields = map[string]bool{ + "grid_export": true, "grid_import": true, "pv": true, "load_total": true, + "base": true, "wallbox": true, "heat_pump": true, "battery_charge": true, + "battery_discharge": true, "gap_applied": true, "autarkie": true, + "eigenverbrauch": true, "battery_soc": true, "battery_capacity_kwh": true, + "battery_energy_kwh": true, +} + +// parseClock reads "HH:MM". +func parseClock(text string) (int, int, error) { + var h, m int + if _, err := fmt.Sscanf(text, "%d:%d", &h, &m); err != nil || h < 0 || h > 23 || m < 0 || m > 59 { + return 0, 0, fmt.Errorf("%w: clock %q", ErrNotReplayable, text) + } + return h, m, nil +} diff --git a/dashboard/internal/autolearn/replay_scenario.go b/dashboard/internal/autolearn/replay_scenario.go new file mode 100644 index 00000000..7492cdd6 --- /dev/null +++ b/dashboard/internal/autolearn/replay_scenario.go @@ -0,0 +1,105 @@ +package autolearn + +import "time" + +// replayScenario is a scenario as far as the replay needs it. Only the modes +// none and hold of the while block are replayable, so the block has no effect +// on the replay. +type replayScenario struct { + id string + enabled bool + when []replayCond + until []replayCond + hasUntil bool + minRunS float64 + maxDurationS float64 + hasMaxDuration bool + cooldownS float64 +} + +// scenarioMachine runs the state machine of one scenario, as the service does: +// idle, active and disabled. +type scenarioMachine struct { + s replayScenario + phase string + since time.Time + endedAt time.Time + hasEnded bool + rearm bool + when []replayCondRT + until []replayCondRT +} + +func newScenarioMachine(s replayScenario) *scenarioMachine { + return &scenarioMachine{s: s, phase: "idle"} +} + +// tick evaluates the scenario at ec.now. It returns the phase after the tick +// and whether the scenario started in it. +func (m *scenarioMachine) tick(ec evalCtx) (string, bool) { + now := ec.now + if !m.s.enabled { + if m.phase == "active" { + m.end(now) + } + m.phase = "disabled" + m.when, m.until = nil, nil + return m.phase, false + } + if len(m.when) != len(m.s.when) { + m.when = make([]replayCondRT, len(m.s.when)) + } + allRawWhen, allHeldWhen, staleWhen := evalConditions(m.s.when, m.when, ec) + untilHeld := false + if !m.s.hasUntil { + m.until = nil + } else { + if len(m.until) != len(m.s.until) { + m.until = make([]replayCondRT, len(m.s.until)) + } + _, untilHeld, _ = evalConditions(m.s.until, m.until, ec) + } + + if m.phase != "active" { + if m.rearm && !allRawWhen { + m.rearm = false + } + switch { + case staleWhen, m.rearm: + case m.hasEnded && now.Sub(m.endedAt).Seconds() < m.s.cooldownS: + case allHeldWhen: + m.start(now) + return m.phase, true + } + return m.phase, false + } + + if m.s.hasMaxDuration && now.Sub(m.since).Seconds() >= m.s.maxDurationS { + m.end(now) + m.rearm = true + return m.phase, false + } + var ends bool + if m.s.hasUntil { + ends = untilHeld + } else { + ends = !m.s.hasMaxDuration && !allRawWhen && !staleWhen + } + if ends && now.Sub(m.since).Seconds() >= m.s.minRunS { + m.end(now) + } + return m.phase, false +} + +func (m *scenarioMachine) start(now time.Time) { + m.phase = "active" + m.since = now +} + +// end returns to idle and drops the condition runtimes, as the service does. +func (m *scenarioMachine) end(now time.Time) { + m.phase = "idle" + m.endedAt = now + m.hasEnded = true + m.when, m.until = nil, nil +} diff --git a/dashboard/internal/autolearn/replay_test.go b/dashboard/internal/autolearn/replay_test.go new file mode 100644 index 00000000..975739e0 --- /dev/null +++ b/dashboard/internal/autolearn/replay_test.go @@ -0,0 +1,397 @@ +package autolearn + +import ( + "context" + "encoding/json" + "errors" + "os" + "slices" + "sort" + "strconv" + "testing" + "time" + _ "time/tzdata" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// replayVectorsPath is the shared vector file that the Python engine tests too. +const replayVectorsPath = "../../../services/automation/tests/replay_vectors.json" + +// defaultLearnedMaxAgeS mirrors DEFAULT_MAX_AGE_S of learned.py. +const defaultLearnedMaxAgeS = 604800 + +type replayVector struct { + Name string `json:"name"` + Rule json.RawMessage `json:"rule"` + Scenario json.RawMessage `json:"scenario"` + Settings map[string]float64 `json:"settings"` + Start string `json:"start"` + Steps []map[string]json.RawMessage `json:"steps"` + Expect struct { + Fires []int64 `json:"fires"` + Phases []string `json:"phases"` + } `json:"expect"` +} + +func loadReplayVectors(t *testing.T) []replayVector { + t.Helper() + raw, err := os.ReadFile(replayVectorsPath) + if err != nil { + t.Fatalf("read vectors: %v", err) + } + var vectors []replayVector + if err := json.Unmarshal(raw, &vectors); err != nil { + t.Fatalf("parse vectors: %v", err) + } + return vectors +} + +// stepTime reads the "t" of a step in seconds. +func stepTime(t *testing.T, step map[string]json.RawMessage) int64 { + t.Helper() + var at int64 + if err := json.Unmarshal(step["t"], &at); err != nil { + t.Fatalf("step t: %v", err) + } + return at +} + +// vectorMaxAges collects max_age_s per learned key from the conditions of a +// vector. A key without max_age_s gets the default. +func vectorMaxAges(t *testing.T, v replayVector) map[string]float64 { + t.Helper() + ages := map[string]float64{} + var conds []json.RawMessage + collect := func(raw json.RawMessage) { + var doc struct { + Conditions []json.RawMessage `json:"conditions"` + } + if len(raw) > 0 && string(raw) != "null" && json.Unmarshal(raw, &doc) == nil { + conds = append(conds, doc.Conditions...) + } + } + if len(v.Rule) > 0 { + var rule struct { + Conditions []json.RawMessage `json:"conditions"` + } + if err := json.Unmarshal(v.Rule, &rule); err != nil { + t.Fatalf("rule: %v", err) + } + conds = append(conds, rule.Conditions...) + } else { + var scenario struct { + When json.RawMessage `json:"when"` + Until json.RawMessage `json:"until"` + } + if err := json.Unmarshal(v.Scenario, &scenario); err != nil { + t.Fatalf("scenario: %v", err) + } + collect(scenario.When) + collect(scenario.Until) + } + for _, c := range conds { + var fields struct { + Learned string `json:"learned"` + MaxAge *float64 `json:"max_age_s"` + } + if err := json.Unmarshal(c, &fields); err != nil || fields.Learned == "" { + continue + } + age := float64(defaultLearnedMaxAgeS) + if fields.MaxAge != nil { + age = *fields.MaxAge + } + ages[fields.Learned] = age + } + return ages +} + +// vectorTicks builds the ticks of a vector on its tick grid, as the Python +// driver does: a step applies at its tick and holds until the next step. +// Learned values expire by their max_age_s and are dropped from the tick. +func vectorTicks(t *testing.T, v replayVector, loc *time.Location, tick int64) ([]ReplayMinute, []int64) { + t.Helper() + start, err := time.ParseInLocation("2006-01-02T15:04:05", v.Start, loc) + if err != nil { + t.Fatalf("start: %v", err) + } + steps := map[int64]map[string]json.RawMessage{} + var last int64 + for _, step := range v.Steps { + at := stepTime(t, step) + steps[at] = step + last = max(last, at) + } + ages := vectorMaxAges(t, v) + + type stored struct { + value float64 + at time.Time + } + store := map[string]stored{} + var balance map[string]float64 + var ticks []ReplayMinute + var offsets []int64 + for off := int64(0); off <= last; off += tick { + if step, ok := steps[off]; ok { + if raw, ok := step["balance"]; ok { + balance = nil + if string(raw) != "null" { + balance = map[string]float64{} + if err := json.Unmarshal(raw, &balance); err != nil { + t.Fatalf("balance at %d: %v", off, err) + } + } + } + if raw, ok := step["learned"]; ok { + var spec map[string]json.RawMessage + if err := json.Unmarshal(raw, &spec); err != nil { + t.Fatalf("learned at %d: %v", off, err) + } + now := start.Add(time.Duration(off) * time.Second) + for key, value := range spec { + if string(value) == "null" { + delete(store, key) + continue + } + var entry struct { + Value float64 `json:"value"` + AgeS float64 `json:"age_s"` + } + if err := json.Unmarshal(value, &entry.Value); err != nil { + if err := json.Unmarshal(value, &entry); err != nil { + t.Fatalf("learned %s at %d: %v", key, off, err) + } + } + store[key] = stored{value: entry.Value, at: now.Add(-time.Duration(entry.AgeS) * time.Second)} + } + } + } + now := start.Add(time.Duration(off) * time.Second) + learned := map[string]float64{} + for key, st := range store { + maxAge, ok := ages[key] + if !ok { + maxAge = defaultLearnedMaxAgeS + } + if now.Sub(st.at).Seconds() > maxAge { + continue + } + learned[key] = st.value + } + ticks = append(ticks, ReplayMinute{At: now, Balance: balance, Learned: learned}) + offsets = append(offsets, off) + } + return ticks, offsets +} + +func TestReplayVectors(t *testing.T) { + loc, err := time.LoadLocation("Europe/Berlin") + if err != nil { + t.Fatalf("Europe/Berlin zone: %v", err) + } + vectors := loadReplayVectors(t) + if len(vectors) < 24 { + t.Fatalf("want at least 24 vectors, got %d", len(vectors)) + } + names := map[string]bool{} + for _, v := range vectors { + if names[v.Name] { + t.Fatalf("duplicate vector name %s", v.Name) + } + names[v.Name] = true + } + for _, v := range vectors { + t.Run(v.Name, func(t *testing.T) { + tick := int64(10) + if s, ok := v.Settings["tick_interval_s"]; ok { + tick = int64(s) + } + lat, lon := 52.52, 13.405 + if s, ok := v.Settings["latitude"]; ok { + lat = s + } + if s, ok := v.Settings["longitude"]; ok { + lon = s + } + raw := v.Rule + if len(raw) == 0 { + raw = v.Scenario + } + ticks, offsets := vectorTicks(t, v, loc, tick) + res, err := replayCore(context.Background(), json.RawMessage(raw), ReplayTarget{}, ticks, nil, + time.Duration(tick)*time.Second, loc, sun.Location{Lat: lat, Lon: lon}) + if err != nil { + t.Fatalf("replay: %v", err) + } + index := map[int64]int{} + for i, off := range offsets { + index[off] = i + } + var phases []string + var stepOffsets []int64 + for _, step := range v.Steps { + stepOffsets = append(stepOffsets, stepTime(t, step)) + } + sort.Slice(stepOffsets, func(i, j int) bool { return stepOffsets[i] < stepOffsets[j] }) + for _, off := range stepOffsets { + i, ok := index[off] + if !ok { + t.Fatalf("%s: step at %d s is off the tick grid", v.Name, off) + } + phases = append(phases, res.Phases[i]) + } + if !slices.Equal(res.Fires, v.Expect.Fires) { + t.Errorf("fires: got %v, want %v", res.Fires, v.Expect.Fires) + } + if !slices.Equal(phases, v.Expect.Phases) { + t.Errorf("phases: got %v, want %v", phases, v.Expect.Phases) + } + }) + } +} + +func TestReplayClosedLoopTakesExportFirst(t *testing.T) { + rule := `{"id":"r1","enabled":true,"conditions":[{"type":"balance_threshold","field":"grid_export","comparison":"above","threshold":800,"hysteresis":0,"hold_seconds":0}]}` + target := ReplayTarget{Device: "heater", OpW: 2000, CycleWh: 100000} + ticks := make([]ReplayMinute, 4) + base := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + for i := range ticks { + ticks[i] = ReplayMinute{At: base.Add(time.Duration(i) * time.Minute), + Balance: map[string]float64{"grid_export": 2500, "grid_import": 0}} + } + res, err := replayCore(context.Background(), json.RawMessage(rule), target, ticks, nil, time.Minute, time.UTC, sun.Location{}) + if err != nil { + t.Fatalf("replay: %v", err) + } + if !res.On[1] || !res.On[3] { + t.Fatalf("device should stay on, On = %v", res.On) + } + // Tick 0 has no device load yet. From tick 1 on the device takes 2000 W, + // so 2500 W of export leave 500 W and no grid import. + if res.ExportWh != (2500+500+500+500)/60.0 { + t.Errorf("export Wh = %v, want %v", res.ExportWh, (2500+500+500+500)/60.0) + } + if res.GridWh != 0 { + t.Errorf("grid Wh = %v, want 0", res.GridWh) + } +} + +func TestReplayStartPeakInFirstTwoMinutes(t *testing.T) { + rule := `{"id":"r1","enabled":true,"conditions":[{"type":"balance_threshold","field":"grid_export","comparison":"above","threshold":800,"hysteresis":0,"hold_seconds":0}]}` + target := ReplayTarget{Device: "heater", OpW: 1000, PeakW: 1500, CycleWh: 100000} + base := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + ticks := make([]ReplayMinute, 4) + for i := range ticks { + ticks[i] = ReplayMinute{At: base.Add(time.Duration(i) * time.Minute), + Balance: map[string]float64{"grid_export": 3000, "grid_import": 0}} + } + res, err := replayCore(context.Background(), json.RawMessage(rule), target, ticks, nil, time.Minute, time.UTC, sun.Location{}) + if err != nil { + t.Fatalf("replay: %v", err) + } + if !res.On[0] { + t.Fatalf("device should be on after the fire, On = %v", res.On) + } + // The device is on from tick 0. Ticks 1 and 2 are within two minutes of + // switching on and take 1000 W plus 1500 W peak, tick 3 takes 1000 W. + // Export per tick: 3000 (no load yet), 500, 500, 2000. + exportWh := 3000.0 + 500.0 + 500.0 + 2000.0 + if res.ExportWh != exportWh/60.0 { + t.Errorf("export Wh = %v, want %v", res.ExportWh, exportWh/60.0) + } +} + +func TestReplayCycleEndsAtCycleEnergy(t *testing.T) { + rule := `{"id":"r1","enabled":true,"conditions":[{"type":"balance_threshold","field":"grid_export","comparison":"above","threshold":800,"hysteresis":0,"hold_seconds":0}]}` + // One minute at 1000 W is 16.67 Wh, so a cycle of 60 Wh runs four ticks. + target := ReplayTarget{Device: "wallbox", OpW: 1000, CycleWh: 60} + base := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + ticks := make([]ReplayMinute, 8) + for i := range ticks { + ticks[i] = ReplayMinute{At: base.Add(time.Duration(i) * time.Minute), + Balance: map[string]float64{"grid_export": 2000, "grid_import": 0}} + } + res, err := replayCore(context.Background(), json.RawMessage(rule), target, ticks, nil, time.Minute, time.UTC, sun.Location{}) + if err != nil { + t.Fatalf("replay: %v", err) + } + want := []bool{true, true, true, true, false, false, false, false} + if !slices.Equal(res.On, want) { + t.Errorf("On = %v, want %v", res.On, want) + } + if res.Switches != 2 { + t.Errorf("switches = %d, want 2", res.Switches) + } +} + +func TestReplayChainConditionIsNotReplayable(t *testing.T) { + raw := `{"id":"r1","enabled":true,"conditions":[{"type":"chain_value","chain_id":"c","field":"x","comparison":"above","value":1}]}` + var rule Rule + rule.ID = "r1" + rule.Enabled = true + rule.Conditions = []Condition{{Type: "chain_value", Raw: json.RawMessage(`{"type":"chain_value","chain_id":"c","field":"x","comparison":"above","value":1}`)}} + if err := Replayable(rule); !errors.Is(err, ErrNotReplayable) { + t.Fatalf("Replayable: got %v, want ErrNotReplayable", err) + } + base := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + ticks := []ReplayMinute{{At: base, Balance: map[string]float64{}}} + if _, err := Replay(context.Background(), json.RawMessage(raw), ReplayTarget{}, ticks, nil, time.UTC, sun.Location{}); !errors.Is(err, ErrNotReplayable) { + t.Fatalf("Replay: got %v, want ErrNotReplayable", err) + } +} + +func TestReplayContextCancelReturnsContextError(t *testing.T) { + rule := `{"id":"r1","enabled":true,"conditions":[{"type":"balance_threshold","field":"grid_export","comparison":"above","threshold":800,"hysteresis":0,"hold_seconds":0}]}` + base := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + ticks := []ReplayMinute{{At: base, Balance: map[string]float64{"grid_export": 900}}} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := Replay(ctx, json.RawMessage(rule), ReplayTarget{}, ticks, nil, time.UTC, sun.Location{}); !errors.Is(err, context.Canceled) { + t.Fatalf("got %v, want context.Canceled", err) + } +} + +func TestReplayClockHelpers(t *testing.T) { + h, m, err := parseClock("06:30") + if err != nil || h != 6 || m != 30 { + t.Fatalf("parseClock: %d %d %v", h, m, err) + } + if _, _, err := parseClock("25:00"); !errors.Is(err, ErrNotReplayable) { + t.Fatalf("parseClock out of range: %v", err) + } + if got := strconv.Itoa(pyWeekday(time.Date(2026, 11, 22, 0, 0, 0, 0, time.UTC))); got != "6" { + t.Fatalf("Sunday should be 6, got %s", got) + } +} + +func TestApplyDeltaDoesNotCreateMissingKeys(t *testing.T) { + b, _ := applyDelta(map[string]float64{"grid_export": 2500}, nil, 2000) + if b["grid_export"] != 500 { + t.Fatalf("grid_export = %v, want 500", b["grid_export"]) + } + if _, ok := b["grid_import"]; ok { + t.Fatalf("grid_import was created with a zero amount: %v", b) + } + cond, err := parseReplayCond(json.RawMessage(`{"type":"balance_threshold","field":"grid_import","comparison":"below","threshold":100,"hysteresis":0,"hold_seconds":0}`)) + if err != nil { + t.Fatalf("parse: %v", err) + } + if raw, _, _ := evalCond(cond, &replayCondRT{}, evalCtx{now: time.Now(), balance: b}); raw { + t.Fatalf("grid_import below 100 became true through a created key") + } +} + +func TestReplayRejectsCustomAndUnknownBalanceFields(t *testing.T) { + for _, field := range []string{"custom:pool_load", "unknown_field"} { + raw := json.RawMessage(`{"type":"balance_threshold","field":"` + field + `","comparison":"above","threshold":500,"hysteresis":0,"hold_seconds":0}`) + if _, err := parseReplayCond(raw); !errors.Is(err, ErrNotReplayable) { + t.Errorf("field %q: got %v, want ErrNotReplayable", field, err) + } + } + raw := json.RawMessage(`{"type":"balance_threshold","field":"grid_export","comparison":"above","threshold":500,"hysteresis":0,"hold_seconds":0}`) + if _, err := parseReplayCond(raw); err != nil { + t.Errorf("grid_export should be replayable: %v", err) + } +} diff --git a/dashboard/internal/autolearn/replaycheck.go b/dashboard/internal/autolearn/replaycheck.go new file mode 100644 index 00000000..7a86d6e3 --- /dev/null +++ b/dashboard/internal/autolearn/replaycheck.go @@ -0,0 +1,55 @@ +package autolearn + +import ( + "context" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// ReplayVerdict is the replay check of a suggestion. Base is the real +// situation without the suggestion, Alt the situation with it, both over the +// same minutes. Estimate is set when stretched quarter hours took part. +type ReplayVerdict struct { + Base, Alt ReplayResult + Estimate bool +} + +// ReplayCheck describes what a suggestion would change. Rule is the proposed +// rule (a Rule or raw JSON), Target the device it switches. Benefit turns the +// two replays into the benefit of the suggestion, with the proposal first. +type ReplayCheck struct { + Rule any + Target ReplayTarget + Benefit func(alt, base ReplayResult) Benefit +} + +// replayBaseRule never fires. Replayed with the real switch state of the +// target, it reproduces the real situation. +var replayBaseRule = Rule{ID: "replay-base", Enabled: false} + +// EvaluateReplay replays the proposal of chk over the last days days. It +// returns a nil verdict and no benefit when there are no minutes to replay. +// An ErrNotReplayable of the proposed rule is passed on, so the caller can +// keep the candidate without a replay and log the reason. +func EvaluateReplay(ctx context.Context, in *Input, chk ReplayCheck, days int, loc *time.Location, site sun.Location) (*ReplayVerdict, Benefit, error) { + minutes, estimate := ReplayDays(in, days) + if len(minutes) == 0 { + return nil, Benefit{}, nil + } + real := RealState(in, chk.Target.Device, minutes) + base, err := Replay(ctx, replayBaseRule, chk.Target, minutes, real, loc, site) + if err != nil { + return nil, Benefit{}, err + } + alt, err := Replay(ctx, chk.Rule, chk.Target, minutes, real, loc, site) + if err != nil { + return nil, Benefit{}, err + } + base.Estimate, alt.Estimate = estimate, estimate + var benefit Benefit + if chk.Benefit != nil { + benefit = chk.Benefit(alt, base) + } + return &ReplayVerdict{Base: base, Alt: alt, Estimate: estimate}, benefit, nil +} diff --git a/dashboard/internal/autolearn/replaycheck_test.go b/dashboard/internal/autolearn/replaycheck_test.go new file mode 100644 index 00000000..c5105e71 --- /dev/null +++ b/dashboard/internal/autolearn/replaycheck_test.go @@ -0,0 +1,132 @@ +package autolearn + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +func replayCheckRule() Rule { + return Rule{ID: "r1", Enabled: true, Conditions: []Condition{{ + Type: "balance_threshold", + Raw: json.RawMessage(`{"type":"balance_threshold","field":"grid_export","comparison":"above",` + + `"threshold":500,"hysteresis":0,"hold_seconds":0}`), + }}} +} + +func replayCheckTarget() ReplayTarget { + return ReplayTarget{RuleID: "r1", Device: "plug.x", OpW: 1000} +} + +// stretchedInput has fourteen days of quarter hours and no minute reader, so +// every replayed day is stretched. +func stretchedInput() *Input { + loc := time.UTC + in := &Input{Now: replayTestNow(), Loc: loc} + for d := 8; d <= 21; d++ { + in.Days = append(in.Days, quarterDay(time.Date(2026, 11, d, 0, 0, 0, 0, loc).Format(dayLayout), + func(int) float32 { return 300 })) + } + return in +} + +func TestEvaluateReplayNotReplayableIsError(t *testing.T) { + rule := replayCheckRule() + rule.Conditions = []Condition{{Type: "chain_value", Raw: json.RawMessage( + `{"type":"chain_value","chain_id":"c","field":"x","comparison":"above","value":1}`)}} + v, benefit, err := EvaluateReplay(context.Background(), stretchedInput(), + ReplayCheck{Rule: rule, Target: replayCheckTarget()}, 14, time.UTC, sun.Location{}) + if !errors.Is(err, ErrNotReplayable) { + t.Fatalf("err = %v, want ErrNotReplayable", err) + } + if v != nil || benefit != (Benefit{}) { + t.Fatalf("verdict = %v, benefit = %v, want none", v, benefit) + } +} + +func TestEvaluateReplayStretchedDaysAreEstimate(t *testing.T) { + v, _, err := EvaluateReplay(context.Background(), stretchedInput(), + ReplayCheck{Rule: replayCheckRule(), Target: replayCheckTarget()}, 14, time.UTC, sun.Location{}) + if err != nil { + t.Fatalf("err = %v", err) + } + if v == nil { + t.Fatal("verdict = nil, want a verdict") + } + if !v.Estimate || !v.Base.Estimate || !v.Alt.Estimate { + t.Fatalf("estimate flags = %v/%v/%v, want all true", v.Estimate, v.Base.Estimate, v.Alt.Estimate) + } + if len(v.Base.On) != 14*1440 || len(v.Alt.On) != len(v.Base.On) { + t.Fatalf("len base/alt = %d/%d, want %d", len(v.Base.On), len(v.Alt.On), 14*1440) + } +} + +func TestEvaluateReplayBaseNeverFires(t *testing.T) { + v, _, err := EvaluateReplay(context.Background(), stretchedInput(), + ReplayCheck{Rule: replayCheckRule(), Target: replayCheckTarget()}, 14, time.UTC, sun.Location{}) + if err != nil || v == nil { + t.Fatalf("verdict = %v, err = %v", v, err) + } + if len(v.Base.Fires) != 0 { + t.Fatalf("base fires = %v, want none, the base is the real situation", v.Base.Fires) + } +} + +func TestEvaluateReplayPassesReplaysToBenefit(t *testing.T) { + var gotAlt, gotBase int + chk := ReplayCheck{Rule: replayCheckRule(), Target: replayCheckTarget(), + Benefit: func(alt, base ReplayResult) Benefit { + gotAlt, gotBase = len(alt.On), len(base.On) + return Benefit{Unit: "kwh_week", Value: 0.3} + }} + _, benefit, err := EvaluateReplay(context.Background(), stretchedInput(), chk, 14, time.UTC, sun.Location{}) + if err != nil { + t.Fatalf("err = %v", err) + } + if benefit != (Benefit{Unit: "kwh_week", Value: 0.3}) { + t.Fatalf("benefit = %v", benefit) + } + if gotAlt != 14*1440 || gotBase != 14*1440 { + t.Fatalf("benefit got %d/%d minutes, want %d", gotAlt, gotBase, 14*1440) + } +} + +func replayCand(kwh float64, base, alt ReplayResult) Candidate { + c := gateCand("g", "x", kwh, 2, 2, true) + c.Replay = &ReplayVerdict{Base: base, Alt: alt} + return c +} + +func TestGateDropsReplayWithMoreGridThanExport(t *testing.T) { + c := replayCand(1, ReplayResult{GridWh: 0, ExportWh: 1000}, ReplayResult{GridWh: 1500, ExportWh: 0}) + if out, _ := Gate([]Candidate{c}, Doc{}, nil); len(out) != 0 { + t.Fatalf("kept %v, want dropped, the suggestion draws more from the grid than it uses", gateIDs(out)) + } +} + +func TestGateKeepsReplayWhenExportCoversGrid(t *testing.T) { + c := replayCand(1, ReplayResult{GridWh: 0, ExportWh: 1000}, ReplayResult{GridWh: 500, ExportWh: 0}) + if out, _ := Gate([]Candidate{c}, Doc{}, nil); len(out) != 1 { + t.Fatalf("kept %v, want one suggestion", gateIDs(out)) + } +} + +func TestGateDropsReplayBelowBenefitMinimum(t *testing.T) { + c := replayCand(0.3, ReplayResult{}, ReplayResult{}) + if out, _ := Gate([]Candidate{c}, Doc{}, nil); len(out) != 0 { + t.Fatalf("kept %v, want dropped at 0,3 kWh per week", gateIDs(out)) + } +} + +func TestGateCapsReplayEstimateAtEstimate(t *testing.T) { + c := replayCand(1, ReplayResult{}, ReplayResult{}) + c.Replay.Estimate = true + out, _ := Gate([]Candidate{c}, Doc{}, nil) + if len(out) != 1 || out[0].Confidence != "estimate" { + t.Fatalf("out = %+v, want one finding with confidence estimate", out) + } +} diff --git a/dashboard/internal/autolearn/replaydata.go b/dashboard/internal/autolearn/replaydata.go new file mode 100644 index 00000000..cc142ee2 --- /dev/null +++ b/dashboard/internal/autolearn/replaydata.go @@ -0,0 +1,480 @@ +package autolearn + +import ( + "math" + "math/rand" + "sort" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/energystats" + "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" +) + +// replayBalanceKeys are the balance keys the replay reads, in the order the +// stretched noise is drawn. battery_soc has no minute key of its own before +// the minute record holds it, so a missing key is simply left out of the tick. +var replayBalanceKeys = []string{"load_total", "grid_import", "grid_export", "pv", + "battery_charge", "battery_discharge", "battery_soc"} + +// ReplayDays returns the minutes of the last days complete days before today, +// oldest first. A day with minutes in in.Minutes is replayed minute by minute. +// Any other day with a day file is stretched from its quarter hours, with a +// noise trace drawn from a seed that depends on the day only, so the same day +// always replays the same way. estimate is true when a stretched day is part +// of the result. Learned values are included in a minute only when they were +// learned at or before that minute. +func ReplayDays(in *Input, days int) (minutes []ReplayMinute, estimate bool) { + if in == nil || days <= 0 { + return nil, false + } + loc := replayLoc(in) + today := in.Now.In(loc) + first := time.Date(today.Year(), today.Month(), today.Day(), 0, 0, 0, 0, loc) + byDay := make(map[string]*DayFile, len(in.Days)) + for i := range in.Days { + byDay[in.Days[i].Day] = &in.Days[i] + } + learned := numericLearned(in.Learned) + type dayPlan struct { + start time.Time + file *DayFile // nil for a minute day + } + var plan []dayPlan + var minuteStarts []time.Time + for k := days; k >= 1; k-- { + start := first.AddDate(0, 0, -k) + end := start.AddDate(0, 0, 1) + if isMinuteDay(in.Minutes, start, end) { + plan = append(plan, dayPlan{start: start}) + minuteStarts = append(minuteStarts, start) + continue + } + if f := byDay[start.Format(dayLayout)]; f != nil { + plan = append(plan, dayPlan{start: start, file: f}) + } + } + var pool map[string][]minuteShape + if in.Minutes != nil { + pool = shapePool(in.Minutes, minuteStarts) + } + for _, p := range plan { + if p.file == nil { + minutes = append(minutes, minuteDay(in.Minutes, p.start, learned)...) + continue + } + estimate = true + minutes = append(minutes, stretchedDay(p.file, p.start, learned, pool)...) + } + return minutes, estimate +} + +// isMinuteDay reports whether the minute record holds the day from start to end. +// A day counts with one minute in it, the same test the replay applies. +func isMinuteDay(r learnrec.Reader, start, end time.Time) bool { + return r != nil && r.Coverage(start, end) >= 1 +} + +// minuteDayCount counts the day files of in that have minutes. +func minuteDayCount(in *Input) int { + if in.Minutes == nil { + return 0 + } + loc := replayLoc(in) + n := 0 + for i := range in.Days { + start, err := time.ParseInLocation(dayLayout, in.Days[i].Day, loc) + if err != nil { + continue + } + if isMinuteDay(in.Minutes, start, start.AddDate(0, 0, 1)) { + n++ + } + } + return n +} + +// minuteShape is one quarter hour of a minute day: its mean and the ratio of +// each minute to that mean. A quarter with mean 0 has the shape of ones. +type minuteShape struct { + mean float64 + shape [15]float64 +} + +// shapePool collects the quarter hours of the minute days per balance key, +// ordered by mean. Quarters with a gap are left out. +func shapePool(r learnrec.Reader, days []time.Time) map[string][]minuteShape { + pool := make(map[string][]minuteShape, len(replayBalanceKeys)) + for _, start := range days { + series := daySeries(r, start) + for _, k := range replayBalanceKeys { + v := series[k] + for q := 0; q < dayQuarters && (q+1)*15 <= len(v); q++ { + var vals [15]float64 + sum, gap := 0.0, false + for m := 0; m < 15; m++ { + x := float64(v[q*15+m]) + if math.IsNaN(x) { + gap = true + break + } + vals[m] = x + sum += x + } + if gap { + continue + } + mean := sum / 15 + ms := minuteShape{mean: mean} + for m := range ms.shape { + ms.shape[m] = 1 + if mean > 0 { + ms.shape[m] = vals[m] / mean + } + } + pool[k] = append(pool[k], ms) + } + } + } + for k := range pool { + sort.SliceStable(pool[k], func(i, j int) bool { return pool[k][i].mean < pool[k][j].mean }) + } + return pool +} + +// nearestShape returns the shape of the pooled quarter whose mean is closest +// to v. Ties go to the lower mean. ok is false for an empty pool. +func nearestShape(pool []minuteShape, v float64) (minuteShape, bool) { + if len(pool) == 0 { + return minuteShape{}, false + } + i := sort.Search(len(pool), func(i int) bool { return pool[i].mean >= v }) + best := i + if i == len(pool) { + best = len(pool) - 1 + } else if i > 0 && v-pool[i-1].mean <= pool[i].mean-v { + best = i - 1 + } + return pool[best], true +} + +// replayLoc is the location of the input, local time when none is set. +func replayLoc(in *Input) *time.Location { + if in.Loc != nil { + return in.Loc + } + return time.Local +} + +// learnedEntry is one numeric learned value with the time it was learned. +type learnedEntry struct { + key string + val float64 + at time.Time +} + +// numericLearned keeps the learned values that hold a number, in key order. +func numericLearned(in map[string]LearnedEntry) []learnedEntry { + keys := make([]string, 0, len(in)) + for k := range in { + keys = append(keys, k) + } + sort.Strings(keys) + var out []learnedEntry + for _, k := range keys { + e := in[k] + var v float64 + switch x := e.Value.(type) { + case float64: + v = x + case float32: + v = float64(x) + case int: + v = float64(x) + case int64: + v = float64(x) + default: + continue + } + out = append(out, learnedEntry{key: k, val: v, at: time.Unix(e.At, 0)}) + } + return out +} + +// learnedAt returns the learned values that were known at t, nil when none. +func learnedAt(entries []learnedEntry, t time.Time) map[string]float64 { + var out map[string]float64 + for _, e := range entries { + if e.at.After(t) { + continue + } + if out == nil { + out = make(map[string]float64, len(entries)) + } + out[e.key] = e.val + } + return out +} + +// minuteDay reads one day of minutes from r. A minute without load total is +// a stale tick, the other keys are left out when they have no value. +func minuteDay(r learnrec.Reader, start time.Time, learned []learnedEntry) []ReplayMinute { + series := daySeries(r, start) + out := make([]ReplayMinute, 0, 1440) + for i := 0; i < 1440; i++ { + at := start.Add(time.Duration(i) * time.Minute) + m := ReplayMinute{At: at, Learned: learnedAt(learned, at)} + if v := series["load_total"]; i < len(v) && !math.IsNaN(float64(v[i])) { + m.Balance = make(map[string]float64, len(replayBalanceKeys)) + for _, k := range replayBalanceKeys { + if v := series[k]; i < len(v) && !math.IsNaN(float64(v[i])) { + m.Balance[k] = float64(v[i]) + } + } + } + out = append(out, m) + } + return out +} + +// daySeries reads the minutes of every balance key of one day. +func daySeries(r learnrec.Reader, start time.Time) map[string][]float32 { + series := make(map[string][]float32, len(replayBalanceKeys)) + for _, k := range replayBalanceKeys { + series[k] = r.Range("b:"+k, start, start.Add(24*time.Hour)).Values + } + return series +} + +// stretchedDay turns the quarter hours of a day file into 1440 minutes. Each +// quarter hour keeps its mean. Where the pool holds minute days for the key, +// the minutes take the shape of the quarter with the closest mean (the minute +// divided by the quarter mean, times the quarter value). Without such a day +// the noise of the quarter is drawn around zero from a seed of the date and +// centred, so the 15 minutes average to the quarter value exactly. +func stretchedDay(f *DayFile, start time.Time, learned []learnedEntry, pool map[string][]minuteShape) []ReplayMinute { + rng := rand.New(rand.NewSource(dayNumber(start))) + quarters := make([][dayQuarters]float64, len(replayBalanceKeys)) + noise := make([][dayQuarters][15]float64, len(replayBalanceKeys)) + for ki, k := range replayBalanceKeys { + series := make([]float32, dayQuarters) + for q := 0; q < dayQuarters; q++ { + quarters[ki][q] = quarterValue(f, k, q) + series[q] = float32(quarters[ki][q]) + } + amp := QuarterNoise(series) + for q := 0; q < dayQuarters; q++ { + sum := 0.0 + for m := 0; m < 15; m++ { + noise[ki][q][m] = amp * (2*rng.Float64() - 1) + sum += noise[ki][q][m] + } + for m := 0; m < 15; m++ { + noise[ki][q][m] -= sum / 15 + } + } + } + + out := make([]ReplayMinute, 0, 1440) + for i := 0; i < 1440; i++ { + q, mi := i/15, i%15 + at := start.Add(time.Duration(i) * time.Minute) + m := ReplayMinute{At: at, Learned: learnedAt(learned, at)} + if !math.IsNaN(quarters[0][q]) { + m.Balance = make(map[string]float64, len(replayBalanceKeys)) + for ki, k := range replayBalanceKeys { + v := quarters[ki][q] + if math.IsNaN(v) { + continue + } + if ps, ok := nearestShape(pool[k], v); ok { + m.Balance[k] = v * ps.shape[mi] + } else { + m.Balance[k] = v + noise[ki][q][mi] + } + } + } + out = append(out, m) + } + return out +} + +// quarterValue is the value of a balance key in quarter q of a day file, NaN +// when the quarter was not seen. +func quarterValue(f *DayFile, key string, q int) float64 { + if f.Site.Seen[q] == 0 { + return math.NaN() + } + switch key { + case "load_total": + return float64(f.Site.LoadTotal[q]) + case "grid_import": + return float64(f.Site.GridImport[q]) + case "grid_export": + return float64(f.Site.GridExport[q]) + case "pv": + return float64(f.Site.PV[q]) + case "battery_charge": + return float64(f.Site.BatteryCharge[q]) + case "battery_discharge": + return float64(f.Site.BatteryDischarge[q]) + case "battery_soc": + if p := f.Site.SoC[q]; p != nil { + return float64(*p) + } + } + return math.NaN() +} + +// dayNumber is the date as a number, YYYYMMDD, the seed of the noise. +func dayNumber(t time.Time) int64 { + return int64(t.Year()*10000 + int(t.Month())*100 + t.Day()) +} + +// RealState returns, per minute, whether the device was on in reality. The last +// switch event of the device at or before the minute decides. Before the first +// event the on minutes of the quarter hour decide (OnMin of the day file). +func RealState(in *Input, device string, minutes []ReplayMinute) []bool { + var events []EventRec + for _, f := range in.Days { + for _, e := range f.Events { + if e.Device == device { + events = append(events, e) + } + } + } + sort.SliceStable(events, func(i, j int) bool { return events[i].At < events[j].At }) + loc := replayLoc(in) + byDay := make(map[string]*DayFile, len(in.Days)) + for i := range in.Days { + byDay[in.Days[i].Day] = &in.Days[i] + } + + out := make([]bool, len(minutes)) + ei, have, state := 0, false, false + for i, m := range minutes { + t := m.At.Unix() + for ei < len(events) && events[ei].At <= t { + state, have = events[ei].On, true + ei++ + } + if have { + out[i] = state + continue + } + out[i] = onMinute(byDay[m.At.In(loc).Format(dayLayout)], device, m.At.In(loc)) + } + return out +} + +// onMinute tells from the on minutes of the quarter hour whether the device +// was on at t: the first OnMin minutes of the quarter are on. +func onMinute(f *DayFile, device string, t time.Time) bool { + if f == nil { + return false + } + dd := f.Devices[device] + if dd == nil { + return false + } + minute := t.Hour()*60 + t.Minute() + return minute%15 < int(dd.OnMin[minute/15]) +} + +// ReplayLastYear returns the minutes of the same calendar weeks one year back, +// for the weeks last years, oldest first. Each hour of the energy statistics +// is spread over its 60 minutes at its mean power, so the result is an +// estimate. ok is false when the statistics hold no hour in those weeks. +func ReplayLastYear(in *Input, stats *energystats.Store, weeks int) (minutes []ReplayMinute, ok bool) { + if in == nil || stats == nil || weeks <= 0 { + return nil, false + } + loc := replayLoc(in) + now := in.Now.In(loc) + for w := weeks - 1; w >= 0; w-- { + monday := isoMonday(now.AddDate(-1, 0, -7*w), loc) + err := stats.Each(monday, monday.AddDate(0, 0, 7), func(hour time.Time, m *energystats.Month, i int) { + if m == nil { + return + } + idx, inRange := m.Index(hour) + if !inRange || m.Covered[idx] == 0 { + minutes = appendGapHour(minutes, hour) + return + } + bal := map[string]float64{} + for _, k := range siteKeys { + s := m.Roles[k] + if s == nil || idx >= len(s.KWh) || math.IsNaN(s.KWh[idx]) { + continue + } + bal[k] = s.KWh[idx] * 1000 + } + if len(bal) == 0 { + minutes = appendGapHour(minutes, hour) + return + } + ok = true + for j := 0; j < 60; j++ { + minutes = append(minutes, ReplayMinute{At: hour.Add(time.Duration(j) * time.Minute), Balance: bal}) + } + }) + if err != nil { + return nil, false + } + } + return minutes, ok +} + +// appendGapHour adds the 60 minutes of an hour without values as stale ticks. +func appendGapHour(minutes []ReplayMinute, hour time.Time) []ReplayMinute { + for j := 0; j < 60; j++ { + minutes = append(minutes, ReplayMinute{At: hour.Add(time.Duration(j) * time.Minute)}) + } + return minutes +} + +// isoMonday is the Monday of the week of t, at midnight in loc. +func isoMonday(t time.Time, loc *time.Location) time.Time { + wd := int(t.Weekday()) + if wd == 0 { + wd = 7 + } + return time.Date(t.Year(), t.Month(), t.Day()-(wd-1), 0, 0, 0, 0, loc) +} + +// MinuteNoise estimates the noise of the signal key of r between from and to. +// It is the 95th percentile of |signal − moving median over 5 minutes|, taken +// only in the minutes where the signal lies within 20 % of threshold. key is +// the full reader key, such as "b:load_total". ok is false without such minutes. +func MinuteNoise(r learnrec.Reader, key string, threshold float64, from, to time.Time) (float64, bool) { + if r == nil { + return 0, false + } + vals := r.Range(key, from, to).Values + band := 0.2 * math.Abs(threshold) + var devs []float64 + for i, v := range vals { + x := float64(v) + if math.IsNaN(x) || math.Abs(x-threshold) >= band { + continue + } + var win []float64 + for j := i - 2; j <= i+2; j++ { + if j < 0 || j >= len(vals) || math.IsNaN(float64(vals[j])) { + continue + } + win = append(win, float64(vals[j])) + } + if len(win) < 3 { + continue + } + sort.Float64s(win) + devs = append(devs, math.Abs(x-win[len(win)/2])) + } + if len(devs) == 0 { + return 0, false + } + sort.Float64s(devs) + rank := int(math.Ceil(0.95*float64(len(devs)))) - 1 + return devs[rank], true +} diff --git a/dashboard/internal/autolearn/replaydata_test.go b/dashboard/internal/autolearn/replaydata_test.go new file mode 100644 index 00000000..de8c1cb1 --- /dev/null +++ b/dashboard/internal/autolearn/replaydata_test.go @@ -0,0 +1,297 @@ +package autolearn + +import ( + "math" + "math/rand" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/energystats" + "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" +) + +// fakeMinutes is a learnrec.Reader over whole days. A day present in days +// counts as covered. Minutes of a day without an entry are gaps. +type fakeMinutes struct { + loc *time.Location + days map[string]map[string][]float32 +} + +func (f fakeMinutes) Range(key string, from, to time.Time) learnrec.Series { + n := int(to.Sub(from) / time.Minute) + out := learnrec.Series{From: from, Values: make([]float32, n)} + for i := range out.Values { + t := from.Add(time.Duration(i) * time.Minute).In(f.loc) + vals := f.days[t.Format(dayLayout)][key] + if vals == nil { + out.Values[i] = float32(math.NaN()) + continue + } + out.Values[i] = vals[t.Hour()*60+t.Minute()] + } + return out +} + +func (f fakeMinutes) Coverage(from, to time.Time) int { + n := 0 + for d := from; d.Before(to); d = d.AddDate(0, 0, 1) { + if _, ok := f.days[d.In(f.loc).Format(dayLayout)]; ok { + n++ + } + } + return n +} + +// quarterDay is a day file with every quarter hour seen and the load total +// given by load. +func quarterDay(day string, load func(q int) float32) DayFile { + f := DayFile{Day: day, Devices: map[string]*DeviceDay{}} + for q := 0; q < dayQuarters; q++ { + f.Site.Seen[q] = 1 + f.Site.LoadTotal[q] = load(q) + } + return f +} + +// minuteValues is a full day of one key with the same value in every minute. +func minuteValues(v float32) []float32 { + out := make([]float32, 1440) + for i := range out { + out[i] = v + } + return out +} + +func replayTestNow() time.Time { + return time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC) +} + +func TestReplayDaysMixesMinutesAndStretchedQuarters(t *testing.T) { + loc := time.UTC + now := replayTestNow() + // Yesterday and the day before have minutes, the twelve days before them + // only quarter hours. + minutes := fakeMinutes{loc: loc, days: map[string]map[string][]float32{ + "2026-11-21": {"b:load_total": minuteValues(500)}, + "2026-11-20": {"b:load_total": minuteValues(500)}, + }} + in := &Input{Now: now, Loc: loc, Minutes: minutes} + for d := 8; d <= 19; d++ { + in.Days = append(in.Days, quarterDay(time.Date(2026, 11, d, 0, 0, 0, 0, loc).Format(dayLayout), + func(int) float32 { return 300 })) + } + + got, est := ReplayDays(in, 14) + if len(got) != 14*1440 { + t.Fatalf("len = %d, want %d", len(got), 14*1440) + } + if !est { + t.Fatal("estimate = false, want true because twelve days are stretched") + } + // The first minute day starts at 2026-11-08 and the minutes of 2026-11-20 + // carry the minute values. + idx := 12 * 1440 + if got[idx].At.Format(dayLayout) != "2026-11-20" { + t.Fatalf("minute %d at %s, want 2026-11-20", idx, got[idx].At) + } + if got[idx].Balance["load_total"] != 500 { + t.Fatalf("minute day load = %v, want 500", got[idx].Balance["load_total"]) + } +} + +func TestReplayDaysWithoutMinutesIsRepeatable(t *testing.T) { + loc := time.UTC + ramp := func(q int) float32 { return float32(100 + 10*q) } + in := &Input{Now: replayTestNow(), Loc: loc, Days: []DayFile{quarterDay("2026-11-21", ramp)}, + Learned: map[string]LearnedEntry{ + "site/pv_reserve_w": {Key: "site/pv_reserve_w", Kind: ValueNumber, Value: 1500.0, + At: time.Date(2026, 11, 1, 0, 0, 0, 0, loc).Unix()}, + }} + + first, est := ReplayDays(in, 1) + if !est { + t.Fatal("estimate = false, want true for a stretched day") + } + if len(first) != 1440 { + t.Fatalf("len = %d, want 1440", len(first)) + } + second, _ := ReplayDays(in, 1) + for i := range first { + if first[i].Balance["load_total"] != second[i].Balance["load_total"] { + t.Fatalf("minute %d differs between two runs", i) + } + } + + // The mean of every quarter hour is its value within one percent. + for q := 0; q < dayQuarters; q++ { + want := float64(ramp(q)) + sum := 0.0 + for m := 0; m < 15; m++ { + sum += first[q*15+m].Balance["load_total"] + } + if mean := sum / 15; math.Abs(mean-want) > 0.01*want { + t.Fatalf("quarter %d mean = %v, want %v within 1 %%", q, mean, want) + } + } + + if got := first[0].Learned["site/pv_reserve_w"]; got != 1500 { + t.Fatalf("learned value = %v, want 1500", got) + } +} + +func TestReplayDaysLeavesOutFutureLearnedValues(t *testing.T) { + loc := time.UTC + now := replayTestNow() + in := &Input{Now: now, Loc: loc, Days: []DayFile{quarterDay("2026-11-21", func(int) float32 { return 1 })}, + Learned: map[string]LearnedEntry{ + "site/pv_reserve_w": {Key: "site/pv_reserve_w", Kind: ValueNumber, Value: 1500.0, At: now.Unix()}, + }} + got, _ := ReplayDays(in, 1) + if len(got) == 0 { + t.Fatal("no minutes") + } + if _, ok := got[0].Learned["site/pv_reserve_w"]; ok { + t.Fatal("a value learned after the minute must not be in that minute") + } +} + +func TestMinuteNoiseFollowsTheNoiseBand(t *testing.T) { + loc := time.UTC + start := time.Date(2026, 11, 21, 0, 0, 0, 0, loc) + rng := rand.New(rand.NewSource(1)) + series := make([]float32, 1440) + for i := range series { + series[i] = float32(500 + 80*(2*rng.Float64()-1)) + } + r := fakeMinutes{loc: loc, days: map[string]map[string][]float32{ + "2026-11-21": {"b:load_total": series}, + }} + got, ok := MinuteNoise(r, "b:load_total", 500, start, start.Add(24*time.Hour)) + if !ok { + t.Fatal("ok = false, want a noise estimate") + } + if math.Abs(got-80) > 15 { + t.Fatalf("noise = %v, want 80 within 15", got) + } +} + +func TestRealStateFollowsEvents(t *testing.T) { + loc := time.UTC + day := time.Date(2026, 11, 21, 0, 0, 0, 0, loc) + at := func(h, m int) int64 { return day.Add(time.Duration(h)*time.Hour + time.Duration(m)*time.Minute).Unix() } + f := quarterDay("2026-11-21", func(int) float32 { return 0 }) + f.Devices["plug.x"] = &DeviceDay{} + f.Events = []EventRec{ + {At: at(8, 0), Device: "plug.x", On: true}, + {At: at(9, 0), Device: "plug.x", On: false}, + } + in := &Input{Now: replayTestNow(), Loc: loc, Days: []DayFile{f}} + minutes := []ReplayMinute{ + {At: day.Add(7*time.Hour + 59*time.Minute)}, + {At: day.Add(8 * time.Hour)}, + {At: day.Add(8*time.Hour + 30*time.Minute)}, + {At: day.Add(9 * time.Hour)}, + {At: day.Add(10 * time.Hour)}, + } + want := []bool{false, true, true, false, false} + got := RealState(in, "plug.x", minutes) + for i := range want { + if got[i] != want[i] { + t.Fatalf("minute %s: on = %v, want %v", minutes[i].At.Format("15:04"), got[i], want[i]) + } + } +} + +func TestReplayLastYearNeedsHourlyValues(t *testing.T) { + loc := time.UTC + now := replayTestNow() + in := &Input{Now: now, Loc: loc} + stats := energystats.NewStore(t.TempDir()) + + if got, ok := ReplayLastYear(in, stats, 2); ok || got != nil { + t.Fatalf("without hourly values: ok = %v, len = %d, want false and nil", ok, len(got)) + } + + // Wednesday 2025-11-12 lies in the week one year before the first week. + hour := time.Date(2025, 11, 12, 8, 0, 0, 0, loc) + if err := stats.AddOwn(energystats.HourRecord{Hour: hour, KWh: map[string]float64{"load_total": 0.5}, Covered: 3600}); err != nil { + t.Fatal(err) + } + got, ok := ReplayLastYear(in, stats, 2) + if !ok { + t.Fatal("ok = false, want true with an hourly value") + } + if len(got) != 2*7*1440 { + t.Fatalf("len = %d, want %d minutes for two weeks", len(got), 2*7*1440) + } + var found int + for _, m := range got { + if !m.At.Before(hour) && m.At.Before(hour.Add(time.Hour)) && m.Balance["load_total"] == 500 { + found++ + } + } + if found != 60 { + t.Fatalf("minutes of the hour at 500 W = %d, want 60", found) + } +} + +func TestStretchedDayBorrowsTheMinuteShape(t *testing.T) { + loc := time.UTC + // The minute day has a ramp of 10 W per minute inside every quarter hour, + // mean 170 W. The stretched day has 170 W in every quarter hour. + ramp := make([]float32, 1440) + for i := range ramp { + ramp[i] = float32(100 + 10*(i%15)) + } + minutes := fakeMinutes{loc: loc, days: map[string]map[string][]float32{ + "2026-11-21": {"b:load_total": ramp}, + }} + in := &Input{Now: replayTestNow(), Loc: loc, Minutes: minutes, + Days: []DayFile{quarterDay("2026-11-20", func(int) float32 { return 170 })}} + + got, est := ReplayDays(in, 2) + if !est { + t.Fatal("estimate = false, want true for the stretched day") + } + if len(got) != 2*1440 { + t.Fatalf("len = %d, want %d", len(got), 2*1440) + } + for q := 0; q < dayQuarters; q++ { + sum := 0.0 + for m := 0; m < 15; m++ { + want := float64(100 + 10*m) + v := got[q*15+m].Balance["load_total"] + if math.Abs(v-want) > 1e-6 { + t.Fatalf("quarter %d minute %d = %v, want the ramp value %v", q, m, v, want) + } + sum += v + } + if mean := sum / 15; math.Abs(mean-170) > 0.01*170 { + t.Fatalf("quarter %d mean = %v, want 170 within 1 %%", q, mean) + } + } +} + +func TestEngineInputCarriesTheMinuteReader(t *testing.T) { + loc := time.UTC + e := newTestEngine(t, learnrec.Limits{}) + reader := fakeMinutes{loc: loc, days: map[string]map[string][]float32{}} + if got := e.input(replayTestNow(), learnrec.Limits{}, nil); got.Minutes != nil { + t.Fatal("without SetMinutes the input has a reader") + } + e.SetMinutes(func() learnrec.Reader { return reader }) + if got := e.input(replayTestNow(), learnrec.Limits{}, nil); got.Minutes == nil { + t.Fatal("after SetMinutes the input has no reader") + } +} + +func TestEngineInputCarriesTheSteps(t *testing.T) { + e := newTestEngine(t, learnrec.Limits{}) + if got := e.input(replayTestNow(), learnrec.Limits{}, nil); got.Steps != nil { + t.Fatal("without SetSteps the input has a step reader") + } + e.SetSteps(func(string, time.Time, time.Time) []Step { return nil }) + if got := e.input(replayTestNow(), learnrec.Limits{}, nil); got.Steps == nil { + t.Fatal("after SetSteps the input has no step reader") + } +} diff --git a/dashboard/internal/autolearn/rules.go b/dashboard/internal/autolearn/rules.go index 53226929..1e68a39b 100644 --- a/dashboard/internal/autolearn/rules.go +++ b/dashboard/internal/autolearn/rules.go @@ -33,6 +33,7 @@ type Rule struct { // balance_threshold, Value from value of a topic_value or entity_value, // HoldSeconds from hold_seconds. A field that holds a learned value is not a // number: it stays 0 or nil here and is listed in Learned under its field name. +// The value a learned_value condition compares is listed under learned. // Raw keeps the original JSON of the condition. type Condition struct { Type string @@ -90,6 +91,13 @@ type Scenario struct { type RegulatorSpec struct { DeadbandW float64 MaxW float64 + // Gain is the regulator gain (gain, default 0.8). + Gain float64 + // MaxChangeW is the largest change per step in W (max_change_w), nil for no limit. + MaxChangeW *float64 + // BaseSource is the regulator base (base.source): last, entity or balance. + // Every base other than last is a measured base. + BaseSource string } // wireDoc mirrors the JSON of the rule document. Unknown fields are ignored. @@ -143,6 +151,14 @@ type wireCondition struct { HoldSeconds json.RawMessage `json:"hold_seconds"` } +// wireLearnedValue holds the top level learned key of a learned_value +// condition, the value it compares, with its fallback and max age. +type wireLearnedValue struct { + Learned string `json:"learned"` + Fallback any `json:"fallback"` + MaxAgeS float64 `json:"max_age_s"` +} + // wireLearnedRef mirrors the JSON of a learned reference. type wireLearnedRef struct { Learned string `json:"learned"` @@ -186,7 +202,12 @@ type wireRegulator struct { Topic string `json:"topic"` Max float64 `json:"max"` } `json:"output"` - DeadbandW *float64 `json:"deadband_w"` + DeadbandW *float64 `json:"deadband_w"` + Gain *float64 `json:"gain"` + MaxChangeW *float64 `json:"max_change_w"` + Base struct { + Source string `json:"source"` + } `json:"base"` } // ParseDoc parses the rule document. Unknown fields are ignored. @@ -234,10 +255,17 @@ func ParseDoc(raw []byte) (Doc, error) { // spec returns the learning view of the regulator block. A missing deadband_w // takes the schema default of 20 W. func (wr *wireRegulator) spec() *RegulatorSpec { - spec := &RegulatorSpec{DeadbandW: 20, MaxW: wr.Output.Max} + spec := &RegulatorSpec{DeadbandW: 20, MaxW: wr.Output.Max, Gain: 0.8, BaseSource: wr.Base.Source} if wr.DeadbandW != nil { spec.DeadbandW = *wr.DeadbandW } + if wr.Gain != nil { + spec.Gain = *wr.Gain + } + if wr.MaxChangeW != nil { + v := *wr.MaxChangeW + spec.MaxChangeW = &v + } return spec } @@ -267,6 +295,11 @@ func parseCondition(rawCond json.RawMessage) (Condition, error) { if _, err := learnedRef(wc.End, "end", learned); err != nil { return Condition{}, err } + if wc.Type == "learned_value" { + if err := learnedValueRef(rawCond, learned); err != nil { + return Condition{}, err + } + } condition := Condition{ Type: wc.Type, Field: wc.Field, Comparison: wc.Comparison, Topic: wc.Topic, EntityID: wc.EntityID, Hysteresis: wc.Hysteresis, Value: value, HoldSeconds: holdSeconds, @@ -298,6 +331,21 @@ func number(raw json.RawMessage, name string, learned map[string]LearnedRef) (*f return &n, nil } +// learnedValueRef records the key a learned_value condition compares under +// learned, with its top level fallback and max_age_s. Without a key nothing is +// recorded. +func learnedValueRef(rawCond json.RawMessage, learned map[string]LearnedRef) error { + var wv wireLearnedValue + if err := json.Unmarshal(rawCond, &wv); err != nil { + return err + } + if wv.Learned == "" { + return nil + } + learned["learned"] = LearnedRef{Key: wv.Learned, Fallback: wv.Fallback, MaxAgeS: wv.MaxAgeS} + return nil +} + // learnedRef records raw under name when it is a learned reference and reports // whether it was one. // An object is a reference only with a non empty text under learned, as the diff --git a/dashboard/internal/autolearn/rules_test.go b/dashboard/internal/autolearn/rules_test.go index 12d2b4c4..10b2f934 100644 --- a/dashboard/internal/autolearn/rules_test.go +++ b/dashboard/internal/autolearn/rules_test.go @@ -404,11 +404,11 @@ func TestParseDocReadsRegulatorSpec(t *testing.T) { if len(doc.Scenarios) != 3 { t.Fatalf("scenarios = %d, want 3", len(doc.Scenarios)) } - want := &RegulatorSpec{DeadbandW: 30, MaxW: 800} + want := &RegulatorSpec{DeadbandW: 30, MaxW: 800, Gain: 0.8, BaseSource: "balance"} if got := doc.Scenarios[0].Regulator; got == nil || *got != *want { t.Errorf("Regulator = %+v, want %+v", got, want) } - wantDefault := &RegulatorSpec{DeadbandW: 20, MaxW: 11000} + wantDefault := &RegulatorSpec{DeadbandW: 20, MaxW: 11000, Gain: 0.8, BaseSource: "entity"} if got := doc.Scenarios[1].Regulator; got == nil || *got != *wantDefault { t.Errorf("entity base Regulator = %+v, want %+v", got, wantDefault) } @@ -416,3 +416,68 @@ func TestParseDocReadsRegulatorSpec(t *testing.T) { t.Errorf("scenario without regulator = %+v, want nil", doc.Scenarios[2].Regulator) } } + +// A learned_value condition keeps the key it compares under learned, with its +// top level fallback and max_age_s. A threshold may be a reference of its own. +func TestParseLearnedValueRules(t *testing.T) { + doc, err := ParseDoc([]byte(`{"rules":[{"id":"r","name":"R","enabled":true,"conditions":[` + + `{"type":"learned_value","learned":"site/pv_reserve_w","comparison":"above","threshold":1500,` + + `"fallback":0,"hysteresis":100,"max_age_s":120,"hold_seconds":30},` + + `{"type":"learned_value","learned":"site/pv_reserve_w","comparison":"below",` + + `"threshold":{"learned":"device/wallbox_1/cycle_wh","min":500,"max":3000,"fallback":1500,"offset":10},` + + `"fallback":0}` + + `],"actions":[]}]}`)) + if err != nil { + t.Fatalf("ParseDoc: %v", err) + } + conds := doc.Rules[0].Conditions + if len(conds) != 2 { + t.Fatalf("conditions = %d, want 2", len(conds)) + } + + plain := conds[0] + if plain.Type != "learned_value" || plain.Comparison != "above" || plain.Threshold != 1500 || plain.Hysteresis != 100 { + t.Errorf("plain condition = %+v", plain) + } + if plain.HoldSeconds == nil || *plain.HoldSeconds != 30 { + t.Errorf("HoldSeconds = %v, want 30", plain.HoldSeconds) + } + ref := plain.Learned["learned"] + if ref.Key != "site/pv_reserve_w" || ref.Fallback != float64(0) || ref.MaxAgeS != 120 { + t.Errorf("compared value reference = %+v", ref) + } + if _, ok := plain.Learned["threshold"]; ok { + t.Errorf("plain threshold is a reference, want a number") + } + if !strings.Contains(string(plain.Raw), `"max_age_s":120`) { + t.Errorf("Raw = %s, want the original condition JSON", plain.Raw) + } + + bound := conds[1] + if bound.Comparison != "below" || bound.Threshold != 0 { + t.Errorf("bound condition = %+v", bound) + } + thr := bound.Learned["threshold"] + if thr.Key != "device/wallbox_1/cycle_wh" || thr.Min != float64(500) || thr.Max != float64(3000) || thr.Fallback != float64(1500) || thr.Offset != 10 { + t.Errorf("threshold reference = %+v", thr) + } + if bound.Learned["learned"].Key != "site/pv_reserve_w" { + t.Errorf("compared value reference = %+v", bound.Learned["learned"]) + } +} + +func TestParseDocReadsTheRegulatorTuning(t *testing.T) { + raw := []byte(`{"scenarios":[{"id":"a","enabled":true,"while":{"mode":"regulate","regulator":{"output":{"topic":"t","max":800},"gain":0.5,"max_change_w":40,"base":{"source":"balance","field":"pv"}}}},{"id":"b","enabled":true,"while":{"mode":"regulate","regulator":{"output":{"topic":"t","max":800},"base":{"source":"last"}}}}]}`) + doc, err := ParseDoc(raw) + if err != nil { + t.Fatal(err) + } + a := doc.Scenarios[0].Regulator + if a.Gain != 0.5 || a.MaxChangeW == nil || *a.MaxChangeW != 40 || a.BaseSource != "balance" { + t.Fatalf("tuning = %+v, want gain 0.5, max change 40, base balance", a) + } + b := doc.Scenarios[1].Regulator + if b.Gain != 0.8 || b.MaxChangeW != nil || b.BaseSource != "last" { + t.Fatalf("defaults = %+v, want gain 0.8, no max change, base last", b) + } +} diff --git a/dashboard/internal/autolearn/steplog.go b/dashboard/internal/autolearn/steplog.go index d5936e02..1003dc63 100644 --- a/dashboard/internal/autolearn/steplog.go +++ b/dashboard/internal/autolearn/steplog.go @@ -139,17 +139,18 @@ func (l *StepLog) WithRingDays(ring func() int) *StepLog { } // Steps liefert die Schritte des Szenarios mit einem Zeitpunkt von from bis to, -// beide Enden einschliesslich. Vor dem Ring liest es aus den Dateien am Ort, im -// Ring aus dem RAM. Ein Schritt vor dem Ring steht im RAM, wenn er noch nicht -// in der Datei steht oder die Datei schon verfallen ist. Ohne Ort zaehlt nur das RAM. +// beide Enden einschliesslich. Vor der Grenze des RAM liest es aus den Dateien am +// Ort, ab der Grenze aus dem RAM. Ein Schritt vor der Grenze steht im RAM, wenn er +// noch nicht in der Datei steht oder die Datei schon verfallen ist. Ohne Ort zaehlt +// nur das RAM. func (l *StepLog) Steps(scenario string, from, to time.Time) []Step { now := l.now() - ringCut := l.ringCutoff(now) fileCut := l.fileCutoff(now) dir := l.dir() + cut := l.coverCutoff(scenario, l.ringCutoff(now), now.Unix()) var out []Step - if dir != "" && from.Unix() < ringCut { - out = l.readFiles(dir, scenario, from, to, ringCut) + if dir != "" && from.Unix() < cut { + out = l.readFiles(dir, scenario, from, to, cut) } l.mu.Lock() defer l.mu.Unlock() @@ -158,7 +159,7 @@ func (l *StepLog) Steps(scenario string, from, to time.Time) []Step { if st.At < from.Unix() || st.At > to.Unix() { continue } - inFile := dir != "" && st.At < ringCut && i < written && st.At >= fileCut + inFile := dir != "" && st.At < cut && i < written && st.At >= fileCut if inFile { continue // steht in der Datei, die readFiles liest } @@ -269,6 +270,24 @@ func (l *StepLog) ringCutoff(now time.Time) int64 { return dayCutoff(now, n) } +// coverCutoff ist der Zeitpunkt, ab dem das RAM die Schritte des Szenarios hat. +// Der Ring reicht bis ringCut. Nach einem Start fuellt sich das RAM aber nur mit +// den Schritten, die seither kamen, deshalb beginnt die Abdeckung beim frueheste +// Schritt im RAM, bei leerem RAM bei now. Davor liest Steps die Dateien. +func (l *StepLog) coverCutoff(scenario string, ringCut, now int64) int64 { + l.mu.Lock() + defer l.mu.Unlock() + list := l.steps[scenario] + if len(list) == 0 { + return now + } + earliest := list[0].At + for _, st := range list[1:] { + earliest = min(earliest, st.At) + } + return max(ringCut, earliest) +} + // fileCutoff ist der Anfang des ersten Tages, dessen Datei am Ort bleibt. func (l *StepLog) fileCutoff(now time.Time) int64 { return dayCutoff(now, l.days()) @@ -281,8 +300,8 @@ func dayCutoff(now time.Time, n int) int64 { return first.Unix() } -// readFiles liest die Schritte des Szenarios aus den Tagesdateien vor dem -// Anfang des Rings, im Bereich von from bis to. +// readFiles liest die Schritte des Szenarios aus den Tagesdateien vor cutoff, +// im Bereich von from bis to. func (l *StepLog) readFiles(dir, scenario string, from, to time.Time, cutoff int64) []Step { var out []Step first := time.Unix(from.Unix(), 0).In(time.Local) diff --git a/dashboard/internal/autolearn/steplog_test.go b/dashboard/internal/autolearn/steplog_test.go index cf2f8d93..b047fd21 100644 --- a/dashboard/internal/autolearn/steplog_test.go +++ b/dashboard/internal/autolearn/steplog_test.go @@ -392,3 +392,57 @@ func TestStepLogRingIsBoundedWhileFilesKeepTheirDays(t *testing.T) { t.Fatalf("Steps = %d, want 3 (two days from files, today from RAM)", len(got)) } } + +// Nach einem Start ist das RAM leer. Der Ring von 7 Tagen darf dann nicht die +// letzten Tage verschlucken: sie stehen in den Dateien, und ein Schritt nach dem +// Start kommt dazu, ohne dass einer doppelt zaehlt. +func TestStepLogReadsTheRingFromFilesAfterAStart(t *testing.T) { + loc := berlinLoc(t) + dir := t.TempDir() + now := time.Date(2026, 11, 22, 12, 0, 0, 0, loc) + before := NewStepLog(func() int { return 14 }, func() string { return dir }) + before.now = func() time.Time { return now } + var want int + for back := 13; back >= 1; back-- { + at := now.AddDate(0, 0, -back).Truncate(24 * time.Hour).Add(12 * time.Hour) + if err := before.Add("heizung", stepPayload(float64(at.Unix()), -5, -5, fptr(1200), fptr(1200), "unchanged")); err != nil { + t.Fatal(err) + } + want++ + } + for _, hour := range []int{8, 9, 10} { + at := time.Date(2026, 11, 22, hour, 0, 0, 0, loc) + if err := before.Add("heizung", stepPayload(float64(at.Unix()), -5, -5, fptr(1200), fptr(1200), "unchanged")); err != nil { + t.Fatal(err) + } + want++ + } + if err := before.Flush(now); err != nil { + t.Fatal(err) + } + + // Der Neustart: Ring 7 Tage, RAM leer. + after := NewStepLog(func() int { return 14 }, func() string { return dir }).WithRingDays(func() int { return 7 }) + after.now = func() time.Time { return now } + from := now.AddDate(0, 0, -14) + if got := after.Steps("heizung", from, now); len(got) != want { + t.Fatalf("after a start Steps = %d, want the %d steps of the files", len(got), want) + } + + // Ein Schritt nach dem Start liegt im RAM und zaehlt genau einmal dazu. + fresh := time.Date(2026, 11, 22, 11, 0, 0, 0, loc) + if err := after.Add("heizung", stepPayload(float64(fresh.Unix()), -5, -5, fptr(1200), fptr(1200), "unchanged")); err != nil { + t.Fatal(err) + } + got := after.Steps("heizung", from, now) + if len(got) != want+1 { + t.Fatalf("Steps with a fresh step = %d, want %d", len(got), want+1) + } + seen := map[int64]bool{} + for _, st := range got { + if seen[st.At] { + t.Fatalf("step at %d counted twice", st.At) + } + seen[st.At] = true + } +} diff --git a/dashboard/internal/learnrec/level.go b/dashboard/internal/learnrec/level.go index fb778cc6..efe2ce94 100644 --- a/dashboard/internal/learnrec/level.go +++ b/dashboard/internal/learnrec/level.go @@ -33,6 +33,8 @@ type Limits struct { SimilarDays int SimilarPoolDays int SimilarLastYear bool + ThresholdSteps int + ReplayJointHold bool } // LimitsFor liefert die Grenzen aus Spec 5.7 fuer die Stufe und die Kernzahl. @@ -42,13 +44,13 @@ func LimitsFor(l Level, cores int) Limits { switch l { case LevelEco: return Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, RAMMinuteBytes: 4 << 20, - PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false} + PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false, ThresholdSteps: 20, ReplayJointHold: false} case LevelFull: return Limits{Workers: workers, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, RAMMinuteBytes: 64 << 20, - PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true} + PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true, ThresholdSteps: 80, ReplayJointHold: true} default: return Limits{Workers: workers, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, RAMMinuteBytes: 16 << 20, - PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true} + PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true, ThresholdSteps: 40, ReplayJointHold: false} } } diff --git a/dashboard/internal/learnrec/level_test.go b/dashboard/internal/learnrec/level_test.go index 218771dc..ecc5be42 100644 --- a/dashboard/internal/learnrec/level_test.go +++ b/dashboard/internal/learnrec/level_test.go @@ -12,12 +12,12 @@ func TestLimitsForLevels(t *testing.T) { cores int want Limits }{ - {"eco 1 core", LevelEco, 1, Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, RAMMinuteBytes: 4 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false}}, - {"eco 4 cores", LevelEco, 4, Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, RAMMinuteBytes: 4 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false}}, - {"balanced 1 core", LevelBalanced, 1, Limits{Workers: 1, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, RAMMinuteBytes: 16 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true}}, - {"balanced 4 cores", LevelBalanced, 4, Limits{Workers: 3, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, RAMMinuteBytes: 16 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true}}, - {"full 1 core", LevelFull, 1, Limits{Workers: 1, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, RAMMinuteBytes: 64 << 20, PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true}}, - {"full 4 cores", LevelFull, 4, Limits{Workers: 3, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, RAMMinuteBytes: 64 << 20, PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true}}, + {"eco 1 core", LevelEco, 1, Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, RAMMinuteBytes: 4 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false, ThresholdSteps: 20, ReplayJointHold: false}}, + {"eco 4 cores", LevelEco, 4, Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, RAMMinuteBytes: 4 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false, ThresholdSteps: 20, ReplayJointHold: false}}, + {"balanced 1 core", LevelBalanced, 1, Limits{Workers: 1, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, RAMMinuteBytes: 16 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true, ThresholdSteps: 40, ReplayJointHold: false}}, + {"balanced 4 cores", LevelBalanced, 4, Limits{Workers: 3, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, RAMMinuteBytes: 16 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true, ThresholdSteps: 40, ReplayJointHold: false}}, + {"full 1 core", LevelFull, 1, Limits{Workers: 1, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, RAMMinuteBytes: 64 << 20, PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true, ThresholdSteps: 80, ReplayJointHold: true}}, + {"full 4 cores", LevelFull, 4, Limits{Workers: 3, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, RAMMinuteBytes: 64 << 20, PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true, ThresholdSteps: 80, ReplayJointHold: true}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -180,3 +180,22 @@ func TestRecordShareKeepsFourteenDays(t *testing.T) { t.Errorf("today = %v, want 0", got) } } + +func TestLimitsForReplayThreshold(t *testing.T) { + tests := []struct { + level Level + steps int + jointHold bool + }{ + {LevelEco, 20, false}, + {LevelBalanced, 40, false}, + {LevelFull, 80, true}, + } + for _, tt := range tests { + got := LimitsFor(tt.level, 4) + if got.ThresholdSteps != tt.steps || got.ReplayJointHold != tt.jointHold { + t.Errorf("LimitsFor(%s) = (steps %d, jointHold %v), want (%d, %v)", + tt.level, got.ThresholdSteps, got.ReplayJointHold, tt.steps, tt.jointHold) + } + } +} diff --git a/dashboard/internal/monitoring/notice.go b/dashboard/internal/monitoring/notice.go index d8118d57..55bf1203 100644 --- a/dashboard/internal/monitoring/notice.go +++ b/dashboard/internal/monitoring/notice.go @@ -28,16 +28,18 @@ type Ack struct { // Notice ist eine Meldung. Since ist der früheste bekannte Beginn aus der // Quelle (Kettenbefund), sonst null. FirstSeen und Ack setzt der Store. type Notice struct { - ID string `json:"id"` - Source string `json:"source"` // energy, chain, learn - Severity string `json:"severity"` // warn, info - Code string `json:"code"` - Params map[string]any `json:"params,omitempty"` - Evidence *autolearn.Evidence `json:"evidence,omitempty"` - Steps []Step `json:"steps"` - FirstSeen int64 `json:"first_seen"` - Ack *Ack `json:"ack"` - Since time.Time `json:"-"` + ID string `json:"id"` + Source string `json:"source"` // energy, chain, learn + Severity string `json:"severity"` // warn, info + Code string `json:"code"` + Params map[string]any `json:"params,omitempty"` + Evidence *autolearn.Evidence `json:"evidence,omitempty"` + // Facts are the figures of a learned finding, shown under its text. + Facts []autolearn.Fact `json:"facts,omitempty"` + Steps []Step `json:"steps"` + FirstSeen int64 `json:"first_seen"` + Ack *Ack `json:"ack"` + Since time.Time `json:"-"` } // Input sind die Quellen einer Sammlung. @@ -191,10 +193,14 @@ func learnSeverity(s string) string { } } +// learnNotices lists the learned findings that no rule shows. A finding with +// RuleIDs or Apply belongs to a rule, and the automations page marks that rule +// with it. A regulator finding is bound to its scenario, which has no mark, so +// it is listed here as well. func learnNotices(findings []autolearn.Finding) []Notice { var out []Notice for _, f := range findings { - if len(f.RuleIDs) != 0 || len(f.Apply) != 0 { + if (len(f.RuleIDs) != 0 || len(f.Apply) != 0) && f.Kind != "regulator" { continue } params := make(map[string]any, len(f.Summary.Params)+1) @@ -224,6 +230,9 @@ func learnNotices(findings []autolearn.Finding) []Notice { ev := f.Evidence n.Evidence = &ev } + if len(f.Facts) > 0 { + n.Facts = append([]autolearn.Fact(nil), f.Facts...) + } out = append(out, n) } return out diff --git a/dashboard/internal/monitoring/notice_test.go b/dashboard/internal/monitoring/notice_test.go index 14621fed..c36f1280 100644 --- a/dashboard/internal/monitoring/notice_test.go +++ b/dashboard/internal/monitoring/notice_test.go @@ -122,3 +122,26 @@ func TestSuggestionsBecomeNoticesThatOpenTheSuggestion(t *testing.T) { t.Errorf("evidence = %+v, want the suggestion evidence", got.Evidence) } } + +// A regulator finding is bound to its scenario by ID and carries a fix, so the +// rule-bound skip would hide it everywhere. It is listed with its facts. +func TestCollectOpensScenarioRegulatorFinding(t *testing.T) { + in := Input{Findings: []autolearn.Finding{{ + ID: "regulator:nulleinspeisung_last", Kind: "regulator", Group: "check", Severity: "info", + RuleIDs: []string{"nulleinspeisung_last"}, + Summary: autolearn.Text{Code: "regulator.quality", Params: map[string]any{"scenario": "Nulleinspeisung", "gain": 0.8}}, + Evidence: autolearn.Evidence{Shape: "scale"}, + Facts: []autolearn.Fact{{Code: "k", Value: 1.0}, {Code: "settle_s", Value: 240}}, + Apply: []autolearn.Fix{{Code: "set_regulator", RuleID: "nulleinspeisung_last"}}, + }}} + got := Collect(in) + if len(got) != 1 || got[0].ID != "learn:regulator:nulleinspeisung_last" || got[0].Code != "regulator.quality" { + t.Fatalf("got %+v", got) + } + if got[0].Evidence == nil || got[0].Evidence.Shape != "scale" { + t.Errorf("evidence = %+v", got[0].Evidence) + } + if len(got[0].Facts) != 2 || got[0].Facts[1].Code != "settle_s" { + t.Errorf("facts = %+v", got[0].Facts) + } +} diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index 0851b028..09da4da6 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,4 +1,12 @@ version,date,asset,v,note +v0.11.22-pre.33,2026-11-22,css/automations.css,24, +v0.11.22-pre.33,2026-11-22,js/automation-evidence.js,6, +v0.11.22-pre.33,2026-11-22,js/automation-learned.js,5, +v0.11.22-pre.33,2026-11-22,js/automation-suggestions.js,5, +v0.11.22-pre.33,2026-11-22,js/automation-templates.js,11, +v0.11.22-pre.33,2026-11-22,js/automations-view.js,13, +v0.11.22-pre.33,2026-11-22,js/automations.page.js,31, +v0.11.22-pre.33,2026-11-22,js/monitoring-model.js,3, v0.11.22-pre.32,2026-11-22,css/learning-settings.css,3, v0.11.22-pre.32,2026-11-22,js/learning-settings.js,3, v0.11.22-pre.32,2026-11-22,js/settings.page.js,43, diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 51622798..19872419 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -151,6 +151,10 @@ "automations.assistant.summary.follow.then_on": "{name} wird eingeschaltet", "automations.assistant.summary.follow.when_off": "Wenn {name} ausgeschaltet wird", "automations.assistant.summary.follow.when_on": "Wenn {name} eingeschaltet wird", + "automations.assistant.summary.full.end": "Das Gerät schaltet danach aus", + "automations.assistant.summary.full.run": "Das Gerät läuft mindestens {min} Sekunden", + "automations.assistant.summary.full.until": "Endet bei Netzbezug über {value} W für {minutes} Minuten", + "automations.assistant.summary.full.when": "Wenn der Akku über {soc} % liegt und mehr als {value} W eingespeist werden", "automations.assistant.summary.full_monthly.end": "Danach geht die Ladeleistung zurück auf den vorherigen Wert", "automations.assistant.summary.full_monthly.grid": "Auch mit Strom aus dem Netz", "automations.assistant.summary.full_monthly.start": "Die Ladeleistung geht auf {value} {unit}", @@ -207,6 +211,11 @@ "automations.assistant.summary.reset": "Beim Ende geht die Grenze auf {value} W zurück", "automations.assistant.summary.restart.then": "Der Schalter {name} geht aus und nach {minutes} Minuten wieder an", "automations.assistant.summary.runtime.when": "Wenn der Schalter {minutes} Minuten lang eingeschaltet ist", + "automations.assistant.summary.shift.end": "Das Gerät schaltet nach dem Zyklus selbst ab", + "automations.assistant.summary.shift.limit": "Ohne Überschuss im Fenster startet das Gerät nicht", + "automations.assistant.summary.shift.run": "Das Gerät startet im Überschuss, bis {time}", + "automations.assistant.summary.shift.surplus": "Und der restliche Überschuss des Tages reicht für einen Zyklus", + "automations.assistant.summary.shift.when": "Wenn die Einspeisung mindestens {minutes} Minuten über {value} W liegt", "automations.assistant.summary.short": "Zusammenfassung", "automations.assistant.summary.silent.again": "Die Mitteilung kommt frühestens nach {hours} h wieder", "automations.assistant.summary.silent.when": "Wenn der Wechselrichter {minutes} Minuten lang keinen neuen Wert meldet", @@ -219,6 +228,7 @@ "automations.assistant.summary.switch.until_runtime": "Nach {minutes} Minuten Laufzeit", "automations.assistant.summary.switch.until_sunset": "Bei Sonnenuntergang", "automations.assistant.summary.switch.when": "Wenn die Einspeisung mindestens {minutes} Minuten über {value} W liegt", + "automations.assistant.summary.switch.when_reserve": "Wenn die PV-Reserve mindestens {minutes} Minuten über {value} W liegt", "automations.assistant.summary.tariff.block": ", Entladen sperren", "automations.assistant.summary.tariff.end": "Ladeleistung zurück auf Automatik", "automations.assistant.summary.tariff.end_block": ", Entladen frei", @@ -237,6 +247,7 @@ "automations.assistant.summary.wallbox.until_min": "Bei Sonnenuntergang", "automations.assistant.summary.wallbox.until_sun": "Wenn der Netzbezug mindestens {minutes} Minuten über {value} W liegt", "automations.assistant.summary.wallbox.when": "Wenn die Einspeisung mindestens {minutes} Minuten über {start} W liegt", + "automations.assistant.summary.wallbox.when_reserve": "Wenn die PV-Reserve mindestens {minutes} Minuten über {start} W liegt", "automations.assistant.surplus.aria": "Überschuss gestern mit Startschwelle", "automations.assistant.surplus.now": "Jetzt {power} W Überschuss, damit {result}.", "automations.assistant.surplus.now_hold": "würde sie jetzt nicht starten", @@ -369,6 +380,7 @@ "automations.condition_type.entity.label": "Gerätewert", "automations.condition_type.entity.short": "Temperatur, Zustand", "automations.condition_type.learned_state.short": "Haus", + "automations.condition_type.learned_value.short": "Lernwert", "automations.condition_type.sun.hint": "Gilt zwischen Sonnenaufgang und Sonnenuntergang oder umgekehrt, jeweils mit Versatz in Minuten. Braucht den Standort in den Einstellungen.", "automations.condition_type.sun.label": "Sonnenzeit", "automations.condition_type.sun.short": "Auf- und Untergang", @@ -536,11 +548,15 @@ "automations.learn.fact.cause.feedback": "Die Last selbst kippt die Bedingung", "automations.learn.fact.cause.offline_window": "Das Gerät war offline", "automations.learn.fact.cause.scattered": "Die Befehle verteilten sich über den Tag", + "automations.learn.fact.dead_steps": "Totzeit in Schritten", "automations.learn.fact.direction_share": "Anteil dieser Richtung", "automations.learn.fact.feature": "Merkmal", + "automations.learn.fact.feature.signal": "Bedingungssignal in W", "automations.learn.fact.feature.sun_elevation": "Sonnenhöhe in Grad", "automations.learn.fact.feature.to_sunset": "Minuten bis Sonnenuntergang", + "automations.learn.fact.flips_h": "Richtungswechsel je Stunde", "automations.learn.fact.hit_rate": "Trefferquote", + "automations.learn.fact.k": "Steigung K", "automations.learn.fact.knee": "Knick der Außentemperatur in °C", "automations.learn.fact.limit_s": "Grenze", "automations.learn.fact.min_runtime": "Mindestlaufzeit", @@ -551,17 +567,20 @@ "automations.learn.fact.peak_w": "Anlaufleistung", "automations.learn.fact.per_hour_max": "Höchstens pro Stunde", "automations.learn.fact.season_months": "Monate in der Saison", + "automations.learn.fact.settle_s": "Ausregelzeit in Sekunden", "automations.learn.fact.spread_min": "Streuung", "automations.learn.fact.window_s": "Zeitfenster", "automations.learn.fix.add_condition": "Bedingung ergänzen", "automations.learn.fix.disable_duplicate": "Diese Regel ausschalten", "automations.learn.fix.feedback_thresholds": "Schwellen auseinanderziehen", + "automations.learn.fix.learned_threshold": "Schwelle an die Betriebsleistung koppeln", "automations.learn.fix.min_runtime": "Mindestlaufzeit setzen", "automations.learn.fix.move_before": "Vor den Ausfall verschieben", "automations.learn.fix.open_rule": "Regel öffnen", "automations.learn.fix.repeat": "Als Wiederholung zusammenfassen", - "automations.learn.fix.set_cooldown": "Abkühlzeit 10 Minuten", + "automations.learn.fix.set_cooldown": "Abkühlzeit {value} s", "automations.learn.fix.set_hysteresis": "Hysterese {value} W", + "automations.learn.fix.set_regulator": "Regler nachstellen", "automations.learn.fix.set_threshold": "Schwelle auf {value}", "automations.learn.fix.shift_time": "Zeitfenster verschieben", "automations.learn.fix.stagger": "Schwellen staffeln", @@ -578,12 +597,27 @@ "automations.learn.legend.label": "Was bedeuten Ist und Soll?", "automations.learn.legend.scale": "Ist: der beobachtete Wert. Soll: der vorgeschlagene Wert.", "automations.learn.mark_label": "Befund zu dieser Regel anzeigen", + "automations.learn.param.deadband_w": "Totzone", + "automations.learn.param.gain": "Verstärkung", + "automations.learn.param.max_change_w": "Änderungsgrenze", + "automations.learn.regulator.quality.line": "Verstärkung {gain}, Soll nahe {gain_soll}", + "automations.learn.regulator.quality.text": "Der Regler von „{scenario}“ passt nicht zur Strecke. Verstärkung {gain}, Soll nahe {gain_soll}. Die Vorschläge setzen die Werte, die zur gemessenen Totzeit und Steigung passen.", + "automations.learn.regulator.quality.title": "Regler von „{scenario}“ ist nicht abgestimmt", "automations.learn.runtime.forgotten.line": "{forgotten} von {runs} Läufen blieben an, üblich sind {usual_min} min", "automations.learn.runtime.forgotten.text": "In {forgotten} von {runs} Läufen blieb das Gerät an, obwohl {usual_min} Minuten üblich sind. Das hat etwa {extra_kwh} kWh zusätzlich verbraucht. Eine Abschaltung nach der üblichen Laufzeit verhindert das.", "automations.learn.runtime.forgotten.title": "Läuft immer wieder zu lange", "automations.learn.season": "Gilt von KW {from} bis KW {to}", "automations.learn.season.all": "Gilt das ganze Jahr", "automations.learn.season.heating": "Heizzeit unter {below} °C", + "automations.learn.shift.load.line": "{kwh} kWh je Woche aus dem Netz verschiebbar", + "automations.learn.shift.load.text": "{device} lief {runs} Mal aus dem Netz, obwohl am selben Tag Überschuss für den ganzen Lauf da war. Ein Start im Überschuss bis {latest} Uhr spart diese Netzenergie.", + "automations.learn.shift.load.title": "{device} in den Überschuss verschieben", + "automations.learn.surplus.reserve.line": "PV-Reserve reicht von {from} bis {to} Uhr, Schwelle {on_w} W", + "automations.learn.surplus.reserve.text": "Die Einspeisung ist gedrosselt, die Anlage könnte zwischen {from} und {to} Uhr mehr Leistung liefern. Eine Regel auf die PV-Reserve mit {on_w} W schaltet {device} in diesem Fenster ein, sobald die Reserve reicht.", + "automations.learn.surplus.reserve.title": "{device} aus der PV-Reserve einschalten", + "automations.learn.surplus.window.line": "Überschuss von {from} bis {to} Uhr, Schwelle {on_w} W", + "automations.learn.surplus.window.text": "Zwischen {from} und {to} Uhr reicht der Überschuss an den meisten der letzten {days} Tage für {device}. Eine Regel mit einer Schwelle von {on_w} W schaltet das Gerät in diesem Fenster ein.", + "automations.learn.surplus.window.title": "{device} im typischen Überschussfenster einschalten", "automations.learn.switch_time.off.line": "An {hits} von {days} Tagen von Hand ausgeschaltet", "automations.learn.switch_time.off.text": "Du schaltest {device} an {hits} von {days} Tagen gegen {time} Uhr selbst aus. Eine Regel mit dieser Uhrzeit übernimmt das für dich.", "automations.learn.switch_time.off.title": "{device} um {time} Uhr ausschalten", @@ -605,6 +639,12 @@ "automations.learn.temperature.limit.line": "In warmen Wochen verbraucht {device} {kwh_warm} kWh pro Woche. Mit der Bedingung schaltet die Regel nur bei Kälte.", "automations.learn.temperature.limit.text": "„{rule}“ schaltet {device} das ganze Jahr ein. Das Dashboard hat gelernt, dass das Gerät nur unter etwa {knee} °C heizt. Darüber braucht es nur noch {kwh_warm} kWh pro Woche. Mit der Bedingung „unter {knee} °C“ läuft die Regel nur in der Heizzeit.", "automations.learn.temperature.limit.title": "{rule} nur bei Außentemperatur unter {knee} °C", + "automations.learn.threshold.too_high.line": "Schwelle {threshold} W, Soll {soll} W", + "automations.learn.threshold.too_high.text": "„{rule}“ schaltet erst bei {threshold} W ein. Nahe {soll} W würden etwa {kwh} kWh je Woche aus dem Überschuss genutzt, die heute ungenutzt ins Netz gehen. Der Vorschlag ist eine feste Schwelle oder ein Lernwert.", + "automations.learn.threshold.too_high.title": "Schwelle von „{rule}“ ist zu hoch", + "automations.learn.threshold.too_low.line": "Schwelle {threshold} W, Soll {soll} W", + "automations.learn.threshold.too_low.text": "„{rule}“ schaltet bei {threshold} W ein und zieht danach Strom aus dem Netz. Nahe {soll} W entfallen etwa {kwh} kWh Netzbezug je Woche.", + "automations.learn.threshold.too_low.title": "Schwelle von „{rule}“ ist zu niedrig", "automations.learn.undo.ignored": "Befund ausgeblendet", "automations.learn.unit.kwh_week": "kWh/Woche", "automations.learn.value.minutes": "{value} min", @@ -664,6 +704,9 @@ "automations.learned.state.now": "Jetzt {state}. Gelernt aus {n} Tagen, aktualisiert vor {age}.", "automations.learned.state.quiet": "Haus ist ruhig", "automations.learned.state.stale": "Der letzte Wert ist älter als {age}. Es gilt: {state}.", + "automations.learned.value.condition": "Lernwert", + "automations.learned.value.help": "Ein gelernter Zahlwert, etwa die PV-Reserve, gegen eine feste Schwelle oder eine andere Bezugsangabe. Ohne frischen Wert gilt die Ersatzwahl.", + "automations.learned.value.max_age": "Wert gilt höchstens", "automations.learned.year.line": "Der Wert lag im {high_month} bei {high} und im {low_month} bei {low}", "automations.limit.rules": "Höchstens {max} Regeln", "automations.limit.scenarios": "Höchstens {max} Szenarien", @@ -874,6 +917,8 @@ "automations.summary.chain_value": "{field} {comparison} {value} {unit}", "automations.summary.entity_value": "{comparison} {expected}", "automations.summary.entity_value_unit": "{comparison} {expected} {unit}", + "automations.summary.learned_value": "{name} {comparison} {threshold} {unit}", + "automations.summary.learned_value_hysteresis": "{name} {comparison} {threshold} {unit}, Hysterese {hysteresis}", "automations.summary.topic_value": "{comparison} {expected}", "automations.sun_event.sunrise": "Sonnenaufgang", "automations.sun_event.sunset": "Sonnenuntergang", @@ -881,6 +926,23 @@ "automations.tab.group_aria": "Ansicht", "automations.tab.rules": "Einzelregeln", "automations.tab.scenarios": "Szenarien", + "automations.templates.after_battery_full.blurb": "Schaltet ein Gerät ein, sobald der Akku voll ist und Strom eingespeist wird. Aus geht es bei Netzbezug.", + "automations.templates.after_battery_full.keywords": "akku voll einspeisung überschuss schalten lasten solar", + "automations.templates.after_battery_full.steps.device.help": "Das Gerät, das nach dem vollen Akku laufen soll.", + "automations.templates.after_battery_full.steps.device.short": "Gerät", + "automations.templates.after_battery_full.steps.device.title": "Schalter", + "automations.templates.after_battery_full.steps.min_run_s.help": "Wie lange das Gerät mindestens läuft, bevor der Netzbezug es abschalten darf.", + "automations.templates.after_battery_full.steps.min_run_s.options.long.text": "Das Gerät läuft mindestens 10 Minuten.", + "automations.templates.after_battery_full.steps.min_run_s.options.long.title": "10 Minuten", + "automations.templates.after_battery_full.steps.min_run_s.options.none.text": "Das Gerät darf sofort wieder abschalten.", + "automations.templates.after_battery_full.steps.min_run_s.options.none.title": "Keine", + "automations.templates.after_battery_full.steps.min_run_s.options.short.text": "Das Gerät läuft mindestens 3 Minuten.", + "automations.templates.after_battery_full.steps.min_run_s.options.short.title": "3 Minuten", + "automations.templates.after_battery_full.steps.min_run_s.options.standard.text": "Das Gerät läuft mindestens 5 Minuten.", + "automations.templates.after_battery_full.steps.min_run_s.options.standard.title": "5 Minuten", + "automations.templates.after_battery_full.steps.min_run_s.short": "Laufzeit", + "automations.templates.after_battery_full.steps.min_run_s.title": "Mindestlaufzeit", + "automations.templates.after_battery_full.title": "Gerät nach vollem Akku", "automations.templates.battery_full_monthly.blurb": "Lädt den Akku an einem festen Tag im Monat auf volle Ladung, mit Überschuss oder auch aus dem Netz.", "automations.templates.battery_full_monthly.keywords": "akku voll monat kalibrieren ladestand überschuss netz laden", "automations.templates.battery_full_monthly.steps.battery.help": "Der Akku, dessen Ladeleistung für diesen Tag gesetzt wird.", @@ -1269,6 +1331,22 @@ "automations.templates.runtime_off.steps.source.short": "Quelle", "automations.templates.runtime_off.steps.source.title": "Feste oder gelernte Laufzeit?", "automations.templates.runtime_off.title": "Laufzeit begrenzen", + "automations.templates.shift_start.blurb": "Startet ein Gerät, sobald der restliche Überschuss des Tages für einen Zyklus reicht. Nach der gewählten Uhrzeit startet es nicht mehr.", + "automations.templates.shift_start.keywords": "verschieben überschuss zyklus spülmaschine waschmaschine solar schalter", + "automations.templates.shift_start.steps.device.help": "Das Gerät, das im Überschuss laufen soll.", + "automations.templates.shift_start.steps.device.short": "Gerät", + "automations.templates.shift_start.steps.device.title": "Schalter", + "automations.templates.shift_start.steps.latest.help": "Bis zu dieser Uhrzeit startet das Gerät im Überschuss. Danach startet es nicht mehr.", + "automations.templates.shift_start.steps.latest.short": "Uhrzeit", + "automations.templates.shift_start.steps.latest.title": "Spätestens um", + "automations.templates.shift_start.steps.on_w.help": "Ab dieser Einspeisung startet das Gerät. Der Wert kommt aus dem Lernwert, wenn einer vorliegt.", + "automations.templates.shift_start.steps.on_w.options.1000.title": "1000 W", + "automations.templates.shift_start.steps.on_w.options.1500.title": "1500 W", + "automations.templates.shift_start.steps.on_w.options.2500.title": "2500 W", + "automations.templates.shift_start.steps.on_w.short": "Start", + "automations.templates.shift_start.steps.on_w.title": "Startleistung", + "automations.templates.shift_start.steps.on_w.unit": "W", + "automations.templates.shift_start.title": "Verbrauch in den Überschuss verschieben", "automations.templates.surplus_switch.blurb": "Schaltet ein Gerät ein, sobald genug Strom ins Netz geht. Aus geht es nach einer festen Laufzeit, bei Sonnenuntergang oder bei Netzbezug.", "automations.templates.surplus_switch.keywords": "schalten schalter überschuss solar relais heizstab einspeisung", "automations.templates.surplus_switch.steps.device.help": "Das schaltbare Gerät, das bei Überschuss eingeschaltet wird.", @@ -1301,6 +1379,13 @@ "automations.templates.surplus_switch.steps.runtime.short": "Laufzeit", "automations.templates.surplus_switch.steps.runtime.title": "Laufzeit", "automations.templates.surplus_switch.steps.runtime.unit": "Minuten", + "automations.templates.surplus_switch.steps.source.help": "Einspeisung startet nur bei Einspeisung. PV-Reserve nutzt auch die gedrosselte Leistung des Wechselrichters.", + "automations.templates.surplus_switch.steps.source.options.export.text": "Das Gerät startet, sobald Strom ins Netz geht.", + "automations.templates.surplus_switch.steps.source.options.export.title": "Einspeisung", + "automations.templates.surplus_switch.steps.source.options.reserve.text": "Das Gerät startet auch dann, wenn der Wechselrichter wegen Nulleinspeisung drosselt.", + "automations.templates.surplus_switch.steps.source.options.reserve.title": "PV-Reserve", + "automations.templates.surplus_switch.steps.source.short": "Quelle", + "automations.templates.surplus_switch.steps.source.title": "Quelle", "automations.templates.surplus_switch.title": "Gerät bei Überschuss schalten", "automations.templates.surplus_wallbox.blurb": "Die Wallbox lädt mit dem Strom, der sonst ins Netz ginge. Die Ladung endet bei Netzbezug, bei Sonnenuntergang oder wenn der Hausakku zu leer wird.", "automations.templates.surplus_wallbox.keywords": "wallbox laden auto überschuss solar ladeleistung", @@ -1327,6 +1412,13 @@ "automations.templates.surplus_wallbox.steps.soc.short": "Ladestand", "automations.templates.surplus_wallbox.steps.soc.title": "Ladestand", "automations.templates.surplus_wallbox.steps.soc.unit": "%", + "automations.templates.surplus_wallbox.steps.source.help": "Einspeisung startet nur bei Einspeisung. PV-Reserve nutzt auch die gedrosselte Leistung des Wechselrichters.", + "automations.templates.surplus_wallbox.steps.source.options.export.text": "Die Wallbox startet, sobald Strom ins Netz geht.", + "automations.templates.surplus_wallbox.steps.source.options.export.title": "Einspeisung", + "automations.templates.surplus_wallbox.steps.source.options.reserve.text": "Die Wallbox startet auch dann, wenn der Wechselrichter wegen Nulleinspeisung drosselt.", + "automations.templates.surplus_wallbox.steps.source.options.reserve.title": "PV-Reserve", + "automations.templates.surplus_wallbox.steps.source.short": "Quelle", + "automations.templates.surplus_wallbox.steps.source.title": "Quelle", "automations.templates.surplus_wallbox.steps.start.help": "Ab dieser Einspeisung startet die Ladung. Die Vorschau zeigt, wann es am Vortag so weit war.", "automations.templates.surplus_wallbox.steps.start.options.1400.title": "1400 W", "automations.templates.surplus_wallbox.steps.start.options.2000.title": "2000 W", @@ -4438,7 +4530,7 @@ "settings.learning.auto.check_body": "läuft immer. Ohne die Zuverlässigkeitsprüfung braucht sie nur den Auslöseverlauf und schreibt nichts Neues.", "settings.learning.auto.check_title": "Regelprüfung", "settings.learning.auto.energy": "Energie", - "settings.learning.auto.energy_help": "Heizzeit nach Außentemperatur, Gerätezyklen, PV-Reserve und Verschattung. Lernt, unter welcher Temperatur geheizt wird und wie viel Leistung die Geräte brauchen.", + "settings.learning.auto.energy_help": "Heizzeit nach Außentemperatur, Gerätezyklen, PV-Reserve und Verschattung. Lernt, unter welcher Temperatur geheizt wird und wie viel Leistung die Geräte brauchen. Schlägt Überschussfenster, Schwellen, Lastverschiebung, Geräte nach vollem Akku und Reglerwerte vor, jeweils geprüft am Nachspielen der letzten Tage.", "settings.learning.auto.excluded": "Geräte ausnehmen", "settings.learning.auto.fine": "Feineinstellung", "settings.learning.auto.habits": "Gewohnheiten", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 77225b18..21fa9a7d 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -151,6 +151,10 @@ "automations.assistant.summary.follow.then_on": "{name} is switched on", "automations.assistant.summary.follow.when_off": "When {name} is switched off", "automations.assistant.summary.follow.when_on": "When {name} is switched on", + "automations.assistant.summary.full.end": "The device switches off afterwards", + "automations.assistant.summary.full.run": "The device runs at least {min} seconds", + "automations.assistant.summary.full.until": "Ends on grid import above {value} W for {minutes} minutes", + "automations.assistant.summary.full.when": "When the battery is above {soc} % and more than {value} W is fed in", "automations.assistant.summary.full_monthly.end": "Afterwards the charging power returns to the previous value", "automations.assistant.summary.full_monthly.grid": "Also with power from the grid", "automations.assistant.summary.full_monthly.start": "Charging power goes to {value} {unit}", @@ -207,6 +211,11 @@ "automations.assistant.summary.reset": "At the end the limit returns to {value} W", "automations.assistant.summary.restart.then": "The switch {name} turns off and back on after {minutes} minutes", "automations.assistant.summary.runtime.when": "When the switch has been on for {minutes} minutes", + "automations.assistant.summary.shift.end": "The device switches off by itself after the cycle", + "automations.assistant.summary.shift.limit": "Without surplus in the window the device does not start", + "automations.assistant.summary.shift.run": "The device starts on surplus until {time}", + "automations.assistant.summary.shift.surplus": "And the rest of today's surplus covers one cycle", + "automations.assistant.summary.shift.when": "When feed-in is above {value} W for at least {minutes} minutes", "automations.assistant.summary.short": "Summary", "automations.assistant.summary.silent.again": "The notice comes back no sooner than {hours} h later", "automations.assistant.summary.silent.when": "When the inverter reports no new value for {minutes} minutes", @@ -219,6 +228,7 @@ "automations.assistant.summary.switch.until_runtime": "After {minutes} minutes of running", "automations.assistant.summary.switch.until_sunset": "At sunset", "automations.assistant.summary.switch.when": "When feed-in is at least {value} W for {minutes} minutes", + "automations.assistant.summary.switch.when_reserve": "When the PV reserve is above {value} W for at least {minutes} minutes", "automations.assistant.summary.tariff.block": ", no discharging", "automations.assistant.summary.tariff.end": "Charging power back to automatic", "automations.assistant.summary.tariff.end_block": ", discharging allowed again", @@ -237,6 +247,7 @@ "automations.assistant.summary.wallbox.until_min": "At sunset", "automations.assistant.summary.wallbox.until_sun": "When grid import stays above {value} W for at least {minutes} minutes", "automations.assistant.summary.wallbox.when": "When feed-in stays above {start} W for at least {minutes} minutes", + "automations.assistant.summary.wallbox.when_reserve": "When the PV reserve is above {start} W for at least {minutes} minutes", "automations.assistant.surplus.aria": "Yesterday's surplus with the start threshold", "automations.assistant.surplus.now": "Now {power} W surplus, so it {result}.", "automations.assistant.surplus.now_hold": "would not start now", @@ -369,6 +380,7 @@ "automations.condition_type.entity.label": "Device value", "automations.condition_type.entity.short": "Temperature, state", "automations.condition_type.learned_state.short": "House", + "automations.condition_type.learned_value.short": "Learned value", "automations.condition_type.sun.hint": "Applies between sunrise and sunset or the other way round, each with an offset in minutes. Needs the location in the settings.", "automations.condition_type.sun.label": "Sun time", "automations.condition_type.sun.short": "Sunrise and sunset", @@ -536,11 +548,15 @@ "automations.learn.fact.cause.feedback": "The load itself flips the condition", "automations.learn.fact.cause.offline_window": "The device was offline", "automations.learn.fact.cause.scattered": "The commands were spread over the day", + "automations.learn.fact.dead_steps": "Dead time in steps", "automations.learn.fact.direction_share": "Share of this direction", "automations.learn.fact.feature": "Feature", + "automations.learn.fact.feature.signal": "Condition signal in W", "automations.learn.fact.feature.sun_elevation": "Sun elevation in degrees", "automations.learn.fact.feature.to_sunset": "Minutes to sunset", + "automations.learn.fact.flips_h": "Direction changes per hour", "automations.learn.fact.hit_rate": "Hit rate", + "automations.learn.fact.k": "Slope K", "automations.learn.fact.knee": "Outdoor temperature knee in °C", "automations.learn.fact.limit_s": "Limit", "automations.learn.fact.min_runtime": "Minimum runtime", @@ -551,17 +567,20 @@ "automations.learn.fact.peak_w": "Start peak", "automations.learn.fact.per_hour_max": "At most per hour", "automations.learn.fact.season_months": "Months in the season", + "automations.learn.fact.settle_s": "Settling time in seconds", "automations.learn.fact.spread_min": "Spread", "automations.learn.fact.window_s": "Time window", "automations.learn.fix.add_condition": "Add a condition", "automations.learn.fix.disable_duplicate": "Turn this rule off", "automations.learn.fix.feedback_thresholds": "Widen the thresholds", + "automations.learn.fix.learned_threshold": "Couple the threshold to the operating power", "automations.learn.fix.min_runtime": "Set a minimum runtime", "automations.learn.fix.move_before": "Move before the outage", "automations.learn.fix.open_rule": "Open rule", "automations.learn.fix.repeat": "Combine as a repeat", - "automations.learn.fix.set_cooldown": "Cooldown 10 minutes", + "automations.learn.fix.set_cooldown": "Cooldown {value} s", "automations.learn.fix.set_hysteresis": "Hysteresis {value} W", + "automations.learn.fix.set_regulator": "Tune the regulator", "automations.learn.fix.set_threshold": "Threshold to {value}", "automations.learn.fix.shift_time": "Shift the time window", "automations.learn.fix.stagger": "Stagger the thresholds", @@ -578,12 +597,27 @@ "automations.learn.legend.label": "What do Actual and Target mean?", "automations.learn.legend.scale": "Actual: the value we saw. Target: the suggested value.", "automations.learn.mark_label": "Show the finding for this rule", + "automations.learn.param.deadband_w": "Deadband", + "automations.learn.param.gain": "Gain", + "automations.learn.param.max_change_w": "Change limit", + "automations.learn.regulator.quality.line": "Gain {gain}, target near {gain_soll}", + "automations.learn.regulator.quality.text": "The regulator of „{scenario}“ does not fit the plant. Gain {gain}, target near {gain_soll}. The suggestions set the values that match the measured dead time and slope.", + "automations.learn.regulator.quality.title": "Regulator of „{scenario}“ is not tuned", "automations.learn.runtime.forgotten.line": "{forgotten} of {runs} runs stayed on, usually {usual_min} min", "automations.learn.runtime.forgotten.text": "In {forgotten} of {runs} runs the device stayed on although {usual_min} minutes is usual. That used about {extra_kwh} kWh extra. Switching off after the usual run time prevents it.", "automations.learn.runtime.forgotten.title": "Keeps running too long", "automations.learn.season": "Applies from week {from} to week {to}", "automations.learn.season.all": "Applies all year", "automations.learn.season.heating": "Heating below {below} °C", + "automations.learn.shift.load.line": "{kwh} kWh per week can move from the grid", + "automations.learn.shift.load.text": "{device} ran {runs} times from the grid although the same day had enough surplus for the whole run. A start in the surplus until {latest} saves that grid energy.", + "automations.learn.shift.load.title": "Move {device} into the surplus", + "automations.learn.surplus.reserve.line": "PV reserve from {from} to {to}, threshold {on_w} W", + "automations.learn.surplus.reserve.text": "The feed-in is throttled, the system could deliver more power between {from} and {to}. A rule on the PV reserve with {on_w} W switches {device} on in this window, once the reserve is there.", + "automations.learn.surplus.reserve.title": "Switch {device} on from the PV reserve", + "automations.learn.surplus.window.line": "Surplus from {from} to {to}, threshold {on_w} W", + "automations.learn.surplus.window.text": "Between {from} and {to} the surplus covers {device} on most of the last {days} days. A rule with a threshold of {on_w} W switches the device on in this window.", + "automations.learn.surplus.window.title": "Switch {device} on in the usual surplus window", "automations.learn.switch_time.off.line": "Switched off by hand on {hits} of {days} days", "automations.learn.switch_time.off.text": "You switch {device} off yourself on {hits} of {days} days at around {time}. A rule with that time does it for you.", "automations.learn.switch_time.off.title": "Switch {device} off at {time}", @@ -605,6 +639,12 @@ "automations.learn.temperature.limit.line": "In warm weeks {device} uses {kwh_warm} kWh per week. With the condition the rule switches only in the cold.", "automations.learn.temperature.limit.text": "\"{rule}\" switches {device} on all year. The dashboard learned that the device only heats below about {knee} °C. Above that it needs just {kwh_warm} kWh per week. With the condition \"below {knee} °C\" the rule runs only in the heating season.", "automations.learn.temperature.limit.title": "{rule} only below {knee} °C outside", + "automations.learn.threshold.too_high.line": "Threshold {threshold} W, target {soll} W", + "automations.learn.threshold.too_high.text": "“{rule}” only switches on at {threshold} W. Near {soll} W about {kwh} kWh per week of surplus would be used that now goes unused into the grid. The suggestion is a fixed threshold or a learned value.", + "automations.learn.threshold.too_high.title": "Threshold of “{rule}” is too high", + "automations.learn.threshold.too_low.line": "Threshold {threshold} W, target {soll} W", + "automations.learn.threshold.too_low.text": "“{rule}” switches on at {threshold} W and then draws power from the grid. Near {soll} W about {kwh} kWh of grid import per week would be avoided.", + "automations.learn.threshold.too_low.title": "Threshold of “{rule}” is too low", "automations.learn.undo.ignored": "Finding hidden", "automations.learn.unit.kwh_week": "kWh/week", "automations.learn.value.minutes": "{value} min", @@ -664,6 +704,9 @@ "automations.learned.state.now": "Now {state}. Learned from {n} days, updated {age} ago.", "automations.learned.state.quiet": "House is quiet", "automations.learned.state.stale": "The last value is older than {age}. This applies: {state}.", + "automations.learned.value.condition": "Learned value", + "automations.learned.value.help": "A learned number, such as the PV reserve, compared with a fixed threshold or another reference. Without a fresh value the fallback applies.", + "automations.learned.value.max_age": "Value counts for at most", "automations.learned.year.line": "The value was {high} in {high_month} and {low} in {low_month}", "automations.limit.rules": "At most {max} rules", "automations.limit.scenarios": "At most {max} scenarios", @@ -874,6 +917,8 @@ "automations.summary.chain_value": "{field} {comparison} {value} {unit}", "automations.summary.entity_value": "{comparison} {expected}", "automations.summary.entity_value_unit": "{comparison} {expected} {unit}", + "automations.summary.learned_value": "{name} {comparison} {threshold} {unit}", + "automations.summary.learned_value_hysteresis": "{name} {comparison} {threshold} {unit}, hysteresis {hysteresis}", "automations.summary.topic_value": "{comparison} {expected}", "automations.sun_event.sunrise": "Sunrise", "automations.sun_event.sunset": "Sunset", @@ -881,6 +926,23 @@ "automations.tab.group_aria": "View", "automations.tab.rules": "Single rules", "automations.tab.scenarios": "Scenarios", + "automations.templates.after_battery_full.blurb": "Switches a device on once the battery is full and power is fed in. It switches off on grid import.", + "automations.templates.after_battery_full.keywords": "battery full feed-in surplus switch loads solar", + "automations.templates.after_battery_full.steps.device.help": "The device that should run after the battery is full.", + "automations.templates.after_battery_full.steps.device.short": "Device", + "automations.templates.after_battery_full.steps.device.title": "Switch", + "automations.templates.after_battery_full.steps.min_run_s.help": "How long the device runs at least before grid import may switch it off.", + "automations.templates.after_battery_full.steps.min_run_s.options.long.text": "The device runs at least 10 minutes.", + "automations.templates.after_battery_full.steps.min_run_s.options.long.title": "10 minutes", + "automations.templates.after_battery_full.steps.min_run_s.options.none.text": "The device may switch off at once.", + "automations.templates.after_battery_full.steps.min_run_s.options.none.title": "None", + "automations.templates.after_battery_full.steps.min_run_s.options.short.text": "The device runs at least 3 minutes.", + "automations.templates.after_battery_full.steps.min_run_s.options.short.title": "3 minutes", + "automations.templates.after_battery_full.steps.min_run_s.options.standard.text": "The device runs at least 5 minutes.", + "automations.templates.after_battery_full.steps.min_run_s.options.standard.title": "5 minutes", + "automations.templates.after_battery_full.steps.min_run_s.short": "Run time", + "automations.templates.after_battery_full.steps.min_run_s.title": "Minimum run time", + "automations.templates.after_battery_full.title": "Device after full battery", "automations.templates.battery_full_monthly.blurb": "Charges the battery to full on a fixed day of the month, with surplus or also from the grid.", "automations.templates.battery_full_monthly.keywords": "battery full month calibrate charge surplus grid", "automations.templates.battery_full_monthly.steps.battery.help": "The battery whose charging power is set for this day.", @@ -1269,6 +1331,22 @@ "automations.templates.runtime_off.steps.source.short": "Source", "automations.templates.runtime_off.steps.source.title": "Fixed or learned runtime?", "automations.templates.runtime_off.title": "Limit the runtime", + "automations.templates.shift_start.blurb": "Starts a device once the rest of today's surplus covers one cycle. After the chosen latest time it no longer starts.", + "automations.templates.shift_start.keywords": "shift surplus cycle dishwasher washing machine solar switch", + "automations.templates.shift_start.steps.device.help": "The device that should run on surplus.", + "automations.templates.shift_start.steps.device.short": "Device", + "automations.templates.shift_start.steps.device.title": "Switch", + "automations.templates.shift_start.steps.latest.help": "The device starts on surplus until this time. After it, it no longer starts.", + "automations.templates.shift_start.steps.latest.short": "Time", + "automations.templates.shift_start.steps.latest.title": "Latest at", + "automations.templates.shift_start.steps.on_w.help": "The device starts from this feed-in. The value comes from the learned value when there is one.", + "automations.templates.shift_start.steps.on_w.options.1000.title": "1000 W", + "automations.templates.shift_start.steps.on_w.options.1500.title": "1500 W", + "automations.templates.shift_start.steps.on_w.options.2500.title": "2500 W", + "automations.templates.shift_start.steps.on_w.short": "Start", + "automations.templates.shift_start.steps.on_w.title": "Start power", + "automations.templates.shift_start.steps.on_w.unit": "W", + "automations.templates.shift_start.title": "Move load into the surplus", "automations.templates.surplus_switch.blurb": "Turns a device on once enough power goes to the grid. It turns off after a fixed runtime, at sunset or when power is drawn from the grid.", "automations.templates.surplus_switch.keywords": "switch relay surplus solar heater feed-in", "automations.templates.surplus_switch.steps.device.help": "The switchable device that turns on with surplus.", @@ -1301,6 +1379,13 @@ "automations.templates.surplus_switch.steps.runtime.short": "Runtime", "automations.templates.surplus_switch.steps.runtime.title": "Runtime", "automations.templates.surplus_switch.steps.runtime.unit": "minutes", + "automations.templates.surplus_switch.steps.source.help": "Feed-in starts only on feed-in. PV reserve also uses the power the inverter curtails.", + "automations.templates.surplus_switch.steps.source.options.export.text": "The device starts as soon as power flows into the grid.", + "automations.templates.surplus_switch.steps.source.options.export.title": "Feed-in", + "automations.templates.surplus_switch.steps.source.options.reserve.text": "The device also starts when the inverter curtails because of zero feed-in.", + "automations.templates.surplus_switch.steps.source.options.reserve.title": "PV reserve", + "automations.templates.surplus_switch.steps.source.short": "Source", + "automations.templates.surplus_switch.steps.source.title": "Source", "automations.templates.surplus_switch.title": "Switch a device on surplus", "automations.templates.surplus_wallbox.blurb": "The wallbox charges with power that would otherwise go to the grid. Charging ends on grid import, at sunset or when the home battery runs low.", "automations.templates.surplus_wallbox.keywords": "wallbox charging car surplus solar charge power", @@ -1327,6 +1412,13 @@ "automations.templates.surplus_wallbox.steps.soc.short": "Charge level", "automations.templates.surplus_wallbox.steps.soc.title": "Charge level", "automations.templates.surplus_wallbox.steps.soc.unit": "%", + "automations.templates.surplus_wallbox.steps.source.help": "Feed-in starts only on feed-in. PV reserve also uses the power the inverter curtails.", + "automations.templates.surplus_wallbox.steps.source.options.export.text": "The wallbox starts as soon as power flows into the grid.", + "automations.templates.surplus_wallbox.steps.source.options.export.title": "Feed-in", + "automations.templates.surplus_wallbox.steps.source.options.reserve.text": "The wallbox also starts when the inverter curtails because of zero feed-in.", + "automations.templates.surplus_wallbox.steps.source.options.reserve.title": "PV reserve", + "automations.templates.surplus_wallbox.steps.source.short": "Source", + "automations.templates.surplus_wallbox.steps.source.title": "Source", "automations.templates.surplus_wallbox.steps.start.help": "Charging starts at this feed-in level. The preview shows when it was reached yesterday.", "automations.templates.surplus_wallbox.steps.start.options.1400.title": "1400 W", "automations.templates.surplus_wallbox.steps.start.options.2000.title": "2000 W", @@ -4438,7 +4530,7 @@ "settings.learning.auto.check_body": "always runs. Without the reliability checks it only needs the trigger history and writes nothing new.", "settings.learning.auto.check_title": "Rule check", "settings.learning.auto.energy": "Energy", - "settings.learning.auto.energy_help": "Heating season by outdoor temperature, device cycles, PV reserve and shade. Learns below which temperature the heating runs and how much power the devices draw.", + "settings.learning.auto.energy_help": "Heating season by outdoor temperature, device cycles, PV reserve and shade. Learns below which temperature the heating runs and how much power the devices draw. Suggests surplus windows, thresholds, load shifts, devices after a full battery and regulator values, each checked by a replay of the last days.", "settings.learning.auto.excluded": "Exclude devices", "settings.learning.auto.fine": "Fine-tuning", "settings.learning.auto.habits": "Habits", diff --git a/dashboard/internal/webui/static/css/automations.css b/dashboard/internal/webui/static/css/automations.css index 26bd3836..f5d2e677 100644 --- a/dashboard/internal/webui/static/css/automations.css +++ b/dashboard/internal/webui/static/css/automations.css @@ -973,9 +973,11 @@ label.settings-toggle.auto-assist-check .settings-toggle-track { flex: none; wid /* Ist-Soll-Grafik: Spuren als SVG, Beschriftung als HTML */ .auto-learn-evidence { margin: .7rem 0 .15rem; } -.auto-learn-is { display: grid; gap: .3rem; transform-origin: left center; animation: auto-learn-chart-in 180ms var(--ease-out) both; } +.auto-learn-is { display: grid; gap: .3rem; transform-origin: left center; } .auto-learn-lane { display: grid; grid-template-columns: 2.2rem minmax(0, 1fr); gap: .5rem; align-items: center; } .auto-learn-lane-label { font-size: .72rem; font-weight: 600; color: var(--text-muted); } +.auto-learn-scale-bar { margin: .6rem 0 .25rem; font-size: .78rem; font-weight: 600; color: var(--text); } +.auto-learn-scale-bar:first-child { margin-top: 0; } .auto-learn-lane.is-soll .auto-learn-lane-label { color: var(--accent-line); } .auto-learn-lane-svg { display: block; width: 100%; height: 16px; background: var(--sunken); border-radius: 5px; } .auto-learn-lane-svg .auto-learn-ist { fill: var(--flow-rest); } @@ -1020,13 +1022,20 @@ label.settings-toggle.auto-assist-check .settings-toggle-track { flex: none; wid .auto-learn-target { justify-self: start; margin-left: calc(2.2rem + .5rem); padding: .15rem .6rem; border-radius: 8px; font-size: .8rem; font-weight: 600; color: var(--text-strong); background: var(--accent-bg); border: 1px solid var(--accent-line); } .auto-learn-target.is-missing { color: var(--bad); background: transparent; border: 1px dashed var(--bad-line); } -/* Soll erscheint nach dem Ist: einmal beim Oeffnen, von links */ -.auto-learn-lane.is-soll .auto-learn-lane-svg { animation: auto-learn-trace 280ms var(--ease-out) 120ms both; } -.auto-learn-plot-svg.is-soll { animation: auto-learn-trace 280ms var(--ease-out) 120ms both; } -@keyframes auto-learn-trace { from { clip-path: inset(0 100% 0 0 round 5px); } to { clip-path: inset(0 0 0 0 round 5px); } } -/* Neue Grafik nach dem Umschalten: blendet ein, ohne Bewegung bei reduzierter Bewegung */ -@keyframes auto-learn-chart-in { from { opacity: 0; transform: scale(.985); } to { opacity: 1; transform: none; } } -@keyframes auto-learn-chart-fade { from { opacity: 0; } to { opacity: 1; } } +/* Einlauf beim Oeffnen eines Belegs. Die Klasse is-enter setzt AutomationEvidence.mount + nur beim ersten Einfuegen, Aktualisierungen laufen deshalb nicht erneut ab. Ist vor Soll, + Soll folgt mit 60 ms Versatz. Nur transform, opacity und clip-path, ohne Schleife. */ +.auto-learn-evidence.is-enter .auto-learn-is { animation: auto-learn-chart-in 200ms cubic-bezier(0.23, 1, 0.32, 1) both; } +.auto-learn-evidence.is-enter .auto-learn-shape-scale .auto-learn-lane-svg .auto-learn-ist { transform-box: fill-box; transform-origin: left center; animation: auto-learn-bar-in 220ms cubic-bezier(0.23, 1, 0.32, 1) both; animation-delay: calc(var(--i, 0) * 40ms); } +.auto-learn-evidence.is-enter .auto-learn-shape-scale .auto-learn-lane-svg .auto-learn-soll { transform-box: fill-box; transform-origin: left center; animation: auto-learn-bar-in 220ms cubic-bezier(0.23, 1, 0.32, 1) both; animation-delay: calc(var(--i, 0) * 40ms + 60ms); } +.auto-learn-evidence.is-enter .auto-learn-shape-events .auto-learn-lane.is-soll .auto-learn-lane-svg { animation: auto-learn-trace 240ms cubic-bezier(0.23, 1, 0.32, 1) 60ms both; } +.auto-learn-evidence.is-enter .auto-learn-plot-svg.is-soll { animation: auto-learn-trace 240ms cubic-bezier(0.23, 1, 0.32, 1) 60ms both; } +/* Die Einlauf-Keyframes setzen nur den Startwert. Der Endwert ist der Ruhewert des Elements + (der Soll-Balken hat eigene Deckkraft .35), sonst blinkt er beim Ende der Animation auf. */ +@keyframes auto-learn-bar-in { from { opacity: 0; transform: scaleX(0.02); } } +@keyframes auto-learn-trace { from { opacity: 0; clip-path: inset(0 100% 0 0 round 5px); } to { clip-path: inset(0 0 0 0 round 5px); } } +@keyframes auto-learn-chart-in { from { opacity: 0; transform: scale(.985); } } +@keyframes auto-learn-chart-fade { from { opacity: 0; } } /* Ausschnitt oder ganzer Tag der Tagesgrafik */ .auto-learn-zoom { box-sizing: border-box; display: flex; justify-content: flex-end; margin: .1rem 0 0; } .auto-learn-zoom-btn { box-sizing: border-box; padding: .2rem .5rem; border: 0; border-radius: 6px; background: transparent; color: var(--text-muted); font-size: .74rem; line-height: 1.2; cursor: pointer; @@ -1040,9 +1049,12 @@ label.settings-toggle.auto-assist-check .settings-toggle-track { flex: none; wid .auto-learn-mark { transition: none; } .auto-learn-mark:active { transform: none; } .auto-learn-pop { animation-name: auto-learn-fade; } - .auto-learn-lane.is-soll .auto-learn-lane-svg { animation: none; } - .auto-learn-plot-svg.is-soll { animation: none; } - .auto-learn-is { animation-name: auto-learn-chart-fade; } + /* Reduzierte Bewegung: nur ein kurzes Einblenden per opacity, ohne Verschiebung */ + .auto-learn-evidence.is-enter .auto-learn-is, + .auto-learn-evidence.is-enter .auto-learn-shape-scale .auto-learn-lane-svg .auto-learn-ist, + .auto-learn-evidence.is-enter .auto-learn-shape-scale .auto-learn-lane-svg .auto-learn-soll, + .auto-learn-evidence.is-enter .auto-learn-shape-events .auto-learn-lane.is-soll .auto-learn-lane-svg, + .auto-learn-evidence.is-enter .auto-learn-plot-svg.is-soll { animation: auto-learn-chart-fade 200ms ease-out both; animation-delay: 0ms; } .auto-learn-zoom-btn { transition: none; } .auto-learn-zoom-btn:active { transform: none; } } diff --git a/dashboard/internal/webui/static/js/automation-evidence.js b/dashboard/internal/webui/static/js/automation-evidence.js index e2959320..e729d788 100644 --- a/dashboard/internal/webui/static/js/automation-evidence.js +++ b/dashboard/internal/webui/static/js/automation-evidence.js @@ -278,7 +278,10 @@ const majors = [from, mid, to]; const grid = gridLines(majors.map((v) => pos(v, from, to))); const ist = grid + histogram(inside, from, (to - from) / EVENT_BINS, EVENT_BINS, xOf); - const soll = grid + spans(ev.soll_spans, from, to, 'auto-learn-soll'); + // Die nachgespielten Auslösungen (soll) zeichnen wie die Ist-Auslösungen, dazu die Spannen. + const sollInside = finiteList(ev.soll).filter((u) => u >= from && u <= to); + const soll = grid + spans(ev.soll_spans, from, to, 'auto-learn-soll') + + histogram(sollInside, from, (to - from) / EVENT_BINS, EVENT_BINS, xOf); const step = to - from <= 10800 ? 15 : 60; const minors = []; if (to > from) { @@ -300,7 +303,35 @@ return UNIT_KEYS[ev.unit] ? t(UNIT_KEYS[ev.unit]) : ev.unit; } + // Ein Balkenpaar je Parameter, wenn die Evidenz Scales liefert. + // i18n-keys: automations.learn.param.gain, automations.learn.param.deadband_w, automations.learn.param.max_change_w + const PARAM_KEYS = { + gain: 'automations.learn.param.gain', + deadband_w: 'automations.learn.param.deadband_w', + max_change_w: 'automations.learn.param.max_change_w', + }; + function scaleBarsShape(ev, t) { + return ev.scales.map((bar, index) => { + const top = Math.max(bar.ist || 0, bar.soll || 0); + const max = top > 0 ? top * 1.2 : 1; + const toX = (v) => pct(v, max); + const unit = bar.unit ? ' ' + bar.unit : ''; + const majors = [0, max / 2, max]; + const grid = gridLines(majors.map(toX)); + // Der Einlauf staffelt die Balken je 40 ms, Soll folgt dem Ist mit 60 ms (CSS, --i). + const istBar = ''; // i18n-ignore + const sollBar = ''; // i18n-ignore + const ticks = majors.map((v) => ({ x: toX(v), major: true })); + const labels = majors.map((v) => ({ x: toX(v), text: (Math.round(v * 100) / 100) + unit })); + return '
' + esc(t(PARAM_KEYS[bar.name] || bar.name)) + '
' + + lane(t('automations.learn.lane.ist'), laneSvg(grid + istBar)) // i18n-ignore + + lane(t('automations.learn.lane.soll'), laneSvg(grid + sollBar), true) + + axisHtml(ticks, labels); + }).join(''); + } + function scaleShape(ev, t) { + if (Array.isArray(ev.scales) && ev.scales.length > 0) return scaleBarsShape(ev, t); const max = scaleMaxOf(ev); const toX = (v) => pct(v, max); const unit = ev.unit ? ' ' + unitOf(ev, t) : ''; @@ -424,5 +455,23 @@ return body ? '
' + body + '
' : ''; } - window.AutomationEvidence = { render, windowOf, zoomable }; + // mount(el, evidence, t) setzt den Beleg in den Behaelter el. Das erste Einfuegen + // bekommt die Klasse is-enter, der Einlauf laeuft dann einmal ab. Eine Aktualisierung + // (Poll) ersetzt nur den Inhalt, und nur wenn er sich geaendert hat. Nach ENTER_MS + // ist die Klasse wieder weg, damit spaetere Aktualisierungen nicht erneut einlaufen. + const ENTER_MS = 700; + function mount(el, evidence, t) { + if (!el) return; + const html = render(evidence, t, {}); + if (el.__evHtml === html) return; + const first = el.__evHtml === undefined; + el.__evHtml = html; + el.innerHTML = html; + if (first) { + el.classList.add('is-enter'); + setTimeout(() => el.classList.remove('is-enter'), ENTER_MS); + } + } + + window.AutomationEvidence = { render, windowOf, zoomable, mount }; })(); diff --git a/dashboard/internal/webui/static/js/automation-learned.js b/dashboard/internal/webui/static/js/automation-learned.js index 12d45362..ba6010c5 100644 --- a/dashboard/internal/webui/static/js/automation-learned.js +++ b/dashboard/internal/webui/static/js/automation-learned.js @@ -21,7 +21,7 @@ pv_reserve_w: 'automations.learned.key.pv_reserve_w', surplus_left_wh: 'automations.learned.key.surplus_left_wh', }; - const FIELD_KIND = { start: 'time', end: 'time', hold_seconds: 'duration', threshold: 'number', value: 'number' }; + const FIELD_KIND = { start: 'time', end: 'time', hold_seconds: 'duration', threshold: 'number', value: 'number', learned: 'number' }; const LEARNABLE = { balance_threshold: ['threshold', 'hold_seconds'], topic_value: ['value', 'hold_seconds'], @@ -29,6 +29,8 @@ time_window: ['start', 'end', 'hold_seconds'], sun_window: ['hold_seconds'], learned_state: ['hold_seconds'], + // learned ist der gelernte Zahlwert selbst, threshold darf eine Bezugsangabe sein. + learned_value: ['learned', 'threshold', 'hold_seconds'], }; const norm = (m) => ((m % DAY) + DAY) % DAY; @@ -111,6 +113,14 @@ return fields.includes(field) ? FIELD_KIND[field] : null; } + // Einheit aus dem Namensende eines Lernwerts: _w ist W, _wh ist Wh, sonst keine. + function unitOfKey(key) { + const name = String(key || ''); + if (name.endsWith('_wh')) return 'Wh'; + if (name.endsWith('_w')) return 'W'; + return ''; + } + // Vorbelegung der Bezugsangabe aus dem festen Wert. Ohne gueltigen Wert keine Vorbelegung. function prefill(kind, value) { if (kind === 'time') { @@ -326,5 +336,5 @@ return coords.length >= YEAR_MIN_WEEKS ? coords.join(' ') : null; } - window.AutomationLearned = { isRef, kindOf, resolve, prefill, choices, keyLabel, validate, origin, valueSuffix, scale, yearLine, yearPlot }; + window.AutomationLearned = { isRef, kindOf, resolve, prefill, choices, keyLabel, unitOfKey, validate, origin, valueSuffix, scale, yearLine, yearPlot }; })(); diff --git a/dashboard/internal/webui/static/js/automation-suggestions.js b/dashboard/internal/webui/static/js/automation-suggestions.js index 650cd4a7..c16206fa 100644 --- a/dashboard/internal/webui/static/js/automation-suggestions.js +++ b/dashboard/internal/webui/static/js/automation-suggestions.js @@ -91,7 +91,9 @@ return t(CAT + 'legend.' + shape, {}); } - const api = { arrange, title, line, text, legend, resolveSummary }; + // Zahlen der Befunde als Zeilen aus Bezeichnung und Wert, wie im Vorschlagsband. + const factRows = (facts, t) => (facts || []).map((f) => ({ label: t(CAT + 'fact.' + f.code, {}), value: valueOf(f, t) })); + const api = { arrange, title, line, text, legend, resolveSummary, factRows }; window.AutomationSuggestions = api; // Vorschlagsband oberhalb der Regeln. Laedt einmal beim Oeffnen der Seite. Die diff --git a/dashboard/internal/webui/static/js/automation-templates.js b/dashboard/internal/webui/static/js/automation-templates.js index ee67d724..6f113394 100644 --- a/dashboard/internal/webui/static/js/automation-templates.js +++ b/dashboard/internal/webui/static/js/automation-templates.js @@ -76,6 +76,20 @@ return typeof power === 'number' && Number.isFinite(power) ? Math.ceil((power + 100) / 100) * 100 : null; }; + // Einschaltbedingung bei Ueberschuss: Einspeisung oder, bei Quelle Reserve, die PV-Reserve. + const startCondition = (source, threshold, holdSeconds) => (source === 'reserve' + ? { + type: 'learned_value', learned: 'site/pv_reserve_w', comparison: 'above', threshold, fallback: 0, + hysteresis: 100, max_age_s: 1800, hold_seconds: holdSeconds, + } + : B('grid_export', 'above', threshold, holdSeconds)); + + // Quelle der Ueberschuss-Vorlagen: Einspeisung oder PV-Reserve. + const sourceStep = { + id: 'source', type: 'tiles', default: 'export', + options: [{ id: 'export' }, { id: 'reserve' }], + }; + // ---------------------------------------------------------------- Ueberschuss in die Wallbox const surplusWallbox = { @@ -99,6 +113,7 @@ options: [{ id: 1400 }, { id: 2000 }, { id: 3000 }], scale: { min: 0, max: 6000, step: 100, ticks: 1000, grow: true, fill: 'above', unit: 'W' }, }, + sourceStep, { id: 'extras', type: 'multi', options: [ @@ -117,7 +132,7 @@ const plug = entry.plugEntity; const switchEntity = entry.switchEntity; - const when = [B('grid_export', 'above', answers.start, 180)]; + const when = [startCondition(answers.source, answers.start, 180)]; if (answers.extras.connected && plug) { when.push({ type: 'entity_value', topic: plug.state_topic, entity_id: plug.unique_id, @@ -163,7 +178,9 @@ const rows = [ { label: phase('when'), - text: t('automations.assistant.summary.wallbox.when', { minutes: 3, start: num(answers.start) }), + text: answers.source === 'reserve' + ? t('automations.assistant.summary.wallbox.when_reserve', { minutes: 3, start: num(answers.start) }) + : t('automations.assistant.summary.wallbox.when', { minutes: 3, start: num(answers.start) }), step: 'start', }, ]; @@ -364,6 +381,7 @@ options: [{ id: 1000 }, { id: 1500 }, { id: 2500 }], scale: { min: 0, max: 6000, step: 100, ticks: 1000, grow: true, fill: 'above', unit: 'W' }, }, + sourceStep, { id: 'off', type: 'tiles', default: 'import', options: [ @@ -389,7 +407,7 @@ const entity = requireEntity(entry); const repeat = !!answers.extras.repeat; - const when = [B('grid_export', 'above', answers.on, 120)]; + const when = [startCondition(answers.source, answers.on, 120)]; if (answers.extras.weekdays) { when.push({ type: 'time_window', start: '00:00', end: '00:00', weekdays: weekdaysOf(answers.extras.weekdays_value), @@ -423,7 +441,9 @@ summary(answers) { const rows = [{ label: phase('when'), - text: t('automations.assistant.summary.switch.when', { minutes: 2, value: num(answers.on) }), + text: answers.source === 'reserve' + ? t('automations.assistant.summary.switch.when_reserve', { minutes: 2, value: num(answers.on) }) + : t('automations.assistant.summary.switch.when', { minutes: 2, value: num(answers.on) }), step: 'on', }]; if (answers.extras.weekdays) { @@ -2075,8 +2095,118 @@ }, }; + // ---------------------------------------------------------------- Start in den Ueberschuss verschieben + + // Ende des Zeitfensters: die Regel startet ab Beginn bis zur spaetesten Startzeit. + const shiftStart = { + id: 'shift_start', + category: 'time', + icon: 'ico-clock', + requires: { devices: 'switch' }, + steps: [ + { id: 'device', type: 'device', filter: 'switch' }, + { + id: 'on_w', type: 'presets', step: 100, default: (ctx, answers) => learnedStartW(ctx.switches, ctx, answers.device) ?? 1500, effect: 'starts', + options: [{ id: 1000 }, { id: 1500 }, { id: 2500 }], + scale: { min: 0, max: 6000, step: 100, ticks: 1000, grow: true, fill: 'above', unit: 'W' }, + }, + { id: 'latest', type: 'time', single: true, default: { from: '18:00', to: '18:05', days: ALL_DAYS } }, + ], + build(answers, ctx) { + const entry = requireEntry(ctx.switches, answers.device); + const entity = requireEntity(entry); + const latest = answers.latest.from; + // Der Zyklusbedarf kommt aus dem Lernwert, ohne Lernwert gilt der Ersatz von 1000 Wh. + const cycle = { learned: `device/${entry.deviceId}/cycle_wh`, min: 100, max: 6000, fallback: 1000 }; + // Ein Szenario: Start nur im Fenster bis zur spaetesten Zeit bei Ueberschuss. Das Ende + // schaltet nichts ab (on_end leer), das Geraet beendet den Zyklus selbst. Ein Netzbezug + // beendet nur das Szenario, und cooldown_s verhindert einen zweiten Start am selben Tag. + const scenario = { + id: uniqueId('shift_start', ctx.usedIds), + name: t('automations.templates.shift_start.title'), + enabled: true, + template: 'shift_start', + when: { + conditions: [ + { type: 'learned_value', learned: 'site/surplus_left_wh', comparison: 'above', threshold: cycle, fallback: 0 }, + B('grid_export', 'above', answers.on_w, 120), + { type: 'time_window', start: '00:00', end: latest, weekdays: [] }, + ], + }, + until: { conditions: [B('grid_import', 'above', 300, 600)] }, + max_duration_s: 14400, + cooldown_s: 86400, + on_start: { actions: [Sw(entity, true)] }, + on_end: { actions: [] }, + while: { mode: 'none' }, + }; + return { kind: 'scenario', entry: scenario }; + }, + summary(answers) { + return [ + { + label: phase('when'), + text: t('automations.assistant.summary.shift.when', { minutes: 2, value: num(answers.on_w) }), + step: 'on_w', + }, + { label: phase('when'), text: t('automations.assistant.summary.shift.surplus'), step: 'device' }, + { label: phase('run'), text: t('automations.assistant.summary.shift.run', { time: answers.latest.from }), step: 'latest' }, + { label: phase('then'), text: t('automations.assistant.summary.shift.limit'), step: 'latest' }, + { label: phase('end'), text: t('automations.assistant.summary.shift.end'), step: 'device' }, + ]; + }, + }; + + // ---------------------------------------------------------------- Gerät nach vollem Akku + + // Mindestlaufzeit in Sekunden je Stufe. Die Tabelle nach Rolle liegt in Go, hier bleibt die Stufe wählbar. + const MIN_RUN_S = { none: 0, short: 180, standard: 300, long: 600 }; + + const afterBatteryFull = { + id: 'after_battery_full', + category: 'switching', + icon: 'ico-switch', + requires: { devices: 'switch', soc: true }, + steps: [ + { id: 'device', type: 'device', filter: 'switch' }, + { + id: 'min_run_s', type: 'tiles', default: 'standard', + options: [{ id: 'none' }, { id: 'short' }, { id: 'standard' }, { id: 'long' }], + }, + ], + build(answers, ctx) { + const entry = requireEntry(ctx.switches, answers.device); + const entity = requireEntity(entry); + const scenario = { + id: uniqueId('after_battery_full', ctx.usedIds), + name: t('automations.templates.after_battery_full.title'), + enabled: true, + template: 'after_battery_full', + when: { conditions: [B('battery_soc', 'above', 96, 0), B('grid_export', 'above', 100, 120)] }, + until: { conditions: [B('grid_import', 'above', 100, 120)] }, + min_run_s: MIN_RUN_S[answers.min_run_s], + on_start: { actions: [Sw(entity, true)] }, + on_end: { actions: [Sw(entity, false)] }, + while: { mode: 'none' }, + }; + return { kind: 'scenario', entry: scenario }; + }, + summary(answers) { + return [ + { label: phase('when'), text: t('automations.assistant.summary.full.when', { soc: 96, value: 100 }), step: 'device' }, + { + label: phase('run'), + text: t('automations.assistant.summary.full.run', { min: num(MIN_RUN_S[answers.min_run_s]) }), + step: 'min_run_s', + }, + { label: phase('until'), text: t('automations.assistant.summary.full.until', { value: num(100), minutes: 2 }), step: 'device' }, + { label: phase('end'), text: t('automations.assistant.summary.full.end'), step: 'device' }, + ]; + }, + }; + window.__automationTemplates = { - TEMPLATES: [zeroFeed, surplusWallbox, surplusSwitch, batteryWarn, timeSwitch, heatPump, tariff, batteryFullMonthly, inverterSilent, wallboxLowTariff, gridCap, gridSignal, pvMissing, heatingRod, chainWatchdog, chainStandby, timePoint, runtimeOff, quietOff, followSwitch, nightOff], + TEMPLATES: [zeroFeed, surplusWallbox, surplusSwitch, batteryWarn, timeSwitch, heatPump, tariff, batteryFullMonthly, inverterSilent, wallboxLowTariff, gridCap, gridSignal, pvMissing, heatingRod, chainWatchdog, chainStandby, timePoint, runtimeOff, quietOff, followSwitch, nightOff, shiftStart, afterBatteryFull], chargeFit, }; })(); diff --git a/dashboard/internal/webui/static/js/automations-view.js b/dashboard/internal/webui/static/js/automations-view.js index 7e07c6dc..b4ac209d 100644 --- a/dashboard/internal/webui/static/js/automations-view.js +++ b/dashboard/internal/webui/static/js/automations-view.js @@ -81,7 +81,7 @@ return event.reason ? [{ kind: 'reason', title: '', text: event.reason }] : []; } - // i18n-keys: automations.condition_type.balance.hint, automations.condition_type.balance.label, automations.condition_type.entity.hint, automations.condition_type.entity.label, automations.condition_type.sun.hint, automations.condition_type.sun.label, automations.condition_type.time.hint, automations.condition_type.time.label, automations.condition_type.learned_state.short, automations.learned.state.condition, automations.learned.state.help + // i18n-keys: automations.condition_type.balance.hint, automations.condition_type.balance.label, automations.condition_type.entity.hint, automations.condition_type.entity.label, automations.condition_type.sun.hint, automations.condition_type.sun.label, automations.condition_type.time.hint, automations.condition_type.time.label, automations.condition_type.learned_state.short, automations.condition_type.learned_value.short, automations.learned.state.condition, automations.learned.state.help, automations.learned.value.condition, automations.learned.value.help // Was der Bearbeiten-Modus als Bedingung anbieten darf. "balance" heisst // bewusst Energiewert und nicht PV-Ueberschuss: der Typ balance_threshold // deckt jedes Bilanzfeld ab - Netzbezug, Autarkiegrad, Batterie-Fuellstand -, @@ -102,6 +102,9 @@ // kommen aus den Lernwert-Texten, die Kurzform hat eigene Texte. { key: 'learned_state', icon: 'ico-learning', label: 'automations.learned.state.condition', hint: 'automations.learned.state.help', short: 'automations.condition_type.learned_state.short' }, + // Gelernter Zahlwert gegen eine feste Schwelle oder eine Bezugsangabe, etwa die PV-Reserve. + { key: 'learned_value', icon: 'ico-learning', label: 'automations.learned.value.condition', + hint: 'automations.learned.value.help', short: 'automations.condition_type.learned_value.short' }, ]; // i18n-keys: automations.chain.signal.finding, automations.chain.signal.loss_w, automations.chain.signal.efficiency_pct, automations.chain.signal.standby_w, automations.chain.kind.any, automations.chain.once, automations.chain.min_age, automations.chain.missing, automations.summary.chain_finding, automations.summary.chain_value, diagnostics.rule.chain_drift.title, diagnostics.rule.chain_frozen.title, diagnostics.rule.chain_contradiction.title, diagnostics.rule.chain_sign.title, diagnostics.rule.chain_unit.title @@ -345,7 +348,8 @@ function learnedValue(condition, field, learned) { const AL = window.AutomationLearned; const cond = condition || {}; - const ref = cond.type === 'learned_state' && field === 'learned' + // learned_state und learned_value tragen den Lernwert flach am Typ. + const ref = (cond.type === 'learned_state' || cond.type === 'learned_value') && field === 'learned' ? { learned: cond.learned, fallback: cond.fallback, max_age_s: cond.max_age_s } : cond[field]; if (!AL || !AL.isRef(ref)) return null; @@ -478,6 +482,19 @@ return { icon: 'ico-sun', title: t('automations.sun_window'), unit: '', summary: `${from} – ${to}${weekdaySuffix(condition)}` }; } + if (type === 'learned_value') { + // Einheit: die der Schwelle, wenn sie eine Bezugsangabe ist, sonst die des Lernwerts. + const AL = window.AutomationLearned; + const thresholdKey = AL && AL.isRef(condition.threshold) ? condition.threshold.learned : condition.learned; + const unit = AL ? AL.unitOfKey(thresholdKey) : ''; + const name = AL ? AL.keyLabel(condition.learned, learned && learned.devices, t) : String(condition.learned || ''); + const comparison = t(COMPARISON_WORDS[condition.comparison] || condition.comparison); + const threshold = shownValue(condition, 'threshold', learned); + const summaryKey = condition.hysteresis ? 'automations.summary.learned_value_hysteresis' : 'automations.summary.learned_value'; + // i18n-keys: automations.summary.learned_value, automations.summary.learned_value_hysteresis + const summary = t(summaryKey, { name, comparison, threshold, unit, hysteresis: condition.hysteresis }).trim(); + return { icon: 'ico-learning', title: t('automations.learned.value.condition'), unit, summary }; + } if (type === 'learned_state') { const state = condition.equals === 'active' ? 'automations.learned.state.active' : 'automations.learned.state.quiet'; return { icon: 'ico-learning', title: t('automations.learned.state.condition'), unit: '', summary: t(state) }; diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index d7a88bf6..3554e082 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -281,7 +281,74 @@ } return out; }, + surplus_switch(prefill) { return surplusPrefill(prefill, 'on', true); }, + surplus_wallbox(prefill) { return surplusPrefill(prefill, 'start', false); }, + after_battery_full(prefill) { + const out = {}; + // Geraet per Geraete-Id vor der Entitaet, wie bei shift_start. + const device = prefill.device !== undefined ? prefill.device : prefill.entity; + if (device !== undefined) { + if (!isPrefillText(device)) return null; + out.device = device; + } + if (prefill.min_run_s !== undefined) { + if (typeof prefill.min_run_s !== 'number' || !Number.isFinite(prefill.min_run_s) || prefill.min_run_s < 0) return null; + // Die Auswahl des Schritts: keine 0, kurz 180, standard 300 und lang 600 Sekunden. + const steps = [['none', 0], ['short', 180], ['standard', 300], ['long', 600]]; + out.min_run_s = steps.reduce((best, step) => ( + Math.abs(step[1] - prefill.min_run_s) < Math.abs(best[1] - prefill.min_run_s) ? step : best + ))[0]; + } + return out; + }, + shift_start(prefill) { + const out = {}; + // Der Erkenner nennt die Geraete-Id und eine Entitaet, die nicht zwingend ein Schalter ist. + // Vorrang hat daher die Geraete-Id, die Aufloesung nimmt den Schalter des Geraets. + const device = prefill.device !== undefined ? prefill.device : prefill.entity; + if (device !== undefined) { + if (!isPrefillText(device)) return null; + out.device = device; + } + if (prefill.on_w !== undefined) { + if (typeof prefill.on_w !== 'number' || !Number.isFinite(prefill.on_w) || prefill.on_w < 0) return null; + out.on_w = Math.round(prefill.on_w / 100) * 100; + } + if (prefill.latest !== undefined) { + if (!isPrefillClock(prefill.latest)) return null; + out.latest = { from: prefill.latest, to: prefillClockAfter(prefill.latest, 5), days: [0, 1, 2, 3, 4, 5, 6] }; + } + return out; + }, }; + // Vorbelegung der Ueberschuss-Vorlagen aus dem Erkenner: Geraet, Startleistung (auf 100 W + // gerundet, Schritt onStep), Quelle export oder reserve. Nur surplus_switch hat eine + // Laufzeit: min_run_s in Sekunden wird zu Minuten im Raster 10 und setzt die feste Laufzeit. + // Eine ungueltige Laufzeit laesst den Schritt leer, ungueltige Leistung oder Quelle ergibt null. + function surplusPrefill(prefill, onStep, withRuntime) { + const out = {}; + const device = prefill.entity !== undefined ? prefill.entity : prefill.device; + if (device !== undefined) { + if (!isPrefillText(device)) return null; + out.device = device; + } + if (prefill.on_w !== undefined) { + if (typeof prefill.on_w !== 'number' || !Number.isFinite(prefill.on_w) || prefill.on_w < 0) return null; + out[onStep] = Math.round(prefill.on_w / 100) * 100; + } + if (prefill.source !== undefined) { + if (prefill.source !== 'export' && prefill.source !== 'reserve') return null; + out.source = prefill.source; + } + if (withRuntime && typeof prefill.min_run_s === 'number' && Number.isFinite(prefill.min_run_s)) { + const minutes = Math.round(prefill.min_run_s / 600) * 10; + if (minutes >= 10 && minutes <= 600) { + out.runtime = minutes; + out.off = 'runtime'; + } + } + return out; + } // Reine Funktion: Vorlage und Vorbelegung zu Antworten, oder null bei unbekannter // Vorlage oder falscher Form. function prefillToAnswers(templateId, prefill) { @@ -1560,8 +1627,11 @@ this.assistant.answers = answers; for (const step of this.assistantSteps()) { if (step.type !== 'device') continue; - const usable = this.assistantDevices(step).some((item) => item.id === answers[step.id] && !item.disabled); - if (!usable) answers[step.id] = ''; + const options = this.assistantDevices(step).filter((item) => !item.disabled); + if (options.some((item) => item.id === answers[step.id])) continue; + // Der Erkenner nennt oft nur die Geraete-Id. Dann gilt der erste nutzbare Eintrag des Geraets. + const byDevice = options.find((item) => item.deviceId !== undefined && item.deviceId === answers[step.id]); + answers[step.id] = byDevice ? byDevice.id : ''; } const steps = this.assistantSteps(); const open = steps.findIndex((step) => !window.__automationWizard.stepComplete(step, answers[step.id])); @@ -1885,12 +1955,15 @@ } catch (error) { return null; } - if (name && name.trim() !== '') built.entry.name = name.trim(); + // Der Name gilt fuer den ersten Eintrag. Eine Vorlage mit zwei Regeln (kind rules) legt beide an. + if (name && name.trim() !== '') (built.kind === 'rules' ? built.entries[0] : built.entry).name = name.trim(); return built; }, - assistantFull(kind) { - return kind === 'scenario' ? !this.canAddScenario() : !this.canAddRule(); + // Ob count neue Eintraege der Art kind in die volle Liste passen wuerden. + assistantFull(kind, count = 1) { + if (kind === 'scenario') return (this.document.scenarios || []).length + count > SCENARIO_LIMIT; + return (this.document.rules || []).length + count > RULE_LIMIT; }, // Zeilen der Zusammenfassung: Phase, Text und der Schritt zum Aendern. @@ -1909,15 +1982,26 @@ assistantListFull() { const built = this.assistantBuild(); - return !!built && this.assistantFull(built.kind); + if (!built) return false; + const { kind, entries } = this.assistantEntries(built); + return this.assistantFull(kind, entries.length); + }, + + // Art (rule oder scenario) und Eintraege eines Builds. Ein Build mit kind rules liefert zwei Regeln. + assistantEntries(built) { + if (built.kind === 'rules') return { kind: 'rule', entries: built.entries }; + return { kind: built.kind, entries: [built.entry] }; }, // Legt die Vorlage an: ungespeichert, aktiv, mit Rueckgaengig. Bei voller Liste - // passiert nichts, der Dialog bleibt offen. + // passiert nichts, der Dialog bleibt offen. Alle Eintraege sind schon gebaut, bevor + // der erste eingefuegt wird, daher bleibt bei einem Fehler nichts halb angelegt. assistantCreate() { const built = this.assistantBuild(); - if (!built || this.assistantFull(built.kind)) return; - this.insertEntry(built.kind, built.entry); + if (!built) return; + const { kind, entries } = this.assistantEntries(built); + if (this.assistantFull(kind, entries.length)) return; + this.insertEntries(kind, entries); this.closeAssistant(); }, @@ -2060,24 +2144,32 @@ // Gemeinsamer Kern fuer neue Regeln und Szenarien: anlegen, als neu // markieren, aufklappen, Editor oeffnen, Reiter wechseln, Rueckgaengig anbieten. insertEntry(kind, entry) { - if (kind === 'scenario') { - this.document.scenarios.push(entry); - this.scenarioExpanded[entry.id] = true; - this.scenarioEditing[entry.id] = true; - this.view = 'scenarios'; - } else { - this.document.rules.push(entry); - this.expanded[entry.id] = true; - this.editing[entry.id] = true; - this.view = 'rules'; + this.insertEntries(kind, [entry]); + return entry; + }, + + // Mehrere Eintraege einer Art, ein Rueckgaengig nimmt alle zurueck. + insertEntries(kind, entries) { + for (const entry of entries) { + if (kind === 'scenario') { + this.document.scenarios.push(entry); + this.scenarioExpanded[entry.id] = true; + this.scenarioEditing[entry.id] = true; + } else { + this.document.rules.push(entry); + this.expanded[entry.id] = true; + this.editing[entry.id] = true; + } + this.newIds[entry.id] = true; } - this.newIds[entry.id] = true; + this.view = kind === 'scenario' ? 'scenarios' : 'rules'; this.armUndo({ label: kind === 'scenario' ? t('automations.undo.scenario_added') : t('automations.undo.rule_added'), kind, - id: entry.id, + id: entries[0].id, + ids: entries.map((entry) => entry.id), }); - return entry; + return entries; }, armUndo(undo) { @@ -2093,16 +2185,22 @@ const undo = this.undo; if (!undo) return; if (undo.findingId) return this.undoIgnoredFinding(undo); + const ids = undo.ids || [undo.id]; if (undo.kind === 'scenario') { - this.document.scenarios = this.document.scenarios.filter((entry) => entry.id !== undo.id); - delete this.scenarioExpanded[undo.id]; - delete this.scenarioEditing[undo.id]; + this.document.scenarios = this.document.scenarios.filter((entry) => !ids.includes(entry.id)); } else { - this.document.rules = this.document.rules.filter((entry) => entry.id !== undo.id); - delete this.expanded[undo.id]; - delete this.editing[undo.id]; + this.document.rules = this.document.rules.filter((entry) => !ids.includes(entry.id)); + } + for (const id of ids) { + if (undo.kind === 'scenario') { + delete this.scenarioExpanded[id]; + delete this.scenarioEditing[id]; + } else { + delete this.expanded[id]; + delete this.editing[id]; + } + delete this.newIds[id]; } - delete this.newIds[undo.id]; clearTimeout(this._undoTimer); this.undo = null; }, @@ -2224,22 +2322,26 @@ return { parent: node, key: path[path.length - 1] }; }; const plans = groups.map((group) => { + // Ein Regler-Befund nennt ein Szenario mit derselben Id. Ein Szenario wird nur + // gesucht, wenn keine Regel dazu passt. const rule = this.document.rules.find((entry) => entry.id === group.rule_id); - if (!rule) return { rule: null, writes: [] }; + const scenario = rule ? null : (this.document.scenarios || []).find((entry) => entry.id === group.rule_id); + const entry = rule || scenario || null; + if (!entry) return { entry: null, kind: null, writes: [] }; // Ein add_condition nennt den Index, den die Bedingung beim Befund hatte. // Seitdem kann eine Bedingung dazugekommen sein, deshalb wird angehaengt. const writes = group.ops.map((op) => { - const target = targetOf(rule, op.path || []); + const target = targetOf(entry, op.path || []); if (group.code === 'add_condition') { return { target: target && Array.isArray(target.parent) ? { parent: target.parent, append: true } : null, value: op.value }; } return { target, value: op.value }; }); - return { rule, writes }; + return { entry, kind: rule ? 'rule' : 'scenario', writes }; }); - const opened = plans.map((plan) => plan.rule).filter(Boolean); + const opened = plans.filter((plan) => plan.entry); if (opened.length === 0) return; - if (plans.every((plan) => plan.rule && plan.writes.every((write) => write.target))) { + if (plans.every((plan) => plan.entry && plan.writes.every((write) => write.target))) { plans.forEach((plan) => plan.writes.forEach((write) => { if (write.target.append) write.target.parent.push(write.value); else write.target.parent[write.target.key] = write.value; @@ -2248,8 +2350,19 @@ this.appliedFindingIds = [...this.appliedFindingIds, finding.id]; } } - this.startEditing(opened[0]); - opened.forEach((rule) => { this.expanded[rule.id] = true; }); + // Geoeffnet wird der erste gefundene Eintrag: eine Regel im Editor, ein Szenario + // im Editor des Szenario-Reiters. Alle gefundenen Eintraege klappen auf. + const first = opened[0]; + if (first.kind === 'rule') { + this.startEditing(first.entry); + } else { + this.view = 'scenarios'; + this.scenarioEditing[first.entry.id] = true; + } + opened.forEach((plan) => { + if (plan.kind === 'rule') this.expanded[plan.entry.id] = true; + else this.scenarioExpanded[plan.entry.id] = true; + }); this.closeFinding(); }, postFindingIgnore(id, undo) { @@ -2348,6 +2461,25 @@ hold_seconds: Math.max(LEARNED_STATE_HOLD_S, this.minPublishInterval()) }); }, + // Gelernter Zahlwert: PV-Reserve ueber 1500 W, mit Hysterese und Ersatzwert. Der Ausgangswert entspricht dem Beispiel im Plan. + addLearnedValueCondition(rule) { + rule.conditions.push({ type: 'learned_value', learned: 'site/pv_reserve_w', comparison: 'above', threshold: 1500, + hysteresis: 100, fallback: 0, max_age_s: 1800, + hold_seconds: Math.max(LEARNED_STATE_HOLD_S, this.minPublishInterval()) }); + }, + + // Lernwerte fuer das Feld learned eines gelernten Zahlwerts. Der gewaehlte Schluessel bleibt auch ohne Eintrag sichtbar. + learnedValueOptions(condition) { + const AL = window.AutomationLearned; + const options = this.learnedChoices(condition, 'learned') + .map((entry) => ({ key: entry.key, label: AL.keyLabel(entry.key, this.devices, t) })); + const key = condition.learned; + if (key && !options.some((option) => option.key === key)) { + options.push({ key, label: AL.keyLabel(key, this.devices, t) }); + } + return options; + }, + // Eintrag des Endpunkts zu einem Lernwert-Schluessel, sonst null. learnedEntry(key) { return this.learnedList().find((value) => value && value.key === key) || null; @@ -2388,6 +2520,12 @@ // Einheit der Lernwerte fuer ein Zahlfeld: Schwellen in W, sonst die Einheit der Entitaet. learnUnitOf(condition, field) { if (this.learnKind(condition, field) !== 'number') return undefined; + // Der gelernte Zahlwert selbst nimmt jede Einheit, die Schwelle die des Lernwerts oder ihrer Bezugsangabe. + if (field === 'learned') return undefined; + if (condition.type === 'learned_value') { + const ref = isRefValue(condition.threshold) ? condition.threshold.learned : condition.learned; + return window.AutomationLearned.unitOfKey(ref) || undefined; + } if (field === 'threshold') return 'W'; const entity = this.entityForCondition(condition); return (entity && entity.unit_of_measurement) || undefined; @@ -2535,7 +2673,9 @@ const kind = AL.kindOf(condition.type, field); if (kind && AL.isRef(condition[field])) codes.push(...AL.validate(condition[field], kind)); } - if (condition.type === 'learned_state') codes.push(...AL.validate({ learned: condition.learned }, 'state')); + if (condition.type === 'learned_state' || condition.type === 'learned_value') { + codes.push(...AL.validate({ learned: condition.learned }, 'state')); + } const keys = { 'learned.min_max': 'automations.learned.error.min_max', 'learned.fallback_range': 'automations.learned.error.fallback_range', @@ -2716,6 +2856,7 @@ if (key === 'time') result = this.addTimeWindowCondition(rule); if (key === 'sun') result = this.addSunWindowCondition(rule); if (key === 'learned_state') result = this.addLearnedStateCondition(rule); + if (key === 'learned_value') result = this.addLearnedValueCondition(rule); if (key === 'chain') result = this.addChainCondition(rule); this.loadEditLive(rule); return result; diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index 2a39581f..59391949 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -145,6 +145,14 @@ return t(`monitoring.notice.${notice.code}.text`, notice.params); } + // Die Zahlen eines Lernbefunds mit dem Format des Vorschlagsbands. Die Seite lädt + // das Band mit; ohne es bleiben die Zahlen weg. + function learnFacts(list, t) { + const band = typeof window !== 'undefined' ? window.AutomationSuggestions : null; + if (band && typeof band.factRows === 'function') return band.factRows(list, t).map((r) => [r.label, r.value]); + return []; + } + function facts(notice, t) { const p = notice.params || {}; if (notice.code === 'unassigned') { @@ -153,6 +161,7 @@ return rows; } if (sourceOf(notice) === 'learn' && p.kind === 'shade') return shadeFacts(notice, p, t); + if (isLearned(notice) && Array.isArray(notice.facts) && notice.facts.length) return learnFacts(notice.facts, t); return []; } diff --git a/dashboard/internal/webui/templates/automations-finding.html b/dashboard/internal/webui/templates/automations-finding.html new file mode 100644 index 00000000..9d09b1cc --- /dev/null +++ b/dashboard/internal/webui/templates/automations-finding.html @@ -0,0 +1,37 @@ +{{define "automations-finding"}} + + +{{end}} diff --git a/dashboard/internal/webui/templates/automations-rows.html b/dashboard/internal/webui/templates/automations-rows.html index 84a9da21..08bdbe84 100644 --- a/dashboard/internal/webui/templates/automations-rows.html +++ b/dashboard/internal/webui/templates/automations-rows.html @@ -160,6 +160,51 @@ + +