diff --git a/changelog/highlights/300.json b/changelog/highlights/300.json new file mode 100644 index 00000000..ed85d8e3 --- /dev/null +++ b/changelog/highlights/300.json @@ -0,0 +1,65 @@ +{ + "de": { + "*": "Monitoring prüft, was übernommene Vorschläge bringen, Regeln melden einen Saisonwechsel" + }, + "en": { + "*": "Monitoring checks the results of adopted suggestions and rules report a season drift" + }, + "tour": { + "*": { + "steps": [ + { + "device": "any", + "need": "view_monitoring", + "open": [ + "monitoring-effect" + ], + "panel": "monitoring-panel", + "target": "monitoring-effect", + "text": { + "de": "Nach dem Übernehmen eines Vorschlags zeigt das Monitoring unter Erfolgskontrolle den Wert vorher und seitdem. Das beginnt nach der ersten vollen Woche.", + "en": "After you adopt a suggestion, Monitoring shows the value before and since under Results check. It appears after the first full week." + }, + "title": { + "de": "Erfolgskontrolle", + "en": "Results check" + } + }, + { + "device": "any", + "need": "view_automations", + "open": [ + "automations-rules" + ], + "panel": "automations-panel", + "target": "rule-effect", + "text": { + "de": "Die Regel trägt dasselbe Ergebnis. Wandern ihre Zeiten oder Werte mit der Jahreszeit, warnt die Marke und bietet eine Anpassung an.", + "en": "The rule carries the same result. When its times or values move with the season, the mark warns and offers an adjustment." + }, + "title": { + "de": "Die Marke an der Regel", + "en": "The mark on the rule" + } + }, + { + "device": "any", + "need": "view_monitoring", + "open": [ + "monitoring-learned" + ], + "panel": "monitoring-panel", + "target": "monitoring-learned", + "text": { + "de": "Das Monitoring listet, was der Node gelernt hat. Regeln können diese Werte nutzen.", + "en": "Monitoring lists what the node has learned. Rules can use these values." + }, + "title": { + "de": "Lernwerte", + "en": "Learned values" + } + } + ] + } + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index 5a8511ba..c3446ba2 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.11.22-pre.37 (2026-11-06) +## v0.11.22-pre.38 (2026-11-06) ### Features @@ -36,10 +36,23 @@ - **autolearn:** Automation suggestions for surplus and load shifts are checked against your data (#295) (6c255ad) - **autolearn:** Learning functions can take minute values from Home Assistant (#294) (7aa657e) - **monitoring:** Monitoring shows the forecast check, a year comparison and the learned values as a usual day (#297) (4f93975) +- **dashboard:** show system versions on the versions page (#299) (18a2b0b) +- **automations:** mark rules that came from a learned suggestion (f85130f) +- **webui:** record which suggestion a saved rule came from (ae2baed) +- **autolearn:** measure the effect of an adopted suggestion against the season (a1e9dc6) +- **autolearn:** keep the effect of adopted rules in a store (f0d3d9e) +- **autolearn:** show the effect of adopted suggestions on the rule and in the band (d024c0d) +- **autolearn:** report when an adopted suggestion drifts with the season (479c125) +- **webui:** show the effect of adopted suggestions in the band (85a5fed) +- **webui:** show the effect and season drift of adopted suggestions (a71c920) +- **demo:** show an effect and a season drift (71ee735) +- **demo:** show every effect state and drift kind (c3e766b) +- **webui:** let a tour expand the suggestions band (fa55c0a) +- **monitoring:** check the results of adopted suggestions in Monitoring (f4755bb) +- **automations:** Monitoring checks the results of adopted suggestions and rules report a season drift (#300) - **dashboard:** read the system package versions (8d025b3) - **dashboard:** serve system versions to setup users (8e71270) - **dashboard:** show the kernel and the Debian point release (93d002d) -- **dashboard:** show system versions on the versions page (#299) - **autolearn:** expose forecast days and the rules that read a learned value (25d731e) - **demo:** seed a forecast check and a year of season weeks (4a39a77) - **monitoring:** serve the forecast check and the season weeks from the api (d11383f) @@ -354,6 +367,21 @@ - **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) - **automations:** correct the learning feature after the full review (#296) (88f3c75) +- **webui:** mark rules adopted from the suggestions band (6e20041) +- **autolearn:** accept baseline weeks with five days of data (fbbda8c) +- **autolearn:** keep the comparison values when a drifted rule is replaced (a95dcb5) +- **webui:** show the assistant for a drift fix and fit the effect card (fdb5ff8) +- **autolearn:** compare only values that drift with the season (51a586e) +- **backup:** include the measured effects in the backup (7aa2448) +- **autolearn:** show only the override count without a measure (b591b99) +- **autolearn:** keep rating a surplus window after its rule was adopted (cfc5906) +- **autolearn:** judge the season drift only after a complete daily round (573643f) +- **demo:** keep every effect state visible on any day (65558cd) +- **webui:** write the drift scale axes in the number format of the page (43f4528) +- **webui:** name the scenario in the surplus window drift (e41a11d) +- **demo:** adopt the surplus window as a scenario and count one effect in hand switches (49a32f9) +- **webui:** fit the effect axis on phones and say what a threshold fix does (0b4bef6) +- **webui:** label only the ends of the before and since axis (222cf12) - **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **monitoring:** keep texts and locale out of the insight model (57e2a44) - **monitoring:** show the legend items for statistics weeks and gaps (82cde6e) @@ -518,6 +546,7 @@ ### Tests +- **demo:** expect a sure effect beside the estimates (aa987aa) - **demo:** fake the system packages for the versions page (ca2dc1e) - **autolearn:** keep the cycle test window open until today (ab438d5) - **webui:** follow the template cache-bust mark (c30a3db) @@ -541,6 +570,7 @@ ### Chores +- **webui:** bump the cache marks of the changed automation assets (fa93e53) - **dashboard:** bump the cache-bust marks for the system card (31ecbb8) - **dashboard:** move the cache history rows to the current pre-release (8a60da5) - **monitoring:** drop the texts of the old learned values list (d6da484) diff --git a/dashboard/VERSION b/dashboard/VERSION index 61e24d2f..4e86b954 100644 --- a/dashboard/VERSION +++ b/dashboard/VERSION @@ -1 +1 @@ -v0.11.22-pre.37 +v0.11.22-pre.38 diff --git a/dashboard/cmd/dashboard/learn_effect_test.go b/dashboard/cmd/dashboard/learn_effect_test.go new file mode 100644 index 00000000..f583daf2 --- /dev/null +++ b/dashboard/cmd/dashboard/learn_effect_test.go @@ -0,0 +1,197 @@ +package main + +import ( + "encoding/json" + "math" + "os" + "path/filepath" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" +) + +// effectTestRunner builds an effect runner over a fixed rule document and +// counts the day file loads. +func effectTestRunner(t *testing.T, doc []byte, loads *int) *effectRunner { + t.Helper() + dir := t.TempDir() + return &effectRunner{ + store: autolearn.LoadEffectStore(filepath.Join(dir, "effects.json"), nil), + readDoc: func() ([]byte, error) { return doc, nil }, + days: func(from, to time.Time) ([]autolearn.DayFile, error) { + *loads++ + return nil, nil + }, + candidates: func() []autolearn.Candidate { return nil }, + shown: func() map[string]autolearn.Shown { return nil }, + season: autolearn.LoadSeasonStore(filepath.Join(dir, "season.json"), nil), + enabled: func() bool { return true }, + // No complete daily round unless a test says so. + round: func() (time.Time, bool) { return time.Time{}, false }, + } +} + +func TestEffectRunnerLoadsDaysOnlyForNewRuleOrDailyRun(t *testing.T) { + loads := 0 + r := effectTestRunner(t, []byte(effectRuleDoc), &loads) + now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.Local) + + r.Run(now) + r.Run(now.Add(time.Minute)) + r.Run(now.Add(2 * time.Minute)) + if loads != 1 { + t.Fatalf("day file loads over three rounds of one day = %d, want 1 (the new rule)", loads) + } + if r.store.Len() != 1 { + t.Fatalf("entries = %d, want 1 for the learned rule", r.store.Len()) + } + + // The next morning the daily run loads the day files again, once. + r.Run(time.Date(2026, 11, 26, 4, 0, 0, 0, time.Local)) + if loads != 2 { + t.Fatalf("day file loads after the daily run = %d, want 2", loads) + } +} + +func TestEffectRunnerUnreadableDocumentKeepsEntries(t *testing.T) { + loads := 0 + r := effectTestRunner(t, []byte(effectRuleDoc), &loads) + now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.Local) + r.Run(now) + + r.readDoc = func() ([]byte, error) { return nil, os.ErrNotExist } + r.Run(now.AddDate(0, 0, 1).Add(5 * time.Hour)) + if r.store.Len() != 1 { + t.Fatalf("entries after an unreadable document = %d, want 1 kept", r.store.Len()) + } +} + +func TestEffectRunnerDisabledDoesNothing(t *testing.T) { + loads := 0 + r := effectTestRunner(t, []byte(effectRuleDoc), &loads) + r.enabled = func() bool { return false } + r.Run(time.Date(2026, 11, 25, 10, 0, 0, 0, time.Local)) + if loads != 0 || r.store.Len() != 0 { + t.Fatalf("disabled runner loads = %d, entries = %d, want none", loads, r.store.Len()) + } +} + +func TestEffectRunnerTakesCandidateValuesWhenNotShown(t *testing.T) { + dir := t.TempDir() + effects := filepath.Join(dir, "effects.json") + loads := 0 + r := effectTestRunner(t, []byte(effectRuleDoc), &loads) + r.store = autolearn.LoadEffectStore(effects, nil) + r.candidates = func() []autolearn.Candidate { + return []autolearn.Candidate{{ + Finding: autolearn.Finding{ID: "switchtime:r1:dev-a"}, + Values: map[string]float64{"time": 1305}, + Spread: map[string]float64{"time": 10}, + }} + } + now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.Local) + r.round = func() (time.Time, bool) { return now.Add(-time.Hour), true } + r.Run(now) + + raw, err := os.ReadFile(effects) + if err != nil { + t.Fatalf("effects file: %v", err) + } + var f struct { + Entries []struct { + Rule string `json:"rule"` + Values map[string]float64 `json:"values"` + Series []float64 `json:"series"` + } `json:"entries"` + } + if err := json.Unmarshal(raw, &f); err != nil { + t.Fatalf("effects file: %v", err) + } + if len(f.Entries) != 1 || f.Entries[0].Rule != "r1" { + t.Fatalf("entries = %+v, want one entry for r1", f.Entries) + } + if f.Entries[0].Values["time"] != 1305 { + t.Errorf("values = %v, want the candidate time 1305", f.Entries[0].Values) + } + if len(f.Entries[0].Series) != 1 { + t.Errorf("series = %v, want one nightly value after the new entry", f.Entries[0].Series) + } +} + +// effectSeriesOnDisk reads the season drift series of the first entry from the +// effect store file. +func effectSeriesOnDisk(t *testing.T, path string) []float64 { + t.Helper() + raw, err := os.ReadFile(path) + if err != nil { + t.Fatalf("effects file: %v", err) + } + var f struct { + Entries []struct { + Series []float64 `json:"series"` + } `json:"entries"` + } + if err := json.Unmarshal(raw, &f); err != nil { + t.Fatalf("effects file: %v", err) + } + if len(f.Entries) != 1 { + t.Fatalf("entries = %d, want 1", len(f.Entries)) + } + return f.Entries[0].Series +} + +// TestEffectRunnerDriftWaitsForCompleteRound checks that the season drift is +// judged only after a complete daily round: a round without one, after a restart, +// leaves the stored drift alone, and a new complete round updates it, on the same day too. +func TestEffectRunnerDriftWaitsForCompleteRound(t *testing.T) { + path := filepath.Join(t.TempDir(), "effects.json") + loads := 0 + r := effectTestRunner(t, []byte(effectRuleDoc), &loads) + r.store = autolearn.LoadEffectStore(path, nil) + shift := 1305.0 + r.candidates = func() []autolearn.Candidate { + return []autolearn.Candidate{{ + Finding: autolearn.Finding{ID: "switchtime:r1:dev-a"}, + Values: map[string]float64{"time": shift}, + Spread: map[string]float64{"time": 10}, + }} + } + now := time.Date(2026, 11, 25, 10, 0, 0, 0, time.Local) + dailyAt := time.Date(2026, 11, 25, 3, 30, 0, 0, time.Local) + + // The new entry comes before any complete round: no drift yet. + r.Run(now) + if got := effectSeriesOnDisk(t, path); len(got) != 0 { + t.Fatalf("series before a complete round = %v, want none", got) + } + + // The first complete round judges the drift, the value is 0 at 1305. + r.round = func() (time.Time, bool) { return dailyAt, true } + r.Run(now) + if got := effectSeriesOnDisk(t, path); len(got) != 1 || got[0] != 0 { + t.Fatalf("series after a complete round = %v, want [0]", got) + } + + // The candidate moved, but the round is incomplete: the stored drift stays. + shift = 1250 + r.round = func() (time.Time, bool) { return time.Time{}, false } + r.Run(now.Add(time.Hour)) + if got := effectSeriesOnDisk(t, path); len(got) != 1 || got[0] != 0 { + t.Fatalf("series during an incomplete round = %v, want [0] kept", got) + } + + // The same complete round again changes nothing. + r.round = func() (time.Time, bool) { return dailyAt, true } + r.Run(now.Add(2 * time.Hour)) + if got := effectSeriesOnDisk(t, path); len(got) != 1 || got[0] != 0 { + t.Fatalf("series after the same round = %v, want [0] kept", got) + } + + // A new complete round the same day judges the drift again: (1250-1305)/10. + r.round = func() (time.Time, bool) { return dailyAt.Add(time.Hour), true } + r.Run(now.Add(3 * time.Hour)) + if got := effectSeriesOnDisk(t, path); len(got) != 1 || math.Abs(got[0]+5.5) > 1e-6 { + t.Fatalf("series after a new complete round = %v, want [-5.5]", got) + } +} diff --git a/dashboard/cmd/dashboard/learn_engine.go b/dashboard/cmd/dashboard/learn_engine.go index d66f1525..d0ccfd8a 100644 --- a/dashboard/cmd/dashboard/learn_engine.go +++ b/dashboard/cmd/dashboard/learn_engine.go @@ -534,3 +534,92 @@ func (c *cycleRunner) Reset() error { } return nil } + +// effectNightlyAt is the time of day from which the effect runner takes its +// daily run, once per calendar day. +const effectNightlyAt = 3*time.Hour + 30*time.Minute + +// effectRunner keeps the effect store current after every engine round. It runs +// in the engine round goroutine, so it needs no lock. done is the calendar day +// of the last daily run. +type effectRunner struct { + store *autolearn.EffectStore + readDoc func() ([]byte, error) + days func(from, to time.Time) ([]autolearn.DayFile, error) + candidates func() []autolearn.Candidate + shown func() map[string]autolearn.Shown + season *autolearn.SeasonStore + enabled func() bool + // round tells the start of the last daily round and whether it is complete. + round func() (time.Time, bool) + done string + // driftDone is the start of the daily round whose drift was judged last. + driftDone time.Time +} + +// Run takes the entries of new learned rules and, once a day, recomputes every +// effect. The day files are read only when a rule is new or on the daily run. +// An unreadable document or day file changes nothing, so the next round retries. +func (r *effectRunner) Run(now time.Time) { + if !r.enabled() { + return + } + raw, err := r.readDoc() + if err != nil { + return + } + doc, err := autolearn.ParseDoc(raw) + if err != nil { + return + } + day := now.Format("2006-01-02") + at := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Add(effectNightlyAt) + nightly := r.done == "" || (day != r.done && !now.Before(at)) + // The season drift is judged once per complete daily round, so a round + // without learned values yet, after a restart, does not clear it. + roundAt, complete := r.round() + drift := complete && !roundAt.Equal(r.driftDone) + needs := r.store.NeedsDays(doc) + var days []autolearn.DayFile + if needs || ((nightly || drift) && r.store.Len() > 0) { + days, err = r.days(now.AddDate(0, 0, -366), now) + if err != nil { + log.Printf("autolearn: effect day files unreadable, retrying next round: %v", err) + return + } + } + cands := r.candidates() + byID := make(map[string]autolearn.Finding, len(cands)) + for _, c := range cands { + f := c.Finding + if f.Benefit == nil { + b := c.Benefit + f.Benefit = &b + } + byID[f.ID] = f + } + // A replaced rule points at a candidate the gate does not show. Its values + // come from the candidate, the shown ones win. + shown := map[string]autolearn.Shown{} + for id, sh := range r.shown() { + shown[id] = sh + } + for _, c := range cands { + if _, ok := shown[c.Finding.ID]; !ok { + shown[c.Finding.ID] = autolearn.Shown{Values: c.Values} + } + } + added := r.store.Sync(doc, now, days, shown, byID) + if added || nightly || drift { + // A nil list leaves the drift of the entries as it is. + var judged []autolearn.Candidate + if drift { + judged = append([]autolearn.Candidate{}, cands...) + r.driftDone = roundAt + } + r.store.Nightly(now, days, r.season, judged) + } + if nightly { + r.done = day + } +} diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index db219128..572bceab 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -519,6 +519,13 @@ func main() { if err := autolearn.SeedDemoMinutes(dataDir, time.Now(), time.Local); err != nil { log.Printf("autolearn: demo minutes: %v", err) } + // Die Wirkung und die Saisonverschiebung der gelernten Demo-Regeln. Der + // Speicher wird unten geladen, daher steht die Datei hier schon bereit. + if raw, err := configManager.Read("automation_rules"); err != nil { + log.Printf("autolearn: demo effects: read rules: %v", err) + } else if err := autolearn.SeedDemoEffects(filepath.Join(autolearnDir, "effects.json"), raw, time.Now()); err != nil { + log.Printf("autolearn: demo effects: %v", err) + } } // PV-Himmelsraster: nur ungedrosselte PV-Minuten zaehlen. Standort und Regler // kommen aus dem Regelwerk, das pvSite.refresh nur beim Speichern liest. @@ -673,6 +680,23 @@ func main() { // Datei liegt unter autolearn/ und wird mit dem Hub gespeichert. learnedStore := autolearn.LoadLearnedStore(filepath.Join(autolearnDir, "learned.json"), log.Printf) learnHub.AddSaver("learned", learnedStore) + // Wirkung der angenommenen Vorschlaege, nach jeder Runde durch den Effektlauf aktualisiert. + effectStore := autolearn.LoadEffectStore(filepath.Join(autolearnDir, "effects.json"), log.Printf) + learnHub.AddSaver("effects", effectStore) + learnHub.AddResetter("effects", effectStore) + // Die Wirkung zeigen die Regelpruefung und das Monitoring, solange das Muster-Lernen an ist. + effectsOn := func() bool { + if value, err := settingsStore.LoadSettings(); err == nil && value.AutomationPatternsDisabled { + return false + } + return true + } + automationChecker.SetEffectSource(func(now time.Time) []autolearn.Finding { + if !effectsOn() { + return nil + } + return effectStore.Findings(now) + }) // Monitoring: Meldungen aus Energie, Ketten und Regelpruefung, je Minute // gesammelt, beim Abruf frisch und mit dem Hub gespeichert. // Vorschlaege fuer das Monitoring. Die Funktion wird unten gesetzt, sobald das @@ -687,6 +711,16 @@ func main() { if monitoringSuggestions != nil { in.Suggestions = monitoringSuggestions() } + if effectsOn() { + var doc autolearn.Doc + ok := false + if raw, err := configManager.Read("automation_rules"); err == nil { + if parsed, err := autolearn.ParseDoc(raw); err == nil { + doc, ok = parsed, true + } + } + in.Effects, in.RuleNames = monitoringEffects(effectStore.Measured(time.Now()), doc, ok) + } return in } monitoringStore := monitoring.OpenStore(filepath.Join(autolearnDir, "monitoring.json"), log.Printf) @@ -727,6 +761,16 @@ func main() { seasonClose := &seasonCloser{store: seasonStore, days: dayStore.Days, learned: learnedClockMinutes(learnedStore), site: ruleSite(func() ([]byte, error) { return configManager.Read("automation_rules") }), loc: time.Local} suggestions := &suggestionBook{state: suggestionState, readDoc: func() ([]byte, error) { return configManager.Read("automation_rules") }} + effectLoop := &effectRunner{ + store: effectStore, + readDoc: func() ([]byte, error) { return configManager.Read("automation_rules") }, + days: dayStore.Days, + candidates: automationEngine.Candidates, + shown: suggestionState.Shown, + season: seasonStore, + enabled: effectsOn, + round: automationEngine.DailyRound, + } suggestionExists := func(device string) bool { if deviceFilterStore.IsIgnored(device) { return false @@ -739,7 +783,14 @@ func main() { if value, err := settingsStore.LoadSettings(); err == nil && value.AutomationPatternsDisabled { return nil } - return suggestions.Visible(time.Now(), suggestionExists) + // The effects of adopted suggestions belong to the rule check, not to Monitoring. + var out []autolearn.Finding + for _, f := range suggestions.Visible(time.Now(), suggestionExists) { + if f.Group != "feedback" { + out = append(out, f) + } + } + return out } origin := newOriginLearner(originTracker, dayStore, reg, func() ([]byte, error) { return configManager.Read("automation_rules") }) @@ -937,10 +988,20 @@ func main() { if strings.TrimSpace(os.Getenv("ENERGY_NODE_AUTOLEARN_FAST")) == "1" { learnedValues = func() []autolearn.Value { return autolearn.WithDemoHouseState(automationEngine.Values()) } } + // Demo: the learned values exist only after a daily round, so the demo runs + // one more daily round after the first one, once. + demoFast := strings.TrimSpace(os.Getenv("ENERGY_NODE_AUTOLEARN_FAST")) == "1" + demoRequested := false engineLoop.afterRound = func() { + // The effects come before the gate, which drops the adopted suggestion from the shown state. + seasonClose.Run(time.Now()) + effectLoop.Run(time.Now()) gateSuggestions(suggestions, automationEngine, func() ([]byte, error) { return configManager.Read("automation_rules") }, engineGroups(), suggestionExists, time.Now()) publishLearned(learnedStore, learnedValues, client, engineGroups()["habit"], learnedExists, time.Now()) - seasonClose.Run(time.Now()) + if demoFast && !demoRequested { + demoRequested = true + automationEngine.RequestDaily() + } } go engineLoop.Run(ctx) diff --git a/dashboard/cmd/dashboard/monitoring.go b/dashboard/cmd/dashboard/monitoring.go index d593d349..dc18a348 100644 --- a/dashboard/cmd/dashboard/monitoring.go +++ b/dashboard/cmd/dashboard/monitoring.go @@ -57,6 +57,36 @@ func (m *monitoringRunner) Save() error { return m.store.Save() } +// monitoringEffects keeps the effects of the rules and scenarios that still came +// from a learned suggestion, and returns their names by ID. Without a readable +// rule document every effect stays, without names. +func monitoringEffects(effects []autolearn.Finding, doc autolearn.Doc, ok bool) ([]autolearn.Finding, map[string]string) { + names := map[string]string{} + if !ok { + return effects, names + } + for _, r := range doc.Rules { + if r.LearnedFrom != nil { + names[r.ID] = r.Name + } + } + for _, sc := range doc.Scenarios { + if sc.LearnedFrom != nil { + names[sc.ID] = sc.Name + } + } + var out []autolearn.Finding + for _, f := range effects { + if len(f.RuleIDs) == 0 { + continue + } + if _, adopted := names[f.RuleIDs[0]]; adopted { + out = append(out, f) + } + } + return out, names +} + // monitoringDeviceIcon wählt das Icon eines Lerngeräts aus seiner Energie-Rolle. func monitoringDeviceIcon(role energy.Role, switchable bool) string { switch { diff --git a/dashboard/cmd/dashboard/monitoring_effects_test.go b/dashboard/cmd/dashboard/monitoring_effects_test.go new file mode 100644 index 00000000..52f0bb0d --- /dev/null +++ b/dashboard/cmd/dashboard/monitoring_effects_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "testing" + + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" +) + +// monitoringEffectDoc holds r1 and s1 from a learned suggestion and r2 made by hand. +const monitoringEffectDoc = `{"rules":[{"id":"r1","name":"Heizung","enabled":true,"conditions":[],"actions":[],"learned_from":{"suggestion":"switchtime:r1:dev-a","kind":"switch_time","at":1700000000}},{"id":"r2","name":"Licht","enabled":true,"conditions":[],"actions":[]}],"scenarios":[{"id":"s1","name":"Trockner","enabled":true,"learned_from":{"suggestion":"surplus:dryer","kind":"surplus_window","at":1700000000}}]}` + +// effectRuleDoc holds r1 from a learned suggestion and r2 made by hand. +const effectRuleDoc = `{"rules":[{"id":"r1","name":"Heizung","enabled":true,"conditions":[],"actions":[],"learned_from":{"suggestion":"switchtime:r1:dev-a","kind":"switch_time","at":1700000000}},{"id":"r2","name":"Licht","enabled":true,"conditions":[],"actions":[]}]}` + +func effectFinding(rule string) autolearn.Finding { + return autolearn.Finding{ID: "effect:" + rule, Kind: "effect", RuleIDs: []string{rule}, Severity: "info"} +} + +func TestMonitoringEffectsKeepsAdoptedEntriesAndNamesThem(t *testing.T) { + doc, err := autolearn.ParseDoc([]byte(monitoringEffectDoc)) + if err != nil { + t.Fatal(err) + } + all := []autolearn.Finding{effectFinding("r1"), effectFinding("r2"), effectFinding("s1"), effectFinding("gone")} + got, names := monitoringEffects(all, doc, true) + if len(got) != 2 || got[0].ID != "effect:r1" || got[1].ID != "effect:s1" { + t.Fatalf("effects = %+v, want r1 and s1", got) + } + if names["r1"] != "Heizung" || names["s1"] != "Trockner" { + t.Errorf("names = %v", names) + } +} + +func TestMonitoringEffectsKeepsAllWhenRulesUnreadable(t *testing.T) { + got, names := monitoringEffects([]autolearn.Finding{effectFinding("r1")}, autolearn.Doc{}, false) + if len(got) != 1 || len(names) != 0 { + t.Fatalf("effects = %+v, names = %v, want the effect without names", got, names) + } +} diff --git a/dashboard/internal/autolearn/applied.go b/dashboard/internal/autolearn/applied.go index 4ffdf40d..9c5e092c 100644 --- a/dashboard/internal/autolearn/applied.go +++ b/dashboard/internal/autolearn/applied.go @@ -7,9 +7,12 @@ import ( ) // AppliedIn reports whether the rule document already holds the condition that -// one of the add_condition fixes of f would add. A finding that was applied -// stops being a suggestion. +// one of the add_condition fixes of f would add, or a rule or scenario was adopted +// from the suggestion f. A finding that was applied stops being a suggestion. func (f Finding) AppliedIn(doc Doc) bool { + if f.ID != "" && adoptedFrom(f.ID, doc) { + return true + } for _, fix := range f.Apply { if FixApplied(fix, doc) { return true @@ -229,3 +232,19 @@ func sameValue(a, b any) bool { } return reflect.DeepEqual(na, nb) } + +// adoptedFrom reports whether a rule or scenario of doc was adopted from the +// suggestion with the ID. +func adoptedFrom(id string, doc Doc) bool { + for _, r := range doc.Rules { + if r.LearnedFrom != nil && r.LearnedFrom.Suggestion == id { + return true + } + } + for _, sc := range doc.Scenarios { + if sc.LearnedFrom != nil && sc.LearnedFrom.Suggestion == id { + return true + } + } + return false +} diff --git a/dashboard/internal/autolearn/applied_test.go b/dashboard/internal/autolearn/applied_test.go index 63590f83..6d757bd1 100644 --- a/dashboard/internal/autolearn/applied_test.go +++ b/dashboard/internal/autolearn/applied_test.go @@ -178,3 +178,24 @@ func TestOpsAppliedMixesRuleAndScenarioGroups(t *testing.T) { t.Fatal("scenario not applied, the group as a whole is not applied") } } + +// TestAppliedInAdoptedScenarioCountsAsApplied checks that a suggestion adopted +// into a scenario is applied, the rule case is covered by the gate test. +func TestAppliedInAdoptedScenarioCountsAsApplied(t *testing.T) { + doc := Doc{Scenarios: []Scenario{{ID: "nulleinspeisung", LearnedFrom: &LearnedFrom{Suggestion: "regulator:nulleinspeisung", Kind: "regulator", At: 1}}}} + if !(Finding{ID: "regulator:nulleinspeisung"}).AppliedIn(doc) { + t.Error("finding adopted into a scenario not counted as applied") + } +} + +// TestAppliedInOtherSuggestionStaysOpen checks that an adopted suggestion with +// another ID does not apply the finding. +func TestAppliedInOtherSuggestionStaysOpen(t *testing.T) { + doc := Doc{Rules: []Rule{{ID: "r1", LearnedFrom: &LearnedFrom{Suggestion: "x:other", Kind: "x", At: 1}}}} + if (Finding{ID: "x:mine"}).AppliedIn(doc) { + t.Error("finding with another ID counted as applied") + } + if (Finding{}).AppliedIn(doc) { + t.Error("finding without ID counted as applied") + } +} diff --git a/dashboard/internal/autolearn/checker.go b/dashboard/internal/autolearn/checker.go index d8f91f55..c8187eae 100644 --- a/dashboard/internal/autolearn/checker.go +++ b/dashboard/internal/autolearn/checker.go @@ -43,6 +43,8 @@ type Checker struct { pv PVSource // replay gives the input of the replay checks, nil until SetReplaySource is called. replay func() *Input + // effects gives the effect findings of the adopted suggestions, nil until SetEffectSource is called. + effects func(now time.Time) []Finding // replayIn is the input built at replayAt, kept for checkerReplayEvery. // replayBuilt is false until the first build. replayIn *Input @@ -110,6 +112,33 @@ func (c *Checker) SetEngineSource(candidates func() []Candidate, reliabilityOn f c.reliabilityOn = reliabilityOn } +// SetEffectSource connects the effect store. Its findings are listed only for +// rules and scenarios that still came from a learned suggestion. +func (c *Checker) SetEffectSource(effects func(now time.Time) []Finding) { + c.mu.Lock() + defer c.mu.Unlock() + c.effects = effects +} + +// effectsLocked returns the effect findings of rules that still came from a +// learned suggestion. Nothing is returned without a source or without a readable document. +func (c *Checker) effectsLocked(now time.Time) []Finding { + if c.effects == nil || !c.docOK { + return nil + } + marks := learnedMarks(c.doc) + var out []Finding + for _, f := range c.effects(now) { + if len(f.RuleIDs) == 0 { + continue + } + if _, ok := marks[f.RuleIDs[0]]; ok { + out = append(out, f) + } + } + return out +} + // 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. @@ -145,7 +174,7 @@ func hasEnabledRule(doc Doc) bool { return false } -// Findings returns the static, observed and reliability findings without the +// Findings returns the static, observed, reliability and effect 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. func (c *Checker) Findings(now time.Time) []Finding { @@ -158,6 +187,7 @@ func (c *Checker) Findings(now time.Time) []Finding { all := StaticFindings(c.doc, c.entityExists) all = append(all, ObservedFindingsWithPV(c.doc, c.obs.Snapshot(), c.season, c.pv, c.replayInputLocked(now), now, c.thresholds)...) all = append(all, c.reliabilityLocked()...) + all = append(all, c.effectsLocked(now)...) sort.SliceStable(all, func(i, j int) bool { ri, rj := severityRank[all[i].Severity], severityRank[all[j].Severity] if ri != rj { diff --git a/dashboard/internal/autolearn/checker_test.go b/dashboard/internal/autolearn/checker_test.go index 2698b105..046bf9a0 100644 --- a/dashboard/internal/autolearn/checker_test.go +++ b/dashboard/internal/autolearn/checker_test.go @@ -470,3 +470,55 @@ func TestNotRuleSendsFindingsWithoutFixToMonitoring(t *testing.T) { } } } + +// effectDoc has two rules: r1 came from a learned suggestion, r2 was made by hand. +const effectDoc = `{"rules":[{"id":"r1","name":"Heizung","enabled":true,"conditions":[],"actions":[],"learned_from":{"suggestion":"switchtime:r1:dev-a","kind":"switch_time","at":1700000000}},{"id":"r2","name":"Licht","enabled":true,"conditions":[],"actions":[]}]}` + +func effectFindingFor(ruleID string) Finding { + return Finding{ID: FindingID("effect", ruleID), Kind: "effect", Group: "check", RuleIDs: []string{ruleID}, Severity: "info", Confidence: "high"} +} + +func checkerWithEffects(t *testing.T, path string) *Checker { + t.Helper() + c := NewChecker(NewObserver(time.UTC), nil, staticRead(effectDoc), nil, path, t.Logf) + c.SetEffectSource(func(time.Time) []Finding { + return []Finding{effectFindingFor("r1"), effectFindingFor("r2")} + }) + return c +} + +func effectIDs(fs []Finding) []string { + var ids []string + for _, f := range fs { + if strings.HasPrefix(f.ID, "effect:") { + ids = append(ids, f.ID) + } + } + return ids +} + +func TestCheckerListsEffectOnlyForLearnedRule(t *testing.T) { + c := checkerWithEffects(t, "") + got := effectIDs(c.Findings(testBase)) + if len(got) != 1 || got[0] != "effect:r1" { + t.Fatalf("effect findings = %v, want [effect:r1]", got) + } +} + +func TestCheckerEffectFindingCanBeIgnored(t *testing.T) { + c := checkerWithEffects(t, filepath.Join(t.TempDir(), "ignored.json")) + if err := c.Ignore("effect:r1"); err != nil { + t.Fatalf("Ignore: %v", err) + } + if got := effectIDs(c.Findings(testBase)); len(got) != 0 { + t.Fatalf("ignored effect still listed: %v", got) + } +} + +func TestCheckerEffectFindingsNeedReadableDocument(t *testing.T) { + c := NewChecker(NewObserver(time.UTC), nil, func() ([]byte, error) { return nil, os.ErrNotExist }, nil, "", t.Logf) + c.SetEffectSource(func(time.Time) []Finding { return []Finding{effectFindingFor("r1")} }) + if got := effectIDs(c.Findings(testBase)); len(got) != 0 { + t.Fatalf("effect findings without a document: %v", got) + } +} diff --git a/dashboard/internal/autolearn/demo.go b/dashboard/internal/autolearn/demo.go index aca1e739..0ab3772c 100644 --- a/dashboard/internal/autolearn/demo.go +++ b/dashboard/internal/autolearn/demo.go @@ -238,7 +238,17 @@ func demoDaysWith(now time.Time, loc *time.Location, rise bool) []DayFile { run = 300 + 60*rng.Float64() } b.emit(start, demoPlugDry, true, OriginHand, "") - b.emit(start+run, demoPlugDry, false, OriginHand, "") + // Die Regel schaltet den Entfeuchter an vier Tagen nach der Laufzeit aus. + // An einem davon schaltet der Nutzer innerhalb der Grenze wieder ein. + if demoEntfeuchterRuleDays[i] { + b.emit(start+run, demoPlugDry, false, OriginRule, demoEntfeuchterRuleID) + if i == demoEntfeuchterReverseDay { + b.emit(start+run+3, demoPlugDry, true, OriginHand, "") + b.emit(start+run+8, demoPlugDry, false, OriginHand, "") + } + } else { + b.emit(start+run, demoPlugDry, false, OriginHand, "") + } // Gewohnheit: die Balkonsteckdose wird an den meisten Tagen um 22:30 von // Hand abgeschaltet, mit etwas Streuung. @@ -312,6 +322,16 @@ const ( demoWasherDevice = "waschmaschine" ) +// demoEntfeuchterRuleID is the adopted rule that switches the dehumidifier off +// after its usual runtime. demoEntfeuchterRuleDays are the day indices on which +// the rule does the switch-off, demoEntfeuchterReverseDay is the one of them that +// the user reverses by hand within the time limit. +const demoEntfeuchterRuleID = "regel_entfeuchter_laufzeit" + +var demoEntfeuchterRuleDays = map[int]bool{4: true, 10: true, 12: true, 16: true} + +const demoEntfeuchterReverseDay = 16 + // demoCloudyDays sind die Tagesindizes mit bedecktem Himmel. var demoCloudyDays = map[int]bool{4: true, 11: true, 18: true} @@ -1130,3 +1150,101 @@ func writeNewFile(path string, data []byte) error { } return os.WriteFile(path, data, 0o644) } + +// demoEffectSpec is the measured effect the demo shows for one adopted rule. +type demoEffectSpec struct { + unit, group, device string + before []float64 + values map[string]float64 + series []float64 +} + +// demoEffects are the adopted rules and scenarios of the demo, by ID, with the +// measure and the season drift each shows. An empty unit is a suggestion without a +// measure (count only). A spec without before has no baseline yet. +var demoEffects = map[string]demoEffectSpec{ + "regel_entfeuchter_laufzeit": { + unit: effectUnitKWh, group: "habit", device: demoPlugDry, + before: []float64{20, 21, 19, 20}, + }, + "regel_balkon_gelernt_aus": { + unit: effectUnitActions, group: "habit", device: demoPlugBalkon, + before: []float64{9, 9, 9, 9}, + values: map[string]float64{"time": 1395}, + series: []float64{-1, -2, -3, -4, -4.5}, + }, + // Adopted without a baseline: only the overrides count. + "regel_wasch_ueberschuss_aus": { + unit: effectUnitActions, group: "habit", device: demoWasherDevice, + }, + // The scenario has no measure, only its count. + "nulleinspeisung": {}, + // Measured in hand switches: about thirty a week before, about a third since. + "regel_entfeuchter_folgt_keller": { + unit: effectUnitActions, group: "habit", device: demoPlugDry, + before: []float64{30, 31, 29, 30}, + }, + // The away standby drifts: the kWh per day sat at 0,8 when adopted, now it is 0,5. + "regel_wp_haus_ruhig": { + unit: effectUnitKWh, group: "habit", device: demoHeatPump, + values: map[string]float64{"kwh_day": 0.8}, + series: []float64{-1.5, -2, -2.5, -3, -3.5, -4, -4.5}, + }, + // Adopted two days ago: the effect waits for a full week. + "regel_wp_ueberschuss_hoch": { + unit: effectUnitKWh, group: effectGroupEnergy, device: demoHeatPump, + before: []float64{4, 4, 4, 4}, + }, + // The threshold drifts: the soll sat at 500 W when adopted, now it is about 1850 W. + "regel_wasch_ueberschuss_an": { + unit: effectUnitKWh, group: effectGroupEnergy, device: demoWasherDevice, + before: []float64{9, 9, 9, 9}, + values: map[string]float64{"soll": 500}, + series: []float64{1, 1.5, 2, 2.5}, + }, + // The surplus window drifts: it was 60 quarters from 08:00 when adopted, now it is about 8 to 21. + "szene_trockner_ueberschuss": { + unit: effectUnitKWh, group: effectGroupEnergy, device: demoDryer, + values: map[string]float64{"start": 480, "window_quarters": 60, "on_w": 3000}, + series: []float64{-2, -2.5, -3, -3.5}, + }, +} + +// SeedDemoEffects writes the effect store of the demo to path, one entry per +// adopted demo rule or scenario of rules with a learned_from time. A file that +// exists stays untouched. The season drift series ends yesterday, as the nightly +// round left it. +func SeedDemoEffects(path string, rules []byte, now time.Time) error { + if demoFileExists(path) { + return nil + } + doc, err := ParseDoc(rules) + if err != nil { + return err + } + store := LoadEffectStore(path, nil) + yesterday := now.AddDate(0, 0, -1).Format(dayLayout) + for id, lf := range learnedMarks(doc) { + spec, ok := demoEffects[id] + if !ok || lf.At <= 0 { + continue + } + e := effectEntry{ + Rule: id, + Suggestion: lf.Suggestion, + Kind: lf.Kind, + At: lf.At, + Unit: spec.unit, + Group: spec.group, + Device: spec.device, + Before: append([]float64(nil), spec.before...), + Values: spec.values, + } + if spec.series != nil { + e.Series = append([]float64(nil), spec.series...) + e.SeriesDay = yesterday + } + store.entries[id] = e + } + return store.Save() +} diff --git a/dashboard/internal/autolearn/demo_test.go b/dashboard/internal/autolearn/demo_test.go index aa0ee7c2..aaa18bf8 100644 --- a/dashboard/internal/autolearn/demo_test.go +++ b/dashboard/internal/autolearn/demo_test.go @@ -181,6 +181,13 @@ func learnedEntriesOf(vals []Value) map[string]LearnedEntry { // demoEngineRun seeds the demo days into dir and runs the real engine over them // at the daily slot, the way the dashboard does at 03:30. func demoEngineRun(t *testing.T, dir string, now time.Time, loc *time.Location) *Engine { + t.Helper() + return demoEngineRunAt(t, dir, now, loc, learnrec.LimitsFor(learnrec.LevelBalanced, 4)) +} + +// demoEngineRunAt is demoEngineRun with the learning limits given, so a test can +// run the engine with the limits of the running demo. +func demoEngineRunAt(t *testing.T, dir string, now time.Time, loc *time.Location, lim learnrec.Limits) *Engine { t.Helper() if err := SeedDemo(dir, now, loc); err != nil { t.Fatalf("SeedDemo: %v", err) @@ -191,7 +198,7 @@ func demoEngineRun(t *testing.T, dir string, now time.Time, loc *time.Location) e := NewEngine(days, NewReactions(), func() ([]byte, error) { return raw, nil }, func() map[string]DeviceInfo { return devices }, - func() learnrec.Limits { return learnrec.LimitsFor(learnrec.LevelBalanced, 4) }, + func() learnrec.Limits { return lim }, loc) for _, d := range []Detector{SwitchTimeDetector, RuntimeDetector, CouplingDetector, OverriddenDetector, AwayStandbyDetector, TemperatureDetector, LearnSwitchTimeDetector, LearnRuntimeDetector, LearnDayBoundsDetector, LearnHouseStateDetector, @@ -984,3 +991,217 @@ func TestDemoForecastFillsFourteenDays(t *testing.T) { t.Fatal("demo forecast should beat the median") } } + +// demoStampLearned turns learned_from.at of every rule and scenario of the raw +// rule document below 1000 into the time that many days before now, the way the +// demo work copy is stamped. +func demoStampLearned(t *testing.T, raw []byte, now time.Time) []byte { + t.Helper() + var doc map[string]any + if err := json.Unmarshal(raw, &doc); err != nil { + t.Fatalf("parse demo rules: %v", err) + } + for _, key := range []string{"rules", "scenarios"} { + list, _ := doc[key].([]any) + for _, r := range list { + rule, _ := r.(map[string]any) + lf, ok := rule["learned_from"].(map[string]any) + if !ok { + continue + } + if days, ok := lf["at"].(float64); ok && days < 1000 { + lf["at"] = float64(now.AddDate(0, 0, -int(days)).Unix()) + } + } + } + out, err := json.Marshal(doc) + if err != nil { + t.Fatalf("encode demo rules: %v", err) + } + return out +} + +// TestDemoSeedEffectsShowEffectAndDrift checks that the demo shows the effect of +// the adopted runtime rule and a season drift of the adopted switch time. +func TestDemoSeedEffectsShowEffectAndDrift(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 20, 9, 0, 0, 0, loc) + raw := demoStampLearned(t, demoRulesRaw(t), now) + in := demoSeedInputFor(t, t.TempDir(), now, loc) + doc, err := ParseDoc(raw) + if err != nil { + t.Fatalf("parse stamped rules: %v", err) + } + in.Doc = doc + + path := filepath.Join(t.TempDir(), "effects.json") + if err := SeedDemoEffects(path, raw, now); err != nil { + t.Fatalf("SeedDemoEffects: %v", err) + } + store := LoadEffectStore(path, noLog) + season := LoadSeasonStore("", noLog) + for _, w := range DemoSeason(now) { + season.Put(w) + } + store.Nightly(now, in.Days, season, demoRunPerDevice(in, SwitchTimeDetector)) + + var effectOK, drift bool + for _, f := range store.Findings(now) { + switch { + case f.Kind == "effect" && containsString(f.RuleIDs, "regel_entfeuchter_laufzeit") && f.Summary.Code == "effect.ok": + effectOK = true + case f.Kind == "season_shift" && containsString(f.RuleIDs, "regel_balkon_gelernt_aus") && f.Summary.Code == "season_shift.switch_time": + drift = true + } + } + if !effectOK { + t.Errorf("no effect.ok for regel_entfeuchter_laufzeit, findings = %v", store.Findings(now)) + } + if !drift { + t.Errorf("no season_shift.switch_time for regel_balkon_gelernt_aus, findings = %v", store.Findings(now)) + } +} + +// TestDemoSeedEffectsKeepsExistingFile checks that a file that exists stays as it is. +func TestDemoSeedEffectsKeepsExistingFile(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 20, 9, 0, 0, 0, loc) + raw := demoStampLearned(t, demoRulesRaw(t), now) + path := filepath.Join(t.TempDir(), "effects.json") + if err := os.WriteFile(path, []byte("keep"), 0o644); err != nil { + t.Fatal(err) + } + if err := SeedDemoEffects(path, raw, now); err != nil { + t.Fatalf("SeedDemoEffects: %v", err) + } + got, err := os.ReadFile(path) + if err != nil || string(got) != "keep" { + t.Fatalf("existing effects file changed: %q, %v", got, err) + } +} + +// demoFindingFor returns the finding of the rule with the kind, false when missing. +func demoFindingFor(findings []Finding, rule, kind string) (Finding, bool) { + for _, f := range findings { + if f.Kind == kind && containsString(f.RuleIDs, rule) { + return f, true + } + } + return Finding{}, false +} + +// TestDemoSeedShowsEveryEffectState checks that the demo shows every state of the +// effect proof and every kind of season drift for the adopted rules, with the +// engine at the eco limits of the running demo, on each day of a fixed week. +func TestDemoSeedShowsEveryEffectState(t *testing.T) { + loc := berlinLoc(t) + eco := learnrec.LimitsFor(learnrec.LevelEco, 16) + for day := 24; day <= 30; day++ { + now := time.Date(2026, 11, day, 9, 0, 0, 0, loc) + raw := demoStampLearned(t, demoRulesRaw(t), now) + in := demoSeedInputFor(t, t.TempDir(), now, loc) + path := filepath.Join(t.TempDir(), "effects.json") + if err := SeedDemoEffects(path, raw, now); err != nil { + t.Fatalf("SeedDemoEffects: %v", err) + } + store := LoadEffectStore(path, noLog) + season := LoadSeasonStore("", noLog) + for _, w := range DemoSeason(now) { + season.Put(w) + } + cands := demoEngineRunAt(t, t.TempDir(), now, loc, eco).Candidates() + store.Nightly(now, in.Days, season, cands) + findings := store.Findings(now) + name := now.Format("2006-01-02") + + want := []struct{ rule, kind, code string }{ + {"regel_entfeuchter_laufzeit", "effect", "effect.ok"}, + {"regel_balkon_gelernt_aus", "season_shift", "season_shift.switch_time"}, + {"regel_wp_haus_ruhig", "effect", "effect.no_baseline"}, + {"regel_wp_haus_ruhig", "season_shift", "season_shift.away_standby"}, + {"regel_wasch_ueberschuss_aus", "effect", "effect.no_baseline"}, + {"regel_wasch_ueberschuss_an", "effect", "effect.ok"}, + {"regel_wasch_ueberschuss_an", "season_shift", "season_shift.threshold"}, + {"regel_wp_ueberschuss_hoch", "effect", "effect.waiting"}, + {"szene_trockner_ueberschuss", "effect", "effect.no_baseline"}, + {"szene_trockner_ueberschuss", "season_shift", "season_shift.surplus_window"}, + {"nulleinspeisung", "effect", "effect.count_only"}, + {"regel_entfeuchter_folgt_keller", "effect", "effect.ok"}, + } + for _, w := range want { + f, ok := demoFindingFor(findings, w.rule, w.kind) + if !ok { + t.Errorf("%s: no %s finding for %s, findings = %v, candidates = %v", name, w.kind, w.rule, findings, ids(cands)) + continue + } + if f.Summary.Code != w.code { + t.Errorf("%s: %s %s code = %q, want %q", name, w.rule, w.kind, f.Summary.Code, w.code) + } + } + + // The balcony plug has a baseline, so its effect is measured or too small to tell. + bal, ok := demoFindingFor(findings, "regel_balkon_gelernt_aus", "effect") + if !ok || (bal.Summary.Code != "effect.ok" && bal.Summary.Code != "effect.not_measurable") { + t.Errorf("%s: regel_balkon_gelernt_aus effect = %+v, want effect.ok or effect.not_measurable", name, bal.Summary) + } + + // The prior-year weeks carry load, so the dehumidifier effect is season + // corrected and sure. Actions stay an estimate. + if f, ok := demoFindingFor(findings, "regel_entfeuchter_laufzeit", "effect"); ok && f.Confidence != "high" { + t.Errorf("%s: dehumidifier confidence = %q, want high", name, f.Confidence) + } + if bal, ok := demoFindingFor(findings, "regel_balkon_gelernt_aus", "effect"); ok && bal.Confidence != "estimate" { + t.Errorf("%s: balcony confidence = %q, want estimate", name, bal.Confidence) + } + + // One effect counts hand switches, so the demo shows that unit with figures. + // Without a season figure for actions it stays an estimate. + if f, ok := demoFindingFor(findings, "regel_entfeuchter_folgt_keller", "effect"); ok { + if got := f.Summary.Params["unit"]; got != effectUnitActions || f.Confidence != "estimate" { + t.Errorf("%s: follow rule unit = %v, confidence = %q, want %q and estimate", name, got, f.Confidence, effectUnitActions) + } + } + + // The surplus templates of the assistant create a scenario, so the adopted + // window suggestion of the demo is one and the drift fix replaces it. + adopted, err := ParseDoc(raw) + if err != nil { + t.Fatalf("%s: parse stamped rules: %v", name, err) + } + var scenario bool + for _, sc := range adopted.Scenarios { + scenario = scenario || (sc.LearnedFrom != nil && sc.LearnedFrom.Kind == "surplus_window") + } + for _, r := range adopted.Rules { + if r.LearnedFrom != nil && r.LearnedFrom.Kind == "surplus_window" { + t.Errorf("%s: rule %s is adopted from a window suggestion, the assistant creates a scenario", name, r.ID) + } + } + if !scenario { + t.Errorf("%s: no scenario adopted from a window suggestion", name) + } + + // The threshold rule has a measured effect with the grid share that Monitoring lists. + var measured bool + for _, f := range store.Measured(now) { + if f.ID == "effect:regel_wasch_ueberschuss_an" && f.Summary.Code == "effect.ok" { + measured = true + } + } + if !measured { + t.Errorf("%s: no measured effect.ok for regel_wasch_ueberschuss_an", name) + } + + // The dehumidifier rule shows one reversal among four switch-offs. + ent, ok := demoFindingFor(findings, "regel_entfeuchter_laufzeit", "effect") + if !ok { + t.Fatalf("%s: no effect finding for regel_entfeuchter_laufzeit", name) + } + if got, _ := ent.Summary.Params["overridden"].(int); got != 1 { + t.Errorf("%s: overridden = %v, want 1", name, ent.Summary.Params["overridden"]) + } + if got, _ := ent.Summary.Params["fired"].(int); got != 4 { + t.Errorf("%s: fired = %v, want 4", name, ent.Summary.Params["fired"]) + } + } +} diff --git a/dashboard/internal/autolearn/detect_overridden.go b/dashboard/internal/autolearn/detect_overridden.go index 9cbc1016..0992bf15 100644 --- a/dashboard/internal/autolearn/detect_overridden.go +++ b/dashboard/internal/autolearn/detect_overridden.go @@ -213,6 +213,64 @@ func overrideFirst(manual []overrideManual, from int64, on bool, sec float64) (i return 0, false } +// overrideRuleIdx returns the positions in sw of the switches of the rule. +func overrideRuleIdx(sw []overrideSwitch, ruleID string) []int { + var idx []int + for i, s := range sw { + if s.rule == ruleID { + idx = append(idx, i) + } + } + return idx +} + +// overrideRuleLimit is the time limit of a rule whose switches sit at the +// positions idx of sw: the valley of the logarithmic distances to the reversal. +func overrideRuleLimit(sw []overrideSwitch, manual []overrideManual, idx []int) float64 { + dist := overrideDistances(sw, manual) + var logs []float64 + for _, i := range idx { + if dist[i] >= 0 { + logs = append(logs, math.Log(math.Max(float64(dist[i]), 1))) + } + } + return overriddenDeadline(logs) +} + +// OverrideCount counts the switches of the rule at or after since (fired) and +// how many of them the user reversed by hand or from outside within the time +// limit the detector learns for the rule (overridden). The limit and the counts +// are per device, the rule's switches of all devices are summed. +func OverrideCount(days []DayFile, ruleID string, since time.Time) (overridden, fired int) { + if ruleID == "" { + return 0, 0 + } + devices := map[string]bool{} + for i := range days { + for _, e := range days[i].Events { + if Origin(e.Origin) == OriginRule && e.Rule == ruleID { + devices[e.Device] = true + } + } + } + from := since.Unix() + for device := range devices { + sw, manual := overrideSwitches(days, device) + idx := overrideRuleIdx(sw, ruleID) + limit := overrideRuleLimit(sw, manual, idx) + for _, i := range idx { + if sw[i].at < from { + continue + } + fired++ + if _, ok := overrideFirst(manual, sw[i].at, !sw[i].on, limit); ok { + overridden++ + } + } + } + return overridden, fired +} + // overriddenDeadline learns the time limit from the valley of the logarithmic // distances. Without a valley it is overriddenFallbackSec. func overriddenDeadline(dists []float64) float64 { @@ -226,23 +284,12 @@ func overriddenDeadline(dists []float64) float64 { // overriddenCandidate builds the candidate of one rule, or reports false when // the rule fails the gates. func overriddenCandidate(device string, in *Input, rule Rule, sw []overrideSwitch, manual []overrideManual, loc *time.Location) (Candidate, bool) { - dist := overrideDistances(sw, manual) - var idx []int - var logs []float64 - for i, s := range sw { - if s.rule != rule.ID { - continue - } - idx = append(idx, i) - if dist[i] >= 0 { - logs = append(logs, math.Log(math.Max(float64(dist[i]), 1))) - } - } + idx := overrideRuleIdx(sw, rule.ID) n := len(idx) if n < overriddenMinCases { return Candidate{}, false } - limit := overriddenDeadline(logs) + limit := overrideRuleLimit(sw, manual, idx) cases := make([]overrideCase, n) hits := 0 diff --git a/dashboard/internal/autolearn/detect_surplus.go b/dashboard/internal/autolearn/detect_surplus.go index 49842517..761859f5 100644 --- a/dashboard/internal/autolearn/detect_surplus.go +++ b/dashboard/internal/autolearn/detect_surplus.go @@ -397,7 +397,8 @@ func longestRun(xs *[dayQuarters]float64, threshold float64) int { // 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. +// device entities. The rule adopted from this very window suggestion does not +// count, so the suggestion keeps coming back and its season drift can be seen. func surWinHasRule(in *Input, device string) bool { entities := in.Devices[device].Entities if len(entities) == 0 { @@ -408,7 +409,7 @@ func surWinHasRule(in *Input, device string) bool { own[e] = true } for _, r := range in.Doc.Rules { - if !r.Enabled || !surWinRuleOnSurplus(r) { + if !r.Enabled || !surWinRuleOnSurplus(r) || surWinAdopted(r, device) { continue } for _, a := range r.Actions { @@ -420,6 +421,12 @@ func surWinHasRule(in *Input, device string) bool { return false } +// surWinAdopted reports whether the rule was adopted from the window suggestion +// of the device. +func surWinAdopted(r Rule, device string) bool { + return r.LearnedFrom != nil && r.LearnedFrom.Suggestion == "surplus:"+device +} + // surWinRuleOnSurplus reports whether a rule has a surplus condition. func surWinRuleOnSurplus(r Rule) bool { for _, c := range r.Conditions { diff --git a/dashboard/internal/autolearn/detect_surplus_test.go b/dashboard/internal/autolearn/detect_surplus_test.go index 1bbdc5f1..7dbbf170 100644 --- a/dashboard/internal/autolearn/detect_surplus_test.go +++ b/dashboard/internal/autolearn/detect_surplus_test.go @@ -206,3 +206,42 @@ func TestSurplusWindowNeedsLearnedPower(t *testing.T) { func sunPosForTest(day time.Time, q int) (float64, float64) { return sun.Position(shadeQuarterTime(day, q), shadeSite.Lat, shadeSite.Lon) } + +// surplusWinAdoptedRule is the surplus rule the window suggestion of the plug +// was adopted into. +func surplusWinAdoptedRule(id string) Rule { + return Rule{ + ID: id, + Enabled: true, + LearnedFrom: &LearnedFrom{Suggestion: "surplus:plug", Kind: "surplus_window", At: 1}, + Conditions: []Condition{{Type: "balance_threshold", Field: "grid_export", + Comparison: "above", Threshold: 1000}}, + Actions: []Action{{Type: "switch", EntityID: "switch.plug"}}, + } +} + +// TestSurplusWindowAdoptedRuleKeepsCandidate checks that the window suggestion +// keeps coming back after its own rule was adopted, so its season drift can be +// measured. +func TestSurplusWindowAdoptedRuleKeepsCandidate(t *testing.T) { + loc := berlinLoc(t) + in := surplusWinInput(t, surplusWinDays(loc, surplusWinExport)) + in.Doc.Rules = []Rule{surplusWinAdoptedRule("adopted")} + got := surplusWinRun(t, in) + if len(got) != 1 || got[0].Finding.ID != "surplus:plug" { + t.Fatalf("candidates = %v, want one surplus:plug with an adopted rule", got) + } +} + +// TestSurplusWindowAdoptedAndHandMadeRuleSilences checks that a hand made surplus +// rule still silences the detector next to the adopted one. +func TestSurplusWindowAdoptedAndHandMadeRuleSilences(t *testing.T) { + loc := berlinLoc(t) + in := surplusWinInput(t, surplusWinDays(loc, surplusWinExport)) + hand := surplusWinAdoptedRule("hand") + hand.LearnedFrom = nil + in.Doc.Rules = []Rule{surplusWinAdoptedRule("adopted"), hand} + if got := surplusWinRun(t, in); len(got) != 0 { + t.Errorf("candidates = %d, want 0 with a hand made surplus rule next to the adopted one", len(got)) + } +} diff --git a/dashboard/internal/autolearn/effect.go b/dashboard/internal/autolearn/effect.go new file mode 100644 index 00000000..0bad967c --- /dev/null +++ b/dashboard/internal/autolearn/effect.go @@ -0,0 +1,279 @@ +package autolearn + +import ( + "math" + "sort" + "time" +) + +// Units of Benefit.Unit that have a measured effect (spec 15.7). The group +// energy selects the grid share of the device energy. +const ( + effectUnitActions = "actions_week" + effectUnitKWh = "kwh_week" + effectGroupEnergy = "energy" +) + +// Status values of an EffectResult. +const ( + // EffectStatusOK means the effect is computed from a baseline and at least one full week since. + EffectStatusOK = "ok" + // EffectStatusWaiting means no full ISO week lies after the adoption yet. + EffectStatusWaiting = "waiting" + // EffectStatusNoBaseline means the baseline is missing, so there is no proof. + EffectStatusNoBaseline = "no_baseline" +) + +const ( + // effectBaseDays is the number of day files a baseline week needs. + effectBaseDays = 5 + // effectMinBaseline is the number of baseline weeks the comparison needs. + effectMinBaseline = 2 + // effectBaselineWeeks is the number of full weeks before the adoption. + effectBaselineWeeks = 4 + // effectSinceWeeks is the largest number of full weeks since the adoption that is shown. + effectSinceWeeks = 8 +) + +// EffectResult is the measured effect of an adopted suggestion. Before is the +// median of the baseline weeks. Since and Expected hold per full week since the +// adoption the measure and the expected measure without the change. Low and High +// span the effect Since minus Expected over those weeks. Measurable is set when +// the span does not contain zero. Estimate is set when the expectation is not +// corrected by the prior year. Overridden and Fired are filled by the caller +// with OverrideCount. +type EffectResult struct { + Unit string + Before float64 + Since []float64 + Expected []float64 + Low, High float64 + Measurable bool + Estimate bool + Overridden int + Fired int + Weeks int + Status string +} + +// effectWeek is one full ISO week (seven day files) with its measure. pv is the +// PV of the week in kWh, kept for the season ratio. +type effectWeek struct { + mon time.Time + days int + value float64 + pv float64 +} + +// EffectMetric returns the measure of the device per ISO week with at least +// effectBaseDays day files, oldest first. A week with fewer than seven day files +// is scaled to a week by the mean per day. The measure follows the unit: actions_week counts the +// hand and external switches, kwh_week the device energy, or in the group +// energy its grid share. ok is false for a unit without a measure. +func EffectMetric(unit, group string, device string, days []DayFile) (perWeek []float64, ok bool) { + if !effectUnitKnown(unit) { + return nil, false + } + for _, w := range effectWeeks(days, unit, group, device, effectBaseDays) { + perWeek = append(perWeek, w.value) + } + return perWeek, true +} + +// ComputeEffect measures the effect of a change made at at. before holds the +// measures of the baseline weeks, the full weeks before at. The expectation of +// each week since at is the baseline times the season ratio r_i (spec 15.7), +// and the effect of the week is its measure minus that expectation. +func ComputeEffect(at time.Time, unit, group, device string, before []float64, days []DayFile, season *SeasonStore, loc *time.Location) EffectResult { + if loc == nil { + loc = time.Local + } + res := EffectResult{Unit: unit, Status: EffectStatusNoBaseline} + if !effectUnitKnown(unit) || len(before) < effectMinBaseline { + return res + } + res.Before = Median(before) + + atMon, _ := isoWeekMonday(isoWeekKey(at.In(loc))) + var since, base []effectWeek + for _, w := range effectWeeks(days, unit, group, device, effectBaseDays) { + switch { + case w.mon.After(atMon) && w.days == 7: + since = append(since, w) + case w.mon.Before(atMon): + base = append(base, w) + } + } + if len(base) > effectBaselineWeeks { + base = base[len(base)-effectBaselineWeeks:] + } + res.Status = EffectStatusWaiting + if len(since) == 0 { + return res + } + if len(since) > effectSinceWeeks { + since = since[len(since)-effectSinceWeeks:] + } + + // The prior-year figure of the baseline weeks is the denominator of every + // season ratio. Without it, the ratio falls back to this year's PV. + var baseSeason []float64 + for k := 1; k <= effectBaselineWeeks; k++ { + if f, ok := effectPriorFigure(season, atMon.AddDate(0, 0, -7*k), unit, group); ok { + baseSeason = append(baseSeason, f) + } + } + var basePV []float64 + for _, w := range base { + basePV = append(basePV, w.pv) + } + denom := Median(baseSeason) + ratio := func(w effectWeek) (r float64, exact bool) { + if len(baseSeason) > 0 { + if f, ok := effectPriorFigure(season, w.mon, unit, group); ok { + return f / denom, true + } + } + if unit == effectUnitKWh && group == effectGroupEnergy && w.pv > 0 && len(basePV) > 0 { + if pv := Median(basePV); pv > 0 { + return pv / w.pv, false + } + } + return 1, false + } + + estimate := false + for i, w := range since { + r, exact := ratio(w) + if !exact { + estimate = true + } + exp := res.Before * r + res.Since = append(res.Since, w.value) + res.Expected = append(res.Expected, exp) + eff := w.value - exp + if i == 0 || eff < res.Low { + res.Low = eff + } + if i == 0 || eff > res.High { + res.High = eff + } + } + res.Measurable = res.Low > 0 || res.High < 0 + res.Estimate = estimate + res.Weeks = len(since) + res.Status = EffectStatusOK + return res +} + +// effectUnitKnown reports whether the unit has a measure. +func effectUnitKnown(unit string) bool { + return unit == effectUnitActions || unit == effectUnitKWh +} + +// effectWeeks sums the ISO weeks of the day files that hold at least minDays +// day files, oldest first. The sums are scaled to seven days by the mean per day, +// so a full week is unchanged. A day counts once even when it appears twice. +func effectWeeks(days []DayFile, unit, group, device string, minDays int) []effectWeek { + type acc struct { + mon time.Time + days int + value float64 + pv float64 + } + byKey := map[string]*acc{} + seen := map[string]bool{} + for i := range days { + d := &days[i] + t, err := time.Parse(dayLayout, d.Day) + if err != nil || seen[d.Day] { + continue + } + seen[d.Day] = true + key := isoWeekKey(t) + a := byKey[key] + if a == nil { + a = &acc{mon: t.AddDate(0, 0, -((int(t.Weekday()) + 6) % 7))} + byKey[key] = a + } + a.days++ + a.value += effectDayValue(d, unit, group, device) + for q := 0; q < dayQuarters; q++ { + a.pv += float64(d.Site.PV[q]) * baseWattQuarterKWh + } + } + var out []effectWeek + for _, a := range byKey { + if a.days < minDays { + continue + } + scale := 7 / float64(a.days) + out = append(out, effectWeek{mon: a.mon, days: a.days, value: a.value * scale, pv: a.pv * scale}) + } + sort.Slice(out, func(i, j int) bool { return out[i].mon.Before(out[j].mon) }) + return out +} + +// effectDayValue is the measure of the device on one day for the unit. +func effectDayValue(d *DayFile, unit, group, device string) float64 { + dd := d.Devices[device] + if dd == nil { + return 0 + } + var sum float64 + switch { + case unit == effectUnitActions: + for q := 0; q < dayQuarters; q++ { + sum += float64(dd.Hand[q]) + float64(dd.Ext[q]) + } + case unit == effectUnitKWh && group == effectGroupEnergy: + // Per quarter hour the grid share is the smaller of the device energy and + // the grid import of the quarter (W over 0.25 h, in Wh). + for q := 0; q < dayQuarters; q++ { + sum += math.Min(float64(dd.Wh[q]), float64(d.Site.GridImport[q])*0.25) + } + sum /= 1000 + case unit == effectUnitKWh: + for q := 0; q < dayQuarters; q++ { + sum += float64(dd.Wh[q]) + } + sum /= 1000 + } + return sum +} + +// effectPriorFigure is the median season figure of the weeks of the same +// calendar week in the years before mon. ok is false without such a figure. +func effectPriorFigure(season *SeasonStore, mon time.Time, unit, group string) (float64, bool) { + if season == nil { + return 0, false + } + _, wk := mon.ISOWeek() + var vals []float64 + for _, w := range season.Same(mon, wk, seasonYears) { + if v := effectSeasonFigure(w, unit, group); v > 0 { + vals = append(vals, v) + } + } + if len(vals) == 0 { + return 0, false + } + return Median(vals), true +} + +// effectSeasonFigure is the season figure of a stored week for the unit: the +// house load for device energy, the inverse PV for the grid share. Actions +// have none, so the figure is zero. +func effectSeasonFigure(w Week, unit, group string) float64 { + switch { + case unit == effectUnitActions: + return 0 + case group == effectGroupEnergy: + if w.PVKWh > 0 { + return 1 / w.PVKWh + } + return 0 + default: + return w.LoadKWh + } +} diff --git a/dashboard/internal/autolearn/effect_store.go b/dashboard/internal/autolearn/effect_store.go new file mode 100644 index 00000000..57727d4c --- /dev/null +++ b/dashboard/internal/autolearn/effect_store.go @@ -0,0 +1,559 @@ +package autolearn + +import ( + "encoding/json" + "log" + "math" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/energystats" +) + +// effectListSpan is how long Monitoring lists the effect of an adopted suggestion. +const effectListSpan = 8 * 7 * 24 * time.Hour + +// effectEntry is the measured effect of one rule or scenario that came from a +// learned suggestion. Before holds the baseline measures, Values the numbers +// shown with the suggestion, Result the last computed effect. +type effectEntry struct { + Rule string `json:"rule"` + Suggestion string `json:"suggestion"` + Kind string `json:"kind"` + At int64 `json:"at"` + Unit string `json:"unit,omitempty"` + Group string `json:"group,omitempty"` + Device string `json:"device,omitempty"` + Before []float64 `json:"before,omitempty"` + Values map[string]float64 `json:"values,omitempty"` + Result EffectResult `json:"result"` + // Series holds the nightly season drift in standard deviations, one value + // per day, the last at SeriesDay. Drift is the season shift finding, nil + // when the adopted suggestion does not drift. + Series []float64 `json:"series,omitempty"` + SeriesDay string `json:"series_day,omitempty"` + Drift *Finding `json:"drift,omitempty"` +} + +// effectFile is the content of the effect store file. +type effectFile struct { + Entries []effectEntry `json:"entries"` +} + +// EffectStore keeps one entry per rule or scenario with LearnedFrom, keyed by +// its ID. It is safe for concurrent use. +type EffectStore struct { + mu sync.Mutex + path string + logf func(string, ...any) + entries map[string]effectEntry +} + +// LoadEffectStore reads the store from path. A missing file means an empty +// store. A damaged file is logged and starts empty. +func LoadEffectStore(path string, logf func(string, ...any)) *EffectStore { + if logf == nil { + logf = log.Printf + } + s := &EffectStore{path: path, logf: logf, entries: map[string]effectEntry{}} + data, err := os.ReadFile(path) + if err != nil { + if !os.IsNotExist(err) { + logf("effect store: read %s: %v", path, err) + } + return s + } + var f effectFile + if err := json.Unmarshal(data, &f); err != nil { + logf("effect store: %s is damaged, starting empty: %v", path, err) + return s + } + for _, e := range f.Entries { + s.entries[e.Rule] = e + } + return s +} + +// Save writes the store atomically. Without a path nothing is written. +func (s *EffectStore) Save() error { + s.mu.Lock() + defer s.mu.Unlock() + return s.saveLocked() +} + +// saveLocked writes the store. The caller holds s.mu. +func (s *EffectStore) saveLocked() error { + if s.path == "" { + return nil + } + data, err := json.Marshal(effectFile{Entries: s.sortedLocked()}) + if err != nil { + return err + } + return energystats.WriteFileAtomic(filepath.Dir(s.path), s.path, data) +} + +// Reset drops all entries and removes the file. A missing file is no error. +func (s *EffectStore) Reset() error { + s.mu.Lock() + defer s.mu.Unlock() + s.entries = map[string]effectEntry{} + if s.path == "" { + return nil + } + if err := os.Remove(s.path); err != nil && !os.IsNotExist(err) { + return err + } + return nil +} + +// Len is the number of entries. +func (s *EffectStore) Len() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.entries) +} + +// NeedsDays tells whether Sync would take a new entry for the doc, so the day +// files of the baseline are needed. +func (s *EffectStore) NeedsDays(doc Doc) bool { + s.mu.Lock() + defer s.mu.Unlock() + for id, lf := range learnedMarks(doc) { + e, ok := s.entries[id] + if !ok || e.At != lf.At || e.Suggestion != lf.Suggestion { + return true + } + } + return false +} + +// Sync brings the entries in line with the doc. Entries of rules or scenarios +// without LearnedFrom are removed. A new entry takes its baseline from the day +// files before the adoption week. An unchanged entry is kept as it was first +// seen. The store is saved when the set changed. added tells whether an entry +// was taken. +func (s *EffectStore) Sync(doc Doc, now time.Time, days []DayFile, shown map[string]Shown, findingsByID map[string]Finding) (added bool) { + marks := learnedMarks(doc) + s.mu.Lock() + defer s.mu.Unlock() + changed := false + for id := range s.entries { + if _, ok := marks[id]; !ok { + delete(s.entries, id) + changed = true + } + } + for id, lf := range marks { + e, ok := s.entries[id] + if ok && e.At == lf.At && e.Suggestion == lf.Suggestion { + continue + } + s.entries[id] = newEffectEntry(id, lf, now, days, shown, findingsByID) + added = true + changed = true + } + if changed { + if err := s.saveLocked(); err != nil { + s.logf("effect store: save: %v", err) + } + } + return added +} + +// Nightly computes the effect of every entry from the day files and the season +// store, then saves the store. The season drift advances with the current +// candidates. A nil cands leaves the drift of every entry untouched, so a round +// that has no candidates yet does not clear it. An empty, non-nil cands pauses +// the drift: the series stays, but no finding is shown. +func (s *EffectStore) Nightly(now time.Time, days []DayFile, season *SeasonStore, cands []Candidate) { + s.mu.Lock() + defer s.mu.Unlock() + loc := now.Location() + for id, e := range s.entries { + at := time.Unix(e.At, 0) + res := ComputeEffect(at, e.Unit, e.Group, e.Device, e.Before, days, season, loc) + res.Overridden, res.Fired = OverrideCount(days, id, at) + e.Result = res + if cands != nil { + shiftStep(&e, now, cands) + } + s.entries[id] = e + } + if err := s.saveLocked(); err != nil { + s.logf("effect store: save: %v", err) + } +} + +// Findings returns one check finding per entry with a computed effect, and the +// season shift finding of every entry that drifts. Sorted by rule ID, the +// effect finding first. +func (s *EffectStore) Findings(now time.Time) []Finding { + s.mu.Lock() + defer s.mu.Unlock() + out := []Finding{} + for _, e := range s.sortedLocked() { + if e.Result.Status != "" { + out = append(out, effectFinding(e, FindingID("effect", e.Rule), "check", now.Location())) + } + if e.Drift != nil { + out = append(out, *e.Drift) + } + } + return out +} + +// Measured returns the effect findings of the entries with a measured effect +// that Monitoring still lists, sorted by rule ID. They are the findings of the +// rule marks. +func (s *EffectStore) Measured(now time.Time) []Finding { + s.mu.Lock() + defer s.mu.Unlock() + out := []Finding{} + for _, e := range s.sortedLocked() { + if e.Result.Status != EffectStatusOK || e.Unit == "" { + continue + } + if !now.Before(time.Unix(e.At, 0).Add(effectListSpan)) { + continue + } + out = append(out, effectFinding(e, FindingID("effect", e.Rule), "check", now.Location())) + } + return out +} + +// sortedLocked returns the entries sorted by rule ID. The caller holds s.mu. +func (s *EffectStore) sortedLocked() []effectEntry { + ids := make([]string, 0, len(s.entries)) + for id := range s.entries { + ids = append(ids, id) + } + sort.Strings(ids) + out := make([]effectEntry, 0, len(ids)) + for _, id := range ids { + out = append(out, s.entries[id]) + } + return out +} + +// learnedMarks lists the rules and scenarios of the doc that came from a +// learned suggestion, by ID. +func learnedMarks(doc Doc) map[string]*LearnedFrom { + out := map[string]*LearnedFrom{} + for _, r := range doc.Rules { + if r.LearnedFrom != nil { + out[r.ID] = r.LearnedFrom + } + } + for _, sc := range doc.Scenarios { + if sc.LearnedFrom != nil { + out[sc.ID] = sc.LearnedFrom + } + } + return out +} + +// newEffectEntry takes the measure, the numbers and the baseline of a new entry. +func newEffectEntry(id string, lf *LearnedFrom, now time.Time, days []DayFile, shown map[string]Shown, findingsByID map[string]Finding) effectEntry { + e := effectEntry{Rule: id, Suggestion: lf.Suggestion, Kind: lf.Kind, At: lf.At} + if f, ok := findingsByID[lf.Suggestion]; ok { + if f.Benefit != nil { + e.Unit = f.Benefit.Unit + } + e.Group = f.Group + e.Device = f.Device + } else { + e.Unit, e.Group, e.Device = effectSpecFromKind(lf.Kind, lf.Suggestion) + } + if e.Device == "" { + e.Unit = "" + } + if sh, ok := shown[lf.Suggestion]; ok { + e.Values = copyValues(sh.Values) + } + e.Before = effectBefore(e.Unit, e.Group, e.Device, lf.At, now, days) + return e +} + +// effectSpecFromKind gives the unit, group and device of a suggestion without +// its finding, from its kind and its ID parts split at ":". +func effectSpecFromKind(kind, sugg string) (unit, group, device string) { + parts := strings.Split(sugg, ":") + part := func(i int) string { + if i < len(parts) { + return parts[i] + } + return "" + } + switch kind { + case "switch_time": + return effectUnitActions, "habit", part(1) + case "coupling": + return effectUnitActions, "habit", part(3) + case "away_standby", "runtime": + return effectUnitKWh, "habit", part(1) + case "surplus_window", "load_shift": + return effectUnitKWh, effectGroupEnergy, part(1) + case "temp_limit", "threshold", "battery": + return effectUnitKWh, effectGroupEnergy, "" + } + return "", "", "" +} + +// effectBefore is the measure of the four full weeks before the adoption week +// at, oldest first. Only the day files of those weeks count. +func effectBefore(unit, group, device string, at int64, now time.Time, days []DayFile) []float64 { + mon, ok := isoWeekMonday(isoWeekKey(time.Unix(at, 0).In(now.Location()))) + if !ok { + return nil + } + from := mon.AddDate(0, 0, -28).Format(dayLayout) + to := mon.Format(dayLayout) + var sel []DayFile + for i := range days { + if days[i].Day >= from && days[i].Day < to { + sel = append(sel, days[i]) + } + } + perWeek, _ := EffectMetric(unit, group, device, sel) + return perWeek +} + +// effectFinding builds the finding of an entry with the given ID and group. +func effectFinding(e effectEntry, id, group string, loc *time.Location) Finding { + r := e.Result + f := Finding{ + ID: id, + Kind: "effect", + Group: group, + RuleIDs: []string{e.Rule}, + Severity: "info", + Confidence: "high", + Device: e.Device, + Facts: []Fact{}, + Apply: []Fix{}, + } + if r.Estimate { + f.Confidence = "estimate" + } + params := map[string]any{"overridden": r.Overridden, "fired": r.Fired} + if r.Unit == "" { + // A suggestion without a measure has nothing to compare, only the overrides count. + f.Summary = Text{Code: "effect.count_only", Params: params} + return f + } + switch r.Status { + case EffectStatusOK: + if !r.Measurable { + f.Summary = Text{Code: "effect.not_measurable", Params: params} + break + } + var mean float64 + for _, v := range r.Since { + mean += v + } + if len(r.Since) > 0 { + mean /= float64(len(r.Since)) + } + before, since := effectRound(r.Before), effectRound(mean) + params["before"] = before + params["since"] = since + params["low"] = effectRound(r.Low) + params["high"] = effectRound(r.High) + params["unit"] = r.Unit + f.Summary = Text{Code: "effect.ok", Params: params} + f.Evidence = Evidence{Shape: "scale", Unit: r.Unit, IstValue: &before, SollValue: &since, + Labels: []string{"before", "since"}} + case EffectStatusWaiting: + mon, _ := isoWeekMonday(isoWeekKey(time.Unix(e.At, 0).In(loc))) + params["date"] = mon.AddDate(0, 0, 14).Format(dayLayout) + f.Summary = Text{Code: "effect.waiting", Params: params} + default: + f.Summary = Text{Code: "effect.no_baseline", Params: params} + } + return f +} + +// effectRound rounds to one decimal. +func effectRound(x float64) float64 { + return math.Round(x*10) / 10 +} + +// shiftSeriesMax is the number of nightly drift values kept per entry. +const shiftSeriesMax = 28 + +// shiftKey is one key of an adopted suggestion that the candidate still has: +// its value at adoption, now and the drift d in spreads. +type shiftKey struct { + name string + at float64 + now float64 + d float64 +} + +// shiftClockKey tells whether a key is a time of day. +func shiftClockKey(k string) bool { + return k == "time" || k == "latest" || k == "start" +} + +// shiftStep appends the drift of the night now to the series of e and sets +// e.Drift. With no matching candidate or no comparable key the series pauses. +func shiftStep(e *effectEntry, now time.Time, cands []Candidate) { + c := shiftMatch(*e, cands) + if c == nil { + e.Drift = nil + return + } + keys := shiftKeys(*e, c) + if len(keys) == 0 { + e.Drift = nil + return + } + best := keys[0] + for _, k := range keys[1:] { + if math.Abs(k.d) > math.Abs(best.d) { + best = k + } + } + today := now.Format(dayLayout) + if e.SeriesDay == today && len(e.Series) > 0 { + e.Series[len(e.Series)-1] = best.d + } else { + e.Series = append(e.Series, best.d) + e.SeriesDay = today + } + if n := len(e.Series); n > shiftSeriesMax { + e.Series = append([]float64(nil), e.Series[n-shiftSeriesMax:]...) + } + e.Drift = shiftFinding(*e, c, keys, best) +} + +// shiftMatch finds the candidate of the entry's suggestion. A switch time +// that moved within 180 minutes keeps its suggestion ID up to the last ":", so +// the candidate with that prefix and the closest time is taken instead. +func shiftMatch(e effectEntry, cands []Candidate) *Candidate { + for i := range cands { + if cands[i].Finding.ID == e.Suggestion { + return &cands[i] + } + } + if e.Kind != "switch_time" { + return nil + } + t0, ok := e.Values["time"] + cut := strings.LastIndex(e.Suggestion, ":") + if !ok || cut < 0 { + return nil + } + prefix := e.Suggestion[:cut+1] + var best *Candidate + bestD := 180.0 + for i := range cands { + id := cands[i].Finding.ID + j := strings.LastIndex(id, ":") + if j < 0 || id[:j+1] != prefix { + continue + } + tv, ok := cands[i].Values["time"] + if !ok { + continue + } + if d := math.Abs(circDelta(tv, t0)); d <= bestD { + best, bestD = &cands[i], d + } + } + return best +} + +// shiftDriftKeys are the values of a suggestion that drift with the season, by +// kind. The other values move because of the adoption itself, so they never drift. +var shiftDriftKeys = map[string][]string{ + "switch_time": {"time"}, + "surplus_window": {"start", "window_quarters", "on_w"}, + "away_standby": {"kwh_day"}, + "threshold": {"soll"}, +} + +// shiftKeys lists the drifting keys of the kind of the entry that are present +// in the entry and in the candidate with a positive spread, sorted by name. +func shiftKeys(e effectEntry, c *Candidate) []shiftKey { + var out []shiftKey + for _, k := range shiftDriftKeys[e.Kind] { + at, inEntry := e.Values[k] + now, ok := c.Values[k] + if !inEntry || !ok || !(c.Spread[k] > 0) { + continue + } + diff := now - at + if shiftClockKey(k) { + diff = circDelta(now, at) + } + out = append(out, shiftKey{name: k, at: at, now: now, d: diff / c.Spread[k]}) + } + return out +} + +// shiftValue formats a key value for the text: HH:MM for times, else one decimal. +func shiftValue(key string, v float64) any { + if shiftClockKey(key) { + return switchTimeClock(wrapMinutes(v)) + } + return effectRound(v) +} + +// shiftFinding is the season shift finding of e when the series has drifted +// beyond the slack in the direction of its latest value, nil otherwise. +func shiftFinding(e effectEntry, c *Candidate, keys []shiftKey, best shiftKey) *Finding { + _, up, ok := CUSUM(e.Series, 0, 1) + if !ok { + return nil + } + last := e.Series[len(e.Series)-1] + if (up && last <= cusumK) || (!up && last >= -cusumK) { + return nil + } + bars := make([]ScaleBar, 0, len(keys)) + for _, k := range keys { + bar := ScaleBar{Name: k.name, Ist: k.at, Soll: k.now} + if shiftClockKey(k.name) { + bar.Unit = "clock" + } + bars = append(bars, bar) + } + fixes := make([]Fix, 0, len(c.Finding.Apply)) + var learned []Fix + for _, fx := range c.Finding.Apply { + fx.RuleID = e.Rule + fx.Replace = true + if strings.Contains(fx.Code, "learned") { + learned = append(learned, fx) + continue + } + fixes = append(fixes, fx) + } + fixes = append(fixes, learned...) + params := map[string]any{ + "key": best.name, + "old": shiftValue(best.name, best.at), + "new": shiftValue(best.name, best.now), + "device": e.Device, + "suggestion": c.Finding.ID, + } + return &Finding{ + ID: FindingID("season_shift", e.Rule), + Kind: "season_shift", + Group: "check", + RuleIDs: []string{e.Rule}, + Severity: "warn", + Confidence: "estimate", + Device: e.Device, + Summary: Text{Code: "season_shift." + e.Kind, Params: params}, + Evidence: Evidence{Shape: "scale", Scales: bars}, + Facts: []Fact{}, + Apply: fixes, + } +} diff --git a/dashboard/internal/autolearn/effect_store_test.go b/dashboard/internal/autolearn/effect_store_test.go new file mode 100644 index 00000000..5b33a254 --- /dev/null +++ b/dashboard/internal/autolearn/effect_store_test.go @@ -0,0 +1,510 @@ +package autolearn + +import ( + "os" + "path/filepath" + "reflect" + "testing" + "time" +) + +const effSugg = "switch_time:plug.heater:on:0:0700" + +// effDoc is a doc with one rule learned from suggestion sugg at the time at. +func effDoc(rule, sugg, kind string, at time.Time) Doc { + return Doc{Rules: []Rule{{ID: rule, LearnedFrom: &LearnedFrom{Suggestion: sugg, Kind: kind, At: at.Unix()}}}} +} + +// effMark is the finding of the suggestion: actions per week on the heater. +func effMark() map[string]Finding { + return map[string]Finding{effSugg: {ID: effSugg, Group: "habit", Device: effDev, + Benefit: &Benefit{Unit: effectUnitActions}}} +} + +// effHandHeater: ten switches a week in weeks 1 to 4, then two a week. +var effHandHeater = map[int]uint8{1: 10, 2: 10, 3: 10, 4: 10, 5: 0, 6: 2, 7: 2} + +func effStoreAt(t *testing.T) *EffectStore { + t.Helper() + return LoadEffectStore(filepath.Join(t.TempDir(), "effect.json"), nil) +} + +func TestEffectStoreSyncNewMark(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(effHandHeater)) + s := effStoreAt(t) + doc := effDoc("r1", effSugg, "switch_time", at) + shown := map[string]Shown{effSugg: {Values: map[string]float64{"n": 3}}} + + if !s.Sync(doc, at, days, shown, effMark()) { + t.Fatal("Sync added nothing for a new mark") + } + e := s.entries["r1"] + if want := []float64{10, 10, 10, 10}; !reflect.DeepEqual(e.Before, want) { + t.Errorf("Before = %v, want %v", e.Before, want) + } + if e.Values["n"] != 3 { + t.Errorf("Values = %v, want n=3", e.Values) + } + if s.Sync(doc, at, days, shown, effMark()) { + t.Error("second Sync reported an added entry") + } + if s.NeedsDays(doc) { + t.Error("NeedsDays after a complete Sync") + } +} + +func TestEffectStoreFindingsAndBand(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(effHandHeater)) + s := effStoreAt(t) + s.Sync(effDoc("r1", effSugg, "switch_time", at), at, days, nil, effMark()) + now := effAt(2026, 7, loc).AddDate(0, 0, 7) + s.Nightly(now, days, effStore(t), []Candidate{}) + + fs := s.Findings(now) + if len(fs) != 1 { + t.Fatalf("Findings = %d, want 1", len(fs)) + } + f := fs[0] + if f.ID != "effect:r1" || f.Kind != "effect" || f.Group != "check" || f.Severity != "info" { + t.Errorf("finding = %+v", f) + } + if f.Summary.Code != "effect.ok" { + t.Fatalf("Summary.Code = %q, want effect.ok", f.Summary.Code) + } + p := f.Summary.Params + if p["before"] != 10.0 || p["since"] != 2.0 || p["low"] != -8.0 || p["high"] != -8.0 || p["unit"] != effectUnitActions { + t.Errorf("Params = %v", p) + } + if f.Evidence.IstValue == nil || *f.Evidence.IstValue != 10 || f.Evidence.SollValue == nil || *f.Evidence.SollValue != 2 { + t.Errorf("Evidence values = %v / %v, want 10 and 2", f.Evidence.IstValue, f.Evidence.SollValue) + } + if !reflect.DeepEqual(f.Evidence.Labels, []string{"before", "since"}) || f.Evidence.Shape != "scale" { + t.Errorf("Evidence = %+v", f.Evidence) + } + + measured := s.Measured(now) + if len(measured) != 1 || measured[0].ID != "effect:r1" || measured[0].Group != "check" { + t.Fatalf("Measured = %+v, want the finding of the rule mark", measured) + } + if late := s.Measured(at.Add(8*7*24*time.Hour + time.Hour)); len(late) != 0 { + t.Errorf("Measured eight weeks later = %d, want 0", len(late)) + } +} + +func TestEffectStoreRemovedRuleIsDropped(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(effHandHeater)) + now := effAt(2026, 7, loc).AddDate(0, 0, 7) + docs := map[string]Doc{ + "rule deleted": {}, + "learned_from unset": {Rules: []Rule{{ID: "r1"}}}, + } + for name, doc := range docs { + s := effStoreAt(t) + s.Sync(effDoc("r1", effSugg, "switch_time", at), at, days, nil, effMark()) + s.Nightly(now, days, effStore(t), []Candidate{}) + if added := s.Sync(doc, at, days, nil, effMark()); added { + t.Errorf("%s: Sync reported an added entry", name) + } + if s.Len() != 0 || len(s.Findings(now)) != 0 || len(s.Measured(now)) != 0 { + t.Errorf("%s: entry kept, Len = %d", name, s.Len()) + } + } +} + +func TestEffectStoreChangedAtRestarts(t *testing.T) { + loc := berlinLoc(t) + hand := map[int]uint8{1: 10, 2: 10, 3: 10, 4: 10, 5: 4, 6: 4, 7: 4} + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(hand)) + s := effStoreAt(t) + at := effAt(2026, 5, loc) + s.Sync(effDoc("r1", effSugg, "switch_time", at), at, days, nil, effMark()) + + at2 := effAt(2026, 7, loc) + doc := effDoc("r1", effSugg, "switch_time", at2) + if !s.NeedsDays(doc) { + t.Fatal("NeedsDays false after learned_from.at changed") + } + if !s.Sync(doc, at2, days, nil, effMark()) { + t.Fatal("Sync did not restart the entry") + } + if want := []float64{10, 10, 4, 4}; !reflect.DeepEqual(s.entries["r1"].Before, want) { + t.Errorf("Before = %v, want %v", s.entries["r1"].Before, want) + } +} + +func TestEffectStoreResetWithoutDays(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + now := effAt(2026, 7, loc).AddDate(0, 0, 7) + s := effStoreAt(t) + doc := effDoc("r1", effSugg, "switch_time", at) + s.Sync(doc, at, nil, nil, effMark()) + s.Save() + if err := s.Reset(); err != nil { + t.Fatalf("Reset: %v", err) + } + if s.Len() != 0 { + t.Fatalf("Len after Reset = %d", s.Len()) + } + if _, err := os.Stat(s.path); !os.IsNotExist(err) { + t.Errorf("file after Reset: %v", err) + } + if err := s.Reset(); err != nil { + t.Errorf("Reset of a missing file: %v", err) + } + + if !s.Sync(doc, at, nil, nil, effMark()) { + t.Fatal("Sync after Reset added nothing") + } + s.Nightly(now, nil, effStore(t), []Candidate{}) + fs := s.Findings(now) + if len(fs) != 1 || fs[0].Summary.Code != "effect.no_baseline" { + t.Fatalf("Findings = %+v, want one effect.no_baseline", fs) + } + if len(s.Measured(now)) != 0 { + t.Error("Measured not empty without a baseline") + } +} + +func TestEffectStoreDerivesFromKind(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + s := effStoreAt(t) + sugg := "switch_time:plug.heater:on:0:0700" + s.Sync(effDoc("r1", sugg, "switch_time", at), at, nil, nil, nil) + e := s.entries["r1"] + if e.Unit != effectUnitActions || e.Group != "habit" || e.Device != "plug.heater" { + t.Errorf("derived unit, group, device = %q, %q, %q", e.Unit, e.Group, e.Device) + } + + s2 := effStoreAt(t) + sugg2 := "temp_limit:plug.heater:x" + s2.Sync(effDoc("r2", sugg2, "temp_limit", at), at, nil, nil, nil) + if e := s2.entries["r2"]; e.Unit != "" || e.Device != "" { + t.Errorf("temp_limit without device: unit %q, device %q, want empty", e.Unit, e.Device) + } +} + +func TestEffectStoreSaveLoadAndDamaged(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(effHandHeater)) + path := filepath.Join(t.TempDir(), "effect.json") + s := LoadEffectStore(path, nil) + shown := map[string]Shown{effSugg: {Values: map[string]float64{"n": 3}}} + s.Sync(effDoc("r1", effSugg, "switch_time", at), at, days, shown, effMark()) + + back := LoadEffectStore(path, nil) + if back.Len() != 1 { + t.Fatalf("reloaded Len = %d, want 1", back.Len()) + } + e := back.entries["r1"] + if !reflect.DeepEqual(e.Before, []float64{10, 10, 10, 10}) || e.Values["n"] != 3 || e.Device != effDev { + t.Errorf("reloaded entry = %+v", e) + } + + if err := os.WriteFile(path, []byte("{not json"), 0o644); err != nil { + t.Fatal(err) + } + logged := 0 + damaged := LoadEffectStore(path, func(string, ...any) { logged++ }) + if damaged.Len() != 0 || logged == 0 { + t.Errorf("damaged file: Len = %d, logged = %d, want empty and logged", damaged.Len(), logged) + } +} + +const driftSugg = "switch_time:plug.heater:on:0:2230" + +// driftCand is a candidate of the switch time suggestion at minute tm with two +// fixes, the learned one listed first. +func driftCand(id string, tm float64) Candidate { + return Candidate{ + Finding: Finding{ID: id, Kind: "switch_time", Apply: []Fix{ + {Code: "time_point_learned", Ops: []Op{}}, + {Code: "time_point", Ops: []Op{}}, + }}, + Values: map[string]float64{"time": tm, "hit_rate": 0.9}, + Spread: map[string]float64{"time": 10}, + } +} + +// driftStore adopts driftSugg at week 5 with the time 1350 and returns the store and the adoption. +func driftStore(t *testing.T) (*EffectStore, Doc, time.Time) { + t.Helper() + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + s := effStoreAt(t) + doc := effDoc("r1", driftSugg, "switch_time", at) + shown := map[string]Shown{driftSugg: {Values: map[string]float64{"time": 1350, "hit_rate": 0.9}}} + s.Sync(doc, at, nil, shown, nil) + return s, doc, at +} + +// driftNight runs one nightly pass n days after the adoption with the candidates cands. +func driftNight(t *testing.T, s *EffectStore, at time.Time, n int, cands []Candidate) { + t.Helper() + s.Nightly(at.AddDate(0, 0, n), nil, effStore(t), cands) +} + +func seasonFindings(fs []Finding) []Finding { + var out []Finding + for _, f := range fs { + if f.Kind == "season_shift" { + out = append(out, f) + } + } + return out +} + +func TestSeasonDriftReported(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 20; n++ { + switch { + case n <= 8: + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, 1350)}) + default: + driftNight(t, s, at, n, []Candidate{driftCand("switch_time:plug.heater:on:0:2200", 1305)}) + } + } + now := at.AddDate(0, 0, 20) + fs := seasonFindings(s.Findings(now)) + if len(fs) != 1 { + t.Fatalf("season findings = %d, want 1", len(fs)) + } + f := fs[0] + if f.ID != "season_shift:r1" || f.Group != "check" || f.Severity != "warn" || f.Confidence != "estimate" { + t.Errorf("finding = %+v", f) + } + if f.Summary.Code != "season_shift.switch_time" { + t.Fatalf("Summary.Code = %q", f.Summary.Code) + } + if f.Summary.Params["old"] != "22:30" || f.Summary.Params["new"] != "21:45" || f.Summary.Params["key"] != "time" { + t.Errorf("Params = %v", f.Summary.Params) + } + if f.Summary.Params["suggestion"] != "switch_time:plug.heater:on:0:2200" { + t.Errorf("suggestion param = %v, want the matching candidate ID", f.Summary.Params["suggestion"]) + } + if len(f.Apply) != 2 { + t.Fatalf("Apply = %d fixes, want 2", len(f.Apply)) + } + if f.Apply[0].Code != "time_point" || f.Apply[1].Code != "time_point_learned" { + t.Errorf("Apply order = %q, %q", f.Apply[0].Code, f.Apply[1].Code) + } + for _, fx := range f.Apply { + if fx.RuleID != "r1" || !fx.Replace { + t.Errorf("fix %+v, want RuleID r1 and Replace", fx) + } + } + if f.Evidence.Shape != "scale" || len(f.Evidence.Scales) != 1 || f.Evidence.Scales[0].Unit != "clock" { + t.Errorf("Evidence = %+v", f.Evidence) + } + if !reflect.DeepEqual(f.RuleIDs, []string{"r1"}) { + t.Errorf("RuleIDs = %v", f.RuleIDs) + } +} + +func TestSeasonDriftOneOutlierNoDrift(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 20; n++ { + tm := 1350.0 + if n == 10 { + tm = 1250 + } + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) + } + if fs := seasonFindings(s.Findings(at.AddDate(0, 0, 20))); len(fs) != 0 { + t.Errorf("season findings = %d after one outlier, want 0", len(fs)) + } +} + +func TestSeasonDriftPausesWithoutCandidate(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 12; n++ { + tm := 1350.0 + if n > 8 { + tm = 1305 + } + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) + } + before := len(s.entries["r1"].Series) + driftNight(t, s, at, 13, []Candidate{}) + if got := len(s.entries["r1"].Series); got != before { + t.Errorf("series length = %d after a night without candidate, want %d", got, before) + } + if s.entries["r1"].Drift != nil { + t.Error("Drift kept without candidate") + } + if fs := seasonFindings(s.Findings(at.AddDate(0, 0, 13))); len(fs) != 0 { + t.Errorf("season findings = %d without candidate, want 0", len(fs)) + } +} + +func TestSeasonDriftGoneWhenBackAtAdoption(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 17; n++ { + tm := 1350.0 + if n >= 9 && n <= 12 { + tm = 1305 + } + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) + } + if s.entries["r1"].Drift != nil { + t.Error("Drift still set after several nights back at the adopted time") + } + if fs := seasonFindings(s.Findings(at.AddDate(0, 0, 17))); len(fs) != 0 { + t.Errorf("season findings = %d, want 0", len(fs)) + } +} + +func TestSeasonDriftResetsOnNewAt(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 12; n++ { + tm := 1350.0 + if n > 8 { + tm = 1305 + } + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) + } + if len(s.entries["r1"].Series) == 0 { + t.Fatal("series empty before the restart") + } + loc := berlinLoc(t) + at2 := effAt(2026, 7, loc) + s.Sync(effDoc("r1", driftSugg, "switch_time", at2), at2, nil, nil, nil) + if n := len(s.entries["r1"].Series); n != 0 { + t.Errorf("series length after a new At = %d, want 0", n) + } +} + +func TestSeasonDriftOneValuePerDay(t *testing.T) { + s, _, at := driftStore(t) + now := at.AddDate(0, 0, 1) + s.Nightly(now, nil, effStore(t), []Candidate{driftCand(driftSugg, 1305)}) + s.Nightly(now.Add(2*time.Hour), nil, effStore(t), []Candidate{driftCand(driftSugg, 1300)}) + if n := len(s.entries["r1"].Series); n != 1 { + t.Errorf("series length after two nights of one day = %d, want 1", n) + } +} + +func TestSeasonDriftNotMeasured(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 12; n++ { + tm := 1350.0 + if n > 8 { + tm = 1305 + } + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, tm)}) + } + if len(seasonFindings(s.Findings(at.AddDate(0, 0, 12)))) != 1 { + t.Fatal("no season finding to test the measured list against") + } + for _, f := range s.Measured(at.AddDate(0, 0, 12)) { + if f.Kind == "season_shift" { + t.Errorf("Measured contains %q", f.ID) + } + } +} + +// kindDriftNights adopts sugg of kind with the values adopted and runs ten +// nights where the candidate has the values now, both with spread 2. +func kindDriftNights(t *testing.T, sugg, kind string, adopted, now map[string]float64) *EffectStore { + t.Helper() + at := effAt(2026, 5, berlinLoc(t)) + s := effStoreAt(t) + s.Sync(effDoc("r1", sugg, kind, at), at, nil, map[string]Shown{sugg: {Values: adopted}}, nil) + spread := map[string]float64{} + for k := range now { + spread[k] = 2 + } + c := Candidate{Finding: Finding{ID: sugg, Kind: kind}, Values: now, Spread: spread} + for n := 1; n <= 10; n++ { + driftNight(t, s, at, n, []Candidate{c}) + } + return s +} + +func TestSeasonDriftThresholdIgnoresAdoptionValue(t *testing.T) { + s := kindDriftNights(t, "threshold:plug.x:1", "threshold", + map[string]float64{"today": 20, "soll": 30}, + map[string]float64{"today": 40, "soll": 30}) + if s.entries["r1"].Drift != nil { + t.Errorf("threshold drifted on today, Drift = %+v, series = %v", s.entries["r1"].Drift, s.entries["r1"].Series) + } +} + +func TestSeasonDriftThresholdSollDrifts(t *testing.T) { + s := kindDriftNights(t, "threshold:plug.x:1", "threshold", + map[string]float64{"today": 20, "soll": 30}, + map[string]float64{"today": 20, "soll": 40}) + if s.entries["r1"].Drift == nil { + t.Fatal("no drift although soll moved by five spreads") + } + if got := s.entries["r1"].Drift.Summary.Params["key"]; got != "soll" { + t.Errorf("drift key = %v, want soll", got) + } +} + +func TestSeasonDriftNeverForOtherKinds(t *testing.T) { + s := kindDriftNights(t, "overridden:plug.x:1", "overridden", + map[string]float64{"share": 0.5}, + map[string]float64{"share": 0.1}) + if s.entries["r1"].Drift != nil || len(s.entries["r1"].Series) != 0 { + t.Errorf("kind overridden drifted, Drift = %+v, series = %v", s.entries["r1"].Drift, s.entries["r1"].Series) + } +} + +func TestEffectStoreCountOnlyWithoutUnit(t *testing.T) { + loc := berlinLoc(t) + at := effAt(2026, 5, loc) + now := effAt(2026, 7, loc).AddDate(0, 0, 7) + s := effStoreAt(t) + // No device, so the suggestion has no measure and no unit. + doc := effDoc("r2", "temp_limit:plug.heater:x", "temp_limit", at) + s.Sync(doc, at, nil, nil, nil) + s.Nightly(now, nil, effStore(t), []Candidate{}) + + fs := s.Findings(now) + if len(fs) != 1 { + t.Fatalf("Findings = %d, want 1 count only finding", len(fs)) + } + f := fs[0] + if f.Summary.Code != "effect.count_only" { + t.Fatalf("Summary.Code = %q, want effect.count_only", f.Summary.Code) + } + if len(f.Summary.Params) != 2 || f.Summary.Params["overridden"] == nil || f.Summary.Params["fired"] == nil { + t.Errorf("Params = %v, want only overridden and fired", f.Summary.Params) + } + if f.Evidence.Shape != "" || len(f.Evidence.Scales) != 0 || f.Evidence.IstValue != nil || f.Evidence.SollValue != nil { + t.Errorf("Evidence = %+v, want none", f.Evidence) + } + if band := s.Measured(now); len(band) != 0 { + t.Errorf("Measured = %d, want none without a unit", len(band)) + } +} + +// TestSeasonDriftSurvivesNightWithoutCandidates checks that a night without a +// candidate list leaves a stored drift, its series and its day as they are. +func TestSeasonDriftSurvivesNightWithoutCandidates(t *testing.T) { + s, _, at := driftStore(t) + for n := 1; n <= 12; n++ { + driftNight(t, s, at, n, []Candidate{driftCand(driftSugg, 1305)}) + } + before := s.entries["r1"] + if before.Drift == nil { + t.Fatal("no drift to keep") + } + s.Nightly(at.AddDate(0, 0, 13), nil, effStore(t), nil) + after := s.entries["r1"] + if !reflect.DeepEqual(before.Series, after.Series) || before.SeriesDay != after.SeriesDay { + t.Errorf("series changed by a night without candidates: %v %q, was %v %q", after.Series, after.SeriesDay, before.Series, before.SeriesDay) + } + if !reflect.DeepEqual(before.Drift, after.Drift) { + t.Errorf("drift changed by a night without candidates: %+v, was %+v", after.Drift, before.Drift) + } +} diff --git a/dashboard/internal/autolearn/effect_test.go b/dashboard/internal/autolearn/effect_test.go new file mode 100644 index 00000000..3c00afd9 --- /dev/null +++ b/dashboard/internal/autolearn/effect_test.go @@ -0,0 +1,319 @@ +package autolearn + +import ( + "math" + "path/filepath" + "testing" + "time" +) + +const effDev = "plug.heater" + +// effDays builds the day files of the given ISO weeks of year in loc, Monday to +// Sunday. fill sets the values of one day of week w (d is 0 for Monday). +func effDays(t *testing.T, loc *time.Location, year int, weeks []int, fill func(w, d int, dd *DeviceDay, f *DayFile)) []DayFile { + t.Helper() + var out []DayFile + for _, w := range weeks { + mon := isoWeekMondayOf(year, w) + for d := 0; d < 7; d++ { + day := time.Date(mon.Year(), mon.Month(), mon.Day()+d, 0, 0, 0, 0, loc) + f := relDay(day) + for q := 0; q < dayQuarters; q++ { + f.Site.PV[q] = 1000 + f.Site.LoadTotal[q] = 300 + } + dd := &DeviceDay{} + f.Devices[effDev] = dd + if fill != nil { + fill(w, d, dd, &f) + } + out = append(out, f) + } + } + return out +} + +// effAt is noon of the Monday of week w of year in loc. +func effAt(year, w int, loc *time.Location) time.Time { + mon := isoWeekMondayOf(year, w) + return time.Date(mon.Year(), mon.Month(), mon.Day(), 12, 0, 0, 0, loc) +} + +func effClose(a, b float64) bool { + return math.Abs(a-b) < 1e-6 +} + +// effStore is an empty season store in a temporary file. +func effStore(t *testing.T) *SeasonStore { + t.Helper() + return LoadSeasonStore(filepath.Join(t.TempDir(), "season.json"), nil) +} + +// effHandWeeks gives each week its hand switches on the Monday. +func effHandWeeks(hand map[int]uint8) func(w, d int, dd *DeviceDay, f *DayFile) { + return func(w, d int, dd *DeviceDay, f *DayFile) { + if d == 0 { + dd.Hand[0] = hand[w] + } + } +} + +func TestEffectHandSwitchesDropBelowBaseline(t *testing.T) { + loc := berlinLoc(t) + hand := map[int]uint8{1: 10, 2: 10, 3: 10, 4: 10, 5: 0, 6: 2, 7: 2} + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(hand)) + + perWeek, ok := EffectMetric(effectUnitActions, "", effDev, days) + if !ok { + t.Fatal("actions_week has no metric") + } + want := []float64{10, 10, 10, 10, 0, 2, 2} + if len(perWeek) != len(want) { + t.Fatalf("perWeek = %v, want %v", perWeek, want) + } + for i := range want { + if perWeek[i] != want[i] { + t.Fatalf("perWeek = %v, want %v", perWeek, want) + } + } + if _, ok := EffectMetric("minutes", "", effDev, days); ok { + t.Error("unknown unit has a metric") + } + + res := ComputeEffect(effAt(2026, 5, loc), effectUnitActions, "", effDev, + []float64{10, 10, 10, 10}, days, effStore(t), loc) + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if res.Before != 10 || res.Weeks != 2 { + t.Errorf("Before = %v, Weeks = %d, want 10 and 2", res.Before, res.Weeks) + } + if len(res.Since) != 2 || res.Since[0] != 2 || res.Since[1] != 2 { + t.Errorf("Since = %v, want [2 2]", res.Since) + } + if !effClose(res.Low, -8) || !effClose(res.High, -8) { + t.Errorf("span = [%v, %v], want [-8, -8]", res.Low, res.High) + } + if !res.Measurable { + t.Error("a span below zero is not measurable") + } +} + +func TestEffectNoiseSpanContainsZero(t *testing.T) { + loc := berlinLoc(t) + hand := map[int]uint8{1: 5, 2: 5, 3: 5, 4: 5, 5: 0, 6: 3, 7: 7} + days := effDays(t, loc, 2026, []int{1, 2, 3, 4, 5, 6, 7}, effHandWeeks(hand)) + + res := ComputeEffect(effAt(2026, 5, loc), effectUnitActions, "", effDev, + []float64{5, 5, 5, 5}, days, effStore(t), loc) + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if !effClose(res.Low, -2) || !effClose(res.High, 2) { + t.Errorf("span = [%v, %v], want [-2, 2]", res.Low, res.High) + } + if res.Measurable { + t.Error("a span around zero is measurable") + } +} + +// effGridFill gives the device 20 Wh per quarter and the grid import per week, +// so the grid share is 10 Wh per quarter in weeks before 9 and 11 Wh after. +func effGridFill(grid map[int]float32) func(w, d int, dd *DeviceDay, f *DayFile) { + return func(w, d int, dd *DeviceDay, f *DayFile) { + for q := 0; q < dayQuarters; q++ { + dd.Wh[q] = 20 + f.Site.GridImport[q] = grid[w] + } + } +} + +// effGridDays are weeks 5 to 11 of 2026: four baseline weeks, the adoption +// week 9 and the weeks 10 and 11 since. +func effGridDays(t *testing.T, loc *time.Location) []DayFile { + grid := map[int]float32{5: 40, 6: 40, 7: 40, 8: 40, 9: 40, 10: 44, 11: 44} + return effDays(t, loc, 2026, []int{5, 6, 7, 8, 9, 10, 11}, effGridFill(grid)) +} + +// effPriorPV puts the prior-year PV of the weeks 4 to 12 of 2025 in the store: +// 100 kWh up to week 8, 70 kWh from week 9 on. +func effPriorPV(t *testing.T) *SeasonStore { + t.Helper() + s := effStore(t) + for w := 4; w <= 12; w++ { + pv := 100.0 + if w >= 9 { + pv = 70 + } + s.Put(Week{Key: isoWeekKey(isoWeekMondayOf(2025, w)), PVKWh: pv}) + } + return s +} + +func TestEffectGridShareWithPriorYearIsSeasonAdjusted(t *testing.T) { + loc := berlinLoc(t) + days := effGridDays(t, loc) + before := []float64{6.72, 6.72, 6.72, 6.72} + + res := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + before, days, effPriorPV(t), loc) + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if res.Estimate { + t.Error("Estimate set although the prior year is there") + } + if len(res.Since) != 2 || len(res.Expected) != 2 { + t.Fatalf("Since = %v, Expected = %v, want two weeks", res.Since, res.Expected) + } + for i := range res.Since { + if !(res.Expected[i] > res.Since[i]) { + t.Errorf("week %d: Expected %v not above Since %v", i, res.Expected[i], res.Since[i]) + } + } + if !(res.High < 0) { + t.Errorf("effect span [%v, %v], want below zero (good)", res.Low, res.High) + } + if !res.Measurable { + t.Error("the grid share effect is not measurable") + } +} + +func TestEffectWithoutPriorYearIsEstimate(t *testing.T) { + loc := berlinLoc(t) + days := effGridDays(t, loc) + before := []float64{6.72, 6.72, 6.72, 6.72} + + res := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + before, days, effStore(t), loc) + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if !res.Estimate { + t.Error("Estimate not set without a prior year") + } +} + +func TestEffectAdoptionFiveDaysAgoIsWaiting(t *testing.T) { + loc := berlinLoc(t) + grid := map[int]float32{5: 40, 6: 40, 7: 40, 8: 40, 9: 40} + days := effDays(t, loc, 2026, []int{5, 6, 7, 8, 9}, effGridFill(grid)) + at := effAt(2026, 9, loc).AddDate(0, 0, 5) + + res := ComputeEffect(at, effectUnitKWh, "energy", effDev, + []float64{6.72, 6.72, 6.72, 6.72}, days, effStore(t), loc) + if res.Status != EffectStatusWaiting { + t.Errorf("Status = %q, want waiting", res.Status) + } +} + +func TestEffectOneBaselineWeekIsNoBaseline(t *testing.T) { + loc := berlinLoc(t) + days := effGridDays(t, loc) + + res := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + []float64{6.72}, days, effStore(t), loc) + if res.Status != EffectStatusNoBaseline { + t.Errorf("Status = %q, want no_baseline", res.Status) + } +} + +func TestEffectWithoutUnitHasNoBaseline(t *testing.T) { + loc := berlinLoc(t) + days := effGridDays(t, loc) + + res := ComputeEffect(effAt(2026, 9, loc), "", "", effDev, + []float64{6.72, 6.72}, days, effStore(t), loc) + if res.Status != EffectStatusNoBaseline || len(res.Since) != 0 { + t.Errorf("Status = %q, Since = %v, want no_baseline without weeks", res.Status, res.Since) + } +} + +func TestOverrideCountReversedWithinLimit(t *testing.T) { + loc := berlinLoc(t) + start := isoWeekMondayOf(2026, 1) + var days []DayFile + for i := 0; i < 3; i++ { + day := time.Date(start.Year(), start.Month(), start.Day()+i, 0, 0, 0, 0, loc) + f := relDay(day) + at := relAt(day, 18, 0, 0) + f.Events = append(f.Events, EventRec{At: at, Device: effDev, Entity: "switch." + effDev, + On: true, Origin: string(OriginRule), Rule: "heat"}) + if i == 0 { + f.Events = append(f.Events, EventRec{At: at + 120, Device: effDev, Entity: "switch." + effDev, + On: false, Origin: string(OriginHand)}) + } + days = append(days, f) + } + + if ov, fired := OverrideCount(days, "heat", time.Time{}); ov != 1 || fired != 3 { + t.Errorf("OverrideCount = (%d, %d), want (1, 3)", ov, fired) + } + since := time.Date(start.Year(), start.Month(), start.Day()+2, 0, 0, 0, 0, loc) + if ov, fired := OverrideCount(days, "heat", since); ov != 0 || fired != 1 { + t.Errorf("OverrideCount since day 3 = (%d, %d), want (0, 1)", ov, fired) + } + if ov, fired := OverrideCount(days, "", time.Time{}); ov != 0 || fired != 0 { + t.Errorf("OverrideCount without rule = (%d, %d), want (0, 0)", ov, fired) + } +} + +// TestEffectBaselineWeeksWithFiveDaysAreOK: the baseline weeks 5 to 8 hold only +// their Monday to Friday, which is enough for a baseline week. The prior-year +// ratio then applies, so the result is exact and not an estimate. +func TestEffectBaselineWeeksWithFiveDaysAreOK(t *testing.T) { + loc := berlinLoc(t) + var days []DayFile + for _, f := range effGridDays(t, loc) { + d, err := time.Parse(dayLayout, f.Day) + if err != nil { + t.Fatal(err) + } + if _, wk := d.ISOWeek(); wk < 9 && (d.Weekday() == time.Saturday || d.Weekday() == time.Sunday) { + continue + } + days = append(days, f) + } + before := []float64{6.72, 6.72, 6.72, 6.72} + + res := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + before, days, effPriorPV(t), loc) + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if res.Estimate { + t.Error("Estimate set although the baseline weeks have five days and the prior year is there") + } +} + +// TestEffectSeasonDenominatorWithoutBaselineDays: the prior-year denominator +// comes from the adoption date, so it holds once the baseline day files are +// pruned. The expectation equals the one with the baseline day files. +func TestEffectSeasonDenominatorWithoutBaselineDays(t *testing.T) { + loc := berlinLoc(t) + before := []float64{6.72, 6.72, 6.72, 6.72} + full := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + before, effGridDays(t, loc), effPriorPV(t), loc) + + grid := map[int]float32{9: 40, 10: 44, 11: 44} + pruned := effDays(t, loc, 2026, []int{9, 10, 11}, effGridFill(grid)) + res := ComputeEffect(effAt(2026, 9, loc), effectUnitKWh, "energy", effDev, + before, pruned, effPriorPV(t), loc) + + if res.Status != EffectStatusOK { + t.Fatalf("Status = %q, want ok", res.Status) + } + if res.Estimate { + t.Error("Estimate set although the prior year is there") + } + if len(res.Expected) != len(full.Expected) || len(res.Since) != len(full.Since) { + t.Fatalf("Expected = %v, want %v", res.Expected, full.Expected) + } + for i := range full.Expected { + if !effClose(res.Expected[i], full.Expected[i]) || !effClose(res.Since[i], full.Since[i]) { + t.Errorf("week %d: Expected %v, Since %v, want %v and %v", + i, res.Expected[i], res.Since[i], full.Expected[i], full.Since[i]) + } + } +} diff --git a/dashboard/internal/autolearn/engine.go b/dashboard/internal/autolearn/engine.go index 1b86d80f..269ec5c8 100644 --- a/dashboard/internal/autolearn/engine.go +++ b/dashboard/internal/autolearn/engine.go @@ -436,6 +436,32 @@ func (e *Engine) Load() (overruns int, share float64, took map[string]time.Durat return st.Overruns, st.Share, st.Took } +// DailyRound reports the start of the last daily round and whether its results +// are complete: a round ran and no work of a daily detector is left over. The +// season drift waits for a complete round. +func (e *Engine) DailyRound() (at time.Time, complete bool) { + e.mu.Lock() + defer e.mu.Unlock() + at = e.lastDaily + if at.IsZero() { + return at, false + } + for _, p := range e.queue { + if !p.det.Light { + return at, false + } + } + return at, true +} + +// RequestDaily makes the next due tick run a daily round, even when one already +// ran today. The catch-up rule does it, so the round needs no slot. +func (e *Engine) RequestDaily() { + e.mu.Lock() + defer e.mu.Unlock() + e.lastDaily = time.Time{} +} + // Downgrade reports whether the load asked for a lower level since the last // call. The signal is read once: the caller lowers the level, the engine // starts counting again from zero. diff --git a/dashboard/internal/autolearn/engine_test.go b/dashboard/internal/autolearn/engine_test.go index 7aa91271..9351292a 100644 --- a/dashboard/internal/autolearn/engine_test.go +++ b/dashboard/internal/autolearn/engine_test.go @@ -434,3 +434,55 @@ func TestEngineCarryKeepsOtherDevices(t *testing.T) { t.Fatalf("candidates = %+v, want the results of A (daily round) and B (carried)", got) } } + +// TestEngineDailyRoundReportsCompleteRound checks that DailyRound reports the +// start of the last daily round, complete once no daily work is left over. +func TestEngineDailyRoundReportsCompleteRound(t *testing.T) { + e := newTestEngine(t, learnrec.LimitsFor(learnrec.LevelBalanced, 4)) + e.Register(Detector{Name: "daily", Group: "habit", Light: false, Run: func(ctx context.Context, in *Input, device string) []Candidate { + return nil + }}) + if got, complete := e.DailyRound(); !got.IsZero() || complete { + t.Fatalf("before any round = %v, %v, want zero and not complete", got, complete) + } + e.Tick(at(t, "2026-11-20", "03:00"), habitOnly) + e.Tick(at(t, "2026-11-20", "03:30"), habitOnly) + if got, complete := e.DailyRound(); !got.Equal(at(t, "2026-11-20", "03:30")) || !complete { + t.Fatalf("after the daily round = %v, %v, want 03:30 and complete", got, complete) + } + // Work of a daily detector left over from a round makes the round incomplete. + e.mu.Lock() + e.queue = []pending{{det: Detector{Name: "daily", Group: "habit"}}} + e.mu.Unlock() + if _, complete := e.DailyRound(); complete { + t.Error("a round with pending daily work reports complete") + } + // Pending light work does not count. + e.mu.Lock() + e.queue = []pending{{det: Detector{Name: "light", Group: "habit", Light: true}}} + e.mu.Unlock() + if _, complete := e.DailyRound(); !complete { + t.Error("a round with only light work pending reports not complete") + } +} + +// TestEngineRequestDailyRunsAgainOnNextDueTick checks that RequestDaily makes the +// next due tick run a daily round again on the same day. +func TestEngineRequestDailyRunsAgainOnNextDueTick(t *testing.T) { + e := newTestEngine(t, learnrec.LimitsFor(learnrec.LevelBalanced, 4)) + var runs atomic.Int32 + e.Register(Detector{Name: "daily", Group: "habit", Light: false, Run: func(ctx context.Context, in *Input, device string) []Candidate { + runs.Add(1) + return nil + }}) + e.Tick(at(t, "2026-11-20", "03:00"), habitOnly) + e.Tick(at(t, "2026-11-20", "03:30"), habitOnly) + if got := runs.Load(); got != 1 { + t.Fatalf("runs at 03:30 = %d, want 1", got) + } + e.RequestDaily() + e.Tick(at(t, "2026-11-20", "04:00"), habitOnly) + if got := runs.Load(); got != 2 { + t.Fatalf("runs after RequestDaily = %d, want 2", got) + } +} diff --git a/dashboard/internal/autolearn/finding.go b/dashboard/internal/autolearn/finding.go index 6f3581c6..09e3ea7b 100644 --- a/dashboard/internal/autolearn/finding.go +++ b/dashboard/internal/autolearn/finding.go @@ -55,6 +55,8 @@ type Fix struct { Template string `json:"template,omitempty"` Prefill map[string]any `json:"prefill,omitempty"` Rules []RuleOps `json:"rules,omitempty"` + // Replace replaces the rule RuleID with the new one instead of adding a rule. + Replace bool `json:"replace,omitempty"` } // RuleOps is the ops of one rule. A fix that changes several rules at once @@ -90,6 +92,8 @@ type Evidence struct { SollQ []float32 `json:"soll_q,omitempty"` BestQ []float32 `json:"best_q,omitempty"` Unit string `json:"unit,omitempty"` + // Labels names the Ist and Soll side of a scale, such as "before" and "since". + Labels []string `json:"labels,omitempty"` Max float64 `json:"max,omitempty"` Seen [2]float64 `json:"seen,omitempty"` IstValue *float64 `json:"ist_value,omitempty"` diff --git a/dashboard/internal/autolearn/gates_test.go b/dashboard/internal/autolearn/gates_test.go index 9c8ce1e2..1d34c635 100644 --- a/dashboard/internal/autolearn/gates_test.go +++ b/dashboard/internal/autolearn/gates_test.go @@ -471,3 +471,19 @@ func TestThresholdSpreadOfDailyPeaks(t *testing.T) { t.Errorf("gain_week spread = %v, want %v", spread["gain_week"], want) } } + +// TestGateDropsAdoptedSurplusSuggestion checks that the window suggestion of a +// device does not come back as a tile once its rule was adopted, with the targets +// the way the suggestions band builds them. +func TestGateDropsAdoptedSurplusSuggestion(t *testing.T) { + loc := berlinLoc(t) + in := surplusWinInput(t, surplusWinDays(loc, surplusWinExport)) + if out, _ := Gate(surplusWinRun(t, in), in.Doc, nil, GateOptions{}); len(out) != 1 { + t.Fatalf("gate keeps %d tiles before the adoption, want 1", len(out)) + } + in.Doc.Rules = []Rule{surplusWinAdoptedRule("adopted")} + out, _ := Gate(surplusWinRun(t, in), in.Doc, nil, GateOptions{Targets: RuleTargets(in.Doc, nil)}) + if len(out) != 0 { + t.Errorf("gate keeps %d tiles after the adoption, want 0: %v", len(out), out[0].ID) + } +} diff --git a/dashboard/internal/autolearn/rules.go b/dashboard/internal/autolearn/rules.go index 7f97721f..f3878fad 100644 --- a/dashboard/internal/autolearn/rules.go +++ b/dashboard/internal/autolearn/rules.go @@ -27,6 +27,17 @@ type Rule struct { Actions []Action CooldownSeconds float64 RepeatSeconds float64 + // LearnedFrom is nil when the rule was not made from a learned suggestion. + LearnedFrom *LearnedFrom +} + +// LearnedFrom marks a rule or a scenario that came from a learned suggestion. +// Suggestion is the text of the suggestion, Kind its kind and At the time in +// Unix seconds when it was accepted. +type LearnedFrom struct { + Suggestion string `json:"suggestion"` + Kind string `json:"kind"` + At int64 `json:"at"` } // Condition is one condition of a rule. Threshold is read from threshold of a @@ -113,6 +124,8 @@ type Scenario struct { // Regulator is nil when the scenario has no regulator block. Regulator *RegulatorSpec ActionTopics []string + // LearnedFrom is nil when the scenario was not made from a learned suggestion. + LearnedFrom *LearnedFrom } // RegulatorSpec is the part of a scenario regulator that the learning steps @@ -164,6 +177,7 @@ type wireRule struct { RepeatSeconds float64 `json:"repeat_seconds"` Conditions []json.RawMessage `json:"conditions"` Actions []wireAction `json:"actions"` + LearnedFrom *LearnedFrom `json:"learned_from"` } // wireCondition keeps the fields that may hold a learned reference as raw @@ -209,12 +223,13 @@ type wireAction struct { } type wireScenario struct { - ID string `json:"id"` - Name string `json:"name"` - Enabled bool `json:"enabled"` - OnStart wirePhase `json:"on_start"` - While wireWhile `json:"while"` - OnEnd wirePhase `json:"on_end"` + ID string `json:"id"` + Name string `json:"name"` + Enabled bool `json:"enabled"` + LearnedFrom *LearnedFrom `json:"learned_from"` + OnStart wirePhase `json:"on_start"` + While wireWhile `json:"while"` + OnEnd wirePhase `json:"on_end"` } type wirePhase struct { @@ -250,7 +265,7 @@ func ParseDoc(raw []byte) (Doc, error) { doc := Doc{Location: wire.Settings.location()} for _, wr := range wire.Rules { rule := Rule{ID: wr.ID, Name: wr.Name, Enabled: wr.Enabled, - CooldownSeconds: wr.CooldownSeconds, RepeatSeconds: wr.RepeatSeconds} + CooldownSeconds: wr.CooldownSeconds, RepeatSeconds: wr.RepeatSeconds, LearnedFrom: wr.LearnedFrom} for _, rawCond := range wr.Conditions { condition, err := parseCondition(rawCond) if err != nil { @@ -264,7 +279,7 @@ func ParseDoc(raw []byte) (Doc, error) { doc.Rules = append(doc.Rules, rule) } for _, ws := range wire.Scenarios { - scenario := Scenario{ID: ws.ID, Name: ws.Name, Enabled: ws.Enabled} + scenario := Scenario{ID: ws.ID, Name: ws.Name, Enabled: ws.Enabled, LearnedFrom: ws.LearnedFrom} if wr := ws.While.Regulator; wr != nil { scenario.RegulatorTopic = wr.Output.Topic scenario.Regulator = wr.spec() diff --git a/dashboard/internal/autolearn/rules_test.go b/dashboard/internal/autolearn/rules_test.go index a68e472a..c4068dd0 100644 --- a/dashboard/internal/autolearn/rules_test.go +++ b/dashboard/internal/autolearn/rules_test.go @@ -497,3 +497,36 @@ func TestLearnedReadersFindsRulesOnce(t *testing.T) { t.Fatalf("empty doc: %#v", got) } } + +// TestParseDocReadsLearnedFrom reads learned_from of a rule and of a scenario. +// A rule without the field has no LearnedFrom. +func TestParseDocReadsLearnedFrom(t *testing.T) { + raw := `{ + "version": 1, + "settings": {}, + "rules": [ + {"id": "pump", "name": "Pump", "enabled": true, "conditions": [], "actions": [], + "learned_from": {"suggestion": "Pumpe bei Export", "kind": "threshold", "at": 1700000000}}, + {"id": "plain", "name": "Plain", "enabled": true, "conditions": [], "actions": []} + ], + "scenarios": [ + {"id": "nulleinspeisung", "name": "N", "enabled": true, + "learned_from": {"suggestion": "Nulleinspeisung", "kind": "scenario", "at": 1700000001}} + ] +}` + doc, err := ParseDoc([]byte(raw)) + if err != nil { + t.Fatal(err) + } + want := &LearnedFrom{Suggestion: "Pumpe bei Export", Kind: "threshold", At: 1700000000} + if !reflect.DeepEqual(doc.Rules[0].LearnedFrom, want) { + t.Errorf("rule learned_from = %+v, want %+v", doc.Rules[0].LearnedFrom, want) + } + if doc.Rules[1].LearnedFrom != nil { + t.Errorf("rule without learned_from has %+v", doc.Rules[1].LearnedFrom) + } + wantScenario := &LearnedFrom{Suggestion: "Nulleinspeisung", Kind: "scenario", At: 1700000001} + if !reflect.DeepEqual(doc.Scenarios[0].LearnedFrom, wantScenario) { + t.Errorf("scenario learned_from = %+v, want %+v", doc.Scenarios[0].LearnedFrom, wantScenario) + } +} diff --git a/dashboard/internal/backup/catalog.go b/dashboard/internal/backup/catalog.go index ed4f2399..905bd546 100644 --- a/dashboard/internal/backup/catalog.go +++ b/dashboard/internal/backup/catalog.go @@ -99,6 +99,7 @@ var catalog = []Entry{ {RootData, "autolearn/suggestions.json", ClassRuntime, AreaHistory}, {RootData, "autolearn/reaction.json", ClassRuntime, AreaHistory}, {RootData, "autolearn/season.json", ClassRuntime, AreaHistory}, + {RootData, "autolearn/effects.json", ClassRuntime, AreaHistory}, {RootData, "autolearn/pvraster.json", ClassRuntime, AreaHistory}, {RootData, "autolearn/forecast.json", ClassRuntime, AreaHistory}, {RootData, "autolearn/pvmodel.json", ClassRuntime, AreaHistory}, diff --git a/dashboard/internal/config/automation_schema_test.go b/dashboard/internal/config/automation_schema_test.go index 8e31706f..b6c9f73d 100644 --- a/dashboard/internal/config/automation_schema_test.go +++ b/dashboard/internal/config/automation_schema_test.go @@ -300,3 +300,43 @@ func TestAutomationSchemaAcceptsLearnedValues(t *testing.T) { } } } + +// learned_from marks a rule or a scenario that came from a learned suggestion. +// All three keys are required and no other key is allowed. +func TestAutomationSchemaCasesLearnedFrom(t *testing.T) { + ruleWith := func(learned string) string { + return `{"version":1,"settings":` + defaultAutomationSettings + `,"rules":[{"id":"r1","name":"R","enabled":true,` + + `"conditions":[{"type":"balance_threshold","field":"grid_export","comparison":"above","threshold":800,"hysteresis":0,"hold_seconds":0}],` + + `"actions":[{"type":"notification","severity":"info","title":"t","message":"m"}],` + + `"learned_from":` + learned + `}],"scenarios":[]}` + } + scenarioWith := func(learned string) string { + return automationDoc(defaultAutomationSettings, + `[`+strings.Replace(minimalScenario("x"), `"enabled":true,`, `"enabled":true,"learned_from":`+learned+`,`, 1)+`]`) + } + valid := `{"suggestion":"Pumpe bei Export","kind":"threshold_low","at":1700000000}` + cases := []struct { + name string + doc string + ok bool + }{ + {"rule with learned_from", ruleWith(valid), true}, + {"scenario with learned_from", scenarioWith(valid), true}, + {"rule without at", ruleWith(`{"suggestion":"x","kind":"threshold"}`), false}, + {"scenario without at", scenarioWith(`{"suggestion":"x","kind":"threshold"}`), false}, + {"negative at", ruleWith(`{"suggestion":"x","kind":"threshold","at":-1}`), false}, + {"empty suggestion", ruleWith(`{"suggestion":"","kind":"threshold","at":0}`), false}, + {"suggestion over 200 characters", ruleWith(`{"suggestion":"` + strings.Repeat("a", 201) + `","kind":"threshold","at":0}`), false}, + {"kind with upper case", ruleWith(`{"suggestion":"x","kind":"Threshold","at":0}`), false}, + {"unknown key in learned_from", ruleWith(`{"suggestion":"x","kind":"threshold","at":0,"extra":1}`), false}, + } + for _, tc := range cases { + err := ValidateDocument([]byte(tc.doc), automationSchema(t)) + if tc.ok && err != nil { + t.Errorf("%s: expected acceptance, got %v", tc.name, err) + } + if !tc.ok && err == nil { + t.Errorf("%s: expected rejection", tc.name) + } + } +} diff --git a/dashboard/internal/monitoring/notice.go b/dashboard/internal/monitoring/notice.go index 55bf1203..832e8d55 100644 --- a/dashboard/internal/monitoring/notice.go +++ b/dashboard/internal/monitoring/notice.go @@ -29,7 +29,7 @@ type Ack struct { // Quelle (Kettenbefund), sonst null. FirstSeen und Ack setzt der Store. type Notice struct { ID string `json:"id"` - Source string `json:"source"` // energy, chain, learn + Source string `json:"source"` // energy, chain, learn, effect, suggest Severity string `json:"severity"` // warn, info Code string `json:"code"` Params map[string]any `json:"params,omitempty"` @@ -50,14 +50,20 @@ type Input struct { // Suggestions are the suggestions of the band as the automations page shows // them. Each one becomes a notice that opens it there. Suggestions []autolearn.Finding + // Effects are the measured effects of adopted suggestions. RuleNames gives + // the names of their rules and scenarios by ID. + Effects []autolearn.Finding + RuleNames map[string]string } -// Collect baut die Meldungen in fester Reihenfolge: energy, chain, learn. +// Collect baut die Meldungen in fester Reihenfolge: energy, chain, learn, +// effect, suggest. func Collect(in Input) []Notice { out := []Notice{} out = append(out, energyNotices(in)...) out = append(out, chainNotices(in.Snapshot)...) out = append(out, learnNotices(in.Findings)...) + out = append(out, effectNotices(in.Effects, in.RuleNames)...) out = append(out, suggestionNotices(in.Suggestions)...) return out } @@ -238,6 +244,42 @@ func learnNotices(findings []autolearn.Finding) []Notice { return out } +// effectNotices turns the measured effects into notices. They check an adopted +// suggestion and ask for nothing, so the step only opens the rule or scenario. +func effectNotices(list []autolearn.Finding, names map[string]string) []Notice { + var out []Notice + for _, f := range list { + if len(f.RuleIDs) == 0 { + continue + } + rule := f.RuleIDs[0] + params := make(map[string]any, len(f.Summary.Params)+3) + for k, v := range f.Summary.Params { + params[k] = v + } + params["kind"] = f.Kind + params["confidence"] = f.Confidence + params["rule"] = rule + if name := names[rule]; name != "" { + params["rule"] = name + } + n := Notice{ + ID: f.ID, + Source: "effect", + Severity: learnSeverity(f.Severity), + Code: f.Summary.Code, + Params: params, + Steps: []Step{{Code: "rule_open", Target: "rule", IDs: []string{rule}}}, + } + if f.Evidence.Shape != "" { + ev := f.Evidence + n.Evidence = &ev + } + out = append(out, n) + } + return out +} + // suggestionNotices turns the visible suggestions into notices. The step opens // the suggestion on the automations page. Their source is suggest, the page lists // them under the filter Vorschläge. diff --git a/dashboard/internal/monitoring/notice_test.go b/dashboard/internal/monitoring/notice_test.go index c36f1280..90ef58f4 100644 --- a/dashboard/internal/monitoring/notice_test.go +++ b/dashboard/internal/monitoring/notice_test.go @@ -145,3 +145,42 @@ func TestCollectOpensScenarioRegulatorFinding(t *testing.T) { t.Errorf("facts = %+v", got[0].Facts) } } + +// A measured effect becomes a notice of its own source that names the rule and opens it. +func TestMeasuredEffectsBecomeNoticesThatOpenTheRule(t *testing.T) { + in := Input{ + Effects: []autolearn.Finding{{ + ID: "effect:r1", Kind: "effect", Severity: "info", Confidence: "estimate", RuleIDs: []string{"r1"}, + Summary: autolearn.Text{Code: "effect.ok", Params: map[string]any{"before": 20.0, "since": 2.0}}, + Evidence: autolearn.Evidence{Shape: "scale", Labels: []string{"before", "since"}}, + }, { + ID: "effect:gone", Kind: "effect", Severity: "info", Confidence: "high", RuleIDs: []string{"gone"}, + Summary: autolearn.Text{Code: "effect.not_measurable"}, + }}, + RuleNames: map[string]string{"r1": "Entfeuchter aus"}, + } + got := Collect(in) + if len(got) != 2 { + t.Fatalf("notices = %+v, want two", got) + } + n := got[0] + if n.ID != "effect:r1" || n.Source != "effect" || n.Severity != "info" || n.Code != "effect.ok" { + t.Errorf("notice = %+v", n) + } + if n.Params["rule"] != "Entfeuchter aus" || n.Params["kind"] != "effect" || n.Params["confidence"] != "estimate" || n.Params["before"] != 20.0 { + t.Errorf("params = %+v", n.Params) + } + if len(n.Steps) != 1 || n.Steps[0].Code != "rule_open" || n.Steps[0].Target != "rule" || + len(n.Steps[0].IDs) != 1 || n.Steps[0].IDs[0] != "r1" { + t.Errorf("steps = %+v, want one rule_open step with the rule id", n.Steps) + } + if n.Evidence == nil || n.Evidence.Shape != "scale" { + t.Errorf("evidence = %+v", n.Evidence) + } + if got[1].Params["rule"] != "gone" || got[1].Evidence != nil { + t.Errorf("without a name the ID stands, without a shape no evidence: %+v", got[1]) + } + if in.Effects[0].Summary.Params["rule"] != nil { + t.Error("Collect changed the params of the finding") + } +} diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index 03d61511..79354015 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,11 +1,17 @@ version,date,asset,v,note +v0.11.22-pre.38,2026-11-29,css/automations.css,26, +v0.11.22-pre.38,2026-11-29,js/automation-evidence.js,7, +v0.11.22-pre.38,2026-11-29,js/automation-suggestions.js,7, +v0.11.22-pre.38,2026-11-29,js/automations.page.js,33, +v0.11.22-pre.38,2026-11-29,js/monitoring-model.js,5, +v0.11.22-pre.38,2026-11-29,js/monitoring.page.js,4, +v0.11.22-pre.37,2026-11-25,css/settings-controls.css,21,"settings, diagnostics: system card on the versions page" +v0.11.22-pre.37,2026-11-25,js/versions.page.js,11,"settings, diagnostics: system card on the versions page" v0.11.22-pre.36,2026-11-23,css/monitoring.css,2, v0.11.22-pre.36,2026-11-23,js/monitoring-insight-model.js,1, v0.11.22-pre.36,2026-11-23,js/monitoring-insight.js,1, v0.11.22-pre.36,2026-11-23,js/monitoring-model.js,4, v0.11.22-pre.36,2026-11-23,js/monitoring.page.js,3, -v0.11.22-pre.37,2026-11-25,css/settings-controls.css,21,"settings, diagnostics: system card on the versions page" -v0.11.22-pre.37,2026-11-25,js/versions.page.js,11,"settings, diagnostics: system card on the versions page" v0.11.22-pre.35,2026-11-23,css/automations.css,25, v0.11.22-pre.35,2026-11-23,js/automation-suggestions.js,6, v0.11.22-pre.35,2026-11-23,js/automations.page.js,32, diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 3d68e529..fc8e3481 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -547,6 +547,21 @@ "automations.learn.coupling.follow.text": "{b} wurde {hits} von {cases} Mal innerhalb von {lag_s} Sekunden geschaltet, nachdem {a} geschaltet wurde. Eine Regel kann das übernehmen, dann musst du nur noch {a} schalten.", "automations.learn.coupling.follow.title": "{b} folgt {a}", "automations.learn.drop_failed": "Das Verwerfen hat nicht geklappt. Bitte versuche es erneut.", + "automations.learn.effect.count_only.line": "Von Hand überstimmt {overridden} von {fired} Mal", + "automations.learn.effect.count_only.text": "Von Hand überstimmt {overridden} von {fired} Mal.", + "automations.learn.effect.count_only.title": "{rule}", + "automations.learn.effect.no_baseline.line": "Keine Vergleichsdaten", + "automations.learn.effect.no_baseline.text": "Keine Vergleichsdaten aus der Zeit vor der Übernahme. Von Hand überstimmt {overridden} von {fired} Mal.", + "automations.learn.effect.no_baseline.title": "{rule}", + "automations.learn.effect.not_measurable.line": "Noch nicht messbar", + "automations.learn.effect.not_measurable.text": "Noch nicht messbar, die Woche schwankt mehr als die Wirkung. Von Hand überstimmt {overridden} von {fired} Mal.", + "automations.learn.effect.not_measurable.title": "{rule}", + "automations.learn.effect.ok.line": "Vorher {before} {unit}, seitdem {since} {unit}", + "automations.learn.effect.ok.text": "Vorher {before} {unit}, seitdem {since} {unit}. Von Hand überstimmt {overridden} von {fired} Mal.", + "automations.learn.effect.ok.title": "{rule}", + "automations.learn.effect.waiting.line": "Wirkung ab dem {date} sichtbar", + "automations.learn.effect.waiting.text": "Wirkung ab dem {date} sichtbar. Von Hand überstimmt {overridden} von {fired} Mal.", + "automations.learn.effect.waiting.title": "{rule}", "automations.learn.fact.cause": "Ursache", "automations.learn.fact.cause.clustered": "Die Befehle kamen gebündelt", "automations.learn.fact.cause.feedback": "Die Last selbst kippt die Bedingung", @@ -581,6 +596,7 @@ "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.quiet_off": "Regel neu anlegen", "automations.learn.fix.repeat": "Als Wiederholung zusammenfassen", "automations.learn.fix.set_cooldown": "Abkühlzeit {value} s", "automations.learn.fix.set_hysteresis": "Hysterese {value} W", @@ -588,13 +604,19 @@ "automations.learn.fix.set_threshold": "Schwelle auf {value}", "automations.learn.fix.shift_time": "Zeitfenster verschieben", "automations.learn.fix.stagger": "Schwellen staffeln", + "automations.learn.fix.surplus_switch": "Szenario neu anlegen", + "automations.learn.fix.surplus_wallbox": "Szenario neu anlegen", + "automations.learn.fix.time_point": "Neue Zeit übernehmen", + "automations.learn.fix.time_point_learned": "Auf den Lernwert umstellen", "automations.learn.group.check": "Regelprüfung", "automations.learn.group.energy": "Energie", "automations.learn.group.habit": "Gewohnheit", "automations.learn.group.reliability": "Zuverlässigkeit", "automations.learn.hint.dismissed": "Vorschlag ausgeblendet", "automations.learn.ignore": "Ignorieren", + "automations.learn.lane.before": "Vorher", "automations.learn.lane.ist": "Ist", + "automations.learn.lane.since": "Seitdem", "automations.learn.lane.soll": "Soll", "automations.learn.legend.day": "Ist: wann es passiert ist. Soll: wann der Vorschlag schalten würde.", "automations.learn.legend.events": "Ist: jedes beobachtete Ereignis. Soll: was der Vorschlag ändern würde.", @@ -603,7 +625,13 @@ "automations.learn.mark_label": "Befund zu dieser Regel anzeigen", "automations.learn.param.deadband_w": "Totzone", "automations.learn.param.gain": "Verstärkung", + "automations.learn.param.kwh_day": "Verbrauch am Tag", "automations.learn.param.max_change_w": "Änderungsgrenze", + "automations.learn.param.on_w": "Einschaltschwelle", + "automations.learn.param.soll": "Schwelle", + "automations.learn.param.start": "Beginn", + "automations.learn.param.time": "Uhrzeit", + "automations.learn.param.window_quarters": "Länge in Viertelstunden", "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", @@ -613,6 +641,18 @@ "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.season_shift.away_standby.line": "Bisher {old} kWh am Tag, jetzt {new} kWh", + "automations.learn.season_shift.away_standby.text": "Der Verbrauch von {device} bei Abwesenheit lag bei {old} kWh am Tag und liegt jetzt bei {new} kWh. Der Assistent ersetzt die Regel, gespeichert wird erst mit Speichern.", + "automations.learn.season_shift.away_standby.title": "{rule}: Verbrauch bei Abwesenheit hat sich geändert", + "automations.learn.season_shift.generic.line": "{param}: bisher {old}, jetzt {new}", + "automations.learn.season_shift.generic.text": "{param} lag bei {old} und liegt jetzt bei {new}. Die Lösung ändert die Regel, gespeichert wird erst mit Speichern.", + "automations.learn.season_shift.generic.title": "{rule}: Werte haben sich verschoben", + "automations.learn.season_shift.surplus_window.line": "{param}: bisher {old}, jetzt {new}", + "automations.learn.season_shift.surplus_window.text": "Das typische Überschussfenster für {device} hat sich geändert. {param} lag bei {old} und liegt jetzt bei {new}. Der Assistent ersetzt das Szenario, gespeichert wird erst mit Speichern.", + "automations.learn.season_shift.surplus_window.title": "{rule}: Überschussfenster hat sich verschoben", + "automations.learn.season_shift.switch_time.line": "Bisher {old} Uhr, jetzt passt {new} Uhr", + "automations.learn.season_shift.switch_time.text": "Als die Regel entstand, passte {old} Uhr. Inzwischen passt {new} Uhr besser. Der Assistent ersetzt die Regel, gespeichert wird erst mit Speichern.", + "automations.learn.season_shift.switch_time.title": "{rule}: Schaltzeit hat sich verschoben", "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", @@ -650,6 +690,7 @@ "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.actions_week": "Handgriffe/Woche", "automations.learn.unit.kwh_week": "kWh/Woche", "automations.learn.value.minutes": "{value} min", "automations.learn.value.per_hour": "{value} pro Stunde", @@ -3772,6 +3813,7 @@ "monitoring.energy_line.new": "{count} neu", "monitoring.energy_line.none": "Keine offenen Meldungen zur Energie", "monitoring.energy_line.open": "Im Monitoring ansehen", + "monitoring.fact.confidence": "Belastbarkeit", "monitoring.fact.direction": "Richtung", "monitoring.fact.direction_value": "{az}° ({compass}), {el}° über dem Horizont", "monitoring.fact.loss": "Verlust", @@ -3782,6 +3824,7 @@ "monitoring.fact.value": "Wert", "monitoring.fact.weeks": "Kalenderwochen", "monitoring.filter.all": "Alle", + "monitoring.filter.effect": "Erfolgskontrolle", "monitoring.filter.energy": "Energie", "monitoring.filter.label": "Quelle", "monitoring.filter.learn": "Lernfunktionen", @@ -3857,6 +3900,7 @@ "monitoring.site.surplus_note": "Prognose von 10 Uhr", "monitoring.site.to_forecast": "Zur Prognose", "monitoring.source.chain": "Messketten", + "monitoring.source.effect": "Erfolgskontrolle", "monitoring.source.energy": "Energie-Bilanz", "monitoring.source.learn": "Lernfunktionen", "monitoring.source.suggest": "Vorschläge", @@ -3880,6 +3924,8 @@ "monitoring.step.load_mode_auto.button": "Zur Einstellung", "monitoring.step.role_keep": "Oder alle ohne Rolle lassen", "monitoring.step.role_keep.button": "Ohne Rolle lassen", + "monitoring.step.rule_open": "Die geprüfte Regel steht unter Automationen", + "monitoring.step.rule_open.button": "Regel öffnen", "monitoring.step.set_load_role": "Dem Hauszähler die Rolle Hauszähler geben", "monitoring.step.set_load_role.button": "Rolle setzen", "monitoring.step.set_role": "Rolle der Werte neu setzen", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 683fc1c9..a1561a1e 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -547,6 +547,21 @@ "automations.learn.coupling.follow.text": "{b} was switched {hits} of {cases} times within {lag_s} seconds after {a} was switched. A rule can take that over, so you only have to switch {a}.", "automations.learn.coupling.follow.title": "{b} follows {a}", "automations.learn.drop_failed": "Dismissing did not work. Please try again.", + "automations.learn.effect.count_only.line": "Overridden by hand {overridden} of {fired} times", + "automations.learn.effect.count_only.text": "Overridden by hand {overridden} of {fired} times.", + "automations.learn.effect.count_only.title": "{rule}", + "automations.learn.effect.no_baseline.line": "No comparison data", + "automations.learn.effect.no_baseline.text": "No comparison data from before the change. Overridden by hand {overridden} of {fired} times.", + "automations.learn.effect.no_baseline.title": "{rule}", + "automations.learn.effect.not_measurable.line": "Not measurable yet", + "automations.learn.effect.not_measurable.text": "Not measurable yet, the week varies more than the effect. Overridden by hand {overridden} of {fired} times.", + "automations.learn.effect.not_measurable.title": "{rule}", + "automations.learn.effect.ok.line": "Before {before} {unit}, since then {since} {unit}", + "automations.learn.effect.ok.text": "Before {before} {unit}, since then {since} {unit}. Overridden by hand {overridden} of {fired} times.", + "automations.learn.effect.ok.title": "{rule}", + "automations.learn.effect.waiting.line": "Effect visible from {date}", + "automations.learn.effect.waiting.text": "Effect visible from {date}. Overridden by hand {overridden} of {fired} times.", + "automations.learn.effect.waiting.title": "{rule}", "automations.learn.fact.cause": "Cause", "automations.learn.fact.cause.clustered": "The commands came in bunches", "automations.learn.fact.cause.feedback": "The load itself flips the condition", @@ -581,6 +596,7 @@ "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.quiet_off": "Rebuild the rule", "automations.learn.fix.repeat": "Combine as a repeat", "automations.learn.fix.set_cooldown": "Cooldown {value} s", "automations.learn.fix.set_hysteresis": "Hysteresis {value} W", @@ -588,13 +604,19 @@ "automations.learn.fix.set_threshold": "Threshold to {value}", "automations.learn.fix.shift_time": "Shift the time window", "automations.learn.fix.stagger": "Stagger the thresholds", + "automations.learn.fix.surplus_switch": "Rebuild the scenario", + "automations.learn.fix.surplus_wallbox": "Rebuild the scenario", + "automations.learn.fix.time_point": "Use the new time", + "automations.learn.fix.time_point_learned": "Switch to the learned value", "automations.learn.group.check": "Rule check", "automations.learn.group.energy": "Energy", "automations.learn.group.habit": "Habit", "automations.learn.group.reliability": "Reliability", "automations.learn.hint.dismissed": "Suggestion hidden", "automations.learn.ignore": "Ignore", + "automations.learn.lane.before": "Before", "automations.learn.lane.ist": "Actual", + "automations.learn.lane.since": "Since", "automations.learn.lane.soll": "Target", "automations.learn.legend.day": "Actual: when it happened. Target: when the suggestion would switch.", "automations.learn.legend.events": "Actual: each event we saw. Target: what the suggestion would change.", @@ -603,7 +625,13 @@ "automations.learn.mark_label": "Show the finding for this rule", "automations.learn.param.deadband_w": "Deadband", "automations.learn.param.gain": "Gain", + "automations.learn.param.kwh_day": "Consumption per day", "automations.learn.param.max_change_w": "Change limit", + "automations.learn.param.on_w": "Switch on threshold", + "automations.learn.param.soll": "Threshold", + "automations.learn.param.start": "Start", + "automations.learn.param.time": "Time", + "automations.learn.param.window_quarters": "Length in quarter hours", "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", @@ -613,6 +641,18 @@ "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.season_shift.away_standby.line": "So far {old} kWh a day, now {new} kWh", + "automations.learn.season_shift.away_standby.text": "The consumption of {device} while away was {old} kWh a day and is {new} kWh now. The assistant replaces the rule, nothing is stored until you save.", + "automations.learn.season_shift.away_standby.title": "{rule}: the consumption while away has changed", + "automations.learn.season_shift.generic.line": "{param}: so far {old}, now {new}", + "automations.learn.season_shift.generic.text": "{param} was {old} and is {new} now. The fix changes the rule, nothing is stored until you save.", + "automations.learn.season_shift.generic.title": "{rule}: the values have moved", + "automations.learn.season_shift.surplus_window.line": "{param}: so far {old}, now {new}", + "automations.learn.season_shift.surplus_window.text": "The typical surplus window for {device} has changed. {param} was {old} and is {new} now. The assistant replaces the scenario, nothing is stored until you save.", + "automations.learn.season_shift.surplus_window.title": "{rule}: the surplus window has moved", + "automations.learn.season_shift.switch_time.line": "So far {old}, now {new} fits", + "automations.learn.season_shift.switch_time.text": "When the rule was made, {old} fitted. {new} fits better now. The assistant replaces the rule, nothing is stored until you save.", + "automations.learn.season_shift.switch_time.title": "{rule}: the switching time has moved", "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", @@ -650,6 +690,7 @@ "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.actions_week": "manual actions/week", "automations.learn.unit.kwh_week": "kWh/week", "automations.learn.value.minutes": "{value} min", "automations.learn.value.per_hour": "{value} per hour", @@ -3772,6 +3813,7 @@ "monitoring.energy_line.new": "{count} new", "monitoring.energy_line.none": "No open notices about energy", "monitoring.energy_line.open": "Open in monitoring", + "monitoring.fact.confidence": "Confidence", "monitoring.fact.direction": "Direction", "monitoring.fact.direction_value": "{az}° ({compass}), {el}° above the horizon", "monitoring.fact.loss": "Loss", @@ -3782,6 +3824,7 @@ "monitoring.fact.value": "Value", "monitoring.fact.weeks": "Calendar weeks", "monitoring.filter.all": "All", + "monitoring.filter.effect": "Results check", "monitoring.filter.energy": "Energy", "monitoring.filter.label": "Source", "monitoring.filter.learn": "Learning", @@ -3857,6 +3900,7 @@ "monitoring.site.surplus_note": "Forecast from 10:00", "monitoring.site.to_forecast": "To the forecast", "monitoring.source.chain": "Measurement chains", + "monitoring.source.effect": "Results check", "monitoring.source.energy": "Energy balance", "monitoring.source.learn": "Learning", "monitoring.source.suggest": "Suggestions", @@ -3880,6 +3924,8 @@ "monitoring.step.load_mode_auto.button": "To the setting", "monitoring.step.role_keep": "Or leave all of them without a role", "monitoring.step.role_keep.button": "Leave without role", + "monitoring.step.rule_open": "The checked rule is under Automations", + "monitoring.step.rule_open.button": "Open the rule", "monitoring.step.set_load_role": "Give the house meter the role house meter", "monitoring.step.set_load_role.button": "Set role", "monitoring.step.set_role": "Set the role of the values again", diff --git a/dashboard/internal/webui/learn_summary_catalog_test.go b/dashboard/internal/webui/learn_summary_catalog_test.go index 266ebb81..634917e4 100644 --- a/dashboard/internal/webui/learn_summary_catalog_test.go +++ b/dashboard/internal/webui/learn_summary_catalog_test.go @@ -52,6 +52,12 @@ func autolearnSummaryKeys(t *testing.T) []string { for _, match := range summaryCodeLiteral.FindAllStringSubmatch(string(src), -1) { code := match[1] switch { + case code == "season_shift.": + // The suffix is the kind of the adopted suggestion. The browser maps + // every other kind to generic. + for _, kind := range []string{"switch_time", "away_standby", "surplus_window", "generic"} { + codes[code+kind] = true + } case strings.HasSuffix(code, "sun_"): codes[code+"on.after"] = true codes[code+"on.before"] = true diff --git a/dashboard/internal/webui/static/css/automations.css b/dashboard/internal/webui/static/css/automations.css index 59938f67..ab60598e 100644 --- a/dashboard/internal/webui/static/css/automations.css +++ b/dashboard/internal/webui/static/css/automations.css @@ -1013,6 +1013,10 @@ label.settings-toggle.auto-assist-check .settings-toggle-track { flex: none; wid .auto-learn-plot-svg .auto-learn-best { fill: none; stroke: var(--accent); stroke-width: 2; stroke-linejoin: round; } .auto-learn-plot-svg .auto-learn-throttled { fill: var(--accent-bg); stroke: none; } .auto-learn-axis { display: grid; grid-template-columns: 2.2rem minmax(0, 1fr); gap: .5rem; } +/* Spuren und Achse teilen die Spalte, deshalb bleiben die Ticks auf den Balken. */ +.auto-learn-labelled { --auto-learn-label-w: 4.2rem; } +.auto-learn-labelled .auto-learn-lane, +.auto-learn-labelled .auto-learn-axis { grid-template-columns: var(--auto-learn-label-w) minmax(0, 1fr); } .auto-learn-axis-track { position: relative; height: 1.1rem; min-width: 0; } .auto-learn-ticks { position: absolute; top: 0; left: 0; width: 100%; height: 5px; overflow: visible; } .auto-learn-ticks line { stroke: var(--text-faint); stroke-width: 1; } diff --git a/dashboard/internal/webui/static/js/automation-evidence.js b/dashboard/internal/webui/static/js/automation-evidence.js index e729d788..7d632b55 100644 --- a/dashboard/internal/webui/static/js/automation-evidence.js +++ b/dashboard/internal/webui/static/js/automation-evidence.js @@ -298,31 +298,45 @@ } // Einheiten mit Katalogtext, sonst die Einheit wie geliefert. - const UNIT_KEYS = { kwh_week: 'automations.learn.unit.kwh_week' }; + const UNIT_KEYS = { kwh_week: 'automations.learn.unit.kwh_week', actions_week: 'automations.learn.unit.actions_week' }; function unitOf(ev, t) { return UNIT_KEYS[ev.unit] ? t(UNIT_KEYS[ev.unit]) : ev.unit; } + // Eine gerundete Zahl im Zahlformat der Seite, ohne Seitenformat wie geliefert. + function numberText(v) { + const format = window.I18n && window.I18n.formatNumber; + return format ? format(v, Number.isInteger(v) ? 0 : String(v).split('.')[1].length) : v; + } + // 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 + // i18n-keys: automations.learn.param.gain, automations.learn.param.deadband_w, automations.learn.param.max_change_w, automations.learn.param.time, automations.learn.param.start, automations.learn.param.window_quarters, automations.learn.param.on_w, automations.learn.param.soll, automations.learn.param.kwh_day const PARAM_KEYS = { gain: 'automations.learn.param.gain', deadband_w: 'automations.learn.param.deadband_w', max_change_w: 'automations.learn.param.max_change_w', + time: 'automations.learn.param.time', + start: 'automations.learn.param.start', + window_quarters: 'automations.learn.param.window_quarters', + on_w: 'automations.learn.param.on_w', + soll: 'automations.learn.param.soll', + kwh_day: 'automations.learn.param.kwh_day', }; function scaleBarsShape(ev, t) { return ev.scales.map((bar, index) => { + // Uhrzeiten laufen ueber den ganzen Tag, ohne Einheit an der Achse. + const clock = bar.unit === 'clock'; const top = Math.max(bar.ist || 0, bar.soll || 0); - const max = top > 0 ? top * 1.2 : 1; + const max = clock ? DAY : (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 unit = bar.unit && !clock ? ' ' + bar.unit : ''; + const majors = clock ? [0, DAY / 2, DAY] : [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 })); + const labels = majors.map((v) => ({ x: toX(v), text: clock ? clockText(v, true) : numberText(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) @@ -347,10 +361,22 @@ const sollBar = hasSoll ? '' : ''; const soll = hasSoll ? marks([ev.soll_value], toX, 'auto-learn-mark-soll auto-learn-mark-wide') : ''; const ticks = majors.map((v) => ({ x: toX(v), major: true })); - const labels = majors.map((v) => ({ x: toX(v), text: Math.round(v) + unit })); - return lane(t('automations.learn.lane.ist'), laneSvg(grid + seen + istBar + threshold)) // i18n-ignore - + lane(t('automations.learn.lane.soll'), laneSvg(grid + sollBar + soll), true) + // Unter 10 mit einer Nachkommastelle im Zahlformat der Seite, sonst als Zahl. + const decimal = (v) => { + if (Math.abs(v) >= 10) return Math.round(v); + return numberText(Math.round(v * 10) / 10); + }; + // Zwei Labels (Vorher und Seitdem) benennen die Spuren, sonst Ist und Soll. + const beforeSince = Array.isArray(ev.labels) && ev.labels.length === 2; + // Die langen Einheiten je Woche stossen auf dem Handy zusammen, dort stehen nur Anfang und Ende + // und die Einheit nur am Ende. + const named = beforeSince ? [0, max] : majors; + const labels = named.map((v) => ({ x: toX(v), text: decimal(v) + (beforeSince && v !== max ? '' : unit) })); + const body = lane(beforeSince ? t('automations.learn.lane.before') : t('automations.learn.lane.ist'), laneSvg(grid + seen + istBar + threshold)) // i18n-ignore + + lane(beforeSince ? t('automations.learn.lane.since') : t('automations.learn.lane.soll'), laneSvg(grid + sollBar + soll), true) + axisHtml(ticks, labels); + // Die Wortmarken Vorher und Seitdem brauchen eine breitere Spalte, Spuren und Achse teilen sie. + return beforeSince ? '
' + body + '
' : body; } // Ist und Soll teilen eine Kurvenflaeche, die Soll-Ebene liegt ueber der Ist-Ebene. diff --git a/dashboard/internal/webui/static/js/automation-suggestions.js b/dashboard/internal/webui/static/js/automation-suggestions.js index c49f4228..a5a8a83c 100644 --- a/dashboard/internal/webui/static/js/automation-suggestions.js +++ b/dashboard/internal/webui/static/js/automation-suggestions.js @@ -34,6 +34,19 @@ // Ohne gemessenen Verbraucher bleibt der Name leer, der Text nennt dann den Verbraucher ohne Messung. if (code === 'baseload.drift' && !params.candidate) params.candidate = t('automations.learn.baseload.candidate.none'); if (code === 'battery.empty_early' && !params.candidates) params.candidates = t('automations.learn.battery.candidate.none'); + // Wirkung: die Einheit als Katalogtext, das Datum im Format der Seite. + if (code.indexOf('effect.') === 0) { + // i18n-keys: automations.learn.unit.kwh_week, automations.learn.unit.actions_week + if (params.unit) params.unit = t(CAT + 'unit.' + params.unit); + const formatDate = window.I18n && window.I18n.formatDate; + if (params.date && formatDate) params.date = formatDate(new Date(params.date + 'T12:00:00')); + } + // Schaltzeit, Verbrauch und Fenster haben je einen Katalogtext. Unbekannte Arten nehmen den allgemeinen. + if (code.indexOf('season_shift.') === 0) { + // i18n-keys: automations.learn.param.time, automations.learn.param.start, automations.learn.param.window_quarters, automations.learn.param.on_w, automations.learn.param.soll, automations.learn.param.kwh_day, automations.learn.param.gain, automations.learn.param.deadband_w, automations.learn.param.max_change_w + if (params.key) params.param = t(CAT + 'param.' + params.key); + if (!/^season_shift\.(switch_time|away_standby|surplus_window)$/.test(code)) code = 'season_shift.generic'; + } if (/^switch_time\.sun_(on|off)$/.test(code)) { const offset = Number(params.offset_min) || 0; params.minutes = Math.abs(offset); @@ -93,7 +106,17 @@ // 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 }; + // Der Befund nennt seine Regel oder Szene beim Namen. Ohne Treffer bleibt die Kennung. + function withRuleName(finding, doc) { + const ids = finding && Array.isArray(finding.rule_ids) ? finding.rule_ids : []; + const id = ids[0]; + const known = ((doc && doc.rules) || []).concat((doc && doc.scenarios) || []); + const hit = known.find((x) => x && x.id === id); + const name = hit && hit.name ? hit.name : id; + const summary = finding.summary || {}; + return { ...finding, summary: { ...summary, params: { ...(summary.params || {}), rule: name } } }; + } + const api = { arrange, title, line, text, legend, resolveSummary, factRows, withRuleName }; window.AutomationSuggestions = api; // Vorschlagsband oberhalb der Regeln. Laedt einmal beim Oeffnen der Seite. Die @@ -278,6 +301,8 @@ fixOf(s) { return (s.apply || []).find((f) => f && f.template) || null; }, // Ein Befehl mit Ops schreibt seine Pfade direkt in den Regelentwurf (applyFix der Seite). opFixOf(s) { return (s.apply || []).find((f) => f && !f.template && Array.isArray(f.ops) && f.ops.length > 0) || null; }, + // Herkunft fuer den Assistenten: Id und Art des Vorschlags, learned_from der angelegten Regel. + originOf(s) { return { suggestion: s.id, kind: s.kind }; }, applyLabelOf(s, t) { const fix = this.opFixOf(s); return fix ? t(CAT + 'fix.' + fix.code, {}) : ''; @@ -286,7 +311,6 @@ const edit = Boolean(this.canEdit) && Boolean(s); return { assistant: edit && Boolean(this.fixOf(s)), apply: edit && Boolean(this.opFixOf(s)), later: edit, dismiss: edit }; }, - async send(s, action) { const response = await window.fetch(base() + REQUEST_PATH + '/' + encodeURIComponent(s.id) + '/' + action, { method: 'POST', diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index 55763a09..6e4e3792 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -159,7 +159,7 @@ // Zustand des Vorlagen-Assistenten im Ruhezustand (Dialog zu). const assistantIdle = () => ({ open: false, templateId: '', answers: {}, index: 0, name: '', query: '', category: 'all', context: null, effects: {}, - band: { tolOn: false, errors: null }, surplus: null, + band: { tolOn: false, errors: null }, surplus: null, origin: null, }); // Zielband im Assistenten: Griff und Zustand leben ausserhalb der reaktiven Daten. let bandHandle = null; @@ -1377,9 +1377,22 @@ // Die Device Map verweist auf eine Regel: aufklappen, zur Regel scrollen // und sie kurz hervorheben. + // Zeigt die Regel im Reiter Regeln, ein Szenario aufgeklappt im Reiter Szenarien. focusRule(ruleId) { window.__automationFocusRequest__ = null; if (!ruleId) return; + const doc = this.document || {}; + if ((doc.scenarios || []).some((scenario) => scenario.id === ruleId)) { + this.view = 'scenarios'; + this.scenarioExpanded[ruleId] = true; + const show = () => { + const node = document.querySelector(`[data-scenario-id="${CSS.escape(ruleId)}"]`); + if (node) node.scrollIntoView({behavior: window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', block: 'start'}); + }; + if (this.$nextTick) this.$nextTick(show); else show(); + return; + } + if ((doc.rules || []).some((rule) => rule.id === ruleId)) this.view = 'rules'; this.expanded[ruleId] = true; this.flashRule = ruleId; setTimeout(() => { if (this.flashRule === ruleId) this.flashRule = ''; }, 1600); @@ -1621,10 +1634,17 @@ // falsch geformte Vorbelegung oeffnet die Galerie ohne Vorbelegung. Vorbelegte // Geraete, die es nicht gibt oder die gesperrt sind, werden leer. Danach springt // der Assistent zum ersten unvollstaendigen Schritt, sonst zur Zusammenfassung. - async openAssistantWith(templateId, prefill) { + // origin (optional) ist { suggestion, kind, replaceId? } des Vorschlags. assistantCreate + // setzt daraus learned_from an den angelegten Eintrag. + async openAssistantWith(templateId, prefill, origin = null) { await this.openAssistant(); const mapped = prefillToAnswers(templateId, prefill); - if (!mapped || !assistantTemplateList().some((item) => item.id === templateId) || !this.assistant.context) return; + if (!mapped || !assistantTemplateList().some((item) => item.id === templateId) || !this.assistant.context) { + // Ohne Vorlage gibt es keinen Ursprung. Sonst bekaeme eine spaeter von Hand gewaehlte Vorlage learned_from. + this.assistant.origin = null; + return; + } + this.assistant.origin = origin && origin.suggestion ? origin : null; this.startTemplate(templateId); const answers = { ...this.assistant.answers }; for (const [key, value] of Object.entries(mapped)) { @@ -2003,12 +2023,34 @@ // Legt die Vorlage an: ungespeichert, aktiv, mit Rueckgaengig. Bei voller Liste // passiert nichts, der Dialog bleibt offen. Alle Eintraege sind schon gebaut, bevor // der erste eingefuegt wird, daher bleibt bei einem Fehler nichts halb angelegt. + // Kommt die Vorlage aus einem vorschlag (origin), traegt jeder Eintrag learned_from. + // Mit replaceId ersetzt der erste Eintrag die Regel mit dieser ID, die ID bleibt. assistantCreate() { const built = this.assistantBuild(); if (!built) return; const { kind, entries } = this.assistantEntries(built); - if (this.assistantFull(kind, entries.length)) return; - this.insertEntries(kind, entries); + const origin = this.assistant.origin; + const list = kind === 'scenario' ? this.document.scenarios : this.document.rules; + const replaceIndex = origin && origin.replaceId ? list.findIndex((entry) => entry.id === origin.replaceId) : -1; + if (replaceIndex < 0 && this.assistantFull(kind, entries.length)) return; + if (origin) { + const at = Math.floor(Date.now() / 1000); + entries.forEach((entry) => { + entry.learned_from = { suggestion: origin.suggestion, kind: origin.kind, at }; + }); + } + if (replaceIndex < 0) { + this.insertEntries(kind, entries); + } else { + const [first, ...rest] = entries; + first.id = list[replaceIndex].id; + list.splice(replaceIndex, 1, first); + this.newIds[first.id] = true; + this.expanded[first.id] = true; + this.editing[first.id] = true; + this.view = kind === 'scenario' ? 'scenarios' : 'rules'; + if (rest.length) this.insertEntries(kind, rest); + } this.closeAssistant(); }, @@ -2267,7 +2309,11 @@ }, findingText(finding) { // Schluessel und Parameter teilen sich Vorschlagsband und Regelmarken (automation-suggestions.js). - const { code, params } = window.AutomationSuggestions.resolveSummary(finding.summary, t); + // Wirkung und Jahreszeit nennen die Regel beim Namen (withRuleName). + const named = finding.kind === 'effect' || finding.kind === 'season_shift' + ? window.AutomationSuggestions.withRuleName(finding, this.document) + : finding; + const { code, params } = window.AutomationSuggestions.resolveSummary(named.summary, t); return { title: t(`automations.learn.${code}.title`, params), text: t(`automations.learn.${code}.text`, params), @@ -2316,7 +2362,21 @@ // seit dem Befund geaendert), wird nichts geschrieben, die Regel oeffnet sich trotzdem. // Ein Befund mit fix.rules aendert mehrere Regeln: alle oder keine. // finding (optional) ist der Befund des Popovers, er bleibt bis zum Speichern verborgen. - applyFix(fix, finding = null) { + // Mit finding setzt jede Regel oder jedes Szenario, auf die alle Ops geschrieben wurden, + // learned_from mit der Befund-Id als suggestion. + applyFix(fix, finding = null, asSuggestion = true) { + // Ein Ersatz-Vorschlag oeffnet den Assistenten mit der Vorbelegung. Die Regel + // bleibt unveraendert, bis der Assistent sie ersetzt. + if (fix.template && fix.replace) { + const summary = (finding && finding.summary) || {}; + const origin = { + suggestion: (summary.params || {}).suggestion, + kind: String(summary.code || '').split('.')[1], + replaceId: fix.rule_id, + }; + // Der Befund bleibt offen, bis der Assistent offen ist. Sonst sucht er seine Flaeche im entfernten Popover. + return Promise.resolve(this.openAssistantWith(fix.template, fix.prefill, origin)).then(() => this.closeFinding()); + } const groups = Array.isArray(fix.rules) && fix.rules.length ? fix.rules.map((entry) => ({ code: fix.code, rule_id: entry.rule_id, ops: entry.ops || [] })) : [{ code: fix.code, rule_id: fix.rule_id, ops: fix.ops || [] }]; @@ -2353,6 +2413,26 @@ if (write.target.append) write.target.parent.push(write.value); else write.target.parent[write.target.key] = write.value; })); + // Ein Ersatz mit Ops (etwa ein Schwellen-Befund) erneuert die Markierung auf den + // Vorschlag des Befunds, damit der Verlauf der Regel weiterlaeuft. + const renewal = fix.replace && !fix.template && finding && finding.summary + && finding.summary.params && finding.summary.params.suggestion; + if (renewal) { + const at = Math.floor(Date.now() / 1000); + const kind = String(finding.summary.code || '').split('.')[1]; + plans.forEach((plan) => { + if (plan.entry && plan.writes.length > 0) { + plan.entry.learned_from = { suggestion: finding.summary.params.suggestion, kind, at }; + } + }); + } else if (asSuggestion && finding && finding.id) { + const at = Math.floor(Date.now() / 1000); + plans.forEach((plan) => { + if (plan.entry && plan.writes.length > 0) { + plan.entry.learned_from = { suggestion: finding.id, kind: finding.kind, at }; + } + }); + } if (finding && finding.id && !this.appliedFindingIds.includes(finding.id)) { this.appliedFindingIds = [...this.appliedFindingIds, finding.id]; } diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index a8484694..46f1b61a 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -7,20 +7,19 @@ const pad = (n) => String(n).padStart(2, '0'); // Quelle für Filter und Gruppen: Energie-Bilanz und Messketten zusammen, Vorschläge - // für sich, sonst Lernfunktionen. + // und Erfolgskontrolle für sich, sonst Lernfunktionen. function sourceOf(notice) { if (notice.source === 'energy' || notice.source === 'chain') return 'energy'; - return notice.source === 'suggest' ? 'suggest' : 'learn'; + return notice.source === 'suggest' || notice.source === 'effect' ? notice.source : 'learn'; } - // Lernbefunde und Vorschläge teilen Texte und Belege der Automationen. + // Lernbefunde, Vorschläge und Erfolgskontrolle teilen Texte und Belege der Automationen. function isLearned(notice) { - const source = sourceOf(notice); - return source === 'learn' || source === 'suggest'; + return sourceOf(notice) !== 'energy'; } function filterNotices(notices, filter) { - if (filter === 'energy' || filter === 'learn' || filter === 'suggest') { + if (filter === 'energy' || filter === 'learn' || filter === 'suggest' || filter === 'effect') { return notices.filter((n) => sourceOf(n) === filter); } return notices.slice(); @@ -161,6 +160,10 @@ return rows; } if (sourceOf(notice) === 'learn' && p.kind === 'shade') return shadeFacts(notice, p, t); + if (sourceOf(notice) === 'effect') { + const confidence = p.confidence === 'high' ? t('automations.learn.confidence.sure') : t('automations.learn.confidence.estimate'); + return [[t('monitoring.fact.confidence'), confidence]]; + } if (isLearned(notice) && Array.isArray(notice.facts) && notice.facts.length) return learnFacts(notice.facts, t); return []; } @@ -173,7 +176,7 @@ if (target === 'efficiency') return !!can.view_efficiency; if (target === 'devicemap') return !!can.view_device_map; if (target === 'action.role_keep') return !!can.edit_energy; - if (target === 'suggestion') return !!can.view_automations; + if (target === 'suggestion' || target === 'rule') return !!can.view_automations; return false; } diff --git a/dashboard/internal/webui/static/js/monitoring.page.js b/dashboard/internal/webui/static/js/monitoring.page.js index 382786ad..924273f5 100644 --- a/dashboard/internal/webui/static/js/monitoring.page.js +++ b/dashboard/internal/webui/static/js/monitoring.page.js @@ -3,8 +3,9 @@ // mit dem CSRF-Token der Sitzung. Die Texte baut window.MonitoringModel. // // i18n-keys: monitoring.filter.all, monitoring.filter.energy, monitoring.filter.learn, -// monitoring.filter.suggest, monitoring.source.energy, monitoring.source.chain, -// monitoring.source.learn, monitoring.source.suggest, +// monitoring.filter.suggest, monitoring.filter.effect, monitoring.source.energy, +// monitoring.source.chain, monitoring.source.learn, monitoring.source.suggest, +// monitoring.source.effect, // monitoring.group.new, monitoring.group.known, monitoring.steps.title, // monitoring.ack.button, monitoring.ack.done, monitoring.ack.undo, monitoring.ack.no_right, // monitoring.badge.new @@ -21,12 +22,14 @@ { id: 'energy', key: 'monitoring.filter.energy' }, { id: 'learn', key: 'monitoring.filter.learn' }, { id: 'suggest', key: 'monitoring.filter.suggest' }, + { id: 'effect', key: 'monitoring.filter.effect' }, ]; const SOURCE_KEYS = { energy: 'monitoring.source.energy', chain: 'monitoring.source.chain', learn: 'monitoring.source.learn', suggest: 'monitoring.source.suggest', + effect: 'monitoring.source.effect', }; const GROUP_KEYS = { new: 'monitoring.group.new', known: 'monitoring.group.known' }; // Sprungziel der Schritte auf die Seite (Reiter) und das Panel, das den Reiter besitzt. @@ -232,6 +235,7 @@ if (!step || !step.target) return; if (step.target === 'learned') { this.goLearned(step.key); return; } if (step.target === 'suggestion') { this.goSuggestion((step.ids || [])[0]); return; } + if (step.target === 'rule') { this.goRule((step.ids || [])[0]); return; } if (step.target === 'action.role_keep') { this.roleKeep(step.ids); return; } const panel = panelFor(step.target); if (!panel) return; @@ -262,6 +266,18 @@ }); }, + // Sprung zur Regel oder zum Szenario. Erst der Reiter, damit die Seite beim Scrollen + // sichtbar ist. Ist sie noch nicht geladen, nimmt sie die Anfrage beim Laden entgegen. + goRule(id) { + if (!id) return; + window.__automationFocusRequest__ = id; + openTab('automations-panel'); + this.$nextTick(() => { + if (window.__automationFocusRequest__ !== id) return; + window.dispatchEvent(new CustomEvent('automation-focus-rule', { detail: { id } })); + }); + }, + // Sprung zum aufgeklappten Vorschlag. Ist die Automationen-Seite noch nicht // geladen, nimmt ihr Band die Anfrage in load() entgegen. goSuggestion(id) { diff --git a/dashboard/internal/webui/templates/automations-finding.html b/dashboard/internal/webui/templates/automations-finding.html index b488cbe8..231a0d98 100644 --- a/dashboard/internal/webui/templates/automations-finding.html +++ b/dashboard/internal/webui/templates/automations-finding.html @@ -1,6 +1,6 @@ {{define "automations-finding"}}