From 80c444e6d2727b22b4fd208f09c8fd854216de57 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:48:40 +0100 Subject: [PATCH 01/37] feat(autolearn): let a fix change several rules and estimate signal noise Fix gets Rules, one RuleOps per rule, so a change over several rules is applied in the draft as a whole or not at all. QuarterNoise estimates the reading noise of a quarter hour series. Input gets the learned values by key, wired through Engine.SetLearned. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/engine.go | 13 ++++++ dashboard/internal/autolearn/engine_test.go | 14 +++++++ dashboard/internal/autolearn/finding.go | 9 ++++ dashboard/internal/autolearn/input.go | 3 ++ dashboard/internal/autolearn/stats.go | 22 ++++++++++ dashboard/internal/autolearn/stats_test.go | 27 ++++++++++++ .../webui/static/js/automations.page.js | 41 +++++++++++-------- dashboard/test/automations.page.test.mjs | 34 +++++++++++++++ 8 files changed, 147 insertions(+), 16 deletions(-) diff --git a/dashboard/internal/autolearn/engine.go b/dashboard/internal/autolearn/engine.go index cc09c237..d7fff7ce 100644 --- a/dashboard/internal/autolearn/engine.go +++ b/dashboard/internal/autolearn/engine.go @@ -69,6 +69,7 @@ type Engine struct { season *SeasonStore outdoor func() OutdoorSource pv func() (PVModel, *Raster, bool) + learned func() map[string]LearnedEntry // recentC is the mean outdoor temperature of the last three days as the // last round read it, nil when unknown. recentC *float64 @@ -417,7 +418,11 @@ func (e *Engine) input(now time.Time, limits learnrec.Limits, devices map[string e.recentC = in.Base.RecentOutdoorC outdoor := e.outdoor in.PV = e.pv + learned := e.learned e.mu.Unlock() + if learned != nil { + in.Learned = learned() + } if outdoor != nil { in.Outdoor = outdoor() } @@ -433,6 +438,14 @@ func (e *Engine) SetPV(f func() (PVModel, *Raster, bool)) { e.pv = f } +// SetLearned gives the engine the learned values by key. A round reads them +// into Input.Learned. Without it the round has no learned values. +func (e *Engine) SetLearned(f func() map[string]LearnedEntry) { + e.mu.Lock() + defer e.mu.Unlock() + e.learned = f +} + // SetOutdoor gives the engine the outdoor temperature entity. It is read on // every round into Input.Outdoor. Without it the round has no entity. func (e *Engine) SetOutdoor(f func() OutdoorSource) { diff --git a/dashboard/internal/autolearn/engine_test.go b/dashboard/internal/autolearn/engine_test.go index cb1d0d45..fac24c0f 100644 --- a/dashboard/internal/autolearn/engine_test.go +++ b/dashboard/internal/autolearn/engine_test.go @@ -344,3 +344,17 @@ func TestEngineShareLimitPerLevel(t *testing.T) { t.Fatal("balanced: 12 % share did not ask for a downgrade") } } + +func TestEngineInputCarriesLearnedValues(t *testing.T) { + e := newTestEngine(t, learnrec.Limits{}) + if in := e.input(at(t, "2026-11-22", "12:00"), learnrec.Limits{}, nil); in.Learned != nil { + t.Fatalf("Learned without a source = %v, want nil", in.Learned) + } + e.SetLearned(func() map[string]LearnedEntry { + return map[string]LearnedEntry{"site/base_w": {Key: "site/base_w", Value: 300.0}} + }) + in := e.input(at(t, "2026-11-22", "12:00"), learnrec.Limits{}, nil) + if got := in.Learned["site/base_w"].Value; got != 300.0 { + t.Fatalf("Learned[site/base_w].Value = %v, want 300", got) + } +} diff --git a/dashboard/internal/autolearn/finding.go b/dashboard/internal/autolearn/finding.go index cba03f62..f028455b 100644 --- a/dashboard/internal/autolearn/finding.go +++ b/dashboard/internal/autolearn/finding.go @@ -54,6 +54,15 @@ type Fix struct { Ops []Op `json:"ops"` Template string `json:"template,omitempty"` Prefill map[string]any `json:"prefill,omitempty"` + Rules []RuleOps `json:"rules,omitempty"` +} + +// RuleOps is the ops of one rule. A fix that changes several rules at once +// carries one RuleOps per rule in Fix.Rules. The browser applies all of them +// or none. +type RuleOps struct { + RuleID string `json:"rule_id"` + Ops []Op `json:"ops"` } // Op sets Value at Path, relative to the rule, for example diff --git a/dashboard/internal/autolearn/input.go b/dashboard/internal/autolearn/input.go index 29af8244..f3919144 100644 --- a/dashboard/internal/autolearn/input.go +++ b/dashboard/internal/autolearn/input.go @@ -37,6 +37,9 @@ type Input struct { // exists. Nil means no model is wired, and the detectors that need one // return nothing. PV func() (PVModel, *Raster, bool) + // Learned holds the learned values by key, such as site/base_w. Nil when + // no store is wired. + Learned map[string]LearnedEntry } // OutdoorSource names the outdoor temperature entity: its unique id, its state diff --git a/dashboard/internal/autolearn/stats.go b/dashboard/internal/autolearn/stats.go index 4bb9d479..696ece61 100644 --- a/dashboard/internal/autolearn/stats.go +++ b/dashboard/internal/autolearn/stats.go @@ -326,3 +326,25 @@ func OtsuSplit(xs []float64, bins int) (cut float64, ok bool) { } return cut, true } + +// QuarterNoise estimates the noise of one reading of a quarter hour series in +// W. It is the 95th percentile of the absolute differences between consecutive +// quarter hours, halved: a jump of two noisy readings is twice the noise. +// Differences with a gap (NaN) are left out. A series with fewer than two +// readings has no noise estimate and returns 0. +func QuarterNoise(series []float32) float64 { + diffs := make([]float64, 0, len(series)) + for i := 1; i < len(series); i++ { + d := math.Abs(float64(series[i]) - float64(series[i-1])) + if math.IsNaN(d) { + continue + } + diffs = append(diffs, d) + } + if len(diffs) == 0 { + return 0 + } + sort.Float64s(diffs) + rank := int(math.Ceil(0.95*float64(len(diffs)))) - 1 + return diffs[rank] / 2 +} diff --git a/dashboard/internal/autolearn/stats_test.go b/dashboard/internal/autolearn/stats_test.go index d18580da..2017b08a 100644 --- a/dashboard/internal/autolearn/stats_test.go +++ b/dashboard/internal/autolearn/stats_test.go @@ -211,3 +211,30 @@ func TestOtsuSplitNeedsFourPerSide(t *testing.T) { t.Fatalf("OtsuSplit with 3 values on one side: ok = true, want false") } } + +func TestQuarterNoise(t *testing.T) { + // Alternating +100 and -100 W around 500 W: every quarter hour difference + // is 200 W, so the noise of one reading is 100 W. + series := make([]float32, 96) + for i := range series { + if i%2 == 0 { + series[i] = 600 + } else { + series[i] = 400 + } + } + if got := QuarterNoise(series); got < 80 || got > 120 { + t.Fatalf("QuarterNoise = %v, want 100 +- 20", got) + } + if got := QuarterNoise(nil); got != 0 { + t.Fatalf("QuarterNoise(nil) = %v, want 0", got) + } + if got := QuarterNoise([]float32{500}); got != 0 { + t.Fatalf("QuarterNoise(one value) = %v, want 0", got) + } + // A gap (NaN) does not count as a difference. + gapped := []float32{500, float32(math.NaN()), 500, 600, 400} + if got := QuarterNoise(gapped); math.IsNaN(got) || got < 0 { + t.Fatalf("QuarterNoise with gap = %v, want a finite value", got) + } +} diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index adbb1777..4487a87b 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -2188,10 +2188,12 @@ // Schreibt die Ops als Pfade in den Entwurf der Regel. Gespeichert wird nicht. // Alle Ziele werden zuerst aufgeloest. Fehlt ein Pfadteil (die Regel hat sich // seit dem Befund geaendert), wird nichts geschrieben, die Regel oeffnet sich trotzdem. + // Ein Befund mit fix.rules aendert mehrere Regeln: alle oder keine. applyFix(fix) { - const rule = this.document.rules.find((entry) => entry.id === fix.rule_id); - if (!rule) return; - const targetOf = (path) => { + 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 || [] }]; + const targetOf = (rule, path) => { let node = rule; path.slice(0, -1).forEach((key) => { node = node && typeof node === 'object' ? node[key] : undefined; @@ -2199,23 +2201,30 @@ if (path.length === 0 || !node || typeof node !== 'object') return null; return { parent: node, key: path[path.length - 1] }; }; - // Ein add_condition nennt den Index, den die Bedingung beim Befund hatte. - // Seitdem kann eine Bedingung dazugekommen sein, deshalb wird angehaengt. - const writes = (fix.ops || []).map((op) => { - const target = targetOf(op.path || []); - if (fix.code === 'add_condition') { - return { target: target && Array.isArray(target.parent) ? { parent: target.parent, append: true } : null, value: op.value }; - } - return { target, value: op.value }; + const plans = groups.map((group) => { + const rule = this.document.rules.find((entry) => entry.id === group.rule_id); + if (!rule) return { rule: null, writes: [] }; + // Ein add_condition nennt den Index, den die Bedingung beim Befund hatte. + // Seitdem kann eine Bedingung dazugekommen sein, deshalb wird angehaengt. + const writes = group.ops.map((op) => { + const target = targetOf(rule, op.path || []); + if (group.code === 'add_condition') { + return { target: target && Array.isArray(target.parent) ? { parent: target.parent, append: true } : null, value: op.value }; + } + return { target, value: op.value }; + }); + return { rule, writes }; }); - if (writes.every((write) => write.target)) { - writes.forEach((write) => { + const opened = plans.map((plan) => plan.rule).filter(Boolean); + if (opened.length === 0) return; + if (plans.every((plan) => plan.rule && plan.writes.every((write) => write.target))) { + plans.forEach((plan) => plan.writes.forEach((write) => { if (write.target.append) write.target.parent.push(write.value); else write.target.parent[write.target.key] = write.value; - }); + })); } - this.startEditing(rule); - this.expanded[rule.id] = true; + this.startEditing(opened[0]); + opened.forEach((rule) => { this.expanded[rule.id] = true; }); this.closeFinding(); }, postFindingIgnore(id, undo) { diff --git a/dashboard/test/automations.page.test.mjs b/dashboard/test/automations.page.test.mjs index 191788a0..8cd9f08b 100644 --- a/dashboard/test/automations.page.test.mjs +++ b/dashboard/test/automations.page.test.mjs @@ -3442,6 +3442,40 @@ test('applying a temperature limit suggestion adds the condition to the draft an assert.deepEqual(posted, []); }); +test('applyFix with rules changes every listed rule in the draft', () => { + const { component } = createAutomationsPanel(); + component.document = { version: 1, settings: {}, rules: [ + { id: 'r1', name: 'Pumpe', conditions: [{ type: 'balance_threshold', threshold: 100, hysteresis: 0 }], actions: [] }, + { id: 'r2', name: 'Heizstab', conditions: [{ type: 'balance_threshold', threshold: 300, hysteresis: 0 }], actions: [] }, + ] }; + const started = []; + component.startEditing = (rule) => started.push(rule.id); + component.applyFix({ code: 'shift_thresholds', rule_id: 'r1', ops: [], rules: [ + { rule_id: 'r1', ops: [{ path: ['conditions', 0, 'threshold'], value: 120 }] }, + { rule_id: 'r2', ops: [{ path: ['conditions', 0, 'threshold'], value: 320 }] }, + ] }); + assert.equal(component.document.rules[0].conditions[0].threshold, 120); + assert.equal(component.document.rules[1].conditions[0].threshold, 320); + assert.deepEqual(started, ['r1']); + assert.equal(component.expanded.r1, true); + assert.equal(component.expanded.r2, true); +}); + +test('applyFix with rules changes none when a path of the second rule does not resolve', () => { + const { component } = createAutomationsPanel(); + component.document = { version: 1, settings: {}, rules: [ + { id: 'r1', name: 'Pumpe', conditions: [{ type: 'balance_threshold', threshold: 100, hysteresis: 0 }], actions: [] }, + { id: 'r2', name: 'Heizstab', conditions: [{ type: 'balance_threshold', threshold: 300, hysteresis: 0 }], actions: [] }, + ] }; + component.startEditing = () => {}; + component.applyFix({ code: 'shift_thresholds', rule_id: 'r1', ops: [], rules: [ + { rule_id: 'r1', ops: [{ path: ['conditions', 0, 'threshold'], value: 120 }] }, + { rule_id: 'r2', ops: [{ path: ['conditions', 4, 'threshold'], value: 320 }] }, + ] }); + assert.equal(component.document.rules[0].conditions[0].threshold, 100); + assert.equal(component.document.rules[1].conditions[0].threshold, 300); +}); + test('applyFix writes nothing and still opens the rule when a path element is missing', () => { const { component, window } = createAutomationsPanel(); component.document = { version: 1, settings: {}, rules: [ From 67cbc3214c223af4d2c2439c2086741917b78cf0 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:52:32 +0100 Subject: [PATCH 02/37] feat(autolearn): flag rules whose own load flips their condition A rule that switches a load on above X and off below Xaus on the export turns itself off again when X - P_Anlauf - noise <= Xaus. The feedback check runs as a light reliability detector, uses the learned operating power and the start peak, and proposes new thresholds as one change over both rules. Observed export steps after switch-ons raise the confidence. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 11 +- .../internal/autolearn/check_feedback.go | 281 ++++++++++++++++++ .../internal/autolearn/check_feedback_test.go | 144 +++++++++ dashboard/internal/webui/catalogs/de.json | 7 + dashboard/internal/webui/catalogs/en.json | 7 + .../webui/learn_summary_catalog_test.go | 1 + 6 files changed, 450 insertions(+), 1 deletion(-) create mode 100644 dashboard/internal/autolearn/check_feedback.go create mode 100644 dashboard/internal/autolearn/check_feedback_test.go diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 294f3788..c70d4c32 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -561,7 +561,7 @@ func main() { // Erkenner: Gewohnheiten (habit) und Zuverlaessigkeit (reliability). for _, det := range []autolearn.Detector{ autolearn.SwitchTimeDetector, autolearn.RuntimeDetector, autolearn.CouplingDetector, - autolearn.FlappingDetector, autolearn.NoEffectDetector, autolearn.OverriddenDetector, autolearn.OfflineDetector, + autolearn.FlappingDetector, autolearn.FeedbackDetector, autolearn.NoEffectDetector, autolearn.OverriddenDetector, autolearn.OfflineDetector, autolearn.AwayStandbyDetector, } { automationEngine.Register(det) @@ -644,6 +644,15 @@ func main() { monitoringLoop := newMonitoringRunner(monitoringStore, collectMonitoring) learnHub.AddMinute("monitoring", monitoringLoop) learnHub.AddSaver("monitoring", monitoringLoop) + // Die gelernten Werte der Engine, etwa die Betriebsleistung fuer die Rueckkopplung. + automationEngine.SetLearned(func() map[string]autolearn.LearnedEntry { + entries := learnedStore.Entries() + out := make(map[string]autolearn.LearnedEntry, len(entries)) + for _, e := range entries { + out[e.Key] = e + } + return out + }) // Wochenwerte fuer den Saisonvergleich. Fehlt season.json, fuellt die // Energiestatistik der letzten drei Jahre sie einmal nach. seasonPath := filepath.Join(autolearnDir, "season.json") diff --git a/dashboard/internal/autolearn/check_feedback.go b/dashboard/internal/autolearn/check_feedback.go new file mode 100644 index 00000000..76cd14d0 --- /dev/null +++ b/dashboard/internal/autolearn/check_feedback.go @@ -0,0 +1,281 @@ +package autolearn + +import ( + "context" + "math" + "sort" + "time" +) + +// FeedbackDetector checks a rule pair that switches one load on and off by the +// same balance value. The load itself moves that value, so the rule can switch +// itself off again (spec 15.4 "Rueckkopplung"). It runs with the light rounds +// and needs no history for the static part. +var FeedbackDetector = Detector{ + Name: "feedback", + Group: "reliability", + Light: true, + PerDevice: false, + Run: feedbackRun, +} + +const ( + // feedbackField is the balance value the pair switches on: the export, which is the surplus. + feedbackField = "grid_export" + // feedbackRoundW is the step the proposed thresholds are rounded up to. + feedbackRoundW = 10.0 + // feedbackConfirmShare is how far the observed step may be from the operating power. + feedbackConfirmShare = 0.3 + // feedbackMinChanges is the number of switch-ons needed to observe the step. + feedbackMinChanges = 3 +) + +// feedbackRun lists the feedback findings as candidates. The check is static, so +// one case is enough and the candidate always passes the gate. +func feedbackRun(ctx context.Context, in *Input, _ string) []Candidate { + if ctx.Err() != nil { + return nil + } + var out []Candidate + for _, f := range FeedbackFindings(in) { + out = append(out, Candidate{Finding: f, Detector: "feedback", NEff: 1, MinNEff: 1, Lower: 1, Limit: 1}) + } + return out +} + +// FeedbackFindings returns the rules that switch themselves off again. For each +// device with an operating power, a rule with "above X" and a rule with +// "below Xaus" on the export that both act on it form a pair. The pair is +// unstable when X - P_Anlauf - Rauschen <= Xaus. A learned threshold counts +// with its smallest value for the switch-on rule and its largest for the +// switch-off rule, since that is the worst case. The finding is confirmed, and +// its confidence high, when the median export step after the switch-ons is the +// operating power within 30 %. +func FeedbackFindings(in *Input) []Finding { + if in == nil || len(in.Doc.Rules) == 0 { + return nil + } + noise := feedbackNoise(in.Days) + reserve := 2 * noise + rules := ruleByID(in.Doc) + var out []Finding + seen := map[string]bool{} + for _, device := range sortedDeviceIDs(in.Devices) { + info := in.Devices[device] + p, ok := learnedOperatingPower(in.Learned, device) + if !ok { + continue + } + pAnlauf := feedbackInrush(in.Days, device, p) + for _, on := range in.Doc.Rules { + if !on.Enabled || seen[on.ID] || !actsOnDevice(on, info) { + continue + } + onIdx, x, ok := balanceSide(on, "above", true) + if !ok { + continue + } + off, offIdx, xAus, ok := feedbackOffRule(in.Doc, info, on.ID, rules) + if !ok || x-pAnlauf-noise > xAus { + continue + } + seen[on.ID] = true + newOn := feedbackCeil(pAnlauf + reserve) + newOff := 0 - feedbackCeil(reserve) + confidence := "estimate" + if feedbackConfirmed(in, device, p) { + confidence = "high" + } + out = append(out, Finding{ + ID: FindingID("feedback", on.ID), + Kind: "feedback", + Group: "check", + RuleIDs: []string{on.ID, off.ID}, + Severity: "warn", + Confidence: confidence, + Summary: Text{Code: "check.feedback", Params: map[string]any{ + "rule": ruleName(rules, on.ID), "device": feedbackDeviceName(info, device)}}, + Evidence: Evidence{Shape: "scale", IstValue: &xAus, SollValue: &newOn}, + Facts: []Fact{ + {Code: "op_w", Value: roundTenth(p)}, + {Code: "peak_w", Value: roundTenth(pAnlauf)}, + {Code: "noise_w", Value: roundTenth(noise)}, + }, + Apply: []Fix{{Code: "feedback_thresholds", RuleID: on.ID, Rules: []RuleOps{ + {RuleID: on.ID, Ops: []Op{{Path: []any{"conditions", onIdx, "threshold"}, Value: newOn}}}, + {RuleID: off.ID, Ops: []Op{{Path: []any{"conditions", offIdx, "threshold"}, Value: newOff}}}, + }}}, + Device: device, + }) + } + } + return out +} + +// feedbackOffRule returns the first enabled rule that switches the device off +// on the export below a threshold, with its condition index and the threshold. +func feedbackOffRule(doc Doc, info DeviceInfo, onID string, rules map[string]Rule) (Rule, int, float64, bool) { + for _, r := range doc.Rules { + if r.ID == onID || !r.Enabled || !actsOnDevice(r, info) { + continue + } + idx, xAus, ok := balanceSide(r, "below", false) + if ok { + return r, idx, xAus, true + } + } + return Rule{}, 0, 0, false +} + +// balanceSide returns the index and the number of the export condition with the +// given comparison. A learned threshold gives its minimum when low is true and +// its maximum otherwise. It reports false without such a condition or without a +// number. +func balanceSide(r Rule, comparison string, low bool) (int, float64, bool) { + for i, c := range r.Conditions { + if c.Type != "balance_threshold" || c.Field != feedbackField || c.Comparison != comparison { + continue + } + if ref, learned := c.Learned["threshold"]; learned { + bound := ref.Max + if low { + bound = ref.Min + } + v, ok := asFloat(bound) + return i, v, ok + } + return i, c.Threshold, true + } + return 0, 0, false +} + +// actsOnDevice reports whether one action of the rule targets an entity of the device. +func actsOnDevice(r Rule, info DeviceInfo) bool { + for _, a := range r.Actions { + if a.EntityID == "" { + continue + } + for _, e := range info.Entities { + if a.EntityID == e { + return true + } + } + } + return false +} + +// feedbackConfirmed reports whether the median export step around the switch-ons +// of the device, from the quarter before to the quarter after, is the operating +// power within feedbackConfirmShare. The step is negative when the load draws. +func feedbackConfirmed(in *Input, device string, p float64) bool { + if p <= 0 { + return false + } + loc := in.Loc + if loc == nil { + loc = time.Local + } + days := make(map[string]*DayFile, len(in.Days)) + for i := range in.Days { + days[in.Days[i].Day] = &in.Days[i] + } + var steps []float64 + for _, e := range ruleEventsOf(in.Days, device) { + if !e.on { + continue + } + t := time.Unix(e.at, 0).In(loc) + f := days[t.Format(dayLayout)] + q := quarterOf(t) + if f == nil || q < 1 || q+1 >= dayQuarters { + continue + } + if f.Site.Seen[q-1] == 0 || f.Site.Seen[q+1] == 0 { + continue + } + steps = append(steps, float64(f.Site.GridExport[q+1]-f.Site.GridExport[q-1])) + } + if len(steps) < feedbackMinChanges { + return false + } + med := Median(steps) + return med < 0 && math.Abs(-med-p) <= feedbackConfirmShare*p +} + +// feedbackNoise is QuarterNoise of the export over all days in order. Quarters +// without a reading are gaps and do not count as steps. +func feedbackNoise(days []DayFile) float64 { + sorted := append([]DayFile(nil), days...) + sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].Day < sorted[j].Day }) + var series []float32 + for i := range sorted { + for q := 0; q < dayQuarters; q++ { + if sorted[i].Site.Seen[q] == 0 { + series = append(series, float32(math.NaN())) + continue + } + series = append(series, sorted[i].Site.GridExport[q]) + } + } + return QuarterNoise(series) +} + +// feedbackInrush is the median start peak of the device over its cycles, or the +// operating power when no cycle has a peak. +func feedbackInrush(days []DayFile, device string, p float64) float64 { + var peaks []float64 + for i := range days { + for _, c := range days[i].Cycles { + if c.Device == device && c.PeakW > 0 { + peaks = append(peaks, float64(c.PeakW)) + } + } + } + if len(peaks) == 0 { + return p + } + return Median(peaks) +} + +// learnedOperatingPower reads device//op_power_w, false when it is missing or not positive. +func learnedOperatingPower(learned map[string]LearnedEntry, device string) (float64, bool) { + e, ok := learned["device/"+device+"/op_power_w"] + if !ok { + return 0, false + } + v, ok := asFloat(e.Value) + return v, ok && v > 0 +} + +// asFloat reads a number of the types a learned value or a rule can carry. +func asFloat(v any) (float64, bool) { + switch n := v.(type) { + case float64: + return n, true + case float32: + return float64(n), true + case int: + return float64(n), true + case int64: + return float64(n), true + } + return 0, false +} + +// feedbackCeil rounds up to feedbackRoundW. +func feedbackCeil(v float64) float64 { + return math.Ceil(v/feedbackRoundW) * feedbackRoundW +} + +// feedbackDeviceName is the device name, or its ID when the name is empty. +func feedbackDeviceName(info DeviceInfo, id string) string { + if info.Name != "" { + return info.Name + } + return id +} + +// roundTenth rounds to one decimal, for the facts. +func roundTenth(v float64) float64 { + return math.Round(v*10) / 10 +} diff --git a/dashboard/internal/autolearn/check_feedback_test.go b/dashboard/internal/autolearn/check_feedback_test.go new file mode 100644 index 00000000..1417df12 --- /dev/null +++ b/dashboard/internal/autolearn/check_feedback_test.go @@ -0,0 +1,144 @@ +package autolearn + +import ( + "testing" + "time" +) + +// fbDay is the local midnight of the November day 10+d. +func fbDay(loc *time.Location, d int) time.Time { + return time.Date(2026, 11, d, 0, 0, 0, 0, loc) +} + +// fbDevice is a switchable device with one switch entity. +func fbDevice() map[string]DeviceInfo { + return map[string]DeviceInfo{"plug.kettle": {ID: "plug.kettle", Name: "Kessel", Switchable: true, + Entities: []string{"switch.plug.kettle"}}} +} + +// fbRule is a rule that switches the kettle on the balance grid_export with a +// fixed threshold. cmp is "above" for the switching-on rule, "below" for the +// switching-off rule. +func fbRule(id, cmp string, x float64) Rule { + return Rule{ID: id, Name: id, Enabled: true, + Conditions: []Condition{{Type: "balance_threshold", Field: "grid_export", Comparison: cmp, Threshold: x}}, + Actions: []Action{{Type: "publish", EntityID: "switch.plug.kettle"}}} +} + +// fbLearned gives the kettle an operating power of p watt. +func fbLearned(p float64) map[string]LearnedEntry { + return map[string]LearnedEntry{"device/plug.kettle/op_power_w": { + Key: "device/plug.kettle/op_power_w", Device: "plug.kettle", Kind: ValueNumber, Unit: "W", Value: p, N: 10}} +} + +func TestFeedbackFlagsSelfSwitchingRule(t *testing.T) { + loc := berlinLoc(t) + cases := []struct { + name string + on, off float64 + flagged bool + }{ + {"on 3000 off 500, stable", 3000, 500, false}, + {"on 1500 off 500, unstable", 1500, 500, true}, + // Exactly on the boundary X - P = X_aus: the spec counts it as unstable. + {"on 2500 off 500, on the boundary", 2500, 500, true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + in := relInput(loc, nil, fbDevice(), fbRule("on", "above", c.on), fbRule("off", "below", c.off)) + in.Learned = fbLearned(2000) + got := FeedbackFindings(in) + if (len(got) == 1) != c.flagged { + t.Fatalf("findings = %+v, want flagged %v", got, c.flagged) + } + }) + } +} + +func TestFeedbackFindingShape(t *testing.T) { + loc := berlinLoc(t) + in := relInput(loc, nil, fbDevice(), fbRule("on", "above", 1500), fbRule("off", "below", 500)) + in.Learned = fbLearned(2000) + got := FeedbackFindings(in) + if len(got) != 1 { + t.Fatalf("findings = %d, want 1", len(got)) + } + f := got[0] + if f.ID != "feedback:on" || f.Kind != "feedback" || f.Group != "check" || f.Severity != "warn" { + t.Errorf("finding = id %q kind %q group %q severity %q", f.ID, f.Kind, f.Group, f.Severity) + } + if f.Device != "plug.kettle" || f.Summary.Code != "check.feedback" { + t.Errorf("device %q summary %q", f.Device, f.Summary.Code) + } + if f.Confidence != "estimate" { + t.Errorf("confidence = %q, want estimate without observation", f.Confidence) + } + if f.Evidence.IstValue == nil || *f.Evidence.IstValue != 500 { + t.Errorf("ist value = %v, want the off threshold 500", f.Evidence.IstValue) + } + if f.Evidence.SollValue == nil || *f.Evidence.SollValue != 2000 { + // Noise is 0 without days, so the reserve is 0 and the new threshold is P_Anlauf = 2000. + t.Errorf("soll value = %v, want 2000", f.Evidence.SollValue) + } + if len(f.Apply) != 1 || f.Apply[0].Code != "feedback_thresholds" || f.Apply[0].RuleID != "on" { + t.Fatalf("apply = %+v, want feedback_thresholds on the on rule", f.Apply) + } + rules := f.Apply[0].Rules + if len(rules) != 2 || rules[0].RuleID != "on" || rules[1].RuleID != "off" { + t.Fatalf("rules = %+v, want one RuleOps for on and one for off", rules) + } + if rules[0].Ops[0].Value != 2000.0 || rules[1].Ops[0].Value != 0.0 { + t.Errorf("values = %v and %v, want 2000 and 0", rules[0].Ops[0].Value, rules[1].Ops[0].Value) + } +} + +func TestFeedbackNeedsOperatingPower(t *testing.T) { + loc := berlinLoc(t) + in := relInput(loc, nil, fbDevice(), fbRule("on", "above", 1500), fbRule("off", "below", 500)) + if got := FeedbackFindings(in); len(got) != 0 { + t.Fatalf("findings without op_power_w = %+v, want none", got) + } +} + +func TestFeedbackUsesLearnedThresholdMinimum(t *testing.T) { + loc := berlinLoc(t) + on := fbRule("on", "above", 0) + on.Conditions[0].Learned = map[string]LearnedRef{"threshold": {Key: "site/grid_on_w", Min: 1200.0}} + in := relInput(loc, nil, fbDevice(), on, fbRule("off", "below", 500)) + in.Learned = fbLearned(2000) + got := FeedbackFindings(in) + if len(got) != 1 || got[0].ID != "feedback:on" { + t.Fatalf("findings = %+v, want feedback:on from the learned minimum 1200", got) + } +} + +func TestFeedbackConfirmedByObservation(t *testing.T) { + loc := berlinLoc(t) + var days []DayFile + for d := 0; d < 3; d++ { + day := relDay(fbDay(loc, 10+d)) + relReachable(&day, "plug.kettle") + // A switch-on at 08:00:30 drops the export by 2000 W from the quarter before to the quarter after. + q := 32 + day.Site.Seen[q-1], day.Site.Seen[q], day.Site.Seen[q+1] = 1, 1, 1 + day.Site.GridExport[q-1], day.Site.GridExport[q], day.Site.GridExport[q+1] = 2500, 500, 500 + relRuleEvent(&day, relAt(fbDay(loc, 10+d), 8, 0, 30), "plug.kettle", "on", true) + days = append(days, day) + } + in := relInput(loc, days, fbDevice(), fbRule("on", "above", 1500), fbRule("off", "below", 500)) + in.Learned = fbLearned(2000) + got := FeedbackFindings(in) + if len(got) != 1 || got[0].Confidence != "high" { + t.Fatalf("findings = %+v, want one finding with confidence high", got) + } +} + +func TestFeedbackDetectorWrapsFindingsAsCandidates(t *testing.T) { + loc := berlinLoc(t) + in := relInput(loc, nil, fbDevice(), fbRule("on", "above", 1500), fbRule("off", "below", 500)) + in.Learned = fbLearned(2000) + got := relRun(FeedbackDetector.Run, in, "") + if len(got) != 1 || got[0].Finding.ID != "feedback:on" || got[0].NEff < got[0].MinNEff { + t.Fatalf("candidates = %+v, want one listed feedback candidate", got) + } +} diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 75c7f321..ed14482c 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -479,6 +479,8 @@ "automations.learn.check.contradiction.title": "Widerspricht „{other}“", "automations.learn.check.duplicate.text": "„{rule}“ macht genau dasselbe wie „{other}“. Eine der beiden Regeln reicht.", "automations.learn.check.duplicate.title": "Doppelt mit „{other}“", + "automations.learn.check.feedback.text": "„{rule}“ schaltet {device} ein, und die Last zieht danach den Überschuss unter die Ausschaltgrenze. Die Regel schaltet sich deshalb selbst wieder aus.", + "automations.learn.check.feedback.title": "„{rule}“ schaltet sich selbst aus", "automations.learn.check.flapping.line": "{device} wechselt etwa alle {period_s} s den Zustand", "automations.learn.check.flapping.text": "„{rule}“ und „{other}“ schalten {device} abwechselnd, etwa alle {period_s} Sekunden. Eine Mindestlaufzeit beruhigt das.", "automations.learn.check.flapping.title": "„{rule}“ und „{other}“ schalten sich gegenseitig um", @@ -514,6 +516,7 @@ "automations.learn.coupling.follow.title": "{b} folgt {a}", "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", "automations.learn.fact.cause.offline_window": "Das Gerät war offline", "automations.learn.fact.cause.scattered": "Die Befehle verteilten sich über den Tag", "automations.learn.fact.direction_share": "Anteil dieser Richtung", @@ -525,13 +528,17 @@ "automations.learn.fact.limit_s": "Grenze", "automations.learn.fact.min_runtime": "Mindestlaufzeit", "automations.learn.fact.no_location": "Kein Standort hinterlegt", + "automations.learn.fact.noise_w": "Rauschen", + "automations.learn.fact.op_w": "Betriebsleistung", "automations.learn.fact.overnight": "Über Nacht", + "automations.learn.fact.peak_w": "Anlaufleistung", "automations.learn.fact.per_hour_max": "Höchstens pro Stunde", "automations.learn.fact.season_months": "Monate in der Saison", "automations.learn.fact.spread_min": "Streuung", "automations.learn.fact.window_s": "Zeitfenster", "automations.learn.fix.add_condition": "Bedingung ergänzen", "automations.learn.fix.disable_duplicate": "Diese Regel ausschalten", + "automations.learn.fix.feedback_thresholds": "Schwellen auseinanderziehen", "automations.learn.fix.min_runtime": "Mindestlaufzeit setzen", "automations.learn.fix.move_before": "Vor den Ausfall verschieben", "automations.learn.fix.open_rule": "Regel öffnen", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 03e90a20..4339ecd1 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -479,6 +479,8 @@ "automations.learn.check.contradiction.title": "Contradicts “{other}”", "automations.learn.check.duplicate.text": "“{rule}” does exactly the same as “{other}”. One of the two rules is enough.", "automations.learn.check.duplicate.title": "Duplicate of “{other}”", + "automations.learn.check.feedback.text": "“{rule}” switches {device} on, and the load then pulls the surplus below the switch-off limit. The rule therefore switches itself off again.", + "automations.learn.check.feedback.title": "“{rule}” switches itself off", "automations.learn.check.flapping.line": "{device} changes state about every {period_s} s", "automations.learn.check.flapping.text": "“{rule}” and “{other}” switch {device} back and forth about every {period_s} seconds. A minimum runtime calms that down.", "automations.learn.check.flapping.title": "“{rule}” and “{other}” keep switching each other", @@ -514,6 +516,7 @@ "automations.learn.coupling.follow.title": "{b} follows {a}", "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", "automations.learn.fact.cause.offline_window": "The device was offline", "automations.learn.fact.cause.scattered": "The commands were spread over the day", "automations.learn.fact.direction_share": "Share of this direction", @@ -525,13 +528,17 @@ "automations.learn.fact.limit_s": "Limit", "automations.learn.fact.min_runtime": "Minimum runtime", "automations.learn.fact.no_location": "No location set", + "automations.learn.fact.noise_w": "Noise", + "automations.learn.fact.op_w": "Operating power", "automations.learn.fact.overnight": "Overnight", + "automations.learn.fact.peak_w": "Start peak", "automations.learn.fact.per_hour_max": "At most per hour", "automations.learn.fact.season_months": "Months in the season", "automations.learn.fact.spread_min": "Spread", "automations.learn.fact.window_s": "Time window", "automations.learn.fix.add_condition": "Add a condition", "automations.learn.fix.disable_duplicate": "Turn this rule off", + "automations.learn.fix.feedback_thresholds": "Widen the thresholds", "automations.learn.fix.min_runtime": "Set a minimum runtime", "automations.learn.fix.move_before": "Move before the outage", "automations.learn.fix.open_rule": "Open rule", diff --git a/dashboard/internal/webui/learn_summary_catalog_test.go b/dashboard/internal/webui/learn_summary_catalog_test.go index 7d0d5290..4bfbac1a 100644 --- a/dashboard/internal/webui/learn_summary_catalog_test.go +++ b/dashboard/internal/webui/learn_summary_catalog_test.go @@ -20,6 +20,7 @@ var summaryCodeLiteral = regexp.MustCompile(`Text\{Code: "([a-z_.]+)"`) var learnLineGaps = map[string]bool{ "check.contradiction": true, "check.duplicate": true, + "check.feedback": true, "check.frequent": true, "check.never_fired": true, "check.orphan": true, From f6ea3846350561ef1b332ef1514509eef0022982 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:52:51 +0100 Subject: [PATCH 03/37] feat(autolearn): name feedback as the cause of flapping rules When the unstable feedback finding of a device names the two rules of a flapping pair, the flapping finding carries the fact cause=feedback. The min_runtime fix stays as it is. Co-Authored-By: Claude Sonnet 5.5 --- .../internal/autolearn/detect_flapping.go | 27 ++++++++++++++-- .../autolearn/detect_flapping_test.go | 32 +++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/dashboard/internal/autolearn/detect_flapping.go b/dashboard/internal/autolearn/detect_flapping.go index 9c7daeb9..2d3a6e31 100644 --- a/dashboard/internal/autolearn/detect_flapping.go +++ b/dashboard/internal/autolearn/detect_flapping.go @@ -90,12 +90,32 @@ func flappingRun(ctx context.Context, in *Input, device string) []Candidate { if offCount[ids[1]] > offCount[ids[0]] { offRule = ids[1] } - return []Candidate{flappingCandidate(device, info, rules, ids, offRule, minRun, period, gaps, events)} + feedback := flappingFeedback(in, device, ids) + return []Candidate{flappingCandidate(device, info, rules, ids, offRule, minRun, period, gaps, events, feedback)} +} + +// flappingFeedback reports whether an unstable feedback finding of the device +// names the two rules of the flapping pair. Then the switch-ons follow the load +// jump, and the cause is the feedback (spec 15.4 "Takten"). +func flappingFeedback(in *Input, device string, ids []string) bool { + want := append([]string(nil), ids...) + sort.Strings(want) + for _, f := range FeedbackFindings(in) { + if f.Device != device || len(f.RuleIDs) != len(want) { + continue + } + got := append([]string(nil), f.RuleIDs...) + sort.Strings(got) + if got[0] == want[0] && got[1] == want[1] { + return true + } + } + return false } // flappingCandidate builds the finding of a flapping device. func flappingCandidate(device string, info DeviceInfo, rules map[string]Rule, ids []string, offRule string, - minRun, period float64, gaps []float64, events []ruleEvent) Candidate { + minRun, period float64, gaps []float64, events []ruleEvent, feedback bool) Candidate { hold := math.Ceil(math.Max(minRun, 3*period)) apply := []Fix{{Code: "open_rule", RuleID: offRule}} if len(rules[offRule].Conditions) > 0 { @@ -133,6 +153,9 @@ func flappingCandidate(device string, info DeviceInfo, rules map[string]Rule, id Apply: apply, Device: device, } + if feedback { + finding.Facts = append(finding.Facts, Fact{Code: "cause", Value: "feedback"}) + } return Candidate{ Finding: finding, Detector: "flapping", diff --git a/dashboard/internal/autolearn/detect_flapping_test.go b/dashboard/internal/autolearn/detect_flapping_test.go index 033e8d8a..f31b26e6 100644 --- a/dashboard/internal/autolearn/detect_flapping_test.go +++ b/dashboard/internal/autolearn/detect_flapping_test.go @@ -143,3 +143,35 @@ func TestFlappingSparseRulesGiveNothing(t *testing.T) { t.Fatalf("daily switching gave %d candidates, want 0", len(got)) } } + +func TestFlappingCausedByFeedbackNamesTheCause(t *testing.T) { + loc := berlinLoc(t) + days := flapDays(t, loc, "plug.kettle", 10, 60) + devices := map[string]DeviceInfo{"plug.kettle": {ID: "plug.kettle", Name: "Kessel", Switchable: true, + Entities: []string{"switch.plug.kettle"}}} + causeOf := func(in *Input) (string, bool) { + got := relRun(FlappingDetector.Run, in, "plug.kettle") + if len(got) != 1 { + t.Fatalf("candidates = %d, want 1", len(got)) + } + for _, f := range got[0].Finding.Facts { + if f.Code == "cause" { + return f.Value.(string), true + } + } + return "", false + } + + // Without a learned operating power the switch-ons cannot be tied to the load. + plain := relInput(loc, days, devices, fbRule("on", "above", 1500), fbRule("off", "below", 500)) + if cause, ok := causeOf(plain); ok { + t.Errorf("cause without feedback = %q, want none", cause) + } + + // The kettle moves the export by 2000 W, so the thresholds 1500 and 500 feed back. + fed := relInput(loc, days, devices, fbRule("on", "above", 1500), fbRule("off", "below", 500)) + fed.Learned = fbLearned(2000) + if cause, ok := causeOf(fed); !ok || cause != "feedback" { + t.Errorf("cause = %q (found %v), want feedback", cause, ok) + } +} From d725acf67a66bea0a1fc49f6b3daac249319402d Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:56:39 +0100 Subject: [PATCH 04/37] feat(autolearn): stagger rules that compete for the same surplus Rules that switch on from the same balance value and fire in one quarter hour, with the grid import above the smallest of their loads in the two quarters after, form a competition. The detector runs daily in the reliability group and proposes a staircase of thresholds, one step per load. Loads with a fixed cycle energy come first, then the ones started by hand most often, then the higher operating power. Steps the surplus reaches on fewer than 3 of the last 14 days are marked dormant. The fix changes all competing rules at once and offers an open rule fix on the first rule. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 2 +- .../internal/autolearn/check_competition.go | 384 ++++++++++++++++++ .../autolearn/check_competition_test.go | 167 ++++++++ dashboard/internal/autolearn/finding.go | 9 + dashboard/internal/webui/catalogs/de.json | 3 + dashboard/internal/webui/catalogs/en.json | 3 + .../webui/learn_summary_catalog_test.go | 1 + 7 files changed, 568 insertions(+), 1 deletion(-) create mode 100644 dashboard/internal/autolearn/check_competition.go create mode 100644 dashboard/internal/autolearn/check_competition_test.go diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index c70d4c32..711ba2ac 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -562,7 +562,7 @@ func main() { for _, det := range []autolearn.Detector{ autolearn.SwitchTimeDetector, autolearn.RuntimeDetector, autolearn.CouplingDetector, autolearn.FlappingDetector, autolearn.FeedbackDetector, autolearn.NoEffectDetector, autolearn.OverriddenDetector, autolearn.OfflineDetector, - autolearn.AwayStandbyDetector, + autolearn.AwayStandbyDetector, autolearn.CompetitionDetector, } { automationEngine.Register(det) } diff --git a/dashboard/internal/autolearn/check_competition.go b/dashboard/internal/autolearn/check_competition.go new file mode 100644 index 00000000..b4156422 --- /dev/null +++ b/dashboard/internal/autolearn/check_competition.go @@ -0,0 +1,384 @@ +package autolearn + +import ( + "context" + "math" + "sort" + "time" +) + +// CompetitionDetector finds rules that switch on from the same balance value. +// When two or more of them fire in one quarter hour and the grid import stays +// above the smallest of their loads, the loads compete for the surplus (spec +// 15.4 "Konkurrenz"). The proposal is a staircase of thresholds, one step per +// load. It runs once a day and needs the operating powers of the loads. +var CompetitionDetector = Detector{ + Name: "competition", + Group: "reliability", + Light: false, + PerDevice: false, + Run: competitionRun, +} + +const ( + // competitionWindowDays is the number of the latest day files the check counts. + competitionWindowDays = 14 + // competitionMinDays is the number of days with a competing quarter hour a finding needs. + competitionMinDays = 3 + // competitionLimit is the lower Wilson bound of the share of days a finding needs. + competitionLimit = 0.2 + // competitionMinReserveW is the smallest reserve above the staircase, in W. + competitionMinReserveW = 100.0 +) + +// competitionRun lists the competition findings as candidates. +func competitionRun(ctx context.Context, in *Input, _ string) []Candidate { + if ctx.Err() != nil { + return nil + } + return competitionCandidates(in) +} + +// competitionCandidates checks every balance field that rules switch on from. +// The reserve is twice the reading noise of the export, at least 100 W. +func competitionCandidates(in *Input) []Candidate { + if in == nil || len(in.Doc.Rules) == 0 { + return nil + } + days := competitionWindow(in.Days) + reserve := math.Max(2*feedbackNoise(in.Days), competitionMinReserveW) + loc := in.Loc + if loc == nil { + loc = time.Local + } + var out []Candidate + for _, field := range competitionFields(in.Doc) { + if c, ok := competitionField(in, days, field, reserve, loc); ok { + out = append(out, c) + } + } + return out +} + +// competitionWindow returns the latest competitionWindowDays day files in order. +func competitionWindow(days []DayFile) []DayFile { + sorted := append([]DayFile(nil), days...) + sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].Day < sorted[j].Day }) + if len(sorted) > competitionWindowDays { + sorted = sorted[len(sorted)-competitionWindowDays:] + } + return sorted +} + +// competitionFields lists the balance fields of the enabled rules that switch on +// above a value, sorted. +func competitionFields(doc Doc) []string { + seen := map[string]bool{} + var out []string + for _, r := range doc.Rules { + if !r.Enabled { + continue + } + for _, c := range r.Conditions { + if c.Type == "balance_threshold" && c.Comparison == "above" && c.Field != "" && !seen[c.Field] { + seen[c.Field] = true + out = append(out, c.Field) + } + } + } + sort.Strings(out) + return out +} + +// compAcc collects what the competing quarter hours of the window hold. +type compAcc struct { + hits int + rules map[string]bool + devices map[string]bool +} + +// competitionField builds the finding of one balance field, or reports false +// when the rules do not compete in the window. +func competitionField(in *Input, days []DayFile, field string, reserve float64, loc *time.Location) (Candidate, bool) { + members := map[string]bool{} + for _, r := range in.Doc.Rules { + if _, _, ok := compThreshold(r, field); ok && r.Enabled { + members[r.ID] = true + } + } + if len(members) < 2 { + return Candidate{}, false + } + acc := compAcc{rules: map[string]bool{}, devices: map[string]bool{}} + for i := range days { + if competitionDay(in, &days[i], field, members, loc, &acc) { + acc.hits++ + } + } + n := len(days) + lower := WilsonLower(acc.hits, n) + if acc.hits < competitionMinDays || lower < competitionLimit { + return Candidate{}, false + } + stages, ok := competitionStaircase(in, days, field, acc, reserve) + if !ok { + return Candidate{}, false + } + finding, ok := competitionFinding(in, field, acc, stages) + if !ok { + return Candidate{}, false + } + return Candidate{ + Finding: finding, + Detector: "competition", + NEff: float64(n), + MinNEff: competitionMinDays, + Lower: lower, + Limit: competitionLimit, + }, true +} + +// competitionDay reports whether the day has a quarter hour in which two or more +// rules on the field switch on loads and the grid import in the next two quarter +// hours is above the smallest of these loads. The rules, devices and loads of +// such a quarter hour go into acc. +func competitionDay(in *Input, f *DayFile, field string, members map[string]bool, loc *time.Location, acc *compAcc) bool { + fires := map[int]map[string]string{} + for _, a := range f.Actions { + if !members[a.Rule] || a.Want == nil || !*a.Want { + continue + } + q := quarterOf(time.Unix(a.At, 0).In(loc)) + if fires[q] == nil { + fires[q] = map[string]string{} + } + fires[q][a.Rule] = a.Device + } + quarters := make([]int, 0, len(fires)) + for q := range fires { + quarters = append(quarters, q) + } + sort.Ints(quarters) + hit := false + for _, q := range quarters { + byRule := fires[q] + if len(byRule) < 2 || q+2 >= dayQuarters { + continue + } + powers := map[string]float64{} + for _, dev := range byRule { + if p, ok := learnedOperatingPower(in.Learned, dev); ok { + powers[dev] = p + } + } + if len(powers) < 2 { + continue + } + minP := math.Inf(1) + for _, p := range powers { + minP = math.Min(minP, p) + } + if !compImportAbove(f, q+1, minP) || !compImportAbove(f, q+2, minP) { + continue + } + hit = true + for rule, dev := range byRule { + acc.rules[rule] = true + if _, ok := powers[dev]; ok { + acc.devices[dev] = true + } + } + } + return hit +} + +// compImportAbove reports whether quarter q of the day has a reading and a grid +// import above w. +func compImportAbove(f *DayFile, q int, w float64) bool { + return f.Site.Seen[q] != 0 && float64(f.Site.GridImport[q]) > w +} + +// compStage is one step of the staircase: the load that is switched on at it, +// its threshold and whether the season reaches it on too few days. +type compStage struct { + device string + threshold float64 + reached int + dormant bool +} + +// competitionStaircase orders the loads and sums their operating powers. A load +// with a fixed cycle energy comes first, then the one the user starts by hand +// most often, then the higher operating power. Step k is the sum of the first k +// powers plus the reserve. It reports false without two loads with a rule. +func competitionStaircase(in *Input, days []DayFile, field string, acc compAcc, reserve float64) ([]compStage, bool) { + type load struct { + id string + p float64 + fixed bool + hand float64 + } + var loads []load + for dev := range acc.devices { + p, _ := learnedOperatingPower(in.Learned, dev) + loads = append(loads, load{id: dev, p: p, fixed: hasCycleEnergy(days, dev), hand: handShare(days, dev)}) + } + sort.Slice(loads, func(i, j int) bool { + a, b := loads[i], loads[j] + if a.fixed != b.fixed { + return a.fixed + } + if a.hand != b.hand { + return a.hand > b.hand + } + if a.p != b.p { + return a.p > b.p + } + return a.id < b.id + }) + if len(loads) < 2 { + return nil, false + } + var stages []compStage + sum := 0.0 + for _, l := range loads { + sum += l.p + th := feedbackCeil(sum + reserve) + reached := daysReaching(days, th) + stages = append(stages, compStage{device: l.id, threshold: th, reached: reached, + dormant: reached < competitionMinDays}) + } + return stages, true +} + +// hasCycleEnergy reports whether the window holds a finished cycle of the device with energy. +func hasCycleEnergy(days []DayFile, device string) bool { + for i := range days { + for _, c := range days[i].Cycles { + if c.Device == device && c.Wh > 0 { + return true + } + } + } + return false +} + +// handShare is the share of the device's starts in the window that were made by +// hand, 0 when there were no starts. +func handShare(days []DayFile, device string) float64 { + var hand, rule float64 + for i := range days { + dd := days[i].Devices[device] + if dd == nil { + continue + } + for q := 0; q < dayQuarters; q++ { + hand += float64(dd.Hand[q]) + rule += float64(dd.Rule[q]) + } + } + if hand+rule == 0 { + return 0 + } + return hand / (hand + rule) +} + +// daysReaching counts the days of the window whose export reaches th in some quarter hour. +func daysReaching(days []DayFile, th float64) int { + n := 0 + for i := range days { + for q := 0; q < dayQuarters; q++ { + if days[i].Site.Seen[q] != 0 && float64(days[i].Site.GridExport[q]) >= th { + n++ + break + } + } + } + return n +} + +// competitionFinding builds the finding with one threshold change per competing +// rule, the rule of the first step first, and an open rule fix on that rule. +// It reports false when no competing rule has a threshold on the field. +func competitionFinding(in *Input, field string, acc compAcc, stages []compStage) (Finding, bool) { + rules := ruleByID(in.Doc) + var ids []string + for id := range acc.rules { + ids = append(ids, id) + } + sort.Strings(ids) + + type mapped struct { + rule Rule + step int + index int + cur float64 + } + var ms []mapped + for _, id := range ids { + r, ok := rules[id] + if !ok { + continue + } + for k, st := range stages { + info, ok := in.Devices[st.device] + if !ok || !actsOnDevice(r, info) { + continue + } + idx, cur, ok := compThreshold(r, field) + if ok { + ms = append(ms, mapped{rule: r, step: k, index: idx, cur: cur}) + } + break + } + } + sort.SliceStable(ms, func(a, b int) bool { return ms[a].step < ms[b].step }) + + if len(ms) == 0 { + return Finding{}, false + } + var ops []RuleOps + var marks []Mark + for _, st := range stages { + marks = append(marks, Mark{Value: st.threshold, Dormant: st.dormant}) + } + istValue := math.Inf(1) + for _, m := range ms { + ops = append(ops, RuleOps{RuleID: m.rule.ID, Ops: []Op{{ + Path: []any{"conditions", m.index, "threshold"}, Value: stages[m.step].threshold}}}) + istValue = math.Min(istValue, m.cur) + } + sollValue := stages[0].threshold + first := ms[0].rule.ID + return Finding{ + ID: "competition:" + field, + Kind: "competition", + Group: "check", + RuleIDs: ids, + Severity: "info", + Confidence: "estimate", + Summary: Text{Code: "check.competition", Params: map[string]any{"rules": len(ids), "field": field}}, + Evidence: Evidence{Shape: "scale", IstValue: &istValue, SollValue: &sollValue, Marks: marks}, + Apply: []Fix{ + {Code: "stagger", RuleID: first, Rules: ops}, + {Code: "open_rule", RuleID: first}, + }, + }, true +} + +// compThreshold returns the index and the value of the first condition of the +// rule on the balance field that switches on above a value. A learned threshold +// counts with its minimum, the value the rule can reach first. +func compThreshold(r Rule, field string) (int, float64, bool) { + for i, c := range r.Conditions { + if c.Type != "balance_threshold" || c.Field != field || c.Comparison != "above" { + continue + } + if ref, learned := c.Learned["threshold"]; learned { + v, ok := asFloat(ref.Min) + return i, v, ok + } + return i, c.Threshold, true + } + return 0, 0, false +} diff --git a/dashboard/internal/autolearn/check_competition_test.go b/dashboard/internal/autolearn/check_competition_test.go new file mode 100644 index 00000000..289ad9b2 --- /dev/null +++ b/dashboard/internal/autolearn/check_competition_test.go @@ -0,0 +1,167 @@ +package autolearn + +import ( + "context" + "testing" + "time" +) + +// compRule switches the entity on when the export is above x. +func compRule(id, entity string, x float64) Rule { + return Rule{ID: id, Name: id, Enabled: true, + Conditions: []Condition{{Type: "balance_threshold", Field: "grid_export", Comparison: "above", Threshold: x}}, + Actions: []Action{{Type: "publish", EntityID: entity}}} +} + +// compDevices are two switchable loads: plug.a with 1500 W, plug.b with 2000 W. +func compDevices() map[string]DeviceInfo { + return map[string]DeviceInfo{ + "plug.a": {ID: "plug.a", Name: "Waschmaschine", Switchable: true, Entities: []string{"switch.plug.a"}}, + "plug.b": {ID: "plug.b", Name: "Trockner", Switchable: true, Entities: []string{"switch.plug.b"}}, + } +} + +// compLearned gives both loads their operating power. +func compLearned() map[string]LearnedEntry { + return map[string]LearnedEntry{ + "device/plug.a/op_power_w": {Key: "device/plug.a/op_power_w", Device: "plug.a", Kind: ValueNumber, Unit: "W", Value: 1500.0, N: 10}, + "device/plug.b/op_power_w": {Key: "device/plug.b/op_power_w", Device: "plug.b", Kind: ValueNumber, Unit: "W", Value: 2000.0, N: 10}, + } +} + +// compWeek builds 14 days. The export alternates between 1000 and 1200 W, so the +// noise is 100 W and the reserve 200 W. On the first fireDays both rules a and b +// fire in quarter 40 (10:00) with the export at fireExport, and the import in the +// two quarters after is 2500 W. With bLater set, b fires in quarter 60 instead. +func compWeek(loc *time.Location, fireDays int, fireExport float32, bLater bool) []DayFile { + var days []DayFile + for d := 0; d < 14; d++ { + day := relDay(fbDay(loc, 10+d)) + for q := 0; q < dayQuarters; q++ { + day.Site.Seen[q] = 1 + day.Site.GridExport[q] = 1000 + if q%2 == 1 { + day.Site.GridExport[q] = 1200 + } + } + if d < fireDays { + day.Site.GridExport[40] = fireExport + day.Site.GridImport[41] = 2500 + day.Site.GridImport[42] = 2500 + relRuleAction(&day, relAt(fbDay(loc, 10+d), 10, 0, 5), "plug.a", "a", true, true) + bAt := relAt(fbDay(loc, 10+d), 10, 0, 20) + if bLater { + bAt = relAt(fbDay(loc, 10+d), 15, 0, 20) + } + relRuleAction(&day, bAt, "plug.b", "b", true, true) + } + days = append(days, day) + } + // One finished cycle of plug.a makes its load a fixed cycle energy. + days[0].Cycles = []CycleRec{{Device: "plug.a", Start: relAt(fbDay(loc, 10), 9, 0, 0), DurS: 3600, Wh: 1500}} + return days +} + +func TestCompetitionStaircaseOfTwoRules(t *testing.T) { + loc := berlinLoc(t) + in := relInput(loc, compWeek(loc, 6, 4000, false), compDevices(), + compRule("a", "switch.plug.a", 1800), compRule("b", "switch.plug.b", 1800)) + in.Learned = compLearned() + got := competitionCandidates(in) + if len(got) != 1 { + t.Fatalf("candidates = %d, want 1", len(got)) + } + f := got[0].Finding + if f.ID != "competition:grid_export" || f.Kind != "competition" || f.Group != "check" || f.Severity != "info" { + t.Errorf("finding = id %q kind %q group %q severity %q", f.ID, f.Kind, f.Group, f.Severity) + } + if f.Summary.Code != "check.competition" || f.Device != "" { + t.Errorf("summary %q device %q", f.Summary.Code, f.Device) + } + if len(f.RuleIDs) != 2 || f.RuleIDs[0] != "a" || f.RuleIDs[1] != "b" { + t.Errorf("rule ids = %v, want [a b]", f.RuleIDs) + } + // The fixed cycle energy of plug.a puts it first: 1500 + 200 and 1500 + 2000 + 200. + if len(f.Evidence.Marks) != 2 || f.Evidence.Marks[0].Value != 1700 || f.Evidence.Marks[1].Value != 3700 { + t.Fatalf("marks = %+v, want 1700 and 3700", f.Evidence.Marks) + } + for _, m := range f.Evidence.Marks { + if m.Dormant { + t.Errorf("mark %v is dormant, want reached on 6 days", m.Value) + } + } + if len(f.Apply) != 2 || f.Apply[0].Code != "stagger" || f.Apply[1].Code != "open_rule" || f.Apply[1].RuleID != "a" { + t.Fatalf("apply = %+v, want stagger then open_rule on a", f.Apply) + } + rules := f.Apply[0].Rules + if len(rules) != 2 || rules[0].RuleID != "a" || rules[1].RuleID != "b" { + t.Fatalf("stagger rules = %+v, want a then b", rules) + } + if rules[0].Ops[0].Value != 1700.0 || rules[1].Ops[0].Value != 3700.0 { + t.Errorf("stagger values = %v and %v, want 1700 and 3700", rules[0].Ops[0].Value, rules[1].Ops[0].Value) + } + if rules[0].Ops[0].Path[1] != 0 || rules[0].Ops[0].Path[2] != "threshold" { + t.Errorf("path = %v, want conditions 0 threshold", rules[0].Ops[0].Path) + } +} + +func TestCompetitionMarksDormantStage(t *testing.T) { + loc := berlinLoc(t) + // The export only reaches 2000 W when the rules fire: the first stage is reached, the second is not. + in := relInput(loc, compWeek(loc, 6, 2000, false), compDevices(), + compRule("a", "switch.plug.a", 1800), compRule("b", "switch.plug.b", 1800)) + in.Learned = compLearned() + got := competitionCandidates(in) + if len(got) != 1 { + t.Fatalf("candidates = %d, want 1", len(got)) + } + marks := got[0].Finding.Evidence.Marks + if len(marks) != 2 || marks[0].Dormant || !marks[1].Dormant { + t.Fatalf("marks = %+v, want the first reached and the second dormant", marks) + } +} + +// Review Focus 2: two rules on the same surplus that never fire together give no finding, +// even though the sum of their loads is above the surplus. +func TestCompetitionNoFindingWhenRulesNeverFireTogether(t *testing.T) { + loc := berlinLoc(t) + in := relInput(loc, compWeek(loc, 6, 4000, true), compDevices(), + compRule("a", "switch.plug.a", 1800), compRule("b", "switch.plug.b", 1800)) + in.Learned = compLearned() + if got := competitionCandidates(in); len(got) != 0 { + t.Fatalf("candidates = %+v, want none when the rules never fire in the same quarter hour", got) + } +} + +func TestCompetitionNeedsThreeDays(t *testing.T) { + loc := berlinLoc(t) + in := relInput(loc, compWeek(loc, 2, 4000, false), compDevices(), + compRule("a", "switch.plug.a", 1800), compRule("b", "switch.plug.b", 1800)) + in.Learned = compLearned() + if got := competitionCandidates(in); len(got) != 0 { + t.Fatalf("candidates = %+v, want none on 2 days", got) + } +} + +func TestCompetitionSingleRuleGivesNothing(t *testing.T) { + loc := berlinLoc(t) + in := relInput(loc, compWeek(loc, 6, 4000, false), compDevices(), + compRule("a", "switch.plug.a", 1800)) + in.Learned = compLearned() + if got := competitionCandidates(in); len(got) != 0 { + t.Fatalf("candidates = %+v, want none for one rule", got) + } +} + +func TestCompetitionDetectorRunsDailyInReliability(t *testing.T) { + if CompetitionDetector.Name != "competition" || CompetitionDetector.Group != "reliability" || CompetitionDetector.Light { + t.Fatalf("detector = %+v, want daily competition in reliability", CompetitionDetector) + } + loc := berlinLoc(t) + in := relInput(loc, compWeek(loc, 6, 4000, false), compDevices(), + compRule("a", "switch.plug.a", 1800), compRule("b", "switch.plug.b", 1800)) + in.Learned = compLearned() + if got := CompetitionDetector.Run(context.Background(), in, ""); len(got) != 1 { + t.Fatalf("run = %d candidates, want 1", len(got)) + } +} diff --git a/dashboard/internal/autolearn/finding.go b/dashboard/internal/autolearn/finding.go index f028455b..fd37d879 100644 --- a/dashboard/internal/autolearn/finding.go +++ b/dashboard/internal/autolearn/finding.go @@ -99,6 +99,15 @@ type Evidence struct { IstNames []string `json:"ist_names,omitempty"` SollNames []string `json:"soll_names,omitempty"` Missing bool `json:"missing,omitempty"` + // Marks holds the steps of a scale, such as the stages of staggered thresholds. + Marks []Mark `json:"marks,omitempty"` +} + +// Mark is one step on the scale of a finding. Dormant marks a step that the +// current season reaches on too few days. +type Mark struct { + Value float64 `json:"value"` + Dormant bool `json:"dormant,omitempty"` } // FindingID builds the stable ID of a finding from its kind and rule IDs. The diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index ed14482c..aff52cfe 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -475,6 +475,8 @@ "automations.learn.button.never": "Nicht mehr vorschlagen", "automations.learn.button.open_assistant": "Im Assistenten öffnen", "automations.learn.button.undo": "Rückgängig", + "automations.learn.check.competition.text": "Mehrere Regeln schalten beim selben Überschuss ein. Lösen sie zusammen aus, zieht danach der Netzbezug. Gestaffelte Schwellen geben jeder Last ihren eigenen Platz.", + "automations.learn.check.competition.title": "Regeln konkurrieren um denselben Überschuss", "automations.learn.check.contradiction.text": "„{rule}“ und „{other}“ haben dieselben Bedingungen, schicken aber verschiedene Befehle an {topic}.", "automations.learn.check.contradiction.title": "Widerspricht „{other}“", "automations.learn.check.duplicate.text": "„{rule}“ macht genau dasselbe wie „{other}“. Eine der beiden Regeln reicht.", @@ -547,6 +549,7 @@ "automations.learn.fix.set_hysteresis": "Hysterese {value} W", "automations.learn.fix.set_threshold": "Schwelle auf {value}", "automations.learn.fix.shift_time": "Zeitfenster verschieben", + "automations.learn.fix.stagger": "Schwellen staffeln", "automations.learn.group.check": "Regelprüfung", "automations.learn.group.energy": "Energie", "automations.learn.group.habit": "Gewohnheit", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 4339ecd1..25312a99 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -475,6 +475,8 @@ "automations.learn.button.never": "Do not suggest again", "automations.learn.button.open_assistant": "Open in assistant", "automations.learn.button.undo": "Undo", + "automations.learn.check.competition.text": "Several rules switch on at the same surplus. When they fire together, the grid import follows. Staggered thresholds give each load its own place.", + "automations.learn.check.competition.title": "Rules compete for the same surplus", "automations.learn.check.contradiction.text": "“{rule}” and “{other}” have the same conditions but send different commands to {topic}.", "automations.learn.check.contradiction.title": "Contradicts “{other}”", "automations.learn.check.duplicate.text": "“{rule}” does exactly the same as “{other}”. One of the two rules is enough.", @@ -547,6 +549,7 @@ "automations.learn.fix.set_hysteresis": "Hysteresis {value} W", "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.group.check": "Rule check", "automations.learn.group.energy": "Energy", "automations.learn.group.habit": "Habit", diff --git a/dashboard/internal/webui/learn_summary_catalog_test.go b/dashboard/internal/webui/learn_summary_catalog_test.go index 4bfbac1a..cd4e2610 100644 --- a/dashboard/internal/webui/learn_summary_catalog_test.go +++ b/dashboard/internal/webui/learn_summary_catalog_test.go @@ -18,6 +18,7 @@ var summaryCodeLiteral = regexp.MustCompile(`Text\{Code: "([a-z_.]+)"`) // rule findings from the checker, which the band does not draw as a tile. Each entry must stay // without a .line key, the test fails when one gets its key, so the list is kept current. var learnLineGaps = map[string]bool{ + "check.competition": true, "check.contradiction": true, "check.duplicate": true, "check.feedback": true, From 3769fa63d75afefeed450786f2825307694c7dfe Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:00:50 +0100 Subject: [PATCH 05/37] feat(autolearn): say in which week a PV rule will fire again A PV or grid export threshold that the clear-sky curve reaches later in the year is now reported as an info finding with the first calendar week that reaches it. A threshold the curve never reaches stays a warning with the threshold fix. Without a safe roof model the seasonal maximum is used as before. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 7 +- dashboard/internal/autolearn/checker.go | 12 +- dashboard/internal/autolearn/observed.go | 107 +++++++++++++++- dashboard/internal/autolearn/observed_test.go | 120 +++++++++++++++++- dashboard/internal/webui/catalogs/de.json | 2 + dashboard/internal/webui/catalogs/en.json | 2 + .../webui/learn_summary_catalog_test.go | 1 + 7 files changed, 239 insertions(+), 12 deletions(-) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 711ba2ac..432f9d99 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -575,13 +575,14 @@ func main() { automationEngine.Register(autolearn.NewShadeDetector(pvTracker.Snapshot, pvModelStore.Model)) // Modell und Himmelsraster fuer den Rest-Ueberschuss. Der Raster-Schnappschuss // entsteht nur, wenn ein Modell da ist. - automationEngine.SetPV(func() (autolearn.PVModel, *autolearn.Raster, bool) { + pvSource := func() (autolearn.PVModel, *autolearn.Raster, bool) { m, ok := pvModelStore.Model() if !ok { return autolearn.PVModel{}, nil, false } return m, pvTracker.Snapshot(), true - }) + } + automationEngine.SetPV(pvSource) // Die Aussentemperatur fuer den Heizzeit-Erkenner: die Entitaet aus den // Einstellungen, aufgeloest ueber die Registry wie beim Lernhub. automationEngine.SetOutdoor(func() autolearn.OutdoorSource { @@ -603,6 +604,8 @@ func main() { automationChecker.SetEngineSource(automationEngine.Candidates, func() bool { return engineGroups()["reliability"] }) + // Die Regelpruefung prueft PV-Schwellen gegen dieselbe Bestkurve wie die Engine. + automationChecker.SetPV(pvSource) // Herabstufung: nur bei automatischer Stufe rueckt die gemerkte Stufe eine // nach unten. Eine feste Stufe der Einstellungen bleibt unberuehrt. engineDowngrade := func() { diff --git a/dashboard/internal/autolearn/checker.go b/dashboard/internal/autolearn/checker.go index bb7d06c6..ba1435e4 100644 --- a/dashboard/internal/autolearn/checker.go +++ b/dashboard/internal/autolearn/checker.go @@ -37,6 +37,8 @@ type Checker struct { // are nil until SetEngineSource is called. engineCandidates func() []Candidate reliabilityOn func() bool + // pv gives the roof model for the PV thresholds, nil until SetPV is called. + pv PVSource mu sync.Mutex // doc is the last rule document that parsed. docOK is false when the last @@ -81,6 +83,14 @@ func (c *Checker) SetThresholds(th Thresholds) { c.thresholds = th } +// SetPV gives the checker the roof model and the sky raster, the same source +// the engine reads. Without a safe model the PV thresholds use the seasonal maximum. +func (c *Checker) SetPV(pv PVSource) { + c.mu.Lock() + defer c.mu.Unlock() + c.pv = pv +} + // SetEngineSource connects the engine. candidates returns the last candidates // of the engine, reliabilityOn tells whether the reliability group is on. Only // reliability candidates are listed, and only while the group is on. @@ -102,7 +112,7 @@ func (c *Checker) Findings(now time.Time) []Finding { // must follow at once, not up to checkerDocEvery later. c.refreshLocked(now, true) all := StaticFindings(c.doc, c.entityExists) - all = append(all, ObservedFindingsWith(c.doc, c.obs.Snapshot(), c.season, now, c.thresholds)...) + all = append(all, ObservedFindingsWithPV(c.doc, c.obs.Snapshot(), c.season, c.pv, now, c.thresholds)...) all = append(all, c.reliabilityLocked()...) sort.SliceStable(all, func(i, j int) bool { ri, rj := severityRank[all[i].Severity], severityRank[all[j].Severity] diff --git a/dashboard/internal/autolearn/observed.go b/dashboard/internal/autolearn/observed.go index dd939e58..51d1c1c7 100644 --- a/dashboard/internal/autolearn/observed.go +++ b/dashboard/internal/autolearn/observed.go @@ -6,6 +6,8 @@ import ( "sort" "strings" "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" ) const ( @@ -15,6 +17,10 @@ const ( seasonWindow = 365 * 24 * time.Hour ) +// PVSource returns the stored roof model, the sky raster and whether a model +// exists, as Input.PV does. +type PVSource func() (PVModel, *Raster, bool) + // Thresholds are the limits of the observed checks. type Thresholds struct { // FrequentMinCount is the number of triggers in one hour that counts as frequent. @@ -55,14 +61,21 @@ func ObservedFindings(doc Doc, st ObserverState, season SeasonalSource, now time return ObservedFindingsWith(doc, st, season, now, DefaultThresholds()) } -// ObservedFindingsWith checks the rules against what was observed. A rule that +// ObservedFindingsWith is ObservedFindingsWithPV without a PV source. +func ObservedFindingsWith(doc Doc, st ObserverState, season SeasonalSource, now time.Time, th Thresholds) []Finding { + return ObservedFindingsWithPV(doc, st, season, nil, now, th) +} + +// ObservedFindingsWithPV checks the rules against what was observed. A rule that // fires at least th.FrequentMinCount times in one hour of the last 24 h is // frequent. An enabled rule that did not fire within th.NeverFiredWindow, // although it is at least th.NeverFiredMinAge known and its value has been seen // for th.MinRangeDays, is never fired. A threshold the value never reached is // reported as a seasonal rest when the season had a higher maximum. season may -// be nil, which skips the seasonal check. -func ObservedFindingsWith(doc Doc, st ObserverState, season SeasonalSource, now time.Time, th Thresholds) []Finding { +// be nil, which skips the seasonal check. pv may be nil. With a safe PV model +// and the site location, a PV or grid export threshold is checked against the +// clear-sky curve instead of the seasonal maximum. +func ObservedFindingsWithPV(doc Doc, st ObserverState, season SeasonalSource, pv PVSource, now time.Time, th Thresholds) []Finding { var findings []Finding for _, rule := range doc.Rules { if !rule.Enabled { @@ -75,7 +88,7 @@ func ObservedFindingsWith(doc Doc, st ObserverState, season SeasonalSource, now if f, ok := frequentFinding(rule, stats, now, th.FrequentMinCount); ok { findings = append(findings, f) } - if f, ok := neverFiredFinding(rule, stats, st, season, now, th); ok { + if f, ok := neverFiredFinding(rule, stats, st, season, pv, doc.Location, now, th); ok { findings = append(findings, f) } } @@ -159,7 +172,7 @@ func hysteresisFor(threshold float64) int { // neverFiredFinding checks the first number condition of the rule whose value // never reached the threshold in the last 30 days. -func neverFiredFinding(rule Rule, stats RuleStats, st ObserverState, season SeasonalSource, now time.Time, th Thresholds) (Finding, bool) { +func neverFiredFinding(rule Rule, stats RuleStats, st ObserverState, season SeasonalSource, pv PVSource, loc *sun.Location, now time.Time, th Thresholds) (Finding, bool) { if now.Sub(stats.FirstSeen) < th.NeverFiredMinAge || firedSince(stats, now.Add(-th.NeverFiredWindow)) { return Finding{}, false } @@ -181,7 +194,7 @@ func neverFiredFinding(rule Rule, stats RuleStats, st ObserverState, season Seas lo, hi = min(lo, r.Min), max(hi, r.Max) } if c.Comparison == "above" && hi < x { - return aboveFinding(rule, i, c, x, lo, hi, season, now) + return aboveFinding(rule, i, c, x, lo, hi, season, pv, loc, now) } if c.Comparison == "below" && lo > x { return belowFinding(rule, i, c, x, lo, hi) @@ -190,9 +203,14 @@ func neverFiredFinding(rule Rule, stats RuleStats, st ObserverState, season Seas return Finding{}, false } -func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season SeasonalSource, now time.Time) (Finding, bool) { +func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season SeasonalSource, pv PVSource, loc *sun.Location, now time.Time) (Finding, bool) { var seasonMax *float64 var months []int + if c.Type == "balance_threshold" && (c.Field == "pv" || c.Field == "grid_export") && pv != nil && loc != nil { + if m, r, ok := pv(); ok && m.Safe { + return pvAboveFinding(rule, i, c, x, lo, hi, m, r, *loc, now) + } + } if c.Type == "balance_threshold" && season != nil { if maxW, m, _, ok := season.MaxW(c.Field, now.Add(-seasonWindow), now); ok { seasonMax, months = &maxW, m @@ -234,6 +252,67 @@ func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season Seaso }, true } +// pvAboveFinding is a PV or grid export threshold above the clear-sky curve of +// a safe model. A threshold the curve reaches later in the year is a seasonal +// rest with the first week that reaches it. One the curve never reaches is +// never fired and gets the threshold fix. +func pvAboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, m PVModel, r *Raster, loc sun.Location, now time.Time) (Finding, bool) { + scale := Evidence{Shape: "scale", Seen: [2]float64{lo, hi}, IstValue: &x, Unit: unitOf(c)} + if week, ok := SeasonWeekFor(x, m, r, loc, now); ok { + scale.Max = scaleMax(hi, x) + return Finding{ + ID: FindingID("never_fired", rule.ID), + Kind: "never_fired", + Group: "check", + RuleIDs: []string{rule.ID}, + Severity: "info", + Confidence: "estimate", + Summary: Text{Code: "check.never_fired_season", Params: map[string]any{ + "rule": rule.Name, "threshold": x, "week": week}}, + Evidence: scale, + Facts: []Fact{{Code: "season_week", Value: week}}, + }, true + } + + s := math.Max(50, math.Floor(0.75*hi/50)*50) + scale.SollValue = &s + scale.Max = scaleMax(hi, x, s) + return Finding{ + ID: FindingID("never_fired", rule.ID), + Kind: "never_fired", + Group: "check", + RuleIDs: []string{rule.ID}, + Severity: "warn", + Confidence: "estimate", + Summary: Text{Code: "check.never_fired", Params: map[string]any{ + "rule": rule.Name, "threshold": x}}, + Evidence: scale, + Apply: []Fix{{Code: "set_threshold", RuleID: rule.ID, Ops: []Op{ + {Path: []any{"conditions", i, thresholdKey(c)}, Value: int(s)}}}}, + }, true +} + +// seasonWeeks is how many weeks ahead SeasonWeekFor looks. +const seasonWeeks = 53 + +// seasonStep is the sampling step of the sun elevation within a week. +const seasonStep = 15 * time.Minute + +// SeasonWeekFor is the first ISO week, counted from now, in which the clear-sky +// curve reaches the threshold at the highest sun elevation of that week. ok is +// false when no week within seasonWeeks reaches it. +func SeasonWeekFor(threshold float64, m PVModel, r *Raster, loc sun.Location, now time.Time) (week int, ok bool) { + for k := 0; k <= seasonWeeks; k++ { + start := now.Add(time.Duration(k) * 7 * 24 * time.Hour) + az, el := weekNoon(start, loc) + if m.Best(az, el, r) >= threshold { + _, w := start.ISOWeek() + return w, true + } + } + return 0, false +} + func belowFinding(rule Rule, i int, c Condition, y, lo, hi float64) (Finding, bool) { s := math.Ceil(1.25*lo/50) * 50 scale := Evidence{Shape: "scale", Seen: [2]float64{lo, hi}, IstValue: &y, SollValue: &s, @@ -289,3 +368,17 @@ func scaleMax(values ...float64) float64 { } return math.Round(largest*1.2/100) * 100 } + +// weekNoon is the sun position az/el at the highest elevation of the 7 days +// from start, sampled every seasonStep. It returns the sky position used by +// PVModel.Best. +func weekNoon(start time.Time, loc sun.Location) (az, el float64) { + el = -90 + for s := time.Duration(0); s < 7*24*time.Hour; s += seasonStep { + a, e := sun.Position(start.Add(s), loc.Lat, loc.Lon) + if e > el { + az, el = a, e + } + } + return az, el +} diff --git a/dashboard/internal/autolearn/observed_test.go b/dashboard/internal/autolearn/observed_test.go index 9c66c501..34266044 100644 --- a/dashboard/internal/autolearn/observed_test.go +++ b/dashboard/internal/autolearn/observed_test.go @@ -3,6 +3,8 @@ package autolearn import ( "testing" "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" ) var testNow = time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC) @@ -187,6 +189,16 @@ func TestObservedNeverFiredNeedsFourteenDays(t *testing.T) { // neverFiredState is a rule without triggers since firstSeen, with 8 days of // balance values from 100 W up to max W. func neverFiredState(firstSeen time.Time, max float64) ObserverState { + return neverFiredStateFor("grid_export", firstSeen, max) +} + +// neverFiredStateFor is neverFiredState for the balance field, with the stats +// under the ID of the rule pvRule or observedDoc builds. +func neverFiredStateFor(field string, firstSeen time.Time, max float64) ObserverState { + id := "heat" + if field == "pv" { + id = "sun" + } var ranges []DayRange day := testNow.Unix() / 86400 for i := 0; i < 8; i++ { @@ -194,8 +206,8 @@ func neverFiredState(firstSeen time.Time, max float64) ObserverState { } ranges[0].Max = max return ObserverState{ - Rules: map[string]RuleStats{"heat": {FirstSeen: firstSeen, Hours: map[int64]int{}}}, - Values: map[string][]DayRange{"balance:grid_export": ranges}, + Rules: map[string]RuleStats{id: {FirstSeen: firstSeen, Hours: map[int64]int{}}}, + Values: map[string][]DayRange{"balance:" + field: ranges}, } } @@ -251,3 +263,107 @@ func TestObservedFrequentWithLearnedThresholdHasNoHysteresisFix(t *testing.T) { t.Errorf("fixes = %+v, want only set_cooldown", got[0].Apply) } } + +// pvRoof is the 5 kW south roof of the plan, tilt 30 degrees, with the capped +// peak at 5 % above its PMax. +func pvRoof() PVModel { + return PVModel{Surfaces: []Surface{{PMax: 5000, TiltDeg: 30, AzimuthDeg: 180}}, CapW: 5250, Safe: true} +} + +var berlin = sun.Location{Lat: 52.5, Lon: 13.4} + +// pvRule is a rule on the PV power above threshold, with the site location. +func pvRule(t *testing.T, threshold string) Doc { + t.Helper() + return staticDoc(t, `{"rules": [{"id": "sun", "name": "Sun", "enabled": true, + "cooldown_seconds": 0, + "conditions": [{"type": "balance_threshold", "field": "pv", "comparison": "above", + "threshold": `+threshold+`, "hysteresis": 0}], + "actions": [{"type": "publish", "topic": "sun/set", "payload_source": "constant", "payload": "1"}]}], + "settings": {"latitude": 52.5, "longitude": 13.4}}`) +} + +func pvSource(m PVModel, ok bool) func() (PVModel, *Raster, bool) { + return func() (PVModel, *Raster, bool) { return m, nil, ok } +} + +// Focus 3: 6000 W on a 5 kW roof never fires, so it is not a seasonal rest. +// 4000 W is above the modelled roof as well. +func TestSeasonWeekForAboveTheRoofIsNever(t *testing.T) { + now := time.Date(2026, 12, 10, 12, 0, 0, 0, time.UTC) + for _, th := range []float64{4000, 6000} { + if week, ok := SeasonWeekFor(th, pvRoof(), nil, berlin, now); ok { + t.Errorf("threshold %v: week %d, want never", th, week) + } + } +} + +func TestSeasonWeekForReachedInSpring(t *testing.T) { + now := time.Date(2026, 12, 10, 12, 0, 0, 0, time.UTC) + week, ok := SeasonWeekFor(3000, pvRoof(), nil, berlin, now) + if !ok || week != 13 { + t.Fatalf("SeasonWeekFor(3000) = %d, %v, want 13, true", week, ok) + } +} + +func TestObservedNeverFiredPVSeasonalWeekIsInfo(t *testing.T) { + doc := pvRule(t, "3000") + st := neverFiredStateFor("pv", testNow.Add(-40*24*time.Hour), 1850) + week, ok := SeasonWeekFor(3000, pvRoof(), nil, berlin, testNow) + if !ok { + t.Fatal("SeasonWeekFor(3000) from testNow: not ok, want a week") + } + + findings := ObservedFindingsWithPV(doc, st, fakeSeason{ok: false}, pvSource(pvRoof(), true), testNow, DefaultThresholds()) + got := findKind(findings, "never_fired") + if len(got) != 1 { + t.Fatalf("never_fired findings = %d, want 1: %+v", len(got), findings) + } + f := got[0] + if f.Severity != "info" || f.Summary.Code != "check.never_fired_season" { + t.Errorf("severity/code = %s/%s, want info/check.never_fired_season", f.Severity, f.Summary.Code) + } + if len(f.Apply) != 0 { + t.Errorf("fixes = %+v, want none", f.Apply) + } + if len(f.Facts) != 1 || f.Facts[0].Code != "season_week" || f.Facts[0].Value != week { + t.Errorf("Facts = %+v, want season_week %d", f.Facts, week) + } +} + +func TestObservedNeverFiredPVAboveRoofIsWarnWithFix(t *testing.T) { + doc := pvRule(t, "6000") + st := neverFiredStateFor("pv", testNow.Add(-40*24*time.Hour), 1850) + + findings := ObservedFindingsWithPV(doc, st, fakeSeason{maxW: 5000, months: []int{6}, days: 300, ok: true}, + pvSource(pvRoof(), true), testNow, DefaultThresholds()) + got := findKind(findings, "never_fired") + if len(got) != 1 { + t.Fatalf("never_fired findings = %d, want 1: %+v", len(got), findings) + } + f := got[0] + if f.Severity != "warn" || f.Summary.Code != "check.never_fired" { + t.Errorf("severity/code = %s/%s, want warn/check.never_fired", f.Severity, f.Summary.Code) + } + if len(f.Apply) != 1 || f.Apply[0].Code != "set_threshold" { + t.Fatalf("fixes = %+v, want one set_threshold", f.Apply) + } +} + +func TestObservedNeverFiredPVWithoutModelUsesSeasonMax(t *testing.T) { + doc := pvRule(t, "3000") + st := neverFiredStateFor("pv", testNow.Add(-40*24*time.Hour), 1850) + season := fakeSeason{maxW: 3400, months: []int{6}, days: 300, ok: true} + + for name, src := range map[string]func() (PVModel, *Raster, bool){ + "no source": nil, + "no model": pvSource(PVModel{}, false), + "not safe": pvSource(PVModel{Surfaces: pvRoof().Surfaces, CapW: 5250}, true), + } { + findings := ObservedFindingsWithPV(doc, st, season, src, testNow, DefaultThresholds()) + got := findKind(findings, "never_fired") + if len(got) != 1 || got[0].Summary.Code != "check.seasonal_rest" { + t.Errorf("%s: findings = %+v, want check.seasonal_rest", name, got) + } + } +} diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index aff52cfe..ff398469 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -490,6 +490,8 @@ "automations.learn.check.frequent.title": "Löst sehr oft aus", "automations.learn.check.never_fired.text": "„{rule}“ hat lange nicht ausgelöst. Die Schwelle {threshold} liegt außerhalb dessen, was zuletzt gemessen wurde.", "automations.learn.check.never_fired.title": "Löst nie aus", + "automations.learn.check.never_fired_season.text": "„{rule}“ löst gerade nicht aus, die Schwelle wird ab Kalenderwoche {week} wieder erreicht. Das ist wohl normal.", + "automations.learn.check.never_fired_season.title": "Ruht saisonal", "automations.learn.check.no_effect.line": "{failures} Mal ohne Wirkung auf {device} ({share} %)", "automations.learn.check.no_effect.text": "„{rule}“ hat {failures} Mal versucht, {device} zu schalten, ohne dass sich etwas geändert hat. Das sind {share} % der Aktionen.", "automations.learn.check.no_effect.title": "„{rule}“ erreicht oft nichts", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 25312a99..5f634889 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -490,6 +490,8 @@ "automations.learn.check.frequent.title": "Triggers very often", "automations.learn.check.never_fired.text": "“{rule}” has not triggered for a long time. The threshold {threshold} lies outside what was measured recently.", "automations.learn.check.never_fired.title": "Never triggers", + "automations.learn.check.never_fired_season.text": "“{rule}” does not trigger right now, the threshold is reached again from calendar week {week} on. That is probably normal.", + "automations.learn.check.never_fired_season.title": "Resting for the season", "automations.learn.check.no_effect.line": "{failures} times without effect on {device} ({share} %)", "automations.learn.check.no_effect.text": "“{rule}” tried {failures} times to switch {device} and nothing changed. That is {share} % of its actions.", "automations.learn.check.no_effect.title": "“{rule}” often achieves nothing", diff --git a/dashboard/internal/webui/learn_summary_catalog_test.go b/dashboard/internal/webui/learn_summary_catalog_test.go index cd4e2610..266ebb81 100644 --- a/dashboard/internal/webui/learn_summary_catalog_test.go +++ b/dashboard/internal/webui/learn_summary_catalog_test.go @@ -24,6 +24,7 @@ var learnLineGaps = map[string]bool{ "check.feedback": true, "check.frequent": true, "check.never_fired": true, + "check.never_fired_season": true, "check.orphan": true, "check.regulator_conflict": true, "check.seasonal_rest": true, From b624fb65793b94a9bb94475b0c6ffac53d621388 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:06:08 +0100 Subject: [PATCH 06/37] feat(autolearn): report a rising base load with the device behind it Night load is the 10th percentile between night rest and day start. A sustained rise above the reference is a baseload finding, with the device that accounts for at least half of the rise when one is measured. A fall is no finding. The learned site/base_w is the median of the last 14 nights of today's day type. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 1 + .../internal/autolearn/detect_baseload.go | 329 ++++++++++++++++++ .../autolearn/detect_baseload_test.go | 212 +++++++++++ dashboard/internal/webui/catalogs/de.json | 5 + dashboard/internal/webui/catalogs/en.json | 5 + .../webui/static/js/automation-learned.js | 1 + .../webui/static/js/automation-suggestions.js | 2 + .../test/automation-suggestions.test.mjs | 10 + 8 files changed, 565 insertions(+) create mode 100644 dashboard/internal/autolearn/detect_baseload.go create mode 100644 dashboard/internal/autolearn/detect_baseload_test.go diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 432f9d99..caea5904 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -571,6 +571,7 @@ func main() { forecastCheck := autolearn.LoadForecastCheck(filepath.Join(autolearnDir, "forecast.json"), log.Printf) learnHub.AddSaver("forecast", forecastCheck) registerEnergyDetectors(automationEngine, pvReserve.Current, forecastCheck) + automationEngine.Register(autolearn.BaseLoadDetector) automationEngine.Register(autolearn.NewPVModelDetector(pvTracker.Snapshot, pvModelStore)) automationEngine.Register(autolearn.NewShadeDetector(pvTracker.Snapshot, pvModelStore.Model)) // Modell und Himmelsraster fuer den Rest-Ueberschuss. Der Raster-Schnappschuss diff --git a/dashboard/internal/autolearn/detect_baseload.go b/dashboard/internal/autolearn/detect_baseload.go new file mode 100644 index 00000000..104f12b0 --- /dev/null +++ b/dashboard/internal/autolearn/detect_baseload.go @@ -0,0 +1,329 @@ +package autolearn + +import ( + "context" + "math" + "sort" + "time" +) + +// BaseLoadDetector watches the night load of the house. Each night is the 10th +// percentile of the load between the night rest and the day start of its day +// type. A sustained rise above the expectation is a finding, with the device +// that accounts for at least half of the rise when one is measured. A fall is +// no finding. The learned site/base_w follows the level of the last 14 nights. +// It is daily and not per device. +var BaseLoadDetector = Detector{ + Name: "baseload", + Group: "energy", + Light: false, + PerDevice: false, + Run: baseLoadRun, +} + +const ( + // baseloadRefNights is the reference of the drift without an earlier year: + // the median of the first nights of the window. A reference that followed + // the last nights would absorb a lasting rise after two weeks. + baseloadRefNights = 28 + // baseloadWindow is the number of nights the drift is looked for in. + baseloadWindow = 90 + // baseloadMinNights is the number of nights for a drift: the reference and + // seven more. The spec gives no number, the value is an assumption. + baseloadMinNights = 35 + // baseloadMinYears is the number of earlier weeks that make the expectation + // of a week, the earlier years of the season store. + baseloadMinYears = 3 + // baseloadLearnNights is the number of nights of the learned site/base_w. + baseloadLearnNights = 14 + // baseloadLearnMin is the number of nights a learned site/base_w needs. + baseloadLearnMin = 7 + // baseloadMinSigmaW is the smallest spread in W, so that a flat series does + // not turn every small step into a drift. + baseloadMinSigmaW = 10.0 + // baseloadRoundW rounds the base load and the rise in W. + baseloadRoundW = 10.0 + // baseloadHours is the hours of a week and of a month for the benefit. + baseloadWeekH = 168.0 + baseloadMonthH = 720.0 +) + +// baseloadNight is one night of a day file that has all its quarters seen. +type baseloadNight struct { + date string + week int + group int + night float64 + // dev is the average power of each device with a record in the night, W. + dev map[string]float64 +} + +// baseLoadRun returns the drift finding and the learned site/base_w. +func baseLoadRun(ctx context.Context, in *Input, _ string) []Candidate { + if ctx.Err() != nil { + return nil + } + ns := baseloadNights(in) + var out []Candidate + if g, ok := learnTodayGroup(in); ok { + var same []float64 + for _, n := range ns { + if n.group == g { + same = append(same, n.night) + } + } + if len(same) > baseloadLearnNights { + same = same[len(same)-baseloadLearnNights:] + } + if len(same) >= baseloadLearnMin { + out = append(out, Candidate{ + Detector: "baseload", + NEff: float64(len(same)), + MinNEff: baseloadLearnMin, + Value: &Value{Key: "site/base_w", Kind: ValueNumber, Unit: "W", Group: "energy", + Num: baseloadRound(Median(same), baseloadRoundW), N: len(same)}, + }) + } + } + if len(ns) >= baseloadMinNights { + if len(ns) > baseloadWindow { + ns = ns[len(ns)-baseloadWindow:] + } + out = append(out, baseLoadDrift(in, ns)...) + } + return out +} + +// baseloadNights reads the nights of the day files in date order. Today, days +// without a day type, bounds or a night quarter that was not seen are left out. +func baseloadNights(in *Input) []baseloadNight { + loc := in.Loc + if loc == nil { + loc = time.Local + } + today := in.Now.In(loc).Format(dayLayout) + days := make([]*DayFile, 0, len(in.Days)) + for i := range in.Days { + days = append(days, &in.Days[i]) + } + sort.SliceStable(days, func(a, b int) bool { return days[a].Day < days[b].Day }) + var out []baseloadNight + for _, f := range days { + if f.Day == today { + continue + } + g, ok := in.Base.DayType[f.Day] + if !ok { + continue + } + ds, okS := in.Base.DayStart[g] + nr, okN := in.Base.NightRest[g] + if !okS || !okN { + continue + } + t, err := time.ParseInLocation(dayLayout, f.Day, loc) + if err != nil { + continue + } + var quarters []int + var load []float64 + seen := true + for q := 0; q < dayQuarters; q++ { + if !baseloadNightQuarter(q, ds, nr) { + continue + } + quarters = append(quarters, q) + if f.Site.Seen[q] == 0 { + seen = false + } + load = append(load, float64(f.Site.LoadTotal[q])) + } + if !seen || len(load) == 0 { + continue + } + _, week := t.ISOWeek() + dev := map[string]float64{} + for id, dd := range f.Devices { + if dd == nil { + continue + } + sum, n := 0.0, 0 + for _, q := range quarters { + if dd.Seen[q] != 0 { + sum += float64(dd.AvgW[q]) + n++ + } + } + if n > 0 { + dev[id] = sum / float64(n) + } + } + out = append(out, baseloadNight{date: f.Day, week: week, group: g, night: basePercentile10(load), dev: dev}) + } + return out +} + +// baseloadNightQuarter reports whether quarter q lies in the night: from the +// night rest to the end of the day, and from the start of the day to the day start. +func baseloadNightQuarter(q int, dayStart, nightRest float64) bool { + m := float64(q) * baseQuarterMin + return m < dayStart || m >= nightRest +} + +// baseLoadDrift looks for a sustained rise of the nights above their +// expectation and names the device behind it. The expectation is the median +// of the same weeks of the earlier years when the season store has them, else +// the reference of the window. The spread is the MAD of the nights. +func baseLoadDrift(in *Input, ns []baseloadNight) []Candidate { + exp := baseloadExpect(in, ns) + loads := make([]float64, len(ns)) + for i, n := range ns { + loads[i] = n.night + } + sigma := math.Max(MADScale(loads), baseloadMinSigmaW) + z := make([]float64, len(ns)) + for i, n := range ns { + z[i] = (n.night - exp[i]) / sigma + } + at, ok := baseLoadCUSUM(z) + if !ok || at < 1 { + return nil + } + var before, after []float64 + for i, n := range ns { + if i < at { + before = append(before, n.night) + } else { + after = append(after, n.night) + } + } + shift := Median(after) - Median(before) + if shift <= 0 { + return nil + } + device := baseloadDevice(in, ns, at, shift) + date := ns[at].date + w := baseloadRound(shift, baseloadRoundW) + benefit := Benefit{Unit: "kwh_week", Value: shift * baseloadWeekH / 1000} + candidate := "" + if device != "" { + candidate = deviceName(in.Devices[device], device) + } + after0, before0 := Median(after), Median(before) + finding := Finding{ + ID: FindingID("baseload", date), + Kind: "baseload", + Group: "energy", + Severity: "info", + Confidence: "high", + Summary: Text{Code: "baseload.drift", Params: map[string]any{ + "w": w, "kwh_month": round1(shift * baseloadMonthH / 1000), "candidate": candidate, + }}, + Evidence: Evidence{Shape: "scale", Unit: "W", IstValue: &after0, SollValue: &before0}, + Device: device, + Benefit: &benefit, + } + if device != "" && in.Devices[device].Switchable { + finding.Apply = []Fix{{Code: "night_off", Template: "night_off", + Prefill: map[string]any{"device": device}}} + } + return []Candidate{{ + Finding: finding, + Detector: "baseload", + NEff: float64(len(after)), + MinNEff: baseloadLearnMin, + Lower: 1, + Limit: 1, + HalvesAgree: true, + Benefit: benefit, + }} +} + +// baseloadExpect returns the expected night load of each night. With the same +// weeks of baseloadMinYears earlier years in the season store that is their +// median, else the reference of the window. +func baseloadExpect(in *Input, ns []baseloadNight) []float64 { + loads := make([]float64, 0, baseloadRefNights) + for i := 0; i < len(ns) && i < baseloadRefNights; i++ { + loads = append(loads, ns[i].night) + } + ref := Median(loads) + exp := make([]float64, len(ns)) + for i, n := range ns { + exp[i] = ref + if in.Season == nil { + continue + } + var vals []float64 + for _, w := range in.Season.Same(n.week, baseloadMinYears) { + if w.BaseW > 0 { + vals = append(vals, w.BaseW) + } + } + if len(vals) >= baseloadMinYears { + exp[i] = Median(vals) + } + } + return exp +} + +// baseloadDevice returns the device whose average night power rose by at least +// half of the shift from the nights before at to the nights from at on, the one +// with the largest rise. The empty string when no device qualifies. +func baseloadDevice(in *Input, ns []baseloadNight, at int, shift float64) string { + best, bestRise := "", 0.0 + for _, id := range sortedDeviceIDs(in.Devices) { + var pre, post []float64 + for i, n := range ns { + v, ok := n.dev[id] + if !ok { + continue + } + if i < at { + pre = append(pre, v) + } else { + post = append(post, v) + } + } + if len(post) == 0 { + continue + } + if len(pre) == 0 { + pre = []float64{0} + } + rise := Median(post) - Median(pre) + if rise >= shift/2 && rise > bestRise { + best, bestRise = id, rise + } + } + return best +} + +// baseLoadCUSUM looks for an upward shift in the residuals z, with the slack +// and the threshold of CUSUM and a baseline of 0. It returns the index where +// the shift starts. A run that goes over the threshold counts only when the +// residuals from its start on stay above the slack, so a single night does +// not count as a drift. +func baseLoadCUSUM(z []float64) (int, bool) { + s, start := 0.0, 0 + for t, x := range z { + prev := s + s = math.Max(0, s+x-cusumK) + if prev == 0 && s > 0 { + start = t + } + if s > cusumH { + tail := z[start:] + if len(tail) >= 3 && Median(tail) > cusumK { + return start, true + } + s = 0 + } + } + return 0, false +} + +// baseloadRound rounds v to a multiple of step. +func baseloadRound(v, step float64) float64 { + return math.Round(v/step) * step +} diff --git a/dashboard/internal/autolearn/detect_baseload_test.go b/dashboard/internal/autolearn/detect_baseload_test.go new file mode 100644 index 00000000..c202f254 --- /dev/null +++ b/dashboard/internal/autolearn/detect_baseload_test.go @@ -0,0 +1,212 @@ +package autolearn + +import ( + "context" + "testing" + "time" +) + +// blStart is the first day of the base load fixtures. +var blStart = time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC) + +// blNight reports whether quarter q lies in the night of the fixtures: before +// 06:00 or from 23:00 on, the bounds blDayStart and blNightRest. +func blNight(q int) bool { + m := float64(q) * baseQuarterMin + return m < blDayStart || m >= blNightRest +} + +const ( + blDayStart = 360.0 + blNightRest = 1380.0 +) + +// blInput builds days day files. night(i) is the night load of day i in W, +// heater(i) the average power of plug.heater in its night quarters, false for +// no record of the device on that day. Everything else is 1000 W by day. +func blInput(days int, night func(i int) float64, heater func(i int) (float64, bool)) *Input { + var list []DayFile + types := map[string]int{} + for i := 0; i < days; i++ { + day := blStart.AddDate(0, 0, i) + f := DayFile{V: 1, Day: day.Format(dayLayout), Devices: map[string]*DeviceDay{}} + n := night(i) + for q := 0; q < dayQuarters; q++ { + f.Site.Seen[q] = 1 + f.Site.LoadTotal[q] = 1000 + if blNight(q) { + f.Site.LoadTotal[q] = float32(n) + } + } + if heater != nil { + if w, ok := heater(i); ok { + dd := &DeviceDay{} + for q := 0; q < dayQuarters; q++ { + dd.Seen[q] = 1 + if blNight(q) { + dd.AvgW[q] = float32(w) + } + } + f.Devices["plug.heater"] = dd + } + } + types[f.Day] = 0 + list = append(list, f) + } + return &Input{ + Now: blStart.AddDate(0, 0, days).Add(12 * time.Hour), + Loc: time.UTC, + Days: list, + Base: Base{ + DayType: types, + Groups: [][]time.Weekday{{0, 1, 2, 3, 4, 5, 6}}, + DayStart: map[int]float64{0: blDayStart}, + NightRest: map[int]float64{0: blNightRest}, + }, + Devices: map[string]DeviceInfo{"plug.heater": {ID: "plug.heater", Name: "Heizlüfter", Switchable: true, + Entities: []string{"switch.plug.heater"}}}, + } +} + +// blSplit returns the drift findings and the learned values of the detector run. +func blSplit(in *Input) ([]Finding, map[string]Value) { + var findings []Finding + values := map[string]Value{} + for _, c := range baseLoadRun(context.Background(), in, "") { + if c.Finding.ID != "" { + findings = append(findings, c.Finding) + } + if c.Value != nil { + values[c.Value.Key] = *c.Value + } + } + return findings, values +} + +func TestBaseLoadDriftWithMeasuredDeviceNamesIt(t *testing.T) { + in := blInput(60, func(i int) float64 { + if i < 20 { + return 180 + } + return 260 + }, func(i int) (float64, bool) { + if i < 20 { + return 0, true + } + return 80, true + }) + findings, values := blSplit(in) + if len(findings) != 1 { + t.Fatalf("want one drift finding, got %d", len(findings)) + } + f := findings[0] + if want := "baseload:" + blStart.AddDate(0, 0, 20).Format(dayLayout); f.ID != want { + t.Errorf("ID = %q, want %q", f.ID, want) + } + if f.Summary.Code != "baseload.drift" || f.Group != "energy" { + t.Errorf("summary %q in group %q, want baseload.drift in energy", f.Summary.Code, f.Group) + } + if f.Device != "plug.heater" { + t.Errorf("Device = %q, want plug.heater", f.Device) + } + if w := f.Summary.Params["w"]; w != 80.0 { + t.Errorf("w = %v, want 80", w) + } + if len(f.Apply) != 1 || f.Apply[0].Template != "night_off" || f.Apply[0].Prefill["device"] != "plug.heater" { + t.Errorf("Apply = %+v, want night_off prefilled with plug.heater", f.Apply) + } + if f.Benefit == nil || f.Benefit.Unit != "kwh_week" || f.Benefit.Value < 13.4 || f.Benefit.Value > 13.5 { + t.Errorf("Benefit = %+v, want about 13.44 kwh_week", f.Benefit) + } + if v, ok := values["site/base_w"]; !ok || v.Num != 260 || v.Unit != "W" { + t.Errorf("site/base_w = %+v, want 260 W from the last 14 nights", v) + } +} + +func TestBaseLoadDriftWithoutMeasuredDeviceHasNoCandidate(t *testing.T) { + in := blInput(60, func(i int) float64 { + if i < 20 { + return 180 + } + return 260 + }, nil) + in.Devices = map[string]DeviceInfo{} + findings, _ := blSplit(in) + if len(findings) != 1 { + t.Fatalf("want one drift finding, got %d", len(findings)) + } + if f := findings[0]; f.Device != "" || len(f.Apply) != 0 { + t.Errorf("Device %q, Apply %+v: want no candidate and no fix", f.Device, f.Apply) + } +} + +func TestBaseLoadSingleNightIsNoFinding(t *testing.T) { + in := blInput(60, func(i int) float64 { + if i == 45 { + return 400 + } + return 180 + }, nil) + findings, _ := blSplit(in) + if len(findings) != 0 { + t.Fatalf("one night of 400 W gave %d findings, want none", len(findings)) + } +} + +// TestBaseLoadFridgeSwapIsNoFindingOnlyBaseFollows is review focus 4: the base +// load falls after a fridge is swapped. A fall is no finding, the learned +// site/base_w follows the new level. +func TestBaseLoadFridgeSwapIsNoFindingOnlyBaseFollows(t *testing.T) { + in := blInput(60, func(i int) float64 { + if i < 40 { + return 260 + } + return 180 + }, nil) + findings, values := blSplit(in) + if len(findings) != 0 { + t.Fatalf("a falling base load gave %d findings, want none", len(findings)) + } + if v, ok := values["site/base_w"]; !ok || v.Num != 180 { + t.Errorf("site/base_w = %+v, want 180 after the swap", v) + } +} + +func TestBaseLoadNeedsEnoughNights(t *testing.T) { + in := blInput(20, func(i int) float64 { + if i < 10 { + return 180 + } + return 260 + }, nil) + findings, values := blSplit(in) + if len(findings) != 0 { + t.Errorf("20 nights gave %d findings, want none", len(findings)) + } + if _, ok := values["site/base_w"]; !ok { + t.Errorf("20 nights should still learn site/base_w") + } +} + +func TestBaseLoadDetectorIsEnergyDaily(t *testing.T) { + if BaseLoadDetector.Group != "energy" || BaseLoadDetector.Light || BaseLoadDetector.PerDevice { + t.Errorf("detector = %+v, want energy, daily, not per device", BaseLoadDetector) + } +} + +func TestBaseLoadCUSUMFindsSustainedRiseOnly(t *testing.T) { + up := make([]float64, 40) + down := make([]float64, 40) + for i := range up { + if i >= 20 { + up[i] = 1.4 + down[i] = -1.4 + } + } + if at, ok := baseLoadCUSUM(up); !ok || at != 20 { + t.Errorf("rise: got (%d, %v), want (20, true)", at, ok) + } + if _, ok := baseLoadCUSUM(down); ok { + t.Errorf("fall gave a drift") + } +} diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index ff398469..0f047e56 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -471,6 +471,10 @@ "automations.learn.band.less": "Weniger", "automations.learn.band.more": "+{count}", "automations.learn.band.title": "Vorschläge aus dem Verhalten deiner Geräte", + "automations.learn.baseload.candidate.none": "ein nicht gemessener Verbraucher", + "automations.learn.baseload.drift.line": "Nachts {w} W mehr, rund {kwh_month} kWh im Monat", + "automations.learn.baseload.drift.text": "Nachts braucht das Haus seit einigen Wochen {w} W mehr, rund {kwh_month} kWh im Monat. Verursacher ist {candidate}.", + "automations.learn.baseload.drift.title": "Grundlast steigt", "automations.learn.button.later": "Später", "automations.learn.button.never": "Nicht mehr vorschlagen", "automations.learn.button.open_assistant": "Im Assistenten öffnen", @@ -609,6 +613,7 @@ "automations.learned.estimate": "Schätzung", "automations.learned.fallback": "Ohne Lernwert", "automations.learned.fallback.help": "Gilt, wenn noch nichts gelernt ist oder der Wert älter als 7 Tage ist.", + "automations.learned.key.base_w": "Grundlast", "automations.learned.key.cycle_wh": "Typische Zyklusenergie von {device}", "automations.learned.key.day_start": "Tagesbeginn", "automations.learned.key.house_state": "Hauszustand", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 5f634889..cbb3704d 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -471,6 +471,10 @@ "automations.learn.band.less": "Less", "automations.learn.band.more": "+{count}", "automations.learn.band.title": "Suggestions from how your devices are used", + "automations.learn.baseload.candidate.none": "an unmeasured consumer", + "automations.learn.baseload.drift.line": "{w} W more at night, about {kwh_month} kWh a month", + "automations.learn.baseload.drift.text": "For several weeks the house has needed {w} W more at night, about {kwh_month} kWh a month. The cause is {candidate}.", + "automations.learn.baseload.drift.title": "Base load is rising", "automations.learn.button.later": "Later", "automations.learn.button.never": "Do not suggest again", "automations.learn.button.open_assistant": "Open in assistant", @@ -609,6 +613,7 @@ "automations.learned.estimate": "Estimate", "automations.learned.fallback": "Without a learned value", "automations.learned.fallback.help": "Applies when nothing has been learned yet or the value is older than 7 days.", + "automations.learned.key.base_w": "Base load", "automations.learned.key.cycle_wh": "Typical cycle energy of {device}", "automations.learned.key.day_start": "Start of the day", "automations.learned.key.house_state": "House state", diff --git a/dashboard/internal/webui/static/js/automation-learned.js b/dashboard/internal/webui/static/js/automation-learned.js index e44aa35e..5a0528e8 100644 --- a/dashboard/internal/webui/static/js/automation-learned.js +++ b/dashboard/internal/webui/static/js/automation-learned.js @@ -11,6 +11,7 @@ usual_off: 'automations.learned.key.usual_off', usual_runtime_s: 'automations.learned.key.usual_runtime_s', day_start: 'automations.learned.key.day_start', + base_w: 'automations.learned.key.base_w', night_rest: 'automations.learned.key.night_rest', house_state: 'automations.learned.key.house_state', op_power_w: 'automations.learned.key.op_power_w', diff --git a/dashboard/internal/webui/static/js/automation-suggestions.js b/dashboard/internal/webui/static/js/automation-suggestions.js index 148f2408..b707ee05 100644 --- a/dashboard/internal/webui/static/js/automation-suggestions.js +++ b/dashboard/internal/webui/static/js/automation-suggestions.js @@ -31,6 +31,8 @@ let code = (summary && summary.code) || ''; const params = Object.assign({}, (summary && summary.params) || {}); if (typeof params.share === 'number') params.share = Math.round(params.share * 100); + // 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 (/^switch_time\.sun_(on|off)$/.test(code)) { const offset = Number(params.offset_min) || 0; params.minutes = Math.abs(offset); diff --git a/dashboard/test/automation-suggestions.test.mjs b/dashboard/test/automation-suggestions.test.mjs index 1678a883..1b6c3403 100644 --- a/dashboard/test/automation-suggestions.test.mjs +++ b/dashboard/test/automation-suggestions.test.mjs @@ -549,6 +549,16 @@ test('the temperature limit title and line show the rule, device, knee and weekl assert.equal(api.legend(s, t), catalogs.de['automations.learn.legend.scale']); }); +test('the baseload drift line names the cause, or an unmeasured consumer without a device', () => { + const { api } = load(germanI18n); + const t = catalogT('de'); + const measured = suggestion('baseload.drift', { w: 80, kwh_month: 57.6, candidate: 'Heizlüfter' }, 'scale'); + assert.equal(api.line(measured, t), 'Nachts 80 W mehr, rund 57,6 kWh im Monat'); + assert.ok(api.text(measured, t).endsWith('Verursacher ist Heizlüfter.')); + const unmeasured = suggestion('baseload.drift', { w: 80, kwh_month: 57.6, candidate: '' }, 'scale'); + assert.ok(api.text(unmeasured, t).endsWith('Verursacher ist ein nicht gemessener Verbraucher.')); +}); + test('a scale evidence with the weekly unit shows the catalog unit on the axis', () => { const { evidence } = load(); const t = catalogT('de'); From 20a221ab24c4504bcead7aafeaf350f22593e202 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:07:25 +0100 Subject: [PATCH 07/37] feat(autolearn): add the night off template with learned night bounds The night_off template switches a switch off from the learned night rest to the learned day start, each bound with an hour of slack. Without both learned values it uses the fixed window from 23:00 to 06:00. A baseload finding opens it with its device. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 8 +++ dashboard/internal/webui/catalogs/en.json | 8 +++ .../webui/static/js/automation-templates.js | 58 ++++++++++++++++++- .../webui/static/js/automations.page.js | 8 +++ dashboard/test/automation-templates.test.mjs | 42 ++++++++++++++ dashboard/test/automations.page.test.mjs | 7 +++ 6 files changed, 130 insertions(+), 1 deletion(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 0f047e56..0e2c72e8 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -187,6 +187,8 @@ "automations.assistant.summary.measure.balance": "Die Netzbilanz des Hauses", "automations.assistant.summary.measure.last": "Der zuletzt gesendete Sollwert", "automations.assistant.summary.measure.own": "Der eigene Messwert des Wechselrichters", + "automations.assistant.summary.night.fixed": "Nachts, von {start} bis {end} Uhr", + "automations.assistant.summary.night.learned": "Nachts, von der gelernten Nachtruhe bis zum Tagesbeginn", "automations.assistant.summary.notify": "Eine Mitteilung meldet den Start", "automations.assistant.summary.phase.end": "Beim Ende", "automations.assistant.summary.phase.run": "Läuft", @@ -1192,6 +1194,12 @@ "automations.templates.inverter_silent.steps.switch.short": "Schalter", "automations.templates.inverter_silent.steps.switch.title": "Welcher Schalter?", "automations.templates.inverter_silent.title": "Wechselrichter meldet sich nicht", + "automations.templates.night_off.blurb": "Schaltet ein Gerät nachts aus, von der Nachtruhe bis zum Tagesbeginn. Die Zeiten folgen dem Gelernten.", + "automations.templates.night_off.keywords": "nachts aus nacht grundlast standby schalter ausschalten haus", + "automations.templates.night_off.steps.device.help": "Das Gerät, das nachts ausgeschaltet wird. Zur Wahl stehen nur Schalter.", + "automations.templates.night_off.steps.device.short": "Schalter", + "automations.templates.night_off.steps.device.title": "Schalter", + "automations.templates.night_off.title": "Nachts aus", "automations.templates.pv_missing.blurb": "Tagsüber liefert ein Wechselrichter 30 Minuten lang unter 20 W. Mitteilung, weil er vermutlich hängt.", "automations.templates.pv_missing.keywords": "pv ertrag sonne wechselrichter fehlt hängt warnung leistung", "automations.templates.pv_missing.notice.message": "Der Wechselrichter liefert seit {minutes} Minuten weniger als {value} W, er hängt vermutlich.", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index cbb3704d..fc34ef56 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -187,6 +187,8 @@ "automations.assistant.summary.measure.balance": "The house grid balance", "automations.assistant.summary.measure.last": "The last setpoint sent", "automations.assistant.summary.measure.own": "The inverter's own reading", + "automations.assistant.summary.night.fixed": "At night, from {start} to {end}", + "automations.assistant.summary.night.learned": "At night, from the learned night rest to the day start", "automations.assistant.summary.notify": "A notification reports the start", "automations.assistant.summary.phase.end": "On end", "automations.assistant.summary.phase.run": "Running", @@ -1192,6 +1194,12 @@ "automations.templates.inverter_silent.steps.switch.short": "Switch", "automations.templates.inverter_silent.steps.switch.title": "Which switch?", "automations.templates.inverter_silent.title": "Inverter stops reporting", + "automations.templates.night_off.blurb": "Switches a device off at night, from the night rest to the day start. The times follow what was learned.", + "automations.templates.night_off.keywords": "night off base load standby switch house", + "automations.templates.night_off.steps.device.help": "The device that is switched off at night. Only switches are offered.", + "automations.templates.night_off.steps.device.short": "Switch", + "automations.templates.night_off.steps.device.title": "Switch", + "automations.templates.night_off.title": "Off at night", "automations.templates.pv_missing.blurb": "During the day an inverter yields less than 20 W for 30 minutes. A notification, because it is probably stuck.", "automations.templates.pv_missing.keywords": "pv yield sun inverter missing stuck warning power", "automations.templates.pv_missing.notice.message": "The inverter has yielded less than {value} W for {minutes} minutes, it is probably stuck.", diff --git a/dashboard/internal/webui/static/js/automation-templates.js b/dashboard/internal/webui/static/js/automation-templates.js index fb31219e..ee67d724 100644 --- a/dashboard/internal/webui/static/js/automation-templates.js +++ b/dashboard/internal/webui/static/js/automation-templates.js @@ -2019,8 +2019,64 @@ }, }; + // ---------------------------------------------------------------- Nachts aus + + // Feste Nacht ohne Lernwerte und Abstand der gelernten Grenzen dazu, in Minuten. + const NIGHT_FIXED = { start: '23:00', end: '06:00' }; + const NIGHT_LEARNED_MIN = 60; + const CLOCK_TEXT = /^([01]\d|2[0-3]):[0-5]\d$/; + + // Die Nacht folgt den Lernwerten nur, wenn Nachtruhe und Tagesbeginn beide gelernt sind. + const nightLearned = (ctx) => { + const learned = ctx.learned; + if (!learned || typeof learned.get !== 'function') return false; + return ['site/night_rest', 'site/day_start'].every((key) => CLOCK_TEXT.test(learned.get(key) || '')); + }; + // Gelernte Grenze mit Spielraum von einer Stunde nach beiden Seiten um die feste Uhrzeit. + const nightRef = (key, fixed) => ({ + learned: key, min: clockAfter(fixed, -NIGHT_LEARNED_MIN), max: clockAfter(fixed, NIGHT_LEARNED_MIN), fallback: fixed, + }); + + const nightOff = { + id: 'night_off', + category: 'time', + icon: 'ico-clock', + requires: { devices: 'switch' }, + steps: [ + { id: 'device', type: 'device', filter: 'switch' }, + ], + build(answers, ctx) { + const entry = requireEntry(ctx.switches, answers.device); + const entity = requireEntity(entry); + const bounds = nightLearned(ctx) + ? { start: nightRef('site/night_rest', NIGHT_FIXED.start), end: nightRef('site/day_start', NIGHT_FIXED.end) } + : NIGHT_FIXED; + const rule = { + id: uniqueId('night_off', ctx.usedIds), + name: t('automations.templates.night_off.title'), + enabled: true, + cooldown_seconds: Math.max(600, ctx.publishMinInterval), + conditions: [{ type: 'time_window', start: bounds.start, end: bounds.end, weekdays: [] }], + actions: [Sw(entity, false)], + }; + return { kind: 'rule', entry: rule }; + }, + summary(answers, ctx) { + return [ + { + label: phase('when'), + text: nightLearned(ctx) + ? t('automations.assistant.summary.night.learned') + : t('automations.assistant.summary.night.fixed', { start: NIGHT_FIXED.start, end: NIGHT_FIXED.end }), + step: 'device', + }, + { label: phase('then'), text: t('automations.assistant.summary.switch.end_off'), step: 'device' }, + ]; + }, + }; + window.__automationTemplates = { - TEMPLATES: [zeroFeed, surplusWallbox, surplusSwitch, batteryWarn, timeSwitch, heatPump, tariff, batteryFullMonthly, inverterSilent, wallboxLowTariff, gridCap, gridSignal, pvMissing, heatingRod, chainWatchdog, chainStandby, timePoint, runtimeOff, quietOff, followSwitch], + TEMPLATES: [zeroFeed, surplusWallbox, surplusSwitch, batteryWarn, timeSwitch, heatPump, tariff, batteryFullMonthly, inverterSilent, wallboxLowTariff, gridCap, gridSignal, pvMissing, heatingRod, chainWatchdog, chainStandby, timePoint, runtimeOff, quietOff, followSwitch, nightOff], chargeFit, }; })(); diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index 4487a87b..bc461d91 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -251,6 +251,14 @@ } return out; }, + night_off(prefill) { + const out = {}; + if (prefill.device !== undefined) { + if (!isPrefillText(prefill.device)) return null; + out.device = prefill.device; + } + return out; + }, follow_switch(prefill) { const out = {}; for (const key of ['source', 'target']) { diff --git a/dashboard/test/automation-templates.test.mjs b/dashboard/test/automation-templates.test.mjs index 158933db..7ad2793c 100644 --- a/dashboard/test/automation-templates.test.mjs +++ b/dashboard/test/automation-templates.test.mjs @@ -1948,3 +1948,45 @@ test('surplus_wallbox prefills the start threshold from the learned operating po assert.equal(wizard.defaultAnswers(template, ctx).start, 2000); assert.equal(wizard.defaultAnswers(template, base).start, 1400); }); + +// Nachts aus: mit gelernter Nachtruhe und gelerntem Tagesbeginn ein Fenster um die Lernwerte, +// ohne sie fest von 23:00 bis 06:00. Das Gerät geht zu Beginn des Fensters aus. +test('night_off with learned night rest and day start builds a window around the learned bounds', () => { + const { wizard, templates } = load(); + const template = templateById(templates, 'night_off'); + const base = plain(contextFor(wizard)); + const ctx = withLearned(base, [['site/night_rest', '22:40'], ['site/day_start', '06:10']]); + const entry = plain(template.build(answersFor(wizard, template, ctx, { device: 'lamp_switch' }), ctx).entry); + assert.equal(entry.enabled, true); + assert.deepEqual(entry.conditions, [{ + type: 'time_window', + start: { learned: 'site/night_rest', min: '22:00', max: '00:00', fallback: '23:00' }, + end: { learned: 'site/day_start', min: '05:00', max: '07:00', fallback: '06:00' }, + weekdays: [], + }]); + assert.deepEqual(entry.actions, [{ + type: 'publish', topic: 'werkstatt/lamp/switch', retain: false, payload_source: 'constant', + payload: 'OFF', entity_id: 'lamp_switch', + }]); +}); + +test('night_off without learned values uses the fixed window from 23:00 to 06:00', () => { + const { wizard, templates } = load(); + const template = templateById(templates, 'night_off'); + const ctx = plain(contextFor(wizard)); + const entry = plain(template.build(answersFor(wizard, template, ctx, { device: 'lamp_switch' }), ctx).entry); + assert.deepEqual(entry.conditions, [{ type: 'time_window', start: '23:00', end: '06:00', weekdays: [] }]); + const partial = withLearned(ctx, [['site/night_rest', '22:40']]); + const onlyOne = plain(template.build(answersFor(wizard, template, partial, { device: 'lamp_switch' }), partial).entry); + assert.deepEqual(onlyOne.conditions, [{ type: 'time_window', start: '23:00', end: '06:00', weekdays: [] }]); +}); + +test('night_off offers only switches and shows the night window in its summary', () => { + const { wizard, templates } = load(); + const template = templateById(templates, 'night_off'); + const ctx = withLearned(plain(contextFor(wizard)), [['site/night_rest', '22:40'], ['site/day_start', '06:10']]); + const steps = plain(wizard.visibleSteps(template, answersFor(wizard, template, ctx, { device: 'lamp_switch' }), ctx)); + assert.deepEqual(steps.map((step) => step.id), ['device', 'summary']); + const rows = plain(template.summary(answersFor(wizard, template, ctx, { device: 'lamp_switch' }), ctx)); + assert.ok(rows.some((row) => row.text === catalog('de')['automations.assistant.summary.night.learned'])); +}); diff --git a/dashboard/test/automations.page.test.mjs b/dashboard/test/automations.page.test.mjs index 8cd9f08b..85020512 100644 --- a/dashboard/test/automations.page.test.mjs +++ b/dashboard/test/automations.page.test.mjs @@ -3822,6 +3822,13 @@ test('prefillToAnswers maps the device of a quiet switch-off', () => { assert.equal(prefillToAnswers('quiet_off', { device: 3 }), null); }); +test('prefillToAnswers opens a night off suggestion with its device and nothing else', () => { + const { window } = createAutomationsPanel(); + const { prefillToAnswers } = window.__automationsPrefill; + assert.deepEqual(JSON.parse(JSON.stringify(prefillToAnswers('night_off', { device: 'lamp_switch' }))), { device: 'lamp_switch' }); + assert.equal(prefillToAnswers('night_off', { device: 3 }), null); +}); + // --- Lernwerte im Editor ---------------------------------------------------- const LEARNED_VALUES = [ From aac68e408053fa89d0877f2bca5f7273bc67545c Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:12:27 +0100 Subject: [PATCH 08/37] feat(autolearn): report a battery that is full too early or empty before morning The battery detector reads the charge per quarter. A battery full before solar noon on most days is a finding, and so is one empty before sunrise when the same weeks of the year before were not empty on most days. The empty finding offers a night off for the devices that take over half of the missing night energy, switchable ones only. Without a record of the year before no empty finding is made. The learned values site/battery_full_at and site/night_wh come from the days of today's day type. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 1 + .../internal/autolearn/detect_battery.go | 530 ++++++++++++++++++ .../internal/autolearn/detect_battery_test.go | 217 +++++++ dashboard/internal/autolearn/input.go | 4 + dashboard/internal/webui/catalogs/de.json | 9 + dashboard/internal/webui/catalogs/en.json | 9 + .../webui/static/js/automation-learned.js | 2 + .../webui/static/js/automation-suggestions.js | 1 + .../test/automation-suggestions.test.mjs | 9 + 9 files changed, 782 insertions(+) create mode 100644 dashboard/internal/autolearn/detect_battery.go create mode 100644 dashboard/internal/autolearn/detect_battery_test.go diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index caea5904..03c04fe7 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -572,6 +572,7 @@ func main() { learnHub.AddSaver("forecast", forecastCheck) registerEnergyDetectors(automationEngine, pvReserve.Current, forecastCheck) automationEngine.Register(autolearn.BaseLoadDetector) + automationEngine.Register(autolearn.BatteryDetector) automationEngine.Register(autolearn.NewPVModelDetector(pvTracker.Snapshot, pvModelStore)) automationEngine.Register(autolearn.NewShadeDetector(pvTracker.Snapshot, pvModelStore.Model)) // Modell und Himmelsraster fuer den Rest-Ueberschuss. Der Raster-Schnappschuss diff --git a/dashboard/internal/autolearn/detect_battery.go b/dashboard/internal/autolearn/detect_battery.go new file mode 100644 index 00000000..cfcbb790 --- /dev/null +++ b/dashboard/internal/autolearn/detect_battery.go @@ -0,0 +1,530 @@ +package autolearn + +import ( + "context" + "math" + "sort" + "strings" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// BatteryDetector watches the charge of the battery. A battery that is full +// before solar noon on most days is a finding. A battery that is empty before +// sunrise on most days is a finding too, unless the same weeks of the year +// before were empty on as many days. The learned site/battery_full_at and +// site/night_wh follow the days of today's day type. It is daily and not per +// device. +var BatteryDetector = Detector{ + Name: "battery", + Group: "energy", + Light: false, + PerDevice: false, + Run: batteryRun, +} + +const ( + // batteryFullPct is the charge in percent from which a battery counts as full. + batteryFullPct = 97.0 + // batteryEmptyMargin is the margin in points above the lowest charge of the + // last batteryEmptyWindow days, a charge at or below counts as empty. + batteryEmptyMargin = 3.0 + batteryEmptyWindow = 14 + // batteryMinDays is the number of days a finding or a learned value needs. + // The spec gives no number, the value is an assumption. + batteryMinDays = 10 + // batteryShare is the lower Wilson bound of the share of days, and the + // share of last year, that decide a finding. + batteryShare = 0.5 + // batteryMaxApply is the number of devices that get a night off fix. + batteryMaxApply = 2 + // batteryWeekDays turns the nightly kWh into the weekly benefit. + batteryWeekDays = 7.0 + // batteryLearnRoundWh rounds the learned night energy. + batteryLearnRoundWh = 100.0 +) + +// batteryDay is one day file with a charge. The sun values are local minutes +// of the day and are only set when sunOK is true. fullQ and emptyQ are the +// first quarter at or above batteryFullPct and the first morning quarter at or +// below the empty threshold, -1 for none. +type batteryDay struct { + date string + week int + group int + f *DayFile + sunOK bool + rise float64 + set float64 + fullQ int + thr float64 + hasThr bool + morning bool + emptyQ int + nightWh float64 + nightOK bool +} + +// batteryRun returns the full and empty findings and the learned values. +func batteryRun(ctx context.Context, in *Input, _ string) []Candidate { + if ctx.Err() != nil { + return nil + } + days := batteryDays(in) + if len(days) == 0 { + return nil + } + var out []Candidate + out = append(out, batteryFull(days)...) + out = append(out, batteryEmpty(in, days)...) + out = append(out, batteryLearned(in, days)...) + return out +} + +// batteryDays reads the day files with a charge in date order, today left out. +// Each day gets its sun times, its first full quarter and its empty threshold +// from the lowest charge of the days before it. Then the morning and the night +// of each day are read. +func batteryDays(in *Input) []*batteryDay { + loc := in.Loc + if loc == nil { + loc = time.Local + } + today := in.Now.In(loc).Format(dayLayout) + files := make([]*DayFile, 0, len(in.Days)) + for i := range in.Days { + files = append(files, &in.Days[i]) + } + sort.SliceStable(files, func(a, b int) bool { return files[a].Day < files[b].Day }) + var out []*batteryDay + for _, f := range files { + if f.Day == today || !batteryHasSoC(f) { + continue + } + t, err := time.ParseInLocation(dayLayout, f.Day, loc) + if err != nil { + continue + } + _, week := t.ISOWeek() + d := &batteryDay{date: f.Day, week: week, f: f, fullQ: -1, emptyQ: -1} + if g, ok := in.Base.DayType[f.Day]; ok { + d.group = g + } else { + d.group = -1 + } + if in.Doc.Location != nil { + rise, set, ok := sun.Times(t, in.Doc.Location.Lat, in.Doc.Location.Lon) + if ok { + d.sunOK = true + d.rise = batteryMinute(rise, loc) + d.set = batteryMinute(set, loc) + } + } + for q := 0; q < dayQuarters; q++ { + if v := f.Site.SoC[q]; v != nil && float64(*v) >= batteryFullPct { + d.fullQ = q + break + } + } + out = append(out, d) + } + for i, d := range out { + lo := math.Inf(1) + for k := i - batteryEmptyWindow; k < i; k++ { + if k < 0 { + continue + } + lo = math.Min(lo, batteryMinSoC(out[k].f)) + } + if !math.IsInf(lo, 1) { + d.thr = lo + batteryEmptyMargin + d.hasThr = true + } + } + for _, d := range out { + if !d.sunOK || !d.hasThr { + continue + } + for q := 0; q < dayQuarters && float64(q)*baseQuarterMin < d.rise; q++ { + v := d.f.Site.SoC[q] + if v == nil { + continue + } + d.morning = true + if d.emptyQ < 0 && float64(*v) <= d.thr { + d.emptyQ = q + } + } + } + for i, d := range out { + if i+1 < len(out) && batteryNextDay(d.date, out[i+1].date) { + d.nightWh, d.nightOK = batteryNight(d, out[i+1]) + } + } + return out +} + +// batteryNextDay reports whether the date next is the day after date. +func batteryNextDay(date, next string) bool { + t, err := time.Parse(dayLayout, date) + if err != nil { + return false + } + return t.AddDate(0, 0, 1).Format(dayLayout) == next +} + +// batteryNight returns the house energy in Wh from the sunset of d to the +// sunrise of the next day, or to the quarter where the battery of the next day +// is empty before that. +func batteryNight(d, next *batteryDay) (float64, bool) { + if !d.sunOK || !next.sunOK { + return 0, false + } + var wh float64 + for q := 0; q < dayQuarters; q++ { + if float64(q)*baseQuarterMin < d.set { + continue + } + if d.f.Site.Seen[q] == 0 { + return 0, false + } + wh += float64(d.f.Site.LoadTotal[q]) * batteryQuarterWh + } + for q := 0; q < dayQuarters && float64(q)*baseQuarterMin < next.rise; q++ { + if next.emptyQ >= 0 && q >= next.emptyQ { + break + } + if next.f.Site.Seen[q] == 0 { + return 0, false + } + wh += float64(next.f.Site.LoadTotal[q]) * batteryQuarterWh + } + return wh, true +} + +// batteryQuarterWh turns the mean power of a quarter in W into Wh. +const batteryQuarterWh = 0.25 + +// batteryHasSoC reports whether the day file has a charge in any quarter. +func batteryHasSoC(f *DayFile) bool { + for q := 0; q < dayQuarters; q++ { + if f.Site.SoC[q] != nil { + return true + } + } + return false +} + +// batteryMinSoC returns the lowest charge of the day file. +func batteryMinSoC(f *DayFile) float64 { + lo := math.Inf(1) + for q := 0; q < dayQuarters; q++ { + if v := f.Site.SoC[q]; v != nil { + lo = math.Min(lo, float64(*v)) + } + } + return lo +} + +// batteryFull looks for a battery that is full before solar noon on most days. +// Days without sun are left out. The finding carries the median time of the +// first full quarter and the export after it. +func batteryFull(days []*batteryDay) []Candidate { + var flags []bool + var hits []*batteryDay + for _, d := range days { + if !d.sunOK { + continue + } + hit := d.fullQ >= 0 && float64(d.fullQ)*baseQuarterMin < (d.rise+d.set)/2 + flags = append(flags, hit) + if hit { + hits = append(hits, d) + } + } + n := len(flags) + if n < batteryMinDays { + return nil + } + lower := WilsonLower(len(hits), n) + if lower < batteryShare { + return nil + } + var at, kwh []float64 + for _, d := range hits { + at = append(at, float64(d.fullQ)*baseQuarterMin) + var wh float64 + for q := d.fullQ; q < dayQuarters; q++ { + wh += float64(d.f.Site.GridExport[q]) * batteryQuarterWh + } + kwh = append(kwh, wh/1000) + } + finding := Finding{ + ID: "battery:full", + Kind: "battery", + Group: "energy", + Severity: "info", + Confidence: "high", + Summary: Text{Code: "battery.full_early", Params: map[string]any{ + "time": batteryClock(Median(at)), + "kwh_after": round1(Median(kwh)), + }}, + Evidence: batteryEvidence(days), + } + return []Candidate{{ + Finding: finding, + Detector: "battery", + NEff: float64(n), + MinNEff: batteryMinDays, + Lower: lower, + Limit: batteryShare, + HalvesAgree: batteryHalves(flags), + }} +} + +// batteryEmpty looks for a battery that is empty before sunrise on most days, +// when the same weeks of the year before were empty on less than half of their +// days. Without a record of the year before no finding is made. The fix is a +// night off for the devices that take together over half of the missing night +// energy, switchable ones only, at most batteryMaxApply. +func batteryEmpty(in *Input, days []*batteryDay) []Candidate { + if in.PriorEmptyShare == nil { + return nil + } + var evaluated []*batteryDay + var flags []bool + var hits []*batteryDay + for _, d := range days { + if !d.sunOK || !d.hasThr || !d.morning { + continue + } + evaluated = append(evaluated, d) + hit := d.emptyQ >= 0 + flags = append(flags, hit) + if hit { + hits = append(hits, d) + } + } + n := len(evaluated) + if n < batteryMinDays { + return nil + } + lower := WilsonLower(len(hits), n) + if lower < batteryShare || !batteryHalves(flags) { + return nil + } + var prior float64 + for _, d := range evaluated { + share, ok := in.PriorEmptyShare(d.week) + if !ok { + return nil + } + prior += share + } + if prior/float64(n) >= batteryShare { + return nil + } + var at, missing []float64 + devSum := map[string]float64{} + devDays := map[string]int{} + var loadSum float64 + for _, d := range hits { + at = append(at, float64(d.emptyQ)*baseQuarterMin) + wh, load, dev := batteryMorningLoad(d) + missing = append(missing, wh/1000) + loadSum += load + for id, w := range dev { + devSum[id] += w + devDays[id]++ + } + } + meanLoad := loadSum / float64(len(hits)) + candidates, apply := batteryCandidates(in, devSum, devDays, meanLoad) + kwh := Median(missing) + names := make([]string, 0, len(candidates)) + for _, id := range candidates { + names = append(names, deviceName(in.Devices[id], id)) + } + finding := Finding{ + ID: "battery:empty", + Kind: "battery", + Group: "energy", + Severity: "info", + Confidence: "high", + Summary: Text{Code: "battery.empty_early", Params: map[string]any{ + "time": batteryClock(Median(at)), + "kwh_missing": round1(kwh), + "candidates": strings.Join(names, ", "), + }}, + Evidence: batteryEvidence(days), + Apply: apply, + Benefit: &Benefit{Unit: "kwh_week", Value: kwh * batteryWeekDays}, + } + return []Candidate{{ + Finding: finding, + Detector: "battery", + NEff: float64(n), + MinNEff: batteryMinDays, + Lower: lower, + Limit: batteryShare, + HalvesAgree: true, + Benefit: *finding.Benefit, + }} +} + +// batteryMorningLoad returns the house energy in Wh and the mean house power in +// W of the morning quarters from the empty quarter to sunrise, and the mean +// power of each device with a record in them. +func batteryMorningLoad(d *batteryDay) (float64, float64, map[string]float64) { + var wh, sum float64 + n := 0 + devSum := map[string]float64{} + devN := map[string]int{} + for q := d.emptyQ; q < dayQuarters && float64(q)*baseQuarterMin < d.rise; q++ { + if d.f.Site.Seen[q] == 0 { + continue + } + wh += float64(d.f.Site.LoadTotal[q]) * batteryQuarterWh + sum += float64(d.f.Site.LoadTotal[q]) + n++ + for id, dd := range d.f.Devices { + if dd == nil || dd.Seen[q] == 0 { + continue + } + devSum[id] += float64(dd.AvgW[q]) + devN[id]++ + } + } + dev := map[string]float64{} + for id, s := range devSum { + dev[id] = s / float64(devN[id]) + } + if n == 0 { + return 0, 0, dev + } + return wh, sum / float64(n), dev +} + +// batteryCandidates takes the devices with the largest mean power in the empty +// nights, until together they reach over half of the mean house power. It +// returns the candidates and the night off fixes of the switchable ones. +func batteryCandidates(in *Input, devSum map[string]float64, devDays map[string]int, meanLoad float64) ([]string, []Fix) { + type ranked struct { + id string + w float64 + } + var list []ranked + for id, s := range devSum { + if devDays[id] == 0 { + continue + } + list = append(list, ranked{id: id, w: s / float64(devDays[id])}) + } + sort.SliceStable(list, func(a, b int) bool { + if list[a].w != list[b].w { + return list[a].w > list[b].w + } + return list[a].id < list[b].id + }) + var ids []string + var apply []Fix + acc := 0.0 + for _, r := range list { + if acc > meanLoad/2 || r.w <= 0 { + break + } + acc += r.w + ids = append(ids, r.id) + if info, ok := in.Devices[r.id]; ok && info.Switchable && len(apply) < batteryMaxApply { + apply = append(apply, Fix{Code: "night_off", Template: "night_off", + Prefill: map[string]any{"device": r.id}}) + } + } + return ids, apply +} + +// batteryLearned returns site/battery_full_at and site/night_wh over the days +// of today's day type, when ten days of it have the value. +func batteryLearned(in *Input, days []*batteryDay) []Candidate { + g, ok := learnTodayGroup(in) + if !ok { + return nil + } + var at, nights []float64 + for _, d := range days { + if d.group != g { + continue + } + if d.fullQ >= 0 { + at = append(at, float64(d.fullQ)*baseQuarterMin) + } + if d.nightOK { + nights = append(nights, d.nightWh) + } + } + var out []Candidate + if len(at) >= batteryMinDays { + out = append(out, Candidate{ + Detector: "battery", + NEff: float64(len(at)), + MinNEff: batteryMinDays, + Value: &Value{Key: "site/battery_full_at", Kind: ValueTime, Group: "energy", + Text: batteryClock(Median(at)), N: len(at)}, + }) + } + if len(nights) >= batteryMinDays { + out = append(out, Candidate{ + Detector: "battery", + NEff: float64(len(nights)), + MinNEff: batteryMinDays, + Value: &Value{Key: "site/night_wh", Kind: ValueNumber, Unit: "Wh", Group: "energy", + Num: math.Round(Median(nights)/batteryLearnRoundWh) * batteryLearnRoundWh, N: len(nights)}, + }) + } + return out +} + +// batteryEvidence shows the charge of the last day as the curve, in percent. +func batteryEvidence(days []*batteryDay) Evidence { + last := days[len(days)-1].f + curve := make([]float32, dayQuarters) + for q := 0; q < dayQuarters; q++ { + if v := last.Site.SoC[q]; v != nil { + curve[q] = *v + } + } + return Evidence{Shape: "curve", Quarters: curve, Unit: "%"} +} + +// batteryHalves reports whether the first and the second half of the days both +// reach the share of batteryShare. +func batteryHalves(flags []bool) bool { + h := len(flags) / 2 + return batteryShareOf(flags[:h]) >= batteryShare && batteryShareOf(flags[h:]) >= batteryShare +} + +// batteryShareOf returns the share of true values, 0 for no values. +func batteryShareOf(flags []bool) float64 { + if len(flags) == 0 { + return 0 + } + hits := 0 + for _, f := range flags { + if f { + hits++ + } + } + return float64(hits) / float64(len(flags)) +} + +// batteryClock returns the clock time of minutes of the day, rounded to 5 minutes. +func batteryClock(m float64) string { + return switchTimeClock(learnRoundClock(m)) +} + +// batteryMinute returns the local minute of the day of t. +func batteryMinute(t time.Time, loc *time.Location) float64 { + lt := t.In(loc) + return float64(lt.Hour()*60+lt.Minute()) + float64(lt.Second())/60 +} diff --git a/dashboard/internal/autolearn/detect_battery_test.go b/dashboard/internal/autolearn/detect_battery_test.go new file mode 100644 index 00000000..b871f53d --- /dev/null +++ b/dashboard/internal/autolearn/detect_battery_test.go @@ -0,0 +1,217 @@ +package autolearn + +import ( + "context" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" +) + +// btNovStart is the first day of the November fixtures, btDecStart of the December ones. +var ( + btNovStart = time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + btDecStart = time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC) +) + +// btSoC returns the charge in percent of quarter q of day i, false for no value. +type btSoC func(i, q int) (float32, bool) + +// btInput builds days day files from start. The house draws loadW in every +// quarter, a heater 1500 W and a lamp 40 W, both on every quarter. The heater is +// switchable, the lamp not. The location is 52 N, 0 E on UTC, so the sun rises +// at about 07:00 and sets at about 16:00 and noon is near 12:00. prior is the +// share of empty days of the year before, nil without a record. +func btInput(days int, start time.Time, soc btSoC, loadW float32, prior func(week int) (float64, bool)) *Input { + var list []DayFile + types := map[string]int{} + for i := 0; i < days; i++ { + day := start.AddDate(0, 0, i) + f := DayFile{V: 1, Day: day.Format(dayLayout), Devices: map[string]*DeviceDay{}} + heater := &DeviceDay{} + lamp := &DeviceDay{} + for q := 0; q < dayQuarters; q++ { + f.Site.Seen[q] = 1 + f.Site.LoadTotal[q] = loadW + heater.Seen[q] = 1 + heater.AvgW[q] = 1500 + lamp.Seen[q] = 1 + lamp.AvgW[q] = 40 + if v, ok := soc(i, q); ok { + x := v + f.Site.SoC[q] = &x + } + } + f.Devices["plug.heater"] = heater + f.Devices["lamp.desk"] = lamp + types[f.Day] = 0 + list = append(list, f) + } + return &Input{ + Now: start.AddDate(0, 0, days).Add(12 * time.Hour), + Loc: time.UTC, + Days: list, + Doc: Doc{Location: &sun.Location{Lat: 52, Lon: 0}}, + Base: Base{ + DayType: types, + Groups: [][]time.Weekday{{0, 1, 2, 3, 4, 5, 6}}, + DayStart: map[int]float64{0: 360}, + NightRest: map[int]float64{0: 1380}, + }, + Devices: map[string]DeviceInfo{ + "plug.heater": {ID: "plug.heater", Name: "Heizlüfter", Switchable: true, Entities: []string{"switch.plug.heater"}}, + "lamp.desk": {ID: "lamp.desk", Name: "Schreibtischlampe", Switchable: false, Entities: []string{"light.desk"}}, + }, + PriorEmptyShare: prior, + } +} + +// btSplit returns the findings and the learned values of one run of the detector. +func btSplit(in *Input) ([]Finding, map[string]Value) { + var findings []Finding + values := map[string]Value{} + for _, c := range batteryRun(context.Background(), in, "") { + if c.Finding.ID != "" { + findings = append(findings, c.Finding) + } + if c.Value != nil { + values[c.Value.Key] = *c.Value + } + } + return findings, values +} + +// btFindingByID returns the finding with the ID, false when there is none. +func btFindingByID(findings []Finding, id string) (Finding, bool) { + for _, f := range findings { + if f.ID == id { + return f, true + } + } + return Finding{}, false +} + +// btFullAt11 is the charge of a battery that is full from 11:15 on, the first +// quarter from 11:15 counts as full, the quarters before stay at 40 %. +func btFullAt11(i, q int) (float32, bool) { + if float64(q)*baseQuarterMin >= 11*60+15 { + return 98, true + } + return 40, true +} + +// btEmptyAll is a battery at 10 % all day and night, so it is empty before +// sunrise every day. +func btEmptyAll(i, q int) (float32, bool) { + return 10, true +} + +func TestBatteryFullBeforeNoonFindsAndLearnsTime(t *testing.T) { + in := btInput(14, btNovStart, btFullAt11, 1000, nil) + findings, values := btSplit(in) + f, ok := btFindingByID(findings, "battery:full") + if !ok { + t.Fatalf("want a battery:full finding, got %d findings", len(findings)) + } + if f.Summary.Code != "battery.full_early" || f.Group != "energy" || f.Severity != "info" { + t.Errorf("summary %q in %q with severity %q, want battery.full_early info in energy", f.Summary.Code, f.Group, f.Severity) + } + if got := f.Summary.Params["time"]; got != "11:15" { + t.Errorf("time = %v, want 11:15", got) + } + if _, ok := f.Summary.Params["kwh_after"]; !ok { + t.Errorf("params %+v lack kwh_after", f.Summary.Params) + } + if f.Evidence.Shape != "curve" || len(f.Evidence.Quarters) != dayQuarters { + t.Errorf("evidence shape %q with %d quarters, want curve with %d", f.Evidence.Shape, len(f.Evidence.Quarters), dayQuarters) + } + if len(f.Apply) != 0 { + t.Errorf("Apply = %+v, want none, a load is not offered before PR 5", f.Apply) + } + if v, ok := values["site/battery_full_at"]; !ok || v.Kind != ValueTime || v.Text != "11:15" { + t.Errorf("site/battery_full_at = %+v, want time 11:15", v) + } +} + +func TestBatteryFullNeedsTenDays(t *testing.T) { + in := btInput(9, btNovStart, btFullAt11, 1000, nil) + findings, values := btSplit(in) + if _, ok := btFindingByID(findings, "battery:full"); ok { + t.Errorf("9 days gave a battery:full finding, want none") + } + if _, ok := values["site/battery_full_at"]; ok { + t.Errorf("9 days learned site/battery_full_at, want none") + } +} + +// TestBatteryDecemberEmptyEveryNightWithLastYearEmptyIsNoFinding is review +// focus 5: the battery is empty every night in December, the same weeks of last +// year were empty as well. That is the season, not a finding. +func TestBatteryDecemberEmptyEveryNightWithLastYearEmptyIsNoFinding(t *testing.T) { + lastYearEmpty := func(week int) (float64, bool) { return 1.0, true } + in := btInput(40, btDecStart, btEmptyAll, 1600, lastYearEmpty) + findings, _ := btSplit(in) + if f, ok := btFindingByID(findings, "battery:empty"); ok { + t.Errorf("empty every night with last year empty gave %+v, want no finding", f.Summary) + } +} + +func TestBatteryEmptyWithoutLastYearNamesLargestConsumer(t *testing.T) { + lastYearNever := func(week int) (float64, bool) { return 0, true } + in := btInput(40, btDecStart, btEmptyAll, 1600, lastYearNever) + findings, _ := btSplit(in) + f, ok := btFindingByID(findings, "battery:empty") + if !ok { + t.Fatalf("want a battery:empty finding, got %d findings", len(findings)) + } + if f.Summary.Code != "battery.empty_early" || f.Group != "energy" { + t.Errorf("summary %q in %q, want battery.empty_early in energy", f.Summary.Code, f.Group) + } + if got := f.Summary.Params["candidates"]; got != "Heizlüfter" { + t.Errorf("candidates = %v, want Heizlüfter only", got) + } + if kwh, ok := f.Summary.Params["kwh_missing"].(float64); !ok || kwh < 10 { + t.Errorf("kwh_missing = %v, want more than 10 kWh of night energy", f.Summary.Params["kwh_missing"]) + } + if len(f.Apply) != 1 || f.Apply[0].Template != "night_off" || f.Apply[0].Prefill["device"] != "plug.heater" { + t.Errorf("Apply = %+v, want night_off prefilled with plug.heater", f.Apply) + } + if f.Benefit == nil || f.Benefit.Unit != "kwh_week" || f.Benefit.Value <= 0 { + t.Errorf("Benefit = %+v, want kwh_week above zero", f.Benefit) + } +} + +func TestBatteryEmptyWithoutPriorRecordIsNoFinding(t *testing.T) { + in := btInput(40, btDecStart, btEmptyAll, 1600, nil) + findings, _ := btSplit(in) + if _, ok := btFindingByID(findings, "battery:empty"); ok { + t.Errorf("no record of last year gave a battery:empty finding, want none") + } +} + +func TestBatteryWithoutSoCGivesNothing(t *testing.T) { + none := func(i, q int) (float32, bool) { return 0, false } + in := btInput(40, btNovStart, none, 1000, func(week int) (float64, bool) { return 0, true }) + findings, values := btSplit(in) + if len(findings) != 0 || len(values) != 0 { + t.Errorf("no SoC gave %d findings and %d values, want none", len(findings), len(values)) + } +} + +func TestBatteryNightWhIsLearnedFromTheNight(t *testing.T) { + in := btInput(20, btDecStart, btEmptyAll, 1600, nil) + _, values := btSplit(in) + v, ok := values["site/night_wh"] + if !ok || v.Unit != "Wh" || v.Num < 12000 || v.Num > 14000 { + t.Fatalf("site/night_wh = %+v, want about 13000 Wh from sunset to the empty battery at midnight", v) + } + if int(v.Num)%100 != 0 { + t.Errorf("site/night_wh = %v, want a multiple of 100 Wh", v.Num) + } +} + +func TestBatteryDetectorIsEnergyDaily(t *testing.T) { + if BatteryDetector.Name != "battery" || BatteryDetector.Group != "energy" || BatteryDetector.Light || BatteryDetector.PerDevice { + t.Errorf("detector = %+v, want battery, energy, daily, not per device", BatteryDetector) + } +} diff --git a/dashboard/internal/autolearn/input.go b/dashboard/internal/autolearn/input.go index f3919144..4a33909d 100644 --- a/dashboard/internal/autolearn/input.go +++ b/dashboard/internal/autolearn/input.go @@ -40,6 +40,10 @@ type Input struct { // Learned holds the learned values by key, such as site/base_w. Nil when // no store is wired. Learned map[string]LearnedEntry + // PriorEmptyShare returns the share of the days of an ISO week of the year + // before that were empty before sunrise, and whether a record of that week + // exists. Nil, or a week without a record, means the empty finding is not made. + PriorEmptyShare func(week int) (float64, bool) } // OutdoorSource names the outdoor temperature entity: its unique id, its state diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 0e2c72e8..d5d33264 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -477,6 +477,13 @@ "automations.learn.baseload.drift.line": "Nachts {w} W mehr, rund {kwh_month} kWh im Monat", "automations.learn.baseload.drift.text": "Nachts braucht das Haus seit einigen Wochen {w} W mehr, rund {kwh_month} kWh im Monat. Verursacher ist {candidate}.", "automations.learn.baseload.drift.title": "Grundlast steigt", + "automations.learn.battery.candidate.none": "ein nicht gemessener Verbraucher", + "automations.learn.battery.empty_early.line": "Leer ab {time}, rund {kwh_missing} kWh fehlen", + "automations.learn.battery.empty_early.text": "Vor Sonnenaufgang ist der Akku an den meisten Nächten leer, im Median ab {time}. Dabei fehlen rund {kwh_missing} kWh. Hauptverbraucher in der Nacht: {candidates}.", + "automations.learn.battery.empty_early.title": "Akku ist nachts leer", + "automations.learn.battery.full_early.line": "Voll um {time}, danach rund {kwh_after} kWh Einspeisung", + "automations.learn.battery.full_early.text": "An den meisten Tagen ist der Akku schon vor dem Sonnenhöchststand voll, im Median um {time}. Danach gehen rund {kwh_after} kWh ins Netz.", + "automations.learn.battery.full_early.title": "Akku ist zu früh voll", "automations.learn.button.later": "Später", "automations.learn.button.never": "Nicht mehr vorschlagen", "automations.learn.button.open_assistant": "Im Assistenten öffnen", @@ -616,10 +623,12 @@ "automations.learned.fallback": "Ohne Lernwert", "automations.learned.fallback.help": "Gilt, wenn noch nichts gelernt ist oder der Wert älter als 7 Tage ist.", "automations.learned.key.base_w": "Grundlast", + "automations.learned.key.battery_full_at": "Akku voll um", "automations.learned.key.cycle_wh": "Typische Zyklusenergie von {device}", "automations.learned.key.day_start": "Tagesbeginn", "automations.learned.key.house_state": "Hauszustand", "automations.learned.key.night_rest": "Nachtruhe", + "automations.learned.key.night_wh": "Nachtverbrauch", "automations.learned.key.op_power_w": "Typische Betriebsleistung von {device}", "automations.learned.key.pv_reserve_w": "PV-Reserve", "automations.learned.key.surplus_left_wh": "Rest-Überschuss heute", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index fc34ef56..204b9234 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -477,6 +477,13 @@ "automations.learn.baseload.drift.line": "{w} W more at night, about {kwh_month} kWh a month", "automations.learn.baseload.drift.text": "For several weeks the house has needed {w} W more at night, about {kwh_month} kWh a month. The cause is {candidate}.", "automations.learn.baseload.drift.title": "Base load is rising", + "automations.learn.battery.candidate.none": "an unmeasured consumer", + "automations.learn.battery.empty_early.line": "Empty from {time}, about {kwh_missing} kWh missing", + "automations.learn.battery.empty_early.text": "Before sunrise the battery is empty on most nights, at a median from {time}. About {kwh_missing} kWh are missing. Main night consumers: {candidates}.", + "automations.learn.battery.empty_early.title": "Battery is empty at night", + "automations.learn.battery.full_early.line": "Full at {time}, then about {kwh_after} kWh fed in", + "automations.learn.battery.full_early.text": "On most days the battery is already full before solar noon, at a median of {time}. Afterwards about {kwh_after} kWh go into the grid.", + "automations.learn.battery.full_early.title": "Battery is full too early", "automations.learn.button.later": "Later", "automations.learn.button.never": "Do not suggest again", "automations.learn.button.open_assistant": "Open in assistant", @@ -616,10 +623,12 @@ "automations.learned.fallback": "Without a learned value", "automations.learned.fallback.help": "Applies when nothing has been learned yet or the value is older than 7 days.", "automations.learned.key.base_w": "Base load", + "automations.learned.key.battery_full_at": "Battery full at", "automations.learned.key.cycle_wh": "Typical cycle energy of {device}", "automations.learned.key.day_start": "Start of the day", "automations.learned.key.house_state": "House state", "automations.learned.key.night_rest": "Night rest", + "automations.learned.key.night_wh": "Night consumption", "automations.learned.key.op_power_w": "Typical operating power of {device}", "automations.learned.key.pv_reserve_w": "PV reserve", "automations.learned.key.surplus_left_wh": "Surplus left today", diff --git a/dashboard/internal/webui/static/js/automation-learned.js b/dashboard/internal/webui/static/js/automation-learned.js index 5a0528e8..12d45362 100644 --- a/dashboard/internal/webui/static/js/automation-learned.js +++ b/dashboard/internal/webui/static/js/automation-learned.js @@ -12,7 +12,9 @@ usual_runtime_s: 'automations.learned.key.usual_runtime_s', day_start: 'automations.learned.key.day_start', base_w: 'automations.learned.key.base_w', + battery_full_at: 'automations.learned.key.battery_full_at', night_rest: 'automations.learned.key.night_rest', + night_wh: 'automations.learned.key.night_wh', house_state: 'automations.learned.key.house_state', op_power_w: 'automations.learned.key.op_power_w', cycle_wh: 'automations.learned.key.cycle_wh', diff --git a/dashboard/internal/webui/static/js/automation-suggestions.js b/dashboard/internal/webui/static/js/automation-suggestions.js index b707ee05..f06afb71 100644 --- a/dashboard/internal/webui/static/js/automation-suggestions.js +++ b/dashboard/internal/webui/static/js/automation-suggestions.js @@ -33,6 +33,7 @@ if (typeof params.share === 'number') params.share = Math.round(params.share * 100); // 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'); if (/^switch_time\.sun_(on|off)$/.test(code)) { const offset = Number(params.offset_min) || 0; params.minutes = Math.abs(offset); diff --git a/dashboard/test/automation-suggestions.test.mjs b/dashboard/test/automation-suggestions.test.mjs index 1b6c3403..3b5af760 100644 --- a/dashboard/test/automation-suggestions.test.mjs +++ b/dashboard/test/automation-suggestions.test.mjs @@ -559,6 +559,15 @@ test('the baseload drift line names the cause, or an unmeasured consumer without assert.ok(api.text(unmeasured, t).endsWith('Verursacher ist ein nicht gemessener Verbraucher.')); }); +test('the battery empty line names the night consumers, or an unmeasured one without a device', () => { + const { api } = load(germanI18n); + const t = catalogT('de'); + const measured = suggestion('battery.empty_early', { time: '00:00', kwh_missing: 12.4, candidates: 'Heizlüfter' }, 'curve'); + assert.ok(api.text(measured, t).endsWith('Hauptverbraucher in der Nacht: Heizlüfter.')); + const unmeasured = suggestion('battery.empty_early', { time: '00:00', kwh_missing: 12.4, candidates: '' }, 'curve'); + assert.ok(api.text(unmeasured, t).endsWith('Hauptverbraucher in der Nacht: ein nicht gemessener Verbraucher.')); +}); + test('a scale evidence with the weekly unit shows the catalog unit on the axis', () => { const { evidence } = load(); const t = catalogT('de'); From e6e4e300cd9ebda64675b60c3af8b2c4ae9975ca Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:13:37 +0100 Subject: [PATCH 09/37] feat(monitoring): show base load, battery full time and night energy The monitoring tab lists the learned site values base_w, battery_full_at and night_wh next to the existing site keys, with their icons and labels. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 3 +++ dashboard/internal/webui/catalogs/en.json | 3 +++ .../webui/static/js/monitoring-model.js | 3 ++- dashboard/test/monitoring-model.test.mjs | 17 +++++++++++++++-- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index d5d33264..125c1d5d 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -3671,10 +3671,13 @@ "monitoring.learned.origin.prev": "vorher {value}", "monitoring.learned.origin.runs": "aus {n} Läufen", "monitoring.learned.origin.runs_one": "aus 1 Lauf", + "monitoring.learned.short.base_w": "Grundlast", + "monitoring.learned.short.battery_full_at": "Akku voll um", "monitoring.learned.short.cycle_wh": "Typische Zyklusenergie", "monitoring.learned.short.day_start": "Tagesbeginn", "monitoring.learned.short.house_state": "Hauszustand", "monitoring.learned.short.night_rest": "Nachtruhe", + "monitoring.learned.short.night_wh": "Nachtverbrauch", "monitoring.learned.short.op_power_w": "Typische Betriebsleistung", "monitoring.learned.short.pv_reserve_w": "PV-Reserve", "monitoring.learned.short.surplus_left_wh": "Rest-Überschuss heute", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 204b9234..599fb719 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -3671,10 +3671,13 @@ "monitoring.learned.origin.prev": "before {value}", "monitoring.learned.origin.runs": "from {n} runs", "monitoring.learned.origin.runs_one": "from 1 run", + "monitoring.learned.short.base_w": "Base load", + "monitoring.learned.short.battery_full_at": "Battery full at", "monitoring.learned.short.cycle_wh": "Typical cycle energy", "monitoring.learned.short.day_start": "Start of day", "monitoring.learned.short.house_state": "House state", "monitoring.learned.short.night_rest": "Night rest", + "monitoring.learned.short.night_wh": "Night consumption", "monitoring.learned.short.op_power_w": "Typical operating power", "monitoring.learned.short.pv_reserve_w": "PV reserve", "monitoring.learned.short.surplus_left_wh": "Remaining surplus today", diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index 73912f38..931a311e 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -157,7 +157,7 @@ } // Lernwerte: Anlage mit festen Schlüsseln, Geräte nach Name, feste Reihenfolge der Gerätewerte. - const SITE_KEYS = ['day_start', 'night_rest', 'house_state', 'pv_reserve_w', 'surplus_left_wh']; + const SITE_KEYS = ['day_start', 'night_rest', 'house_state', 'pv_reserve_w', 'surplus_left_wh', 'base_w', 'battery_full_at', 'night_wh']; const RUN_KEYS = ['usual_runtime_s', 'op_power_w', 'cycle_wh']; const ORDER = ['usual_on', 'usual_off', 'usual_runtime_s', 'op_power_w', 'cycle_wh']; // Icons aus dem Sprite (base.html), keine neuen Zeichnungen. @@ -166,6 +166,7 @@ op_power_w: 'ico-gauge', cycle_wh: 'ico-flash', day_start: 'ico-sun', night_rest: 'ico-clock', house_state: 'ico-user', pv_reserve_w: 'ico-gauge', surplus_left_wh: 'ico-flash', + base_w: 'ico-gauge', battery_full_at: 'ico-clock', night_wh: 'ico-flash', }; const isFiniteNumber = (v) => typeof v === 'number' && Number.isFinite(v); diff --git a/dashboard/test/monitoring-model.test.mjs b/dashboard/test/monitoring-model.test.mjs index 72778ab7..701d7ad1 100644 --- a/dashboard/test/monitoring-model.test.mjs +++ b/dashboard/test/monitoring-model.test.mjs @@ -119,14 +119,15 @@ test('weekRanges joins runs', () => { const NOW = 1794000000; -test('learnedGroups lists all five site keys and marks missing ones', () => { +test('learnedGroups lists all eight site keys and marks missing ones', () => { const values = [{ key: 'site/day_start', kind: 'time', value: '06:10', n: 4, at: NOW - 60, changed_at: NOW - 300 }]; const groups = M.learnedGroups(values, NOW, t); assert.equal(groups[0].id, 'site'); - assert.equal(groups[0].total, 5); + assert.equal(groups[0].total, 8); assert.equal(groups[0].have, 1); assert.deepEqual(groups[0].rows.map((r) => r.key), [ 'site/day_start', 'site/night_rest', 'site/house_state', 'site/pv_reserve_w', 'site/surplus_left_wh', + 'site/base_w', 'site/battery_full_at', 'site/night_wh', ]); const dayStart = groups[0].rows[0]; assert.equal(dayStart.have, true); @@ -138,6 +139,18 @@ test('learnedGroups lists all five site keys and marks missing ones', () => { assert.equal(groups[0].rows[3].meta, 'monitoring.learned.missing_pv'); }); +test('learnedGroups shows the night energy with its unit and the battery time', () => { + const values = [ + { key: 'site/night_wh', kind: 'number', unit: 'Wh', value: 13200, n: 12, at: NOW - 60 }, + { key: 'site/battery_full_at', kind: 'time', value: '11:15', n: 10, at: NOW - 60 }, + ]; + const rows = M.learnedGroups(values, NOW, t)[0].rows; + assert.equal(rows[7].key, 'site/night_wh'); + assert.equal(rows[7].have, true); + assert.equal(rows[7].value, '13.200 Wh'); + assert.equal(rows[6].value, 'monitoring.value.time{"time":"11:15"}'); +}); + test('learnedGroups orders device values on, off, runtime, power, cycle', () => { const values = [ { key: 'device/pump/usual_runtime_s', kind: 'duration', value: 600, device_name: 'Pumpe', device_icon: 'ico-pump' }, From 0fbf2697f640d7500a6394a04a6a965f46b37a55 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:16:03 +0100 Subject: [PATCH 10/37] feat(autolearn): store the empty battery share per season week The season week record gets an optional empty_share, the share of days in which the battery fell to the empty threshold before sunrise. The closer computes it with the same scan as the battery detector, judged with the 14 days before the week, and only when the rule document has a site. The engine gives the battery detector the median share of the same weeks in the prior years as Input.PriorEmptyShare, so the empty finding can be made in production. Season files without the field still load. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_engine.go | 44 +++++++++++- .../cmd/dashboard/learn_engine_season_test.go | 47 ++++++++++++ dashboard/cmd/dashboard/main.go | 3 +- .../internal/autolearn/detect_battery.go | 72 +++++++++++++++---- .../internal/autolearn/detect_battery_test.go | 55 ++++++++++++++ dashboard/internal/autolearn/engine.go | 3 + dashboard/internal/autolearn/season_store.go | 23 ++++++ .../internal/autolearn/season_store_test.go | 53 ++++++++++++++ 8 files changed, 284 insertions(+), 16 deletions(-) diff --git a/dashboard/cmd/dashboard/learn_engine.go b/dashboard/cmd/dashboard/learn_engine.go index b9be05a0..18f64d63 100644 --- a/dashboard/cmd/dashboard/learn_engine.go +++ b/dashboard/cmd/dashboard/learn_engine.go @@ -20,6 +20,7 @@ import ( "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" "github.com/Developer-Simon/energy-node-dashboard/internal/registry" "github.com/Developer-Simon/energy-node-dashboard/internal/settings" + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" ) // seasonBackfillYears is how far back the energy statistics refill the season @@ -34,8 +35,11 @@ type seasonCloser struct { store *autolearn.SeasonStore days func(from, to time.Time) ([]autolearn.DayFile, error) learned func() map[string][]float64 - loc *time.Location - done string + // site gives the coordinates of the rule document, nil or nil result means + // no sun, and the closed week gets no empty share. + site func() *sun.Location + loc *time.Location + done string } // Run closes the previous ISO week when the store has no week for it yet, or @@ -68,6 +72,9 @@ func (c *seasonCloser) close(now, prevMonday, thisMonday time.Time) { log.Printf("autolearn: season week day files incomplete: %v", err) } if w, ok := autolearn.WeekOf(days, c.learned(), c.loc); ok { + if share, ok := c.emptyShare(prevMonday, days); ok { + w.EmptyShare = &share + } c.store.Put(w) } else { log.Printf("autolearn: season week %s not closed, fewer than four day files", prevMonday.Format("2006-01-02")) @@ -78,6 +85,39 @@ func (c *seasonCloser) close(now, prevMonday, thisMonday time.Time) { } } +// emptyShare returns the share of the empty mornings of the week, judged with +// the 14 days before it. ok is false without a site or without enough sun days. +func (c *seasonCloser) emptyShare(prevMonday time.Time, week []autolearn.DayFile) (float64, bool) { + if c.site == nil { + return 0, false + } + site := c.site() + if site == nil { + return 0, false + } + prior, err := c.days(prevMonday.AddDate(0, 0, -14), prevMonday.AddDate(0, 0, -1)) + if err != nil { + log.Printf("autolearn: season week prior day files incomplete: %v", err) + } + return autolearn.EmptyShareOf(prior, week, site, c.loc) +} + +// ruleSite reads the coordinates of the rule document. A document that cannot +// be read or parsed gives no site. +func ruleSite(read func() ([]byte, error)) func() *sun.Location { + return func() *sun.Location { + raw, err := read() + if err != nil { + return nil + } + doc, err := autolearn.ParseDoc(raw) + if err != nil { + return nil + } + return doc.Location + } +} + // learnedClockMinutes reads the learned clock times of the store as minutes of // the day, keyed by the learned key. WeekOf takes the median of each key. func learnedClockMinutes(store *autolearn.LearnedStore) func() map[string][]float64 { diff --git a/dashboard/cmd/dashboard/learn_engine_season_test.go b/dashboard/cmd/dashboard/learn_engine_season_test.go index b32f1802..61be71a6 100644 --- a/dashboard/cmd/dashboard/learn_engine_season_test.go +++ b/dashboard/cmd/dashboard/learn_engine_season_test.go @@ -10,6 +10,7 @@ import ( "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" "github.com/Developer-Simon/energy-node-dashboard/internal/energystats" "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" ) // seasonTestDays returns n day files starting at the given day, each with a @@ -216,3 +217,49 @@ func TestDailyShareSaverRecordsOnlyWhenRunning(t *testing.T) { }) } } + +// seasonSoCDays returns one day file per day from start, with the charge in +// every quarter. +func seasonSoCDays(start time.Time, n int, soc float32) []autolearn.DayFile { + var out []autolearn.DayFile + for i := 0; i < n; i++ { + f := autolearn.DayFile{V: 1, Day: start.AddDate(0, 0, i).Format("2006-01-02")} + for q := 0; q < 96; q++ { + v := soc + f.Site.SoC[q] = &v + f.Site.Seen[q] = 1 + } + out = append(out, f) + } + return out +} + +// TestSeasonCloserWritesEmptyShare: with a site the closed week carries the +// share of its empty mornings, judged with the 14 days before it. Without a +// site the week has no share. +func TestSeasonCloserWritesEmptyShare(t *testing.T) { + site := &sun.Location{Lat: 52, Lon: 0} + priorFrom := seasonPrevMon.AddDate(0, 0, -14) + run := func(withSite bool) *seasonCloser { + closer, _ := newSeasonCloserForTest(t, nil, new(int)) + closer.days = func(from, to time.Time) ([]autolearn.DayFile, error) { + if from.Equal(priorFrom) { + return seasonSoCDays(priorFrom, 14, 40), nil + } + return seasonSoCDays(seasonPrevMon, 7, 10), nil + } + if withSite { + closer.site = func() *sun.Location { return site } + } + closer.Run(seasonWednesday) + return closer + } + ws := run(true).store.Weeks("2026-W47", "2026-W47") + if len(ws) != 1 || ws[0].EmptyShare == nil || *ws[0].EmptyShare != 1 { + t.Fatalf("week with site = %+v, want empty share 1", ws) + } + ws = run(false).store.Weeks("2026-W47", "2026-W47") + if len(ws) != 1 || ws[0].EmptyShare != nil { + t.Fatalf("week without site = %+v, want no empty share", ws) + } +} diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 03c04fe7..369a01e2 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -676,7 +676,8 @@ func main() { seasonStore.Put(w) } } - seasonClose := &seasonCloser{store: seasonStore, days: dayStore.Days, learned: learnedClockMinutes(learnedStore), loc: time.Local} + 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") }} suggestionExists := func(device string) bool { if deviceFilterStore.IsIgnored(device) { diff --git a/dashboard/internal/autolearn/detect_battery.go b/dashboard/internal/autolearn/detect_battery.go index cfcbb790..c46a46bc 100644 --- a/dashboard/internal/autolearn/detect_battery.go +++ b/dashboard/internal/autolearn/detect_battery.go @@ -82,10 +82,8 @@ func batteryRun(ctx context.Context, in *Input, _ string) []Candidate { return out } -// batteryDays reads the day files with a charge in date order, today left out. -// Each day gets its sun times, its first full quarter and its empty threshold -// from the lowest charge of the days before it. Then the morning and the night -// of each day are read. +// batteryDays reads the day files with a charge in date order, today left out, +// and scans them with the site of the rule document. func batteryDays(in *Input) []*batteryDay { loc := in.Loc if loc == nil { @@ -94,12 +92,31 @@ func batteryDays(in *Input) []*batteryDay { today := in.Now.In(loc).Format(dayLayout) files := make([]*DayFile, 0, len(in.Days)) for i := range in.Days { - files = append(files, &in.Days[i]) + if in.Days[i].Day != today { + files = append(files, &in.Days[i]) + } + } + out := batteryScan(files, loc, in.Doc.Location) + for _, d := range out { + if g, ok := in.Base.DayType[d.date]; ok { + d.group = g + } else { + d.group = -1 + } } + return out +} + +// batteryScan reads the day files with a charge in date order. Each day gets +// its sun times, its first full quarter and its empty threshold from the lowest +// charge of the 14 days before it in the list. Then the morning before sunrise +// and the night after sunset of each day are read. This is the one definition of +// empty and full that the detector and the season record share. +func batteryScan(files []*DayFile, loc *time.Location, site *sun.Location) []*batteryDay { sort.SliceStable(files, func(a, b int) bool { return files[a].Day < files[b].Day }) var out []*batteryDay for _, f := range files { - if f.Day == today || !batteryHasSoC(f) { + if !batteryHasSoC(f) { continue } t, err := time.ParseInLocation(dayLayout, f.Day, loc) @@ -108,13 +125,8 @@ func batteryDays(in *Input) []*batteryDay { } _, week := t.ISOWeek() d := &batteryDay{date: f.Day, week: week, f: f, fullQ: -1, emptyQ: -1} - if g, ok := in.Base.DayType[f.Day]; ok { - d.group = g - } else { - d.group = -1 - } - if in.Doc.Location != nil { - rise, set, ok := sun.Times(t, in.Doc.Location.Lat, in.Doc.Location.Lon) + if site != nil { + rise, set, ok := sun.Times(t, site.Lat, site.Lon) if ok { d.sunOK = true d.rise = batteryMinute(rise, loc) @@ -165,6 +177,40 @@ func batteryDays(in *Input) []*batteryDay { return out } +// EmptyShareOf returns the share of the days of week in which the charge fell +// to the empty threshold before sunrise, the same definition as the battery +// detector. prior are the day files before the week, the threshold reads the +// last 14 of them. ok is false without sun, without a charge or with fewer than +// seasonMinDays evaluated days. +func EmptyShareOf(prior, week []DayFile, site *sun.Location, loc *time.Location) (float64, bool) { + if loc == nil { + loc = time.Local + } + files := make([]*DayFile, 0, len(prior)+len(week)) + for i := range prior { + files = append(files, &prior[i]) + } + inWeek := map[string]bool{} + for i := range week { + files = append(files, &week[i]) + inWeek[week[i].Day] = true + } + n, hits := 0, 0 + for _, d := range batteryScan(files, loc, site) { + if !inWeek[d.date] || !d.sunOK || !d.hasThr || !d.morning { + continue + } + n++ + if d.emptyQ >= 0 { + hits++ + } + } + if n < seasonMinDays { + return 0, false + } + return float64(hits) / float64(n), true +} + // batteryNextDay reports whether the date next is the day after date. func batteryNextDay(date, next string) bool { t, err := time.Parse(dayLayout, date) diff --git a/dashboard/internal/autolearn/detect_battery_test.go b/dashboard/internal/autolearn/detect_battery_test.go index b871f53d..1ceeded5 100644 --- a/dashboard/internal/autolearn/detect_battery_test.go +++ b/dashboard/internal/autolearn/detect_battery_test.go @@ -215,3 +215,58 @@ func TestBatteryDetectorIsEnergyDaily(t *testing.T) { t.Errorf("detector = %+v, want battery, energy, daily, not per device", BatteryDetector) } } + +// btFileAt is a day file of the given charge in every quarter, the day of start plus i. +func btFileAt(start time.Time, i int, soc float32) DayFile { + f := DayFile{V: 1, Day: start.AddDate(0, 0, i).Format(dayLayout)} + for q := 0; q < dayQuarters; q++ { + v := soc + f.Site.SoC[q] = &v + f.Site.Seen[q] = 1 + } + return f +} + +// TestEmptyShareOfCountsEmptyMornings: the prior 14 days sit at 40 %, the +// threshold is 43 %, so a week at 10 % is empty every morning and a week at 90 % +// never is. The share is the same definition the detector uses. +func TestEmptyShareOfCountsEmptyMornings(t *testing.T) { + site := &sun.Location{Lat: 52, Lon: 0} + priorStart := time.Date(2026, 10, 18, 0, 0, 0, 0, time.UTC) + weekStart := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + var prior []DayFile + for i := 0; i < 14; i++ { + prior = append(prior, btFileAt(priorStart, i, 40)) + } + var empty, full []DayFile + for i := 0; i < 7; i++ { + empty = append(empty, btFileAt(weekStart, i, 10)) + full = append(full, btFileAt(weekStart, i, 90)) + } + share, ok := EmptyShareOf(prior, empty, site, time.UTC) + if !ok || share != 1 { + t.Errorf("empty week: share %v ok %v, want 1 true", share, ok) + } + share, ok = EmptyShareOf(prior, full, site, time.UTC) + if !ok || share != 0 { + t.Errorf("full week: share %v ok %v, want 0 true", share, ok) + } +} + +func TestEmptyShareOfNeedsFourDaysAndSun(t *testing.T) { + weekStart := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + var three []DayFile + for i := 0; i < 3; i++ { + three = append(three, btFileAt(weekStart, i, 10)) + } + if _, ok := EmptyShareOf(nil, three, &sun.Location{Lat: 52, Lon: 0}, time.UTC); ok { + t.Errorf("three days gave a share, want none") + } + var seven []DayFile + for i := 0; i < 7; i++ { + seven = append(seven, btFileAt(weekStart, i, 10)) + } + if _, ok := EmptyShareOf(nil, seven, nil, time.UTC); ok { + t.Errorf("without a site gave a share, want none") + } +} diff --git a/dashboard/internal/autolearn/engine.go b/dashboard/internal/autolearn/engine.go index d7fff7ce..de029a02 100644 --- a/dashboard/internal/autolearn/engine.go +++ b/dashboard/internal/autolearn/engine.go @@ -396,6 +396,9 @@ func (e *Engine) Downgrade() bool { // document is logged and replaced by an empty one, so the round still runs. func (e *Engine) input(now time.Time, limits learnrec.Limits, devices map[string]DeviceInfo) *Input { in := &Input{Now: now, Loc: e.loc, Devices: devices, Reactions: e.reactions, Limits: limits, Season: e.seasonStore()} + if st := e.seasonStore(); st != nil { + in.PriorEmptyShare = st.PriorEmptyShare + } if e.days != nil { days, err := e.days.Days(now.AddDate(0, 0, -engineHistoryDays), now) if err != nil { diff --git a/dashboard/internal/autolearn/season_store.go b/dashboard/internal/autolearn/season_store.go index 5c024824..85f5b1bb 100644 --- a/dashboard/internal/autolearn/season_store.go +++ b/dashboard/internal/autolearn/season_store.go @@ -46,6 +46,9 @@ type Week struct { RunMin map[string]float64 `json:"run_min,omitempty"` Triggers map[string]float64 `json:"triggers,omitempty"` Learned map[string]float64 `json:"learned,omitempty"` + // EmptyShare is the share of the days of the week in which the battery + // fell to the empty threshold before sunrise. Nil without a charge record. + EmptyShare *float64 `json:"empty_share,omitempty"` } // WeekOf summarises the day files of one week. It returns false when there are @@ -309,6 +312,26 @@ func (s *SeasonStore) Weeks(from, to string) []Week { return out } +// PriorEmptyShare returns the median empty share of the same calendar week in +// the years before, the weeks of Same that hold a share. ok is false without +// such a week. The engine gives it to the battery detector as +// Input.PriorEmptyShare. +func (s *SeasonStore) PriorEmptyShare(week int) (float64, bool) { + if s == nil { + return 0, false + } + var vals []float64 + for _, w := range s.Same(week, seasonYears) { + if w.EmptyShare != nil { + vals = append(vals, *w.EmptyShare) + } + } + if len(vals) == 0 { + return 0, false + } + return Median(vals), true +} + // Same lists the weeks of the calendar week and its neighbours (one week before // and after) in the given number of years before the current year, oldest first. func (s *SeasonStore) Same(week int, years int) []Week { diff --git a/dashboard/internal/autolearn/season_store_test.go b/dashboard/internal/autolearn/season_store_test.go index 709236b3..e9eccfbd 100644 --- a/dashboard/internal/autolearn/season_store_test.go +++ b/dashboard/internal/autolearn/season_store_test.go @@ -3,6 +3,7 @@ package autolearn import ( "fmt" "math" + "os" "path/filepath" "reflect" "testing" @@ -289,3 +290,55 @@ func TestSeasonWeekOfTempCountsOnlyDaysWithTemperature(t *testing.T) { t.Errorf("TempC = %v, want 17.5 (mean of the daily means 10 and 25)", *week.TempC) } } + +// TestSeasonPriorEmptyShareReadsPriorYears: the median of the empty share of the +// same weeks of the years before. The current year does not count, and a week +// without a share gives no answer. +func TestSeasonPriorEmptyShareReadsPriorYears(t *testing.T) { + store := LoadSeasonStore(filepath.Join(t.TempDir(), "season.json"), nil) + y := time.Now().Year() + a, b, cur := 0.8, 0.6, 0.1 + store.Put(Week{Key: fmt.Sprintf("%d-W45", y-1), Source: seasonSourceDays, EmptyShare: &a}) + store.Put(Week{Key: fmt.Sprintf("%d-W45", y-2), Source: seasonSourceDays, EmptyShare: &b}) + store.Put(Week{Key: fmt.Sprintf("%d-W45", y), Source: seasonSourceDays, EmptyShare: &cur}) + store.Put(Week{Key: fmt.Sprintf("%d-W20", y-1), Source: seasonSourceDays}) + if got, ok := store.PriorEmptyShare(45); !ok || math.Abs(got-0.7) > 1e-9 { + t.Errorf("PriorEmptyShare(45) = %v %v, want median 0.7 true", got, ok) + } + if _, ok := store.PriorEmptyShare(10); ok { + t.Errorf("PriorEmptyShare(10) gave an answer without a record") + } + var nilStore *SeasonStore + if _, ok := nilStore.PriorEmptyShare(45); ok { + t.Errorf("nil store gave an answer") + } +} + +// TestSeasonWeekWithoutEmptyShareStillLoads: a season file written before the +// empty share has weeks without the field, they load with a nil share. +func TestSeasonWeekWithoutEmptyShareStillLoads(t *testing.T) { + path := filepath.Join(t.TempDir(), "season.json") + old := `{"version":1,"weeks":[{"key":"2026-W46","source":"days","days":7,"base_w":280}]}` + if err := os.WriteFile(path, []byte(old), 0o600); err != nil { + t.Fatal(err) + } + store := LoadSeasonStore(path, nil) + ws := store.Weeks("2026-W46", "2026-W46") + if len(ws) != 1 || ws[0].BaseW != 280 || ws[0].EmptyShare != nil { + t.Fatalf("old week = %+v, want base 280 and no empty share", ws) + } +} + +func TestSeasonEmptyShareSavedAndLoaded(t *testing.T) { + path := filepath.Join(t.TempDir(), "season.json") + share := 0.25 + store := LoadSeasonStore(path, nil) + store.Put(Week{Key: "2026-W46", Source: seasonSourceDays, Days: 7, EmptyShare: &share}) + if err := store.Save(); err != nil { + t.Fatal(err) + } + ws := LoadSeasonStore(path, nil).Weeks("2026-W46", "2026-W46") + if len(ws) != 1 || ws[0].EmptyShare == nil || *ws[0].EmptyShare != 0.25 { + t.Fatalf("reloaded week = %+v, want empty share 0.25", ws) + } +} From e00d60bb68bdeb35717ab27fac56c03627f9e142 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:27:42 +0100 Subject: [PATCH 11/37] feat(autolearn): seed energy findings in the demo The demo seeds a washing machine next to the heat pump on the same PV threshold, a feedback pair on the washing machine, a daily competition of both rules and a house battery that is full before noon, so the energy checks produce their findings from the real detectors. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/demo.go | 86 +++++++++++++++++-- dashboard/internal/autolearn/demo_test.go | 37 +++++++- .../devices/demo/automation_rules.json | 24 ++++++ 3 files changed, 140 insertions(+), 7 deletions(-) diff --git a/dashboard/internal/autolearn/demo.go b/dashboard/internal/autolearn/demo.go index 26b10012..601833d0 100644 --- a/dashboard/internal/autolearn/demo.go +++ b/dashboard/internal/autolearn/demo.go @@ -32,6 +32,13 @@ const ( // demoPVRuleID ist die Regel „PV-Überschuss, WP an“ der Demo. Sie schaltet die // Wärmepumpe an, der Temperaturvorschlag der Demo gilt für sie. demoPVRuleID = "regel_pv_ueberschuss_wp_an" + // demoRuleWashOn ist die Regel „Waschmaschine an bei Überschuss“ der Demo. Sie + // steht mit der Wärmepumpenregel auf derselben Schwelle, die Aus-Regel bildet + // mit ihr die Rückkopplung. + demoRuleWashOn = "regel_wasch_ueberschuss_an" + // demoCompetitionMin ist die Minute, zu der die Regeln der Konkurrenz an den + // Konkurrenztagen gleichzeitig schalten, 11:00. + demoCompetitionMin = 660.0 // demoPlugOffMin ist die Abschaltzeit der Balkonsteckdose, 22:30 in Minuten. demoPlugOffMin = 1350 @@ -85,14 +92,15 @@ const demoHeatKneeC = 15.0 // demoEntities ist die unique_id der Schalter je Gerät, wie sie die Registry hat. var demoEntities = map[string]string{ - demoPlugBalkon: "plug_balkon_steckdose", - demoPlugDry: "plug_entfeuchter_steckdose", - demoRelais: "relais_keller_switch_1", - demoHeatPump: "waermepumpe_mode", + demoPlugBalkon: "plug_balkon_steckdose", + demoPlugDry: "plug_entfeuchter_steckdose", + demoRelais: "relais_keller_switch_1", + demoHeatPump: "waermepumpe_mode", + demoWasherDevice: "waschmaschine_steckdose", } // demoWatts ist die Leistung der Demo-Geräte, wenn sie laufen. -var demoWatts = map[string]float64{demoPlugBalkon: 60, demoPlugDry: 300, demoRelais: 500, demoHeatPump: 1500} +var demoWatts = map[string]float64{demoPlugBalkon: 60, demoPlugDry: 300, demoRelais: 500, demoHeatPump: 1500, demoWasherDevice: 2000} // SeedDemo schreibt die Tagesdateien der letzten 21 Tage vor now in dir, für die // Geräte der Demo. Jede Datei trägt "fake": true, die Konsole der Demo entfernt @@ -135,6 +143,8 @@ func demoDays(now time.Time, loc *time.Location) []DayFile { // Die Waschmaschine hat einen eigenen Zufallsstrom, damit die Geräte oben // dieselben Bytes behalten. wash := rand.New(rand.NewSource(demoSeed + 1)) + // Die Wärmepumpenzyklen haben einen eigenen Zufallsstrom aus demselben Grund. + heat := rand.New(rand.NewSource(demoSeed + 3)) today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc) out := make([]DayFile, 0, demoSeedDays) for i := 0; i < demoSeedDays; i++ { @@ -232,6 +242,13 @@ func demoDays(now time.Time, loc *time.Location) []DayFile { b.solar(i) b.washer(i, wash) + b.battery() + if i < demoAwayFrom || i > demoAwayTo { + b.heatCycle(heat) + } + if demoCompetitionDays[i] { + b.competition() + } b.fill(rng) out = append(out, b.f) } @@ -263,6 +280,11 @@ const ( // demoCloudyDays sind die Tagesindizes mit bedecktem Himmel. var demoCloudyDays = map[int]bool{4: true, 11: true, 18: true} +// demoCompetitionDays sind die Tagesindizes, an denen die Regeln der Wärmepumpe +// und der Waschmaschine um elf Uhr gleichzeitig auslösen. Sechs Tage in den letzten +// vierzehn reichen für die Konkurrenz. +var demoCompetitionDays = map[int]bool{10: true, 12: true, 14: true, 16: true, 18: true, 20: true} + // demoEcoCycleDays und demoShortCycleDays sind die Tagesindizes mit einem // Eco-Zyklus (12 Tage) oder einem kurzen Zyklus (4 Tage) der Waschmaschine. var ( @@ -331,6 +353,53 @@ func (b *demoBuilder) washer(i int, rng *rand.Rand) { b.f.Cycles = append(b.f.Cycles, rec) } +// heatCycle schreibt den Zyklus der Wärmepumpe des Tages, 1400 Wh bei 1500 W, um +// acht Uhr. Die Konkurrenz lernt daraus die Betriebsleistung der Wärmepumpe. +func (b *demoBuilder) heatCycle(rng *rand.Rand) { + wh := 1400 + 50*rng.NormFloat64() + opW := 1500 + 50*rng.NormFloat64() + rec := CycleRec{Device: demoHeatPump, Wh: float32(wh), OpW: float32(opW)} + rec.Start = b.at(480).Unix() + rec.DurS = int(wh / opW * 3600) + rec.End = "self" + b.f.Cycles = append(b.f.Cycles, rec) +} + +// competition schreibt die Konkurrenz des Tages: die Regel der Wärmepumpe und die +// Regel der Waschmaschine schalten um elf Uhr im selben Viertel ein, die +// Waschmaschine läuft dann eine Stunde. +func (b *demoBuilder) competition() { + b.actionFor(demoCompetitionMin, demoPVRuleID, demoHeatPump, true) + b.actionFor(demoCompetitionMin, demoRuleWashOn, demoWasherDevice, true) + b.emit(demoCompetitionMin, demoWasherDevice, true, OriginRule, demoRuleWashOn) + b.emit(demoCompetitionMin+60, demoWasherDevice, false, OriginRule, demoRuleWashOn) +} + +// demoSoC ist der Ladestand des Hausakkus in Prozent zur Minute m ab Mitternacht. +// Der Akku liegt vor dem Morgen bei 35 Prozent, lädt bis 10:00 auf 97 Prozent, +// hält sie bis 17:00 und sinkt bis Mitternacht auf 30 Prozent. Der niedrigste +// Stand des Tages liegt damit am Abend, der Morgen bleibt über der Leergrenze. +func demoSoC(m float64) float64 { + switch { + case m < 360: + return 35 + case m < 600: + return 35 + 62*(m-360)/240 + case m < 1020: + return 97 + default: + return 97 - 67*(m-1020)/405 + } +} + +// battery setzt den Ladestand des Tages je Viertelstunde. +func (b *demoBuilder) battery() { + for q := range b.f.Site.SoC { + v := float32(demoSoC(float64(q) * baseQuarterMin)) + b.f.Site.SoC[q] = &v + } +} + // demoTodayC ist die Außentemperatur des angefangenen Demo-Tages, so kalt wie // die letzten Demo-Tage. const demoTodayC = 9.0 @@ -492,8 +561,13 @@ func (b *demoBuilder) clear() { // action schreibt die Regelaktion zu einem Schaltvorgang der Regel demoRuleID. func (b *demoBuilder) action(minute float64, device string, on bool) { + b.actionFor(minute, demoRuleID, device, on) +} + +// actionFor schreibt die Regelaktion einer Regel zu einem Schaltvorgang. +func (b *demoBuilder) actionFor(minute float64, rule, device string, on bool) { want := on - b.f.Actions = append(b.f.Actions, ActionRec{At: b.at(minute).Unix(), Rule: demoRuleID, Device: device, + b.f.Actions = append(b.f.Actions, ActionRec{At: b.at(minute).Unix(), Rule: rule, Device: device, Entity: demoEntities[device], Want: &want, There: false, OK: true, Reaction: 2.4}) } diff --git a/dashboard/internal/autolearn/demo_test.go b/dashboard/internal/autolearn/demo_test.go index 63284b43..bf00db3a 100644 --- a/dashboard/internal/autolearn/demo_test.go +++ b/dashboard/internal/autolearn/demo_test.go @@ -167,6 +167,16 @@ func TestDemoSeedYieldsFourFindings(t *testing.T) { } } +// learnedEntriesOf gives the learned numbers of the values by key, the way the +// learned store hands them to the energy checks. +func learnedEntriesOf(vals []Value) map[string]LearnedEntry { + out := make(map[string]LearnedEntry, len(vals)) + for _, v := range vals { + out[v.Key] = LearnedEntry{Key: v.Key, Device: v.Device, Unit: v.Unit, Value: v.Num, N: v.N} + } + return out +} + // 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 { @@ -183,9 +193,12 @@ func demoEngineRun(t *testing.T, dir string, now time.Time, loc *time.Location) func() learnrec.Limits { return learnrec.LimitsFor(learnrec.LevelBalanced, 4) }, loc) for _, d := range []Detector{SwitchTimeDetector, RuntimeDetector, CouplingDetector, OverriddenDetector, - AwayStandbyDetector, TemperatureDetector, LearnSwitchTimeDetector, LearnRuntimeDetector, LearnDayBoundsDetector, LearnHouseStateDetector} { + AwayStandbyDetector, TemperatureDetector, LearnSwitchTimeDetector, LearnRuntimeDetector, LearnDayBoundsDetector, LearnHouseStateDetector, + LearnCyclesDetector, FeedbackDetector, CompetitionDetector, BatteryDetector} { e.Register(d) } + // The energy checks read the operating powers the engine learned before them. + e.SetLearned(func() map[string]LearnedEntry { return learnedEntriesOf(e.Values()) }) season := LoadSeasonStore("", noLog) for _, w := range DemoSeason(now) { season.Put(w) @@ -200,6 +213,11 @@ func demoEngineRun(t *testing.T, dir string, now time.Time, loc *time.Location) for i := 0; i < 3; i++ { e.Tick(time.Date(now.Year(), now.Month(), now.Day(), 3, 30, 0, 0, loc), groups) } + // The energy checks read the learned operating powers of the day before, so + // the next day's daily round and a light round after it see them. + next := time.Date(now.Year(), now.Month(), now.Day()+1, 3, 30, 0, 0, loc) + e.Tick(next, groups) + e.Tick(next.Add(time.Hour), groups) return e } @@ -665,3 +683,20 @@ func TestDemoShadeCurveSkipsTheRunningDay(t *testing.T) { t.Fatalf("shade curve has no afternoon PV, it shows the running day: %+v", ev) } } + +// TestDemoSeedYieldsEnergyFindings checks that the demo pipeline yields the +// energy findings: a feedback pair, two competing loads and a battery that is +// full early. +func TestDemoSeedYieldsEnergyFindings(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 20, 9, 0, 0, 0, loc) + kinds := map[string]bool{} + for _, c := range demoEngineRun(t, t.TempDir(), now, loc).Candidates() { + kinds[c.Finding.Kind] = true + } + for _, kind := range []string{"feedback", "competition", "battery"} { + if !kinds[kind] { + t.Errorf("no %s finding in the demo pipeline, kinds %v", kind, kinds) + } + } +} diff --git a/demo/fixtures/devices/demo/automation_rules.json b/demo/fixtures/devices/demo/automation_rules.json index eb86b215..e6daee66 100644 --- a/demo/fixtures/devices/demo/automation_rules.json +++ b/demo/fixtures/devices/demo/automation_rules.json @@ -110,6 +110,30 @@ "actions": [ {"type": "publish", "topic": "waermepumpe/mode/set", "payload_source": "constant", "payload": "OFF"} ] + }, + { + "id": "regel_wasch_ueberschuss_an", + "name": "Waschmaschine an bei Überschuss", + "enabled": true, + "cooldown_seconds": 600, + "conditions": [ + {"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 1000, "hysteresis": 100, "hold_seconds": 30} + ], + "actions": [ + {"type": "publish", "topic": "plug/waschmaschine/output/set", "entity_id": "waschmaschine_steckdose", "payload_source": "constant", "payload": "ON"} + ] + }, + { + "id": "regel_wasch_ueberschuss_aus", + "name": "Waschmaschine aus, wenn der Überschuss fehlt", + "enabled": true, + "cooldown_seconds": 600, + "conditions": [ + {"type": "balance_threshold", "field": "grid_export", "comparison": "below", "threshold": 500, "hysteresis": 100, "hold_seconds": 60} + ], + "actions": [ + {"type": "publish", "topic": "plug/waschmaschine/output/set", "entity_id": "waschmaschine_steckdose", "payload_source": "constant", "payload": "OFF"} + ] } ], "scenarios": [ From 11857c515e96bc88ba37b01b03c096d1a837a8dc Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:28:26 +0100 Subject: [PATCH 12/37] docs(automations): describe the energy findings Co-Authored-By: Claude Sonnet 5.5 --- docs/dashboard/automations-rules.md | 32 +++++++++++++++++++++++++++++ docs/dashboard/settings.md | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/docs/dashboard/automations-rules.md b/docs/dashboard/automations-rules.md index 297ed80c..4cf814ea 100644 --- a/docs/dashboard/automations-rules.md +++ b/docs/dashboard/automations-rules.md @@ -449,6 +449,38 @@ not appear. Each fix changes only the draft in the browser, as described above. +### Energy findings + +These findings use the operating power of a device and the learned values of the +house. They are shown as soon as the data is there. None of them adds a load. + +- **Feedback**: A rule switches on a load whose own power pushes the surplus + below the switch-off threshold, so the rule turns itself off again. The + finding shows the thresholds as a scale and offers **Widen the thresholds** for + both rules in one step. It needs the learned operating power of the device and + follows the **Reliability** switch. **Flapping** names feedback as the cause + when the changes coincide with the power step of the load. +- **Competition**: Two or more rules start in the same quarter hour on the same + surplus, and the grid supplies power afterwards. The finding shows a staircase + of thresholds, one step per rule. A step that is rarely reached in the + recent weeks is marked as resting. **Stagger the thresholds** applies the + staircase to all rules at once. +- **Resting for the season until week n**: A PV threshold that the learned PV + curve reaches again in a later calendar week shows that week. A threshold the + plant never reaches stays **Can never be met**. +- **Base load rises**: The night load of the house stays higher than expected + for several weeks. The finding names a device that explains at least half of + the rise and, for a switchable device, offers the template **Night off**. +- **Battery full early**: The battery reaches 97 % before the sun is highest, on + most of the last days. This is information only. +- **Battery empty before morning**: The battery is empty before sunrise, and it + was not just as empty in the same weeks of the year before. The finding names + the devices that use most of the missing night energy. It needs a record of + the year before and stays silent until the node has collected it. + +The template **Night off** switches a device off from the usual night rest to +the usual start of the day. Without learned values it uses 23:00 to 06:00. + ### The mark and the popover A rule with open findings shows a mark at its head, labelled **Show the finding diff --git a/docs/dashboard/settings.md b/docs/dashboard/settings.md index b02dc219..3d7b22e9 100644 --- a/docs/dashboard/settings.md +++ b/docs/dashboard/settings.md @@ -57,7 +57,7 @@ appear while **Learn patterns** is on, and each works on its own. switching times, run times and devices that follow another device on or off. - **Reliability** turns the reliability checks of the [rule check](automations-rules.md#rule-check) on or off: flapping, no effect, - overridden and runs while offline. + overridden, runs while offline, feedback and competition. **Exclude devices** opens a picker for the devices that the learning leaves out. **Allow all** removes every exclusion. The trigger and value checks of the From 85a44b48e446ef3ee581dc1b9e2dfe1c47e50cd5 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:28:29 +0100 Subject: [PATCH 13/37] chore(dashboard): bump the cache-bust marks for energy findings Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/cache-bust-history.csv | 5 +++++ dashboard/internal/webui/templates/base.html | 6 +++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index 36c8c6b6..a88b254e 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,4 +1,9 @@ version,date,asset,v,note +v0.11.22-pre.31,2026-11-22,js/automation-learned.js,4, +v0.11.22-pre.31,2026-11-22,js/automation-suggestions.js,4, +v0.11.22-pre.31,2026-11-22,js/automation-templates.js,10, +v0.11.22-pre.31,2026-11-22,js/automations.page.js,30, +v0.11.22-pre.31,2026-11-22,js/monitoring-model.js,2, v0.11.22-pre.30,2026-11-22,css/base.css,54, v0.11.22-pre.30,2026-11-22,css/manager.css,53, v0.11.22-pre.30,2026-11-22,css/monitoring.css,1, diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 6703e00c..c46e4228 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -237,14 +237,14 @@

{{t "no_access.title"}}

{{if index .Can "view_history"}}

{{t "panel.history_loading"}}

{{end}} {{if index .Can "view_stats"}}

{{t "panel.stats_loading"}}

{{end}} {{if and .Manager (index .Can "view_efficiency")}}

{{t "panel.efficiency_loading"}}

{{end}} -{{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} +{{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} {{if .Manager}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} {{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} {{if index .Can "view_energy"}}

{{t "panel.energy_loading"}}

{{end}} -{{if index .Can "view_device_map"}}

{{t "panel.devicemap_loading"}}

{{end}} +{{if index .Can "view_device_map"}}

{{t "panel.devicemap_loading"}}

{{end}}

{{t "panel.settings_loading"}}

-{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} +{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} {{else}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} {{end}} From c30a3dbc3add1f2fe3d6b2b759f2ab25824ffece Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:29:38 +0100 Subject: [PATCH 14/37] test(webui): follow the template cache-bust mark Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/webui_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashboard/internal/webui/webui_test.go b/dashboard/internal/webui/webui_test.go index bc4ec71b..9a0ca959 100644 --- a/dashboard/internal/webui/webui_test.go +++ b/dashboard/internal/webui/webui_test.go @@ -1399,7 +1399,7 @@ func TestAutomationsPanelLoadsTheScenarioModules(t *testing.T) { chart := strings.Index(line, "automations-chart.js?v=4") page := strings.Index(line, "automations.page.js?v=") wizard := strings.Index(line, "automation-wizard.js?v=7") - templates := strings.Index(line, "automation-templates.js?v=9") + templates := strings.Index(line, "automation-templates.js?v=10") sheet := strings.Index(line, "automation-sheet.js?v=1") if scenario < 0 || chart < 0 || page < 0 || wizard < 0 || templates < 0 || sheet < 0 { t.Fatalf("Szenario- oder Assistenten-Module fehlen in der Skriptliste: %s", line) From cb2d65bda111c1637eb073724920f55c39fd346c Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:22:02 +0100 Subject: [PATCH 15/37] fix(autolearn): drop findings whose fix is saved and show an early full battery in Monitoring Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/autolearn/applied.go | 94 +++++++++++++++++++ dashboard/internal/autolearn/applied_test.go | 42 +++++++++ dashboard/internal/autolearn/checker.go | 9 +- dashboard/internal/autolearn/checker_test.go | 17 ++++ .../internal/autolearn/detect_battery.go | 4 +- .../internal/autolearn/detect_battery_test.go | 4 +- docs/dashboard/automations-rules.md | 3 +- docs/dashboard/monitoring.md | 2 +- 8 files changed, 169 insertions(+), 6 deletions(-) diff --git a/dashboard/internal/autolearn/applied.go b/dashboard/internal/autolearn/applied.go index 5346969d..d8299b1a 100644 --- a/dashboard/internal/autolearn/applied.go +++ b/dashboard/internal/autolearn/applied.go @@ -2,6 +2,7 @@ package autolearn import ( "encoding/json" + "math" "reflect" ) @@ -92,3 +93,96 @@ func conditionMatches(c Condition, want map[string]any) bool { } return true } + +// OpsApplied reports whether the saved rule document already holds every +// value the ops of fix would write: for its one rule, or for every rule of +// fix.Rules. The engine keeps a finding until its detector runs again, so a +// finding whose fix was saved is stale. A fix without ops, a missing rule and +// a path it cannot read report false. +func OpsApplied(fix Fix, doc Doc) bool { + groups := fix.Rules + if len(groups) == 0 { + groups = []RuleOps{{RuleID: fix.RuleID, Ops: fix.Ops}} + } + seen := false + for _, g := range groups { + rule := ruleNamed(doc, g.RuleID) + if rule == nil { + return false + } + for _, op := range g.Ops { + got, ok := ruleValueAt(*rule, op.Path) + if !ok || !sameValue(got, op.Value) { + return false + } + seen = true + } + } + return seen +} + +// ruleNamed returns the rule with the given ID, nil without one. +func ruleNamed(doc Doc, id string) *Rule { + for i := range doc.Rules { + if doc.Rules[i].ID == id { + return &doc.Rules[i] + } + } + return nil +} + +// ruleValueAt reads a rule field or a field of one condition, the paths the +// fixes write. Any other path reports false. +func ruleValueAt(rule Rule, path []any) (any, bool) { + if len(path) == 1 { + switch path[0] { + case "enabled": + return rule.Enabled, true + case "cooldown_seconds": + return rule.CooldownSeconds, true + case "repeat_seconds": + return rule.RepeatSeconds, true + } + return nil, false + } + if len(path) != 3 || path[0] != "conditions" { + return nil, false + } + idx, ok := pathIndex(path[1]) + key, isKey := path[2].(string) + if !ok || !isKey || idx < 0 || idx >= len(rule.Conditions) { + return nil, false + } + var fields map[string]any + if err := json.Unmarshal(rule.Conditions[idx].Raw, &fields); err != nil { + return nil, false + } + v, found := fields[key] + return v, found +} + +// pathIndex is a list index of a path, as Go int or as JSON number. +func pathIndex(v any) (int, bool) { + switch n := v.(type) { + case int: + return n, true + case float64: + return int(n), n == math.Trunc(n) + } + return 0, false +} + +// sameValue compares two values the way JSON sees them, so 1000 and 1000.0 +// are equal. +func sameValue(a, b any) bool { + ra, errA := json.Marshal(a) + rb, errB := json.Marshal(b) + if errA != nil || errB != nil { + return false + } + var na, nb any + if json.Unmarshal(ra, &na) != nil || json.Unmarshal(rb, &nb) != nil { + return false + } + return reflect.DeepEqual(na, nb) +} diff --git a/dashboard/internal/autolearn/applied_test.go b/dashboard/internal/autolearn/applied_test.go index fbf028bf..12cd6aae 100644 --- a/dashboard/internal/autolearn/applied_test.go +++ b/dashboard/internal/autolearn/applied_test.go @@ -74,3 +74,45 @@ func TestFixAppliedOnlyAddCondition(t *testing.T) { t.Fatal("empty document counted as applied") } } + +// opsDoc has two rules with one balance threshold each. +const opsDoc = `{"rules":[ + {"id":"on","name":"An","enabled":true,"conditions":[{"type":"balance_threshold","field":"grid_export","comparison":"above","threshold":1200}],"actions":[]}, + {"id":"off","name":"Aus","enabled":true,"cooldown_seconds":600,"conditions":[{"type":"balance_threshold","field":"grid_export","comparison":"below","threshold":300}],"actions":[]}]}` + +func TestOpsAppliedNeedsEveryRuleOfTheFix(t *testing.T) { + doc, err := ParseDoc([]byte(opsDoc)) + if err != nil { + t.Fatal(err) + } + fix := Fix{Code: "feedback_thresholds", Rules: []RuleOps{ + {RuleID: "on", Ops: []Op{{Path: []any{"conditions", 0, "threshold"}, Value: 1200}}}, + {RuleID: "off", Ops: []Op{{Path: []any{"conditions", 0, "threshold"}, Value: 300.0}}}, + }} + if !OpsApplied(fix, doc) { + t.Fatal("both thresholds are saved, want applied") + } + fix.Rules[1].Ops[0].Value = 400 + if OpsApplied(fix, doc) { + t.Fatal("one threshold differs, want not applied") + } +} + +func TestOpsAppliedSingleRuleAndOddCases(t *testing.T) { + doc, err := ParseDoc([]byte(opsDoc)) + if err != nil { + t.Fatal(err) + } + if !OpsApplied(Fix{Code: "set_cooldown", RuleID: "off", Ops: []Op{{Path: []any{"cooldown_seconds"}, Value: 600}}}, doc) { + t.Fatal("cooldown 600 is saved, want applied") + } + if OpsApplied(Fix{Code: "set_threshold", RuleID: "gone", Ops: []Op{{Path: []any{"conditions", 0, "threshold"}, Value: 1200}}}, doc) { + t.Fatal("missing rule, want not applied") + } + if OpsApplied(Fix{Code: "open_rule", RuleID: "on"}, doc) { + t.Fatal("fix without ops, want not applied") + } + if OpsApplied(Fix{Code: "set_threshold", RuleID: "on", Ops: []Op{{Path: []any{"conditions", 3, "threshold"}, Value: 1200}}}, doc) { + t.Fatal("index out of range, want not applied") + } +} diff --git a/dashboard/internal/autolearn/checker.go b/dashboard/internal/autolearn/checker.go index ba1435e4..5ed0fc77 100644 --- a/dashboard/internal/autolearn/checker.go +++ b/dashboard/internal/autolearn/checker.go @@ -294,7 +294,7 @@ func (c *Checker) reliabilityLocked() []Finding { var out []Finding for _, cand := range c.engineCandidates() { f := cand.Finding - if f.Group != "check" || cand.NEff < cand.MinNEff || !rulesCurrent(f.RuleIDs, current) { + if f.Group != "check" || cand.NEff < cand.MinNEff || !rulesCurrent(f.RuleIDs, current) || fixSaved(f, c.doc) { continue } out = append(out, f) @@ -312,6 +312,13 @@ func rulesCurrent(ruleIDs []string, current map[string]bool) bool { return true } +// fixSaved reports whether the first fix of f is already in the saved +// document. The engine keeps a finding until its detector runs again, so the +// rule check drops it as soon as its fix is saved. +func fixSaved(f Finding, doc Doc) bool { + return len(f.Apply) > 0 && OpsApplied(f.Apply[0], doc) +} + // dropOrphansLocked removes ignored IDs that are neither in the unfiltered // findings nor mention a current rule. It reports whether anything was removed. func (c *Checker) dropOrphansLocked(all []Finding) bool { diff --git a/dashboard/internal/autolearn/checker_test.go b/dashboard/internal/autolearn/checker_test.go index ba34f0ca..01a04ea1 100644 --- a/dashboard/internal/autolearn/checker_test.go +++ b/dashboard/internal/autolearn/checker_test.go @@ -376,3 +376,20 @@ func TestCheckerIgnoresHabitCandidates(t *testing.T) { t.Fatalf("habit candidate listed in the rule check: %+v", got) } } + +func TestCheckerDropsReliabilityFindingWhoseFixIsSaved(t *testing.T) { + on := true + saved := reliabilityCandidate("flapping", "r1") + saved.Finding.Apply = []Fix{{Code: "set_threshold", RuleID: "r1", Ops: []Op{{Path: []any{"conditions", 0, "threshold"}, Value: 500}}}} + c := checkerWithEngine(t, reliabilityDoc, []Candidate{saved}, &on, "") + if got := c.Findings(testBase); len(got) != 0 { + t.Fatalf("finding with a saved fix listed: %+v", got) + } + + open := reliabilityCandidate("flapping", "r1") + open.Finding.Apply = []Fix{{Code: "set_threshold", RuleID: "r1", Ops: []Op{{Path: []any{"conditions", 0, "threshold"}, Value: 600}}}} + c = checkerWithEngine(t, reliabilityDoc, []Candidate{open}, &on, "") + if got := c.Findings(testBase); len(got) != 1 { + t.Fatalf("finding with an open fix = %d findings, want 1", len(got)) + } +} diff --git a/dashboard/internal/autolearn/detect_battery.go b/dashboard/internal/autolearn/detect_battery.go index c46a46bc..d24fc4e8 100644 --- a/dashboard/internal/autolearn/detect_battery.go +++ b/dashboard/internal/autolearn/detect_battery.go @@ -306,10 +306,12 @@ func batteryFull(days []*batteryDay) []Candidate { } kwh = append(kwh, wh/1000) } + // The finding has no rule and no fix. In the group check it reaches the + // rule check and from there the Monitoring page as a notice, like shade. finding := Finding{ ID: "battery:full", Kind: "battery", - Group: "energy", + Group: "check", Severity: "info", Confidence: "high", Summary: Text{Code: "battery.full_early", Params: map[string]any{ diff --git a/dashboard/internal/autolearn/detect_battery_test.go b/dashboard/internal/autolearn/detect_battery_test.go index 1ceeded5..19ef5240 100644 --- a/dashboard/internal/autolearn/detect_battery_test.go +++ b/dashboard/internal/autolearn/detect_battery_test.go @@ -113,8 +113,8 @@ func TestBatteryFullBeforeNoonFindsAndLearnsTime(t *testing.T) { if !ok { t.Fatalf("want a battery:full finding, got %d findings", len(findings)) } - if f.Summary.Code != "battery.full_early" || f.Group != "energy" || f.Severity != "info" { - t.Errorf("summary %q in %q with severity %q, want battery.full_early info in energy", f.Summary.Code, f.Group, f.Severity) + if f.Summary.Code != "battery.full_early" || f.Group != "check" || f.Severity != "info" { + t.Errorf("summary %q in %q with severity %q, want battery.full_early info in check", f.Summary.Code, f.Group, f.Severity) } if got := f.Summary.Params["time"]; got != "11:15" { t.Errorf("time = %v, want 11:15", got) diff --git a/docs/dashboard/automations-rules.md b/docs/dashboard/automations-rules.md index 4cf814ea..0f67c330 100644 --- a/docs/dashboard/automations-rules.md +++ b/docs/dashboard/automations-rules.md @@ -472,7 +472,8 @@ house. They are shown as soon as the data is there. None of them adds a load. for several weeks. The finding names a device that explains at least half of the rise and, for a switchable device, offers the template **Night off**. - **Battery full early**: The battery reaches 97 % before the sun is highest, on - most of the last days. This is information only. + most of the last days. This is information only and appears as a notice on + the [Monitoring](monitoring.md) page. - **Battery empty before morning**: The battery is empty before sunrise, and it was not just as empty in the same weeks of the year before. The finding names the devices that use most of the missing night energy. It needs a record of diff --git a/docs/dashboard/monitoring.md b/docs/dashboard/monitoring.md index ecc6c4a7..c8be7465 100644 --- a/docs/dashboard/monitoring.md +++ b/docs/dashboard/monitoring.md @@ -30,7 +30,7 @@ Notices come from three sources: |---|---| | Energy balance | The house load is set to measured, but no meter has the role house meter. A battery level exists without a capacity in kWh. Power values have no role. Values were left without a role by a measurement chain. | | Measurement chains | A finding of a [measurement chain](energy.md#measurement-chains), such as a unit error, a frozen value, a contradiction or a sign error. The card shows the time since the finding started. | -| Learning | A finding that belongs to no rule and to no suggestion, for example a fixed shade that reduces the PV power. The card shows the direction and height of the shade, the calendar weeks, the loss per year and a daily curve. | +| Learning | A finding that belongs to no rule and to no suggestion, for example a fixed shade that reduces the PV power or a battery that is full early. The card shows the direction and height of the shade, the calendar weeks, the loss per year and a daily curve. | Findings that belong to a rule stay on the rule card in [Automations](automations-rules.md). Findings with a suggestion to apply stay in From 715cbfd3f44b927faebae8073c38502c10a224ca Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:24:50 +0100 Subject: [PATCH 16/37] fix(automations): keep learned findings while a fix sits in the draft Co-Authored-By: Claude Opus 5.5 --- .../webui/static/js/automations.page.js | 23 ++++++++--- .../webui/templates/automations-rule.html | 2 +- dashboard/test/automations.page.test.mjs | 38 +++++++++++++++++-- 3 files changed, 54 insertions(+), 9 deletions(-) diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index bc461d91..b3d004f6 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -31,6 +31,9 @@ const CHAIN_VALUE_DEFAULT = 10; // Entwurfsvorschau der Regelpruefung: Wartezeit nach der letzten Aenderung. const DRAFT_PREVIEW_DEBOUNCE_MS = 400; + // Befundarten der statischen Pruefung. Nur sie rechnet die Entwurfsvorschau neu, + // alle anderen Befunde bleiben waehrend eines Entwurfs aus der gespeicherten Liste. + const STATIC_FINDING_KINDS = ['regulator_conflict', 'unsatisfiable', 'orphan', 'duplicate', 'contradiction']; // Monatstage fuer Zeitfenster und Sonnenfenster, 1 bis 31. const MONTH_DAY_NUMBERS = Array.from({ length: 31 }, (_, index) => index + 1); @@ -356,6 +359,8 @@ findingStyle: '', // Statische Befunde des ungespeicherten Entwurfs (null, solange er dem Gespeicherten entspricht). draftFindings: null, + // Befunde, deren Aenderung im Entwurf steht. Sie bleiben bis zum Speichern oder Verwerfen verborgen. + appliedFindingIds: [], scenarioExpanded: {}, durationUnits: {}, scenarioEditing: {}, @@ -2106,6 +2111,7 @@ window.dispatchEvent(new CustomEvent('automation-findings-changed')); // Nach dem Speichern entspricht der Entwurf dem Gespeicherten; die Vorschau folgt dem Entwurf. this.draftFindings = null; + this.appliedFindingIds = []; this.refreshDraftPreview(); } catch { // Die bisherige Liste bleibt sichtbar. @@ -2119,6 +2125,7 @@ this._draftSeq = seq; if (JSON.stringify(this.document) === JSON.stringify(this.savedDocument)) { this.draftFindings = null; + this.appliedFindingIds = []; return; } try { @@ -2138,11 +2145,13 @@ this._draftTimer = setTimeout(() => this.refreshDraftPreview(), DRAFT_PREVIEW_DEBOUNCE_MS); }, // Befunde fuer Anzeige und Zaehler: die statischen kommen aus dem Entwurf, wenn - // es einen gibt; beobachtete Befunde (haeufig, nie ausgeloest) bleiben aus der gespeicherten Liste. + // es einen gibt. Alle anderen (beobachtete und gelernte) bleiben aus der gespeicherten + // Liste. Ein Befund, dessen Aenderung im Entwurf steht, ist bis zum Speichern verborgen. allFindings() { - if (this.draftFindings === null) return this.findings; - const observed = this.findings.filter((finding) => finding.kind === 'frequent' || finding.kind === 'never_fired'); - return [...this.draftFindings, ...observed]; + const shown = (finding) => !this.appliedFindingIds.includes(finding.id); + if (this.draftFindings === null) return this.findings.filter(shown); + const kept = this.findings.filter((finding) => !STATIC_FINDING_KINDS.includes(finding.kind)); + return [...this.draftFindings, ...kept].filter(shown); }, findingFor(ruleId) { return this.allFindings().find((finding) => (finding.rule_ids || []).includes(ruleId)) || null; @@ -2197,7 +2206,8 @@ // Alle Ziele werden zuerst aufgeloest. Fehlt ein Pfadteil (die Regel hat sich // seit dem Befund geaendert), wird nichts geschrieben, die Regel oeffnet sich trotzdem. // Ein Befund mit fix.rules aendert mehrere Regeln: alle oder keine. - applyFix(fix) { + // finding (optional) ist der Befund des Popovers, er bleibt bis zum Speichern verborgen. + applyFix(fix, finding = null) { 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 || [] }]; @@ -2230,6 +2240,9 @@ if (write.target.append) write.target.parent.push(write.value); else write.target.parent[write.target.key] = write.value; })); + if (finding && finding.id && !this.appliedFindingIds.includes(finding.id)) { + this.appliedFindingIds = [...this.appliedFindingIds, finding.id]; + } } this.startEditing(opened[0]); opened.forEach((rule) => { this.expanded[rule.id] = true; }); diff --git a/dashboard/internal/webui/templates/automations-rule.html b/dashboard/internal/webui/templates/automations-rule.html index 4ab4a110..fd90ea05 100644 --- a/dashboard/internal/webui/templates/automations-rule.html +++ b/dashboard/internal/webui/templates/automations-rule.html @@ -55,7 +55,7 @@

diff --git a/dashboard/test/automations.page.test.mjs b/dashboard/test/automations.page.test.mjs index 85020512..784ddd9c 100644 --- a/dashboard/test/automations.page.test.mjs +++ b/dashboard/test/automations.page.test.mjs @@ -3623,17 +3623,49 @@ test('a stale preview response does not overwrite a newer one', async () => { assert.deepEqual(component.draftFindings, [draftDuplicate]); }); -test('observed kinds of the saved list stay while a draft preview exists', () => { +test('every non-static kind of the saved list stays while a draft preview exists', () => { const { component } = createAutomationsPanel(); const frequent = { id: 'o-freq', kind: 'frequent', rule_ids: ['r1'], severity: 'info', summary: {}, apply: [] }; const neverFired = { id: 'o-never', kind: 'never_fired', rule_ids: ['r2'], severity: 'info', summary: {}, apply: [] }; - component.findings = [sampleFinding, frequent, neverFired]; + const feedback = { id: 'o-feed', kind: 'feedback', rule_ids: ['r1', 'r2'], severity: 'warn', summary: {}, apply: [] }; + const competition = { id: 'o-comp', kind: 'competition', rule_ids: ['r2'], severity: 'warn', summary: {}, apply: [] }; + component.findings = [sampleFinding, frequent, neverFired, feedback, competition]; component.draftFindings = [draftDuplicate]; const ids = component.allFindings().map((finding) => finding.id).sort(); - assert.equal(ids.join(','), 'd-dup,o-freq,o-never'); + assert.equal(ids.join(','), 'd-dup,o-comp,o-feed,o-freq,o-never'); assert.equal(component.findingFor('r1').id, 'd-dup'); }); +test('applyFix with its finding hides only that finding until the next load', async () => { + const { component, window } = createAutomationsPanel(); + component.document = { version: 1, settings: {}, rules: [ + { id: 'r1', name: 'Pumpe', conditions: [{ type: 'balance_threshold', threshold: 100, hysteresis: 0 }], actions: [] }, + { id: 'r2', name: 'Anderes', conditions: [], actions: [] }, + ] }; + const other = { id: 'o-feed', kind: 'feedback', rule_ids: ['r2'], severity: 'warn', summary: {}, apply: [] }; + component.findings = [sampleFinding, other]; + component.startEditing = () => {}; + component.applyFix(sampleFinding.apply[0], sampleFinding); + assert.deepEqual([...component.appliedFindingIds], ['f-hyst']); + assert.deepEqual([...component.allFindings().map((finding) => finding.id)], ['o-feed']); + component.draftFindings = []; + assert.deepEqual([...component.allFindings().map((finding) => finding.id)], ['o-feed']); + window.fetch = async () => ({ ok: true, json: async () => ({ findings: [sampleFinding, other] }) }); + component.refreshDraftPreview = async () => {}; + await component.loadFindings(); + assert.deepEqual([...component.appliedFindingIds], []); +}); + +test('applyFix keeps the finding visible when the rule changed and nothing was written', () => { + const { component } = createAutomationsPanel(); + component.document = { version: 1, settings: {}, rules: [{ id: 'r1', name: 'Pumpe', conditions: [], actions: [] }] }; + component.findings = [sampleFinding]; + component.startEditing = () => {}; + component.applyFix(sampleFinding.apply[0], sampleFinding); + assert.deepEqual([...component.appliedFindingIds], []); + assert.equal(component.allFindings().length, 1); +}); + test('ignoreFinding removes a draft finding from the draft list', async () => { const { component, window } = createAutomationsPanel(); component.csrfToken = 'tok'; From 5775d14900fb5b1ab086b09bacef6adf4c4e3839 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:33:49 +0100 Subject: [PATCH 17/37] feat(autolearn): seed a rising base load and an empty battery in the demo Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/autolearn/demo.go | 64 ++++++++++++++++++----- dashboard/internal/autolearn/demo_test.go | 26 +++++---- 2 files changed, 69 insertions(+), 21 deletions(-) diff --git a/dashboard/internal/autolearn/demo.go b/dashboard/internal/autolearn/demo.go index 601833d0..46c3176a 100644 --- a/dashboard/internal/autolearn/demo.go +++ b/dashboard/internal/autolearn/demo.go @@ -39,6 +39,14 @@ const ( // demoCompetitionMin ist die Minute, zu der die Regeln der Konkurrenz an den // Konkurrenztagen gleichzeitig schalten, 11:00. demoCompetitionMin = 660.0 + // demoRiseFrom ist der Tagesindex, ab dem ein nicht gemessener Verbraucher + // die Grundlast um demoRiseW hebt. TUNABLE + demoRiseFrom = 12 + // demoRiseW ist der Anstieg der Grundlast in W. TUNABLE + demoRiseW = 80.0 + // demoPriorWeeks ist die Zahl der Wochen vor now, für die das Vorjahr einen + // Anteil leerer Morgen trägt. Sie deckt die 42 Demo-Tage ab. + demoPriorWeeks = 8 // demoPlugOffMin ist die Abschaltzeit der Balkonsteckdose, 22:30 in Minuten. demoPlugOffMin = 1350 @@ -102,8 +110,8 @@ var demoEntities = map[string]string{ // demoWatts ist die Leistung der Demo-Geräte, wenn sie laufen. var demoWatts = map[string]float64{demoPlugBalkon: 60, demoPlugDry: 300, demoRelais: 500, demoHeatPump: 1500, demoWasherDevice: 2000} -// SeedDemo schreibt die Tagesdateien der letzten 21 Tage vor now in dir, für die -// Geräte der Demo. Jede Datei trägt "fake": true, die Konsole der Demo entfernt +// SeedDemo schreibt die Tagesdateien der letzten 42 Tage vor now in dir (zweimal +// das 21-Tage-Muster), für die Geräte der Demo. Jede Datei trägt "fake": true, die Konsole der Demo entfernt // nur solche. Das Ergebnis ist fest, derselbe Aufruf schreibt dieselben Bytes. // Der Aufrufer prüft, ob dir leer ist. func SeedDemo(dir string, now time.Time, loc *time.Location) error { @@ -111,7 +119,11 @@ func SeedDemo(dir string, now time.Time, loc *time.Location) error { loc = time.Local } store := &DayStore{dir: dir} - for _, f := range demoDays(now.In(loc), loc) { + // Vor den 21 Tagen liegt dasselbe Muster ein zweites Mal, ohne Anstieg. So hat + // die Grundlast genug Nächte für ihre Referenz. + days := demoDaysWith(now.In(loc).AddDate(0, 0, -demoSeedDays), loc, false) + days = append(days, demoDays(now.In(loc), loc)...) + for _, f := range days { if err := store.writeFile(f.Day, f); err != nil { return fmt.Errorf("autolearn: demo seed: %w", err) } @@ -136,9 +148,15 @@ type demoChange struct { on bool } -// demoDays erzeugt die 21 Tage vor dem heutigen Tag. Die Zeiten sind zufällig -// nur innerhalb ihrer Grenzen, der Zufall hat den festen Seed demoSeed. +// demoDays erzeugt die 21 Tage vor dem heutigen Tag mit dem Grundlastanstieg. func demoDays(now time.Time, loc *time.Location) []DayFile { + return demoDaysWith(now, loc, true) +} + +// demoDaysWith erzeugt die 21 Tage vor dem heutigen Tag. rise hebt die Grundlast +// der letzten Nächte um demoRiseW (demoRiseFrom). Die Zeiten sind zufällig +// nur innerhalb ihrer Grenzen, der Zufall hat den festen Seed demoSeed. +func demoDaysWith(now time.Time, loc *time.Location, rise bool) []DayFile { rng := rand.New(rand.NewSource(demoSeed)) // Die Waschmaschine hat einen eigenen Zufallsstrom, damit die Geräte oben // dieselben Bytes behalten. @@ -250,6 +268,9 @@ func demoDays(now time.Time, loc *time.Location) []DayFile { b.competition() } b.fill(rng) + if rise && i >= demoRiseFrom { + b.riseBase() + } out = append(out, b.f) } return out @@ -376,19 +397,21 @@ func (b *demoBuilder) competition() { } // demoSoC ist der Ladestand des Hausakkus in Prozent zur Minute m ab Mitternacht. -// Der Akku liegt vor dem Morgen bei 35 Prozent, lädt bis 10:00 auf 97 Prozent, -// hält sie bis 17:00 und sinkt bis Mitternacht auf 30 Prozent. Der niedrigste -// Stand des Tages liegt damit am Abend, der Morgen bleibt über der Leergrenze. +// Der Akku sinkt bis 05:00 von 30 auf 6 Prozent und bleibt dort bis 08:00, also +// leer vor Sonnenaufgang. Er lädt bis 10:00 auf 97 Prozent, hält sie bis 17:00 +// und sinkt bis Mitternacht wieder auf 30 Prozent. func demoSoC(m float64) float64 { switch { - case m < 360: - return 35 + case m < 300: + return 30 - 24*m/300 + case m < 480: + return 6 case m < 600: - return 35 + 62*(m-360)/240 + return 6 + 91*(m-480)/120 case m < 1020: return 97 default: - return 97 - 67*(m-1020)/405 + return 97 - 67*(m-1020)/420 } } @@ -400,6 +423,15 @@ func (b *demoBuilder) battery() { } } +// riseBase hebt die Last des ganzen Tages um demoRiseW, ein Verbraucher ohne +// eigene Messung. Netzbezug folgt der Last. +func (b *demoBuilder) riseBase() { + for q := range b.f.Site.LoadTotal { + b.f.Site.LoadTotal[q] += float32(demoRiseW) + b.f.Site.GridImport[q] = b.f.Site.LoadTotal[q] + } +} + // demoTodayC ist die Außentemperatur des angefangenen Demo-Tages, so kalt wie // die letzten Demo-Tage. const demoTodayC = 9.0 @@ -635,6 +667,14 @@ func DemoSeason(now time.Time) []Week { Learned: map[string]float64{demoBedtimeKey: demoBedtimeMin + 6*math.Sin(float64(k))}, }) } + // Dieselben Wochen ein Jahr früher: der Akku war damals selten leer. Damit + // meldet die Demo „Akku ist nachts leer“. + share := 0.1 + for k := 0; k <= demoPriorWeeks; k++ { + y, w := now.AddDate(0, 0, -7*k).ISOWeek() + s := share + out = append(out, Week{Key: fmt.Sprintf("%d-W%02d", y-1, w), Source: seasonSourceDays, Days: 7, EmptyShare: &s}) + } return out } diff --git a/dashboard/internal/autolearn/demo_test.go b/dashboard/internal/autolearn/demo_test.go index bf00db3a..f45073eb 100644 --- a/dashboard/internal/autolearn/demo_test.go +++ b/dashboard/internal/autolearn/demo_test.go @@ -194,7 +194,7 @@ func demoEngineRun(t *testing.T, dir string, now time.Time, loc *time.Location) loc) for _, d := range []Detector{SwitchTimeDetector, RuntimeDetector, CouplingDetector, OverriddenDetector, AwayStandbyDetector, TemperatureDetector, LearnSwitchTimeDetector, LearnRuntimeDetector, LearnDayBoundsDetector, LearnHouseStateDetector, - LearnCyclesDetector, FeedbackDetector, CompetitionDetector, BatteryDetector} { + LearnCyclesDetector, FeedbackDetector, CompetitionDetector, BatteryDetector, BaseLoadDetector} { e.Register(d) } // The energy checks read the operating powers the engine learned before them. @@ -338,8 +338,8 @@ func TestDemoSeedWritesGzipDayFilesAndIsDeterministic(t *testing.T) { if err != nil { t.Fatal(err) } - if len(entries) != demoSeedDays { - t.Fatalf("files = %d, want %d", len(entries), demoSeedDays) + if len(entries) != 2*demoSeedDays { + t.Fatalf("files = %d, want %d", len(entries), 2*demoSeedDays) } for _, e := range entries { a, err := os.ReadFile(filepath.Join(dirA, e.Name())) @@ -449,8 +449,8 @@ func TestDemoOutdoorSensorIsInBrokerAndSettings(t *testing.T) { func TestDemoSeasonYearCourseOfBedtime(t *testing.T) { now := time.Date(2026, 11, 21, 9, 0, 0, 0, berlinLoc(t)) weeks := DemoSeason(now) - if len(weeks) != demoSeasonWeeks || demoSeasonWeeks < 20 { - t.Fatalf("season weeks = %d, want %d (at least 20)", len(weeks), demoSeasonWeeks) + if len(weeks) != demoSeasonWeeks+demoPriorWeeks+1 || demoSeasonWeeks < 20 { + t.Fatalf("season weeks = %d, want %d (at least 20)", len(weeks), demoSeasonWeeks+demoPriorWeeks+1) } count := 0 for _, w := range weeks { @@ -529,10 +529,11 @@ func TestDemoSeedClockAndSunHabitsContrast(t *testing.T) { codes[c.Finding.ID] = c.Finding.Summary.Code } } + // With 42 days the relay carries the sun habit of switching on, the balcony plug follows it by coupling. want := map[string]string{ "switch_time:" + demoRelais + ":off:0:1830": "switch_time.sun_off", "switch_time:" + demoPlugBalkon + ":off:0:2230": "switch_time.off", - "switch_time:" + demoPlugBalkon + ":on:0:1700": "switch_time.sun_on", + "switch_time:" + demoRelais + ":on:0:1700": "switch_time.sun_on", } for id, code := range want { if codes[id] != code { @@ -685,18 +686,25 @@ func TestDemoShadeCurveSkipsTheRunningDay(t *testing.T) { } // TestDemoSeedYieldsEnergyFindings checks that the demo pipeline yields the -// energy findings: a feedback pair, two competing loads and a battery that is -// full early. +// energy findings: a feedback pair, two competing loads, a battery that is +// full early and empty before morning, and a rising base load. func TestDemoSeedYieldsEnergyFindings(t *testing.T) { loc := berlinLoc(t) now := time.Date(2026, 11, 20, 9, 0, 0, 0, loc) + ids := map[string]bool{} kinds := map[string]bool{} for _, c := range demoEngineRun(t, t.TempDir(), now, loc).Candidates() { + ids[c.Finding.ID] = true kinds[c.Finding.Kind] = true } - for _, kind := range []string{"feedback", "competition", "battery"} { + for _, kind := range []string{"feedback", "competition", "baseload"} { if !kinds[kind] { t.Errorf("no %s finding in the demo pipeline, kinds %v", kind, kinds) } } + for _, id := range []string{"battery:full", "battery:empty"} { + if !ids[id] { + t.Errorf("no %s finding in the demo pipeline, ids %v", id, ids) + } + } } From bb0ea79665a5d1ad5215aa684a0ba87ae13ad0b3 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:35:10 +0100 Subject: [PATCH 18/37] feat(autolearn): keep the PV sky for a year and stop calling summer thresholds unreachable in winter Co-Authored-By: Claude Opus 5.5 --- dashboard/cmd/dashboard/learn_engine.go | 12 +++++ dashboard/cmd/dashboard/learn_engine_test.go | 13 ++++++ dashboard/cmd/dashboard/main.go | 9 ++++ dashboard/internal/autolearn/observed.go | 44 +++++++++++++++++-- dashboard/internal/autolearn/observed_test.go | 36 ++++++++++++++- dashboard/internal/autolearn/pvraster.go | 18 +++++--- dashboard/internal/autolearn/pvraster_test.go | 19 ++++++++ dashboard/internal/autolearn/pvtracker.go | 15 ++++++- dashboard/internal/httpapi/settings_access.go | 1 + .../internal/httpapi/settings_access_test.go | 2 +- dashboard/internal/settings/settings.go | 18 +++++--- .../internal/settings/settings.schema.json | 8 +++- dashboard/internal/settings/settings_test.go | 2 +- 13 files changed, 177 insertions(+), 20 deletions(-) diff --git a/dashboard/cmd/dashboard/learn_engine.go b/dashboard/cmd/dashboard/learn_engine.go index 18f64d63..939b9454 100644 --- a/dashboard/cmd/dashboard/learn_engine.go +++ b/dashboard/cmd/dashboard/learn_engine.go @@ -197,6 +197,18 @@ func engineGroupsFor(value settings.Settings) map[string]bool { } } +// pvKeepDays is how many days the sky raster keeps: a year with the seasonal +// data switch on, else as long as the day profiles. +func pvKeepDays(value settings.Settings) int { + if !value.LearningSeasonYearDisabled { + return autolearn.PVRasterYearDays + } + if value.LearningProfileDays > 0 { + return value.LearningProfileDays + } + return settings.LearningProfileDaysDefault +} + // anyGroupOn reports whether a group of the engine is switched on. func anyGroupOn(groups map[string]bool) bool { for _, on := range groups { diff --git a/dashboard/cmd/dashboard/learn_engine_test.go b/dashboard/cmd/dashboard/learn_engine_test.go index a8ccc468..c2c0801c 100644 --- a/dashboard/cmd/dashboard/learn_engine_test.go +++ b/dashboard/cmd/dashboard/learn_engine_test.go @@ -7,6 +7,7 @@ import ( "testing" "time" + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" "github.com/Developer-Simon/energy-node-dashboard/internal/energy" "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" "github.com/Developer-Simon/energy-node-dashboard/internal/registry" @@ -133,3 +134,15 @@ func TestPVSiteRegulatorCountsEveryRegulator(t *testing.T) { t.Errorf("disabled scenario gives regulator %+v, want none", reg) } } + +func TestPVKeepDaysFollowsTheSeasonSwitch(t *testing.T) { + if got := pvKeepDays(settings.Settings{}); got != autolearn.PVRasterYearDays { + t.Fatalf("default = %d, want a year", got) + } + if got := pvKeepDays(settings.Settings{LearningSeasonYearDisabled: true, LearningProfileDays: 90}); got != 90 { + t.Fatalf("switch off = %d, want the profile days 90", got) + } + if got := pvKeepDays(settings.Settings{LearningSeasonYearDisabled: true}); got != settings.LearningProfileDaysDefault { + t.Fatalf("switch off without profile days = %d, want the default", got) + } +} diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 369a01e2..fa6b9cb5 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -515,6 +515,15 @@ func main() { pvTracker := autolearn.NewPVTracker(loadPVRaster(pvPath, learnLimits(), log.Printf), pvSite.location, pvSite.regulator, func() string { return time.Now().In(time.Local).Format("2006-01-02") }, pvPath) + // Saisonale Daten: der Himmelsraster bleibt ein Jahr, mit abgeschaltetem + // Schalter so lange wie die Tagesprofile. + pvTracker.SetKeepDays(func() int { + value, err := settingsStore.LoadSettings() + if err != nil { + return autolearn.PVRasterYearDays + } + return pvKeepDays(value) + }) learnHub.AddMinute("pvtracker", pvTracker) learnHub.AddSaver("pvtracker", saverFunc(func() error { pvSite.refresh() diff --git a/dashboard/internal/autolearn/observed.go b/dashboard/internal/autolearn/observed.go index 51d1c1c7..e19d4a2c 100644 --- a/dashboard/internal/autolearn/observed.go +++ b/dashboard/internal/autolearn/observed.go @@ -206,9 +206,15 @@ func neverFiredFinding(rule Rule, stats RuleStats, st ObserverState, season Seas func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season SeasonalSource, pv PVSource, loc *sun.Location, now time.Time) (Finding, bool) { var seasonMax *float64 var months []int + // unsure is a PV threshold the curve does not reach while the raster does + // not know the summer sun yet. It never becomes "can never be met". + unsure := false if c.Type == "balance_threshold" && (c.Field == "pv" || c.Field == "grid_export") && pv != nil && loc != nil { if m, r, ok := pv(); ok && m.Safe { - return pvAboveFinding(rule, i, c, x, lo, hi, m, r, *loc, now) + if f, ok := pvAboveFinding(rule, i, c, x, lo, hi, m, r, *loc, now); ok { + return f, true + } + unsure = true } } if c.Type == "balance_threshold" && season != nil { @@ -233,6 +239,9 @@ func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season Seaso Facts: []Fact{{Code: "season_months", Value: months}}, }, true } + if unsure { + return Finding{}, false + } s := math.Max(50, math.Floor(0.75*hi/50)*50) scale.SollValue = &s @@ -254,8 +263,10 @@ func aboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, season Seaso // pvAboveFinding is a PV or grid export threshold above the clear-sky curve of // a safe model. A threshold the curve reaches later in the year is a seasonal -// rest with the first week that reaches it. One the curve never reaches is -// never fired and gets the threshold fix. +// rest with the first week that reaches it. A threshold the curve never reaches +// is never fired with the threshold fix, but only when the raster knows the +// highest noon sun of the year. Otherwise ok is false and the caller falls back +// to the seasonal maximum. func pvAboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, m PVModel, r *Raster, loc sun.Location, now time.Time) (Finding, bool) { scale := Evidence{Shape: "scale", Seen: [2]float64{lo, hi}, IstValue: &x, Unit: unitOf(c)} if week, ok := SeasonWeekFor(x, m, r, loc, now); ok { @@ -273,6 +284,9 @@ func pvAboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, m PVModel, Facts: []Fact{{Code: "season_week", Value: week}}, }, true } + if !rasterCoversYear(r, loc, now) { + return Finding{}, false + } s := math.Max(50, math.Floor(0.75*hi/50)*50) scale.SollValue = &s @@ -292,6 +306,30 @@ func pvAboveFinding(rule Rule, i int, c Condition, x, lo, hi float64, m PVModel, }, true } +// pvCoverMarginDeg is how far the highest cell of the raster may stay below +// the highest noon sun of the coming year. +const pvCoverMarginDeg = 5.0 + +// rasterCoversYear reports whether the raster holds values near the highest +// noon sun of the coming year. Without them the roof model only knows the low +// sun, and a threshold it does not reach may still be reached in summer. A nil +// raster covers nothing. +func rasterCoversYear(r *Raster, loc sun.Location, now time.Time) bool { + if r == nil { + return false + } + top := -90.0 + r.Each(func(_, el, _ float64) { + top = math.Max(top, el) + }) + need := -90.0 + for k := 0; k <= seasonWeeks; k++ { + _, el := weekNoon(now.Add(time.Duration(k)*7*24*time.Hour), loc) + need = math.Max(need, el) + } + return top >= need-pvCoverMarginDeg +} + // seasonWeeks is how many weeks ahead SeasonWeekFor looks. const seasonWeeks = 53 diff --git a/dashboard/internal/autolearn/observed_test.go b/dashboard/internal/autolearn/observed_test.go index 34266044..612a5b10 100644 --- a/dashboard/internal/autolearn/observed_test.go +++ b/dashboard/internal/autolearn/observed_test.go @@ -287,6 +287,19 @@ func pvSource(m PVModel, ok bool) func() (PVModel, *Raster, bool) { return func() (PVModel, *Raster, bool) { return m, nil, ok } } +// pvSourceWith hands out the model with a raster. +func pvSourceWith(m PVModel, r *Raster) func() (PVModel, *Raster, bool) { + return func() (PVModel, *Raster, bool) { return m, r, true } +} + +// rasterAt is a raster with two samples at az/el, enough for a cell value. +func rasterAt(az, el, w float64) *Raster { + r := NewRaster(5, 5) + r.Add(az, el, w, "2026-06-20") + r.Add(az, el, w, "2026-06-21") + return r +} + // Focus 3: 6000 W on a 5 kW roof never fires, so it is not a seasonal rest. // 4000 W is above the modelled roof as well. func TestSeasonWeekForAboveTheRoofIsNever(t *testing.T) { @@ -336,7 +349,7 @@ func TestObservedNeverFiredPVAboveRoofIsWarnWithFix(t *testing.T) { st := neverFiredStateFor("pv", testNow.Add(-40*24*time.Hour), 1850) findings := ObservedFindingsWithPV(doc, st, fakeSeason{maxW: 5000, months: []int{6}, days: 300, ok: true}, - pvSource(pvRoof(), true), testNow, DefaultThresholds()) + pvSourceWith(pvRoof(), rasterAt(180, 61, 5000)), testNow, DefaultThresholds()) got := findKind(findings, "never_fired") if len(got) != 1 { t.Fatalf("never_fired findings = %d, want 1: %+v", len(got), findings) @@ -367,3 +380,24 @@ func TestObservedNeverFiredPVWithoutModelUsesSeasonMax(t *testing.T) { } } } + +// A winter raster does not know the summer sun: a threshold the curve does not +// reach is not "can never be met" and gets no fix. +func TestObservedNeverFiredPVWinterRasterFallsBack(t *testing.T) { + doc := pvRule(t, "6000") + st := neverFiredStateFor("pv", testNow.Add(-40*24*time.Hour), 1850) + winter := rasterAt(180, 14, 1800) + + findings := ObservedFindingsWithPV(doc, st, fakeSeason{maxW: 5000, months: []int{6}, days: 300, ok: true}, + pvSourceWith(pvRoof(), winter), testNow, DefaultThresholds()) + if got := findKind(findings, "never_fired"); len(got) != 0 { + t.Fatalf("never_fired with a winter raster = %+v, want none", got) + } + + findings = ObservedFindingsWithPV(doc, st, fakeSeason{maxW: 6500, months: []int{6}, days: 300, ok: true}, + pvSourceWith(pvRoof(), winter), testNow, DefaultThresholds()) + got := findKind(findings, "never_fired") + if len(got) != 1 || got[0].Summary.Code != "check.seasonal_rest" { + t.Fatalf("findings = %+v, want check.seasonal_rest from the seasonal maximum", got) + } +} diff --git a/dashboard/internal/autolearn/pvraster.go b/dashboard/internal/autolearn/pvraster.go index 4a721213..e49cb88b 100644 --- a/dashboard/internal/autolearn/pvraster.go +++ b/dashboard/internal/autolearn/pvraster.go @@ -10,6 +10,9 @@ import ( const ( // pvRasterDays is how long a sample stays in the raster. pvRasterDays = 45 + // PVRasterYearDays is how long a sample stays while the seasonal data are + // kept for a whole year. + PVRasterYearDays = 366 // pvRasterKeep is how many of the highest values each cell keeps. pvRasterKeep = 3 // pvRasterMinElDeg is the sun elevation below which samples are ignored. @@ -107,12 +110,17 @@ func (r *Raster) Each(fn func(az, el, w float64)) { } } -// Prune drops samples older than pvRasterDays relative to today (format -// 2006-01-02) and removes cells that end up empty. An unparsable today leaves -// the raster unchanged. +// Prune drops samples older than pvRasterDays relative to today, see PruneDays. func (r *Raster) Prune(today string) { + r.PruneDays(today, pvRasterDays) +} + +// PruneDays drops samples older than days relative to today (format +// 2006-01-02) and removes cells that end up empty. An unparsable today or +// days below 1 leave the raster unchanged. +func (r *Raster) PruneDays(today string, days int) { t, err := time.Parse(pvDayLayout, today) - if err != nil { + if err != nil || days < 1 { return } for key, c := range r.cells { @@ -122,7 +130,7 @@ func (r *Raster) Prune(today string) { if err != nil { continue } - if t.Sub(d) <= pvRasterDays*24*time.Hour { + if t.Sub(d) <= time.Duration(days)*24*time.Hour { kept = append(kept, s) } } diff --git a/dashboard/internal/autolearn/pvraster_test.go b/dashboard/internal/autolearn/pvraster_test.go index ef482293..ed275d80 100644 --- a/dashboard/internal/autolearn/pvraster_test.go +++ b/dashboard/internal/autolearn/pvraster_test.go @@ -155,3 +155,22 @@ func TestRasterEachVisitsCellsWithCentre(t *testing.T) { t.Fatalf("Each got %v, want centre 102.5/40.5 value 900", got[0]) } } + +func TestRasterPruneDaysKeepsTheGivenWindow(t *testing.T) { + r := NewRaster(5, 5) + r.Add(180, 30, 1000, "2026-01-10") + r.Add(180, 30, 900, "2026-01-11") + r.Add(180, 60, 4000, "2025-06-20") + r.Add(180, 60, 3900, "2025-06-21") + r.PruneDays("2026-01-20", PVRasterYearDays) + if _, ok := r.Cell(180, 60); !ok { + t.Fatal("summer cell dropped within a year") + } + r.PruneDays("2026-01-20", 56) + if _, ok := r.Cell(180, 60); ok { + t.Fatal("summer cell kept beyond 56 days") + } + if _, ok := r.Cell(180, 30); !ok { + t.Fatal("recent cell dropped") + } +} diff --git a/dashboard/internal/autolearn/pvtracker.go b/dashboard/internal/autolearn/pvtracker.go index b8641248..8f55980c 100644 --- a/dashboard/internal/autolearn/pvtracker.go +++ b/dashboard/internal/autolearn/pvtracker.go @@ -21,6 +21,7 @@ type PVTracker struct { day func() string path string pruned string + keepDays func() int lastUnthrottled bool } @@ -32,6 +33,14 @@ func NewPVTracker(raster *Raster, location func() (lat, lon float64, ok bool), r return &PVTracker{raster: raster, location: location, regulator: regulator, day: day, path: path} } +// SetKeepDays sets how many days the raster keeps. It is read once a day when +// the raster is pruned. Without it the raster keeps pvRasterDays. +func (t *PVTracker) SetKeepDays(fn func() int) { + t.mu.Lock() + defer t.mu.Unlock() + t.keepDays = fn +} + // ObserveMinute adds the PV power of an unthrottled minute at the sun position // of the minute. It prunes the raster once per day. func (t *PVTracker) ObserveMinute(f learnrec.Frame) { @@ -39,7 +48,11 @@ func (t *PVTracker) ObserveMinute(f learnrec.Frame) { defer t.mu.Unlock() day := t.day() if day != "" && day != t.pruned { - t.raster.Prune(day) + if t.keepDays != nil { + t.raster.PruneDays(day, t.keepDays()) + } else { + t.raster.Prune(day) + } t.pruned = day } var reg *RegulatorView diff --git a/dashboard/internal/httpapi/settings_access.go b/dashboard/internal/httpapi/settings_access.go index a7569604..398a9b27 100644 --- a/dashboard/internal/httpapi/settings_access.go +++ b/dashboard/internal/httpapi/settings_access.go @@ -31,6 +31,7 @@ var settingsFieldRoles = map[string]string{ "automation_habits_disabled": auth.RoleEditSetup, "automation_reliability_disabled": auth.RoleEditSetup, "automation_energy_disabled": auth.RoleEditSetup, + "learning_season_year_disabled": auth.RoleEditSetup, "automation_outdoor_entity": auth.RoleEditSetup, "learning_excluded_devices": auth.RoleEditSetup, "learning_profile_days": auth.RoleEditSetup, diff --git a/dashboard/internal/httpapi/settings_access_test.go b/dashboard/internal/httpapi/settings_access_test.go index a45c52c3..ad7b35bd 100644 --- a/dashboard/internal/httpapi/settings_access_test.go +++ b/dashboard/internal/httpapi/settings_access_test.go @@ -28,7 +28,7 @@ func TestSettingsAccessLearningFieldsNeedEditSetup(t *testing.T) { } func TestSettingsAccessAutomationGroupSwitchesNeedEditSetup(t *testing.T) { - for _, key := range []string{"automation_habits_disabled", "automation_reliability_disabled", "automation_energy_disabled", "automation_outdoor_entity"} { + for _, key := range []string{"automation_habits_disabled", "automation_reliability_disabled", "automation_energy_disabled", "learning_season_year_disabled", "automation_outdoor_entity"} { if role := settingsFieldRoles[key]; role != auth.RoleEditSetup { t.Fatalf("%s role = %q, want %q", key, role, auth.RoleEditSetup) } diff --git a/dashboard/internal/settings/settings.go b/dashboard/internal/settings/settings.go index b81ba55f..35c77a0e 100644 --- a/dashboard/internal/settings/settings.go +++ b/dashboard/internal/settings/settings.go @@ -114,13 +114,17 @@ type Settings struct { // AutomationEnergyDisabled schalten die Gruppen unter dem Muster-Lernen // getrennt ab (invertiert benannt wie oben). Ohne Muster-Lernen laufen sie // nicht, egal wie sie stehen. - AutomationHabitsDisabled bool `json:"automation_habits_disabled"` - AutomationReliabilityDisabled bool `json:"automation_reliability_disabled"` - AutomationEnergyDisabled bool `json:"automation_energy_disabled"` - LearningExcludedDevices []string `json:"learning_excluded_devices"` - LearningProfileDays int `json:"learning_profile_days"` - LearningAcknowledged []string `json:"learning_acknowledged"` - LearningLevel string `json:"learning_level"` + AutomationHabitsDisabled bool `json:"automation_habits_disabled"` + AutomationReliabilityDisabled bool `json:"automation_reliability_disabled"` + AutomationEnergyDisabled bool `json:"automation_energy_disabled"` + // LearningSeasonYearDisabled hält die saisonalen Daten (den Himmelsraster + // der PV) nur so lange wie die Tagesprofile statt ein ganzes Jahr. + // Invertiert benannt, damit fehlend „ganzes Jahr“ heisst. + LearningSeasonYearDisabled bool `json:"learning_season_year_disabled"` + LearningExcludedDevices []string `json:"learning_excluded_devices"` + LearningProfileDays int `json:"learning_profile_days"` + LearningAcknowledged []string `json:"learning_acknowledged"` + LearningLevel string `json:"learning_level"` // AutomationOutdoorEntity ist die unique_id der Aussentemperatur-Entitaet // fuers Saisonlernen. Leer heisst: keine Temperatur wird gesammelt. AutomationOutdoorEntity string `json:"automation_outdoor_entity"` diff --git a/dashboard/internal/settings/settings.schema.json b/dashboard/internal/settings/settings.schema.json index 8c57edbb..3c44562e 100644 --- a/dashboard/internal/settings/settings.schema.json +++ b/dashboard/internal/settings/settings.schema.json @@ -3,7 +3,7 @@ "description": "Operational settings for the Energy Node dashboard.", "type": "object", "additionalProperties": false, - "required": ["health_score_threshold", "sweep_interval_seconds", "show_runtime_status", "device_view_mode", "theme", "number_format", "number_grouping", "show_config_entities_on_tile", "show_diagnostic_entities_on_tile", "live_update_interval_seconds", "wide_panels", "status_bar_items", "history_sample_interval_seconds", "history_retention_mode", "history_retention_hours", "history_budget_mb", "history_raw_window_hours", "history_minute_window_days", "history_extra_entities", "history_exchange_disabled", "history_views", "energy_stats_recording", "changelog_history", "update_check_disabled", "language_switch_hidden", "dashboard_title", "dashboard_subtitle", "dashboard_title_hidden", "dashboard_subtitle_hidden", "performance_target_pct", "automation_patterns_disabled", "automation_habits_disabled", "automation_reliability_disabled", "automation_energy_disabled", "learning_excluded_devices", "learning_profile_days", "learning_acknowledged", "learning_level", "automation_outdoor_entity"], + "required": ["health_score_threshold", "sweep_interval_seconds", "show_runtime_status", "device_view_mode", "theme", "number_format", "number_grouping", "show_config_entities_on_tile", "show_diagnostic_entities_on_tile", "live_update_interval_seconds", "wide_panels", "status_bar_items", "history_sample_interval_seconds", "history_retention_mode", "history_retention_hours", "history_budget_mb", "history_raw_window_hours", "history_minute_window_days", "history_extra_entities", "history_exchange_disabled", "history_views", "energy_stats_recording", "changelog_history", "update_check_disabled", "language_switch_hidden", "dashboard_title", "dashboard_subtitle", "dashboard_title_hidden", "dashboard_subtitle_hidden", "performance_target_pct", "automation_patterns_disabled", "automation_habits_disabled", "automation_reliability_disabled", "automation_energy_disabled", "learning_season_year_disabled", "learning_excluded_devices", "learning_profile_days", "learning_acknowledged", "learning_level", "automation_outdoor_entity"], "properties": { "health_score_threshold": { "type": "integer", @@ -182,6 +182,12 @@ "title": "Energie abschalten", "description": "Schaltet die Energie-Befunde unter dem Muster-Lernen ab, etwa die Heizzeit nach Außentemperatur. Nicht gesetzt bedeutet: Befunde werden erkannt." }, + "learning_season_year_disabled": { + "type": "boolean", + "default": false, + "title": "Saisonale Daten nur so lange wie die Profile", + "description": "Hält den Sonnenverlauf der PV nur so lange wie die Tagesprofile. Nicht gesetzt bedeutet: ein ganzes Jahr." + }, "automation_outdoor_entity": { "type": "string", "default": "", diff --git a/dashboard/internal/settings/settings_test.go b/dashboard/internal/settings/settings_test.go index 0798681b..434dfb99 100644 --- a/dashboard/internal/settings/settings_test.go +++ b/dashboard/internal/settings/settings_test.go @@ -3284,7 +3284,7 @@ func TestSchemaKenntDieAutomationGruppenSchalter(t *testing.T) { if err := json.Unmarshal(settingsSchema, &schema); err != nil { t.Fatal(err) } - for _, key := range []string{"automation_habits_disabled", "automation_reliability_disabled", "automation_energy_disabled"} { + for _, key := range []string{"automation_habits_disabled", "automation_reliability_disabled", "automation_energy_disabled", "learning_season_year_disabled"} { property, ok := schema.Properties[key] if !ok { t.Fatalf("%s fehlt im Schema", key) From 2a5c0aa8ba59a2f0a342cf3f30e5ab481e8dc1d0 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:35:55 +0100 Subject: [PATCH 19/37] feat(settings): add the switch for a whole year of seasonal data Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/webui/catalogs/de.json | 2 ++ dashboard/internal/webui/catalogs/en.json | 2 ++ .../internal/webui/static/js/settings.page.js | 3 ++ .../internal/webui/templates/settings.html | 12 ++++++++ dashboard/test/settings.learning.test.mjs | 29 +++++++++++++++++++ docs/dashboard/settings.md | 6 ++++ 6 files changed, 54 insertions(+) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 125c1d5d..8b91075f 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -4483,6 +4483,8 @@ "settings.learning.record.days_increase": "Aufbewahrung der Profile erhöhen", "settings.learning.record.note": "Messketten und Automationen teilen sich eine Aufzeichnung. Jeder Wert wird nur einmal geschrieben.", "settings.learning.record.reset": "Gelerntes löschen", + "settings.learning.record.season_year": "Saisonale Daten ganzes Jahr", + "settings.learning.record.season_year_help": "Behält den Sonnenverlauf der PV ein ganzes Jahr. Damit erkennt die Regelprüfung, ab welcher Kalenderwoche eine PV-Schwelle wieder erreicht wird. Ausgeschaltet bleibt er so lange wie die Profile.", "settings.learning.record.title": "Aufzeichnung", "settings.learning.reset.confirm": "Löschen", "settings.learning.reset.confirm_body": "Alle gelernten Werte werden gelöscht. Verworfene Vorschläge und ignorierte Hinweise bleiben.", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 599fb719..ad7345dc 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -4483,6 +4483,8 @@ "settings.learning.record.days_increase": "Increase profile retention", "settings.learning.record.note": "Chains and automations share one recording. Each value is written only once.", "settings.learning.record.reset": "Delete learned data", + "settings.learning.record.season_year": "Seasonal data for a whole year", + "settings.learning.record.season_year_help": "Keeps the PV sun course for a whole year. The rule check can then tell from which calendar week a PV threshold is reached again. When off, it stays as long as the profiles.", "settings.learning.record.title": "Recording", "settings.learning.reset.confirm": "Delete", "settings.learning.reset.confirm_body": "All learned values will be deleted. Dismissed suggestions and ignored hints stay.", diff --git a/dashboard/internal/webui/static/js/settings.page.js b/dashboard/internal/webui/static/js/settings.page.js index 8a8b5edb..77ac22ef 100644 --- a/dashboard/internal/webui/static/js/settings.page.js +++ b/dashboard/internal/webui/static/js/settings.page.js @@ -89,6 +89,7 @@ automationHabitsDisabled: false, automationReliabilityDisabled: false, automationEnergyDisabled: false, + learningSeasonYearDisabled: false, learningExcludedDevices: [], learningProfileDays: 56, learningAcknowledged: [], @@ -225,6 +226,7 @@ this.automationHabitsDisabled = Boolean(value.automation_habits_disabled); this.automationReliabilityDisabled = Boolean(value.automation_reliability_disabled); this.automationEnergyDisabled = Boolean(value.automation_energy_disabled); + this.learningSeasonYearDisabled = Boolean(value.learning_season_year_disabled); this.learningExcludedDevices = Array.isArray(value.learning_excluded_devices) ? [...value.learning_excluded_devices] : []; this.learningProfileDays = Number(value.learning_profile_days) || 56; this.learningAcknowledged = Array.isArray(value.learning_acknowledged) ? [...value.learning_acknowledged] : []; @@ -679,6 +681,7 @@ automation_habits_disabled: Boolean(this.automationHabitsDisabled), automation_reliability_disabled: Boolean(this.automationReliabilityDisabled), automation_energy_disabled: Boolean(this.automationEnergyDisabled), + learning_season_year_disabled: Boolean(this.learningSeasonYearDisabled), learning_excluded_devices: [...this.learningExcludedDevices], learning_profile_days: Number(this.learningProfileDays), learning_acknowledged: [...this.learningAcknowledged], diff --git a/dashboard/internal/webui/templates/settings.html b/dashboard/internal/webui/templates/settings.html index 2e8f7c1b..bd77ce26 100644 --- a/dashboard/internal/webui/templates/settings.html +++ b/dashboard/internal/webui/templates/settings.html @@ -258,6 +258,18 @@

{{t "settings.learning.record.title"}}

+
diff --git a/dashboard/test/settings.learning.test.mjs b/dashboard/test/settings.learning.test.mjs index 7bb3fbef..577facd4 100644 --- a/dashboard/test/settings.learning.test.mjs +++ b/dashboard/test/settings.learning.test.mjs @@ -181,3 +181,32 @@ test('Der Energie-Schalter liegt in der Feineinstellung nach Zuverlaessigkeit un assert.ok(order.indexOf('learning-energy') > order.indexOf('learning-reliability'), 'Energie steht nach Zuverlaessigkeit'); }); +test('load() liest den Saison-Schalter als Boolean, fehlend heisst ganzes Jahr', async () => { + const { dom, component } = createPanel(loadFetch({ learning_season_year_disabled: true })); + await component.load(); + assert.equal(component.learningSeasonYearDisabled, true); + dom.window.close(); + const fresh = createPanel(loadFetch({})); + await fresh.component.load(); + assert.equal(fresh.component.learningSeasonYearDisabled, false); + fresh.dom.window.close(); +}); + +test('payload() schickt den Saison-Schalter als Boolean', async () => { + const { dom, component } = createPanel(loadFetch({ learning_season_year_disabled: true })); + await component.load(); + const payload = JSON.parse(JSON.stringify(component.payload())); + assert.equal(payload.learning_season_year_disabled, true); + dom.window.close(); +}); + +test('Der Saison-Schalter liegt in der Aufzeichnung, ist ein Label mit for und an canEditSetup gebunden', () => { + const doc = new JSDOM(templateSource).window.document; + const input = doc.getElementById('learning-season-year'); + assert.ok(input, 'learning-season-year fehlt'); + assert.equal(input.getAttribute('role'), 'switch'); + assert.equal(input.getAttribute('x-bind:disabled'), '!canEditSetup'); + const label = input.closest('label'); + assert.ok(label && label.getAttribute('for') === 'learning-season-year'); + assert.ok(input.closest('[data-tour="learning-record"]'), 'nicht in der Karte Aufzeichnung'); +}); diff --git a/docs/dashboard/settings.md b/docs/dashboard/settings.md index 3d7b22e9..608c06a3 100644 --- a/docs/dashboard/settings.md +++ b/docs/dashboard/settings.md @@ -71,6 +71,12 @@ days. The default is 56 days. Chains and automations share one recording, and each value is written only once. The card shows the memory in use and how much is written per day. +**Seasonal data for a whole year** keeps the PV sun course for a year, also +when the profiles are kept for a shorter time. The rule check needs it to tell +from which calendar week a PV threshold is reached again. When it is off, the +sun course stays as long as the profiles. In the first year, while the summer +sun is still missing, a PV threshold is never reported as **Can never be met**. + **Delete learned data** asks for confirmation first. It deletes the day profiles, the reaction times, the sums of the chain suggestions and the learned loss values of the chains. Dismissed suggestions, ignored hints and the counters From 64acfc772d15204914ef2d6584dd8991e0193c7b Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:36:07 +0100 Subject: [PATCH 20/37] docs(automations): name the never triggered finding as the UI does Co-Authored-By: Claude Opus 5.5 --- docs/dashboard/automations-rules.md | 2 +- docs/dashboard/settings.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/dashboard/automations-rules.md b/docs/dashboard/automations-rules.md index 0f67c330..ec3e8ba1 100644 --- a/docs/dashboard/automations-rules.md +++ b/docs/dashboard/automations-rules.md @@ -467,7 +467,7 @@ house. They are shown as soon as the data is there. None of them adds a load. staircase to all rules at once. - **Resting for the season until week n**: A PV threshold that the learned PV curve reaches again in a later calendar week shows that week. A threshold the - plant never reaches stays **Can never be met**. + plant never reaches stays **Never triggers**. - **Base load rises**: The night load of the house stays higher than expected for several weeks. The finding names a device that explains at least half of the rise and, for a switchable device, offers the template **Night off**. diff --git a/docs/dashboard/settings.md b/docs/dashboard/settings.md index 608c06a3..e78337ce 100644 --- a/docs/dashboard/settings.md +++ b/docs/dashboard/settings.md @@ -75,7 +75,7 @@ is written per day. when the profiles are kept for a shorter time. The rule check needs it to tell from which calendar week a PV threshold is reached again. When it is off, the sun course stays as long as the profiles. In the first year, while the summer -sun is still missing, a PV threshold is never reported as **Can never be met**. +sun is still missing, a PV threshold is never reported as **Never triggers**. **Delete learned data** asks for confirmation first. It deletes the day profiles, the reaction times, the sums of the chain suggestions and the learned From a590474b0d1e8bd05a62dc562a278b59cfdc6f3c Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:36:31 +0100 Subject: [PATCH 21/37] chore(dashboard): bump the cache-bust mark of the settings page Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/webui/cache-bust-history.csv | 1 + dashboard/internal/webui/templates/base.html | 2 +- dashboard/internal/webui/webui_test.go | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index a88b254e..cb01213d 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -4,6 +4,7 @@ v0.11.22-pre.31,2026-11-22,js/automation-suggestions.js,4, v0.11.22-pre.31,2026-11-22,js/automation-templates.js,10, v0.11.22-pre.31,2026-11-22,js/automations.page.js,30, v0.11.22-pre.31,2026-11-22,js/monitoring-model.js,2, +v0.11.22-pre.31,2026-11-22,js/settings.page.js,42, v0.11.22-pre.30,2026-11-22,css/base.css,54, v0.11.22-pre.30,2026-11-22,css/manager.css,53, v0.11.22-pre.30,2026-11-22,css/monitoring.css,1, diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index c46e4228..d534c9a5 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -243,7 +243,7 @@

{{t "no_access.title"}}

{{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} {{if index .Can "view_energy"}}

{{t "panel.energy_loading"}}

{{end}} {{if index .Can "view_device_map"}}

{{t "panel.devicemap_loading"}}

{{end}} -

{{t "panel.settings_loading"}}

+

{{t "panel.settings_loading"}}

{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} {{else}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} diff --git a/dashboard/internal/webui/webui_test.go b/dashboard/internal/webui/webui_test.go index 9a0ca959..8e046f15 100644 --- a/dashboard/internal/webui/webui_test.go +++ b/dashboard/internal/webui/webui_test.go @@ -159,7 +159,7 @@ func TestOverviewDoesNotLoadManagerAssetsInitially(t *testing.T) { } for path, script := range map[string]string{ "history-panel": "/static/js-deps/apexcharts.min.js,/static/js-deps/flatpickr.min.js?v=1,/static/js-deps/flatpickr-l10n-de.js?v=1,/static/js/history-export.js?v=2,/static/js/energy-model.js?v=5,/static/js/history-chart.js?v=5,/static/js/history.js?v=21", - "settings-panel": "/static/js-deps/choices.min.js,/static/js/revisions.js?v=4,/static/js/schema-form.js?v=2,/static/js/settings-masonry.js?v=2,/static/js/device-picker.js?v=2,/static/js/learning-settings.js?v=2,/static/js/settings-field.js?v=1,/static/js/settings.page.js?v=41", + "settings-panel": "/static/js-deps/choices.min.js,/static/js/revisions.js?v=4,/static/js/schema-form.js?v=2,/static/js/settings-masonry.js?v=2,/static/js/device-picker.js?v=2,/static/js/learning-settings.js?v=2,/static/js/settings-field.js?v=1,/static/js/settings.page.js?v=42", } { if !strings.Contains(body, `id="`+path+`"`) { t.Fatalf("page is missing %s", path) @@ -4657,7 +4657,7 @@ func TestBackupAssetsAreRegisteredOnTheShell(t *testing.T) { if !strings.Contains(renderPanel(t, "settings"), `data-subpage-css="/static/css/backup.css?v=2"`) { t.Fatal("backup.css ist nicht als Stylesheet der Unterseite Backup eingetragen") } - if !strings.Contains(page, "static/js/settings.page.js?v=41") { + if !strings.Contains(page, "static/js/settings.page.js?v=42") { t.Fatal("settings.page.js ist nicht auf v=40 hochgezaehlt") } } From 2c655b55d9f91208522516aa39109b2fd049e768 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:37:31 +0100 Subject: [PATCH 22/37] feat(autolearn): seed a year of PV sky so the demo shows a seasonal rest Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/autolearn/demo.go | 30 +++++++++++++--- dashboard/internal/autolearn/demo_test.go | 35 +++++++++++++++++++ .../devices/demo/automation_rules.json | 12 +++++++ 3 files changed, 73 insertions(+), 4 deletions(-) diff --git a/dashboard/internal/autolearn/demo.go b/dashboard/internal/autolearn/demo.go index 46c3176a..3915e6d9 100644 --- a/dashboard/internal/autolearn/demo.go +++ b/dashboard/internal/autolearn/demo.go @@ -503,6 +503,28 @@ func DemoPVRaster(now time.Time, lat, lon float64) *Raster { return r } +// demoYearStep ist der Abstand in Tagen der klaren Tage vor den 21 Demo-Tagen. TUNABLE +const demoYearStep = 3 + +// DemoPVRasterYear ist DemoPVRaster mit dem Jahr davor: an jedem demoYearStep-ten +// Tag bis 365 Tage zurück ein klarer Tag. So kennt der Raster die Sommersonne, +// wie bei einem Node, der ein Jahr gelaufen ist. +func DemoPVRasterYear(now time.Time, lat, lon float64) *Raster { + r := DemoPVRaster(now, lat, lon) + today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) + for back := demoSeedDays + 1; back <= 365; back += demoYearStep { + day := today.AddDate(0, 0, -back) + for q := 0; q < dayQuarters; q++ { + az, el := sun.Position(shadeQuarterTime(day, q), lat, lon) + if el < pvRasterMinElDeg { + continue + } + r.Add(az, el, demoPVW(az, el, demoKClear), day.Format(dayLayout)) + } + } + return r +} + // DemoPVModel passt das Dachmodell an das Demo-Raster an, so wie der nächtliche // Erkenner es täte. func DemoPVModel(r *Raster) PVModel { @@ -510,11 +532,11 @@ func DemoPVModel(r *Raster) PVModel { return m } -// SeedDemoPV schreibt das Demo-Raster nach rasterPath und das Dachmodell nach -// modelPath. Der Aufrufer schreibt sie nur beim ersten Start der Demo, zusammen -// mit den Tagesdateien. +// SeedDemoPV schreibt das Demo-Raster, das ein Jahr Himmel umfasst, nach +// rasterPath und das Dachmodell nach modelPath. Der Aufrufer schreibt sie nur +// beim ersten Start der Demo, zusammen mit den Tagesdateien. func SeedDemoPV(rasterPath, modelPath string, now time.Time) error { - r := DemoPVRaster(now, demoLat, demoLon) + r := DemoPVRasterYear(now, demoLat, demoLon) data := r.State() if data == nil { return fmt.Errorf("autolearn: demo raster could not be encoded") diff --git a/dashboard/internal/autolearn/demo_test.go b/dashboard/internal/autolearn/demo_test.go index f45073eb..aa01b3f7 100644 --- a/dashboard/internal/autolearn/demo_test.go +++ b/dashboard/internal/autolearn/demo_test.go @@ -12,6 +12,7 @@ import ( "time" "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" + "github.com/Developer-Simon/energy-node-dashboard/internal/sun" ) // demoFixture is the path of a demo fixture from this package directory. @@ -708,3 +709,37 @@ func TestDemoSeedYieldsEnergyFindings(t *testing.T) { } } } + +// TestDemoPVYearRestsTheFeedInRule checks that the demo year raster knows the +// summer sun and that the feed-in rule of the demo rests until a spring week. +func TestDemoPVYearRestsTheFeedInRule(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 20, 9, 0, 0, 0, loc) + r := DemoPVRasterYear(now, demoLat, demoLon) + m := DemoPVModel(r) + if !m.Safe || !rasterCoversYear(r, sun.Location{Lat: demoLat, Lon: demoLon}, now) { + t.Fatalf("model %+v safe %v, raster must cover the year", m, m.Safe) + } + doc, err := ParseDoc(demoRulesRaw(t)) + if err != nil { + t.Fatal(err) + } + st := neverFiredStateFor("grid_export", now.Add(-40*24*time.Hour), 900) + // The observer knows the feed-in rule for 40 days, it never fired. + st.Rules["regel_einspeisung_entfeuchter"] = RuleStats{FirstSeen: now.Add(-40 * 24 * time.Hour), Hours: map[int64]int{}} + src := func() (PVModel, *Raster, bool) { return m, r, true } + var got *Finding + for _, f := range ObservedFindingsWithPV(doc, st, nil, src, now, DefaultThresholds()) { + if f.ID == FindingID("never_fired", "regel_einspeisung_entfeuchter") { + f := f + got = &f + } + } + if got == nil || got.Summary.Code != "check.never_fired_season" { + t.Fatalf("feed-in rule finding = %+v, want check.never_fired_season", got) + } + week, _ := got.Summary.Params["week"].(int) + if week < 5 || week > 20 { + t.Fatalf("week = %v, want a spring week", got.Summary.Params["week"]) + } +} diff --git a/demo/fixtures/devices/demo/automation_rules.json b/demo/fixtures/devices/demo/automation_rules.json index e6daee66..936d11fd 100644 --- a/demo/fixtures/devices/demo/automation_rules.json +++ b/demo/fixtures/devices/demo/automation_rules.json @@ -134,6 +134,18 @@ "actions": [ {"type": "publish", "topic": "plug/waschmaschine/output/set", "entity_id": "waschmaschine_steckdose", "payload_source": "constant", "payload": "OFF"} ] + }, + { + "id": "regel_einspeisung_entfeuchter", + "name": "Entfeuchter an bei viel Einspeisung", + "enabled": true, + "cooldown_seconds": 600, + "conditions": [ + {"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 2200, "hysteresis": 100, "hold_seconds": 60} + ], + "actions": [ + {"type": "publish", "topic": "plug/entfeuchter/output/set", "payload_source": "constant", "payload": "ON"} + ] } ], "scenarios": [ From e3a09523c42954472290058deaf0391a962f18ab Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:14:03 +0100 Subject: [PATCH 23/37] fix(automations): preselect the switch of night off and quiet off suggestions Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/autolearn/detect_away.go | 2 +- dashboard/internal/autolearn/detect_baseload.go | 2 +- dashboard/internal/autolearn/detect_battery.go | 2 +- dashboard/internal/autolearn/runs.go | 14 ++++++++++++++ dashboard/internal/autolearn/runs_test.go | 13 +++++++++++++ .../internal/webui/static/js/automations.page.js | 16 ++++++++++------ dashboard/test/automations.page.test.mjs | 10 ++++++++++ 7 files changed, 50 insertions(+), 9 deletions(-) diff --git a/dashboard/internal/autolearn/detect_away.go b/dashboard/internal/autolearn/detect_away.go index e9b68bde..06a92a69 100644 --- a/dashboard/internal/autolearn/detect_away.go +++ b/dashboard/internal/autolearn/detect_away.go @@ -121,7 +121,7 @@ func awayStandbyRun(ctx context.Context, in *Input, device string) []Candidate { }}, Evidence: Evidence{Shape: "scale", Unit: "kWh", IstValue: &shown, SollValue: &zero}, Apply: []Fix{{Code: "quiet_off", Template: "quiet_off", - Prefill: map[string]any{"device": device}}}, + Prefill: withEntity(map[string]any{"device": device}, "entity", switchEntityOf(in, device))}}, Device: device, Benefit: &benefit, } diff --git a/dashboard/internal/autolearn/detect_baseload.go b/dashboard/internal/autolearn/detect_baseload.go index 104f12b0..a0d17845 100644 --- a/dashboard/internal/autolearn/detect_baseload.go +++ b/dashboard/internal/autolearn/detect_baseload.go @@ -225,7 +225,7 @@ func baseLoadDrift(in *Input, ns []baseloadNight) []Candidate { } if device != "" && in.Devices[device].Switchable { finding.Apply = []Fix{{Code: "night_off", Template: "night_off", - Prefill: map[string]any{"device": device}}} + Prefill: withEntity(map[string]any{"device": device}, "entity", switchEntityOf(in, device))}} } return []Candidate{{ Finding: finding, diff --git a/dashboard/internal/autolearn/detect_battery.go b/dashboard/internal/autolearn/detect_battery.go index d24fc4e8..3ea0848c 100644 --- a/dashboard/internal/autolearn/detect_battery.go +++ b/dashboard/internal/autolearn/detect_battery.go @@ -486,7 +486,7 @@ func batteryCandidates(in *Input, devSum map[string]float64, devDays map[string] ids = append(ids, r.id) if info, ok := in.Devices[r.id]; ok && info.Switchable && len(apply) < batteryMaxApply { apply = append(apply, Fix{Code: "night_off", Template: "night_off", - Prefill: map[string]any{"device": r.id}}) + Prefill: withEntity(map[string]any{"device": r.id}, "entity", switchEntityOf(in, r.id))}) } } return ids, apply diff --git a/dashboard/internal/autolearn/runs.go b/dashboard/internal/autolearn/runs.go index edb5b8c6..14e970d6 100644 --- a/dashboard/internal/autolearn/runs.go +++ b/dashboard/internal/autolearn/runs.go @@ -111,3 +111,17 @@ func dominantEntity(entities []string) string { } return best } + +// switchEntityOf is the entity the device was switched by most often in the +// day files, the one the assistant selects. Empty without a switch event. +func switchEntityOf(in *Input, device string) string { + var entities []string + for i := range in.Days { + for _, ev := range in.Days[i].Events { + if ev.Device == device { + entities = append(entities, ev.Entity) + } + } + } + return dominantEntity(entities) +} diff --git a/dashboard/internal/autolearn/runs_test.go b/dashboard/internal/autolearn/runs_test.go index f8dbbd1b..3a095b8c 100644 --- a/dashboard/internal/autolearn/runs_test.go +++ b/dashboard/internal/autolearn/runs_test.go @@ -135,3 +135,16 @@ func TestDominantEntityPicksMostFrequentThenSmallest(t *testing.T) { t.Errorf("empty = %q, want empty", got) } } + +func TestSwitchEntityOfTakesTheMostUsedEntity(t *testing.T) { + in := &Input{Days: []DayFile{ + {Events: []EventRec{{Device: "pump", Entity: "pump_switch"}, {Device: "pump", Entity: "pump_switch"}, {Device: "lamp", Entity: "lamp_switch"}}}, + {Events: []EventRec{{Device: "pump", Entity: "pump_other"}}}, + }} + if got := switchEntityOf(in, "pump"); got != "pump_switch" { + t.Fatalf("switchEntityOf(pump) = %q, want pump_switch", got) + } + if got := switchEntityOf(in, "fridge"); got != "" { + t.Fatalf("switchEntityOf(fridge) = %q, want empty", got) + } +} diff --git a/dashboard/internal/webui/static/js/automations.page.js b/dashboard/internal/webui/static/js/automations.page.js index b3d004f6..d7a88bf6 100644 --- a/dashboard/internal/webui/static/js/automations.page.js +++ b/dashboard/internal/webui/static/js/automations.page.js @@ -248,17 +248,21 @@ }, quiet_off(prefill) { const out = {}; - if (prefill.device !== undefined) { - if (!isPrefillText(prefill.device)) return null; - out.device = prefill.device; + // Der Assistent waehlt den Schalter nach Entitaets-ID. Ohne entity gilt das Geraet. + const device = prefill.entity !== undefined ? prefill.entity : prefill.device; + if (device !== undefined) { + if (!isPrefillText(device)) return null; + out.device = device; } return out; }, night_off(prefill) { const out = {}; - if (prefill.device !== undefined) { - if (!isPrefillText(prefill.device)) return null; - out.device = prefill.device; + // Der Assistent waehlt den Schalter nach Entitaets-ID. Ohne entity gilt das Geraet. + const device = prefill.entity !== undefined ? prefill.entity : prefill.device; + if (device !== undefined) { + if (!isPrefillText(device)) return null; + out.device = device; } return out; }, diff --git a/dashboard/test/automations.page.test.mjs b/dashboard/test/automations.page.test.mjs index 784ddd9c..258fe087 100644 --- a/dashboard/test/automations.page.test.mjs +++ b/dashboard/test/automations.page.test.mjs @@ -4063,3 +4063,13 @@ test('applyFix appends an add_condition even when its index is stale', () => { const conditions = JSON.parse(JSON.stringify(component.document.rules[0].conditions)); assert.deepEqual(conditions, [existing, extra, added]); }); + +test('night_off and quiet_off prefer the entity of the prefill over the device', () => { + const { window } = createAutomationsPanel(); + const { prefillToAnswers } = window.__automationsPrefill; + for (const id of ['night_off', 'quiet_off']) { + assert.deepEqual({ ...prefillToAnswers(id, { device: 'pump', entity: 'pump_switch' }) }, { device: 'pump_switch' }); + assert.deepEqual({ ...prefillToAnswers(id, { device: 'pump' }) }, { device: 'pump' }); + assert.equal(prefillToAnswers(id, { entity: 5 }), null); + } +}); From d0e12987205b9e219b90a8b580dfecc7bb5f2712 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:15:16 +0100 Subject: [PATCH 24/37] feat(autolearn): send energy findings without a rule to Monitoring Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/autolearn/detect_baseload.go | 5 +++++ .../internal/autolearn/detect_baseload_test.go | 3 +++ dashboard/internal/autolearn/detect_battery.go | 5 +++++ .../internal/webui/static/js/monitoring-model.js | 12 ++++++++++-- dashboard/test/monitoring-model.test.mjs | 14 ++++++++++++++ docs/dashboard/automations-rules.md | 4 ++-- docs/dashboard/monitoring.md | 2 +- 7 files changed, 40 insertions(+), 5 deletions(-) diff --git a/dashboard/internal/autolearn/detect_baseload.go b/dashboard/internal/autolearn/detect_baseload.go index a0d17845..2d26a40b 100644 --- a/dashboard/internal/autolearn/detect_baseload.go +++ b/dashboard/internal/autolearn/detect_baseload.go @@ -227,6 +227,11 @@ func baseLoadDrift(in *Input, ns []baseloadNight) []Candidate { finding.Apply = []Fix{{Code: "night_off", Template: "night_off", Prefill: withEntity(map[string]any{"device": device}, "entity", switchEntityOf(in, device))}} } + // Without a switchable culprit there is no rule to suggest: the finding goes + // to the rule check and from there to Monitoring as a notice. + if len(finding.Apply) == 0 { + finding.Group = "check" + } return []Candidate{{ Finding: finding, Detector: "baseload", diff --git a/dashboard/internal/autolearn/detect_baseload_test.go b/dashboard/internal/autolearn/detect_baseload_test.go index c202f254..523ce83f 100644 --- a/dashboard/internal/autolearn/detect_baseload_test.go +++ b/dashboard/internal/autolearn/detect_baseload_test.go @@ -138,6 +138,9 @@ func TestBaseLoadDriftWithoutMeasuredDeviceHasNoCandidate(t *testing.T) { if f := findings[0]; f.Device != "" || len(f.Apply) != 0 { t.Errorf("Device %q, Apply %+v: want no candidate and no fix", f.Device, f.Apply) } + if f := findings[0]; f.Group != "check" { + t.Errorf("Group %q, want check without a fix", f.Group) + } } func TestBaseLoadSingleNightIsNoFinding(t *testing.T) { diff --git a/dashboard/internal/autolearn/detect_battery.go b/dashboard/internal/autolearn/detect_battery.go index 3ea0848c..b67e6696 100644 --- a/dashboard/internal/autolearn/detect_battery.go +++ b/dashboard/internal/autolearn/detect_battery.go @@ -409,6 +409,11 @@ func batteryEmpty(in *Input, days []*batteryDay) []Candidate { Apply: apply, Benefit: &Benefit{Unit: "kwh_week", Value: kwh * batteryWeekDays}, } + // Without a switchable culprit there is no rule to suggest: the finding goes + // to the rule check and from there to Monitoring as a notice. + if len(finding.Apply) == 0 { + finding.Group = "check" + } return []Candidate{{ Finding: finding, Detector: "battery", diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index 931a311e..72d1454b 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -71,6 +71,14 @@ return t('monitoring.weeks.and', { a: items.slice(0, -1).join(', '), b: items[items.length - 1] }); } + // Platzhalter eines Lernbefunds ohne Verursacher, wie im Vorschlagsband. + function learnParams(notice, t) { + const p = { ...(notice.params || {}) }; + if (notice.code === 'baseload.drift' && !p.candidate) p.candidate = t('automations.learn.baseload.candidate.none'); + if (notice.code === 'battery.empty_early' && !p.candidates) p.candidates = t('automations.learn.battery.candidate.none'); + return p; + } + function shadeIdParts(id) { const m = SHADE_ID_RE.exec(id || ''); return m ? { az: Number(m[1]), el: Number(m[2]) } : null; @@ -101,12 +109,12 @@ const key = sourceOf(notice) === 'learn' ? 'automations.learn.' + notice.code + '.title' : 'monitoring.notice.' + notice.code + '.title'; - return t(key, notice.params); + return t(key, sourceOf(notice) === 'learn' ? learnParams(notice, t) : notice.params); } function text(notice, t) { const p = notice.params || {}; - if (sourceOf(notice) === 'learn') return t(`automations.learn.${notice.code}.text`, notice.params); + if (sourceOf(notice) === 'learn') return t(`automations.learn.${notice.code}.text`, learnParams(notice, t)); if (notice.code === 'measured_no_meter') return t('energy.roles.notices.measured_warning'); if (notice.code === 'role_needed') return t('energy.chains.role_needed'); if (notice.code === 'chain') { diff --git a/dashboard/test/monitoring-model.test.mjs b/dashboard/test/monitoring-model.test.mjs index 701d7ad1..e6585c88 100644 --- a/dashboard/test/monitoring-model.test.mjs +++ b/dashboard/test/monitoring-model.test.mjs @@ -181,3 +181,17 @@ test('valueText formats time, duration, number and state', () => { assert.equal(M.valueText({ kind: 'state', value: 'active' }, t), 'automations.learned.state.active'); assert.equal(M.valueText({ kind: 'state', value: 'quiet' }, t), 'automations.learned.state.quiet'); }); + +test('learn findings without a culprit name the placeholder instead of the template field', () => { + const calls = []; + const spy = (key, params) => { calls.push(key); return key + JSON.stringify(params || {}); }; + const drift = { source: 'learn', code: 'baseload.drift', params: { w: 80, kwh_month: 57.6, candidate: '' } }; + const text = M.text(drift, spy); + assert.ok(text.includes('automations.learn.baseload.candidate.none')); + assert.ok(!text.includes('{candidate}')); + assert.ok(calls.includes('automations.learn.baseload.candidate.none')); + const empty = { source: 'learn', code: 'battery.empty_early', params: { time: '05:10', kwh_missing: 3.2, candidates: '' } }; + const emptyText = M.text(empty, spy); + assert.ok(emptyText.includes('automations.learn.battery.candidate.none')); + assert.ok(!emptyText.includes('{candidates}')); +}); diff --git a/docs/dashboard/automations-rules.md b/docs/dashboard/automations-rules.md index ec3e8ba1..f466e65f 100644 --- a/docs/dashboard/automations-rules.md +++ b/docs/dashboard/automations-rules.md @@ -470,14 +470,14 @@ house. They are shown as soon as the data is there. None of them adds a load. plant never reaches stays **Never triggers**. - **Base load rises**: The night load of the house stays higher than expected for several weeks. The finding names a device that explains at least half of - the rise and, for a switchable device, offers the template **Night off**. + the rise and, for a switchable device, offers the template **Night off**. Without a switchable device the finding appears as a notice on the [Monitoring](monitoring.md) page. - **Battery full early**: The battery reaches 97 % before the sun is highest, on most of the last days. This is information only and appears as a notice on the [Monitoring](monitoring.md) page. - **Battery empty before morning**: The battery is empty before sunrise, and it was not just as empty in the same weeks of the year before. The finding names the devices that use most of the missing night energy. It needs a record of - the year before and stays silent until the node has collected it. + the year before and stays silent until the node has collected it. With a switchable device it offers **Night off**, without one it appears as a notice on the [Monitoring](monitoring.md) page. The template **Night off** switches a device off from the usual night rest to the usual start of the day. Without learned values it uses 23:00 to 06:00. diff --git a/docs/dashboard/monitoring.md b/docs/dashboard/monitoring.md index c8be7465..c36c53b2 100644 --- a/docs/dashboard/monitoring.md +++ b/docs/dashboard/monitoring.md @@ -30,7 +30,7 @@ Notices come from three sources: |---|---| | Energy balance | The house load is set to measured, but no meter has the role house meter. A battery level exists without a capacity in kWh. Power values have no role. Values were left without a role by a measurement chain. | | Measurement chains | A finding of a [measurement chain](energy.md#measurement-chains), such as a unit error, a frozen value, a contradiction or a sign error. The card shows the time since the finding started. | -| Learning | A finding that belongs to no rule and to no suggestion, for example a fixed shade that reduces the PV power or a battery that is full early. The card shows the direction and height of the shade, the calendar weeks, the loss per year and a daily curve. | +| Learning | A finding that belongs to no rule and to no suggestion, for example a fixed shade that reduces the PV power, a battery that is full early or empty before morning, or a rising base load without a switchable device. The card shows the direction and height of the shade, the calendar weeks, the loss per year and a daily curve. | Findings that belong to a rule stay on the rule card in [Automations](automations-rules.md). Findings with a suggestion to apply stay in From d87e3c1c71872c460072277a9c41b2fbd8131b39 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:15:41 +0100 Subject: [PATCH 25/37] feat(autolearn): let the season expectation shorten the base load history Co-Authored-By: Claude Opus 5.5 --- .../internal/autolearn/detect_baseload.go | 26 ++++++++++++++- .../autolearn/detect_baseload_test.go | 33 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/dashboard/internal/autolearn/detect_baseload.go b/dashboard/internal/autolearn/detect_baseload.go index 2d26a40b..a30ffd40 100644 --- a/dashboard/internal/autolearn/detect_baseload.go +++ b/dashboard/internal/autolearn/detect_baseload.go @@ -31,6 +31,10 @@ const ( // baseloadMinNights is the number of nights for a drift: the reference and // seven more. The spec gives no number, the value is an assumption. baseloadMinNights = 35 + // baseloadSeasonMinNights is the number of nights for a drift when every + // night has its expectation from the earlier years. The reference of the + // window is not needed then. + baseloadSeasonMinNights = 14 // baseloadMinYears is the number of earlier weeks that make the expectation // of a week, the earlier years of the season store. baseloadMinYears = 3 @@ -85,7 +89,7 @@ func baseLoadRun(ctx context.Context, in *Input, _ string) []Candidate { }) } } - if len(ns) >= baseloadMinNights { + if len(ns) >= baseloadMinNights || (len(ns) >= baseloadSeasonMinNights && baseloadSeasonKnown(in, ns)) { if len(ns) > baseloadWindow { ns = ns[len(ns)-baseloadWindow:] } @@ -272,6 +276,26 @@ func baseloadExpect(in *Input, ns []baseloadNight) []float64 { return exp } +// baseloadSeasonKnown reports whether every night has its expectation from the +// same weeks of baseloadMinYears earlier years, as baseloadExpect uses it. +func baseloadSeasonKnown(in *Input, ns []baseloadNight) bool { + if in.Season == nil || len(ns) == 0 { + return false + } + for _, n := range ns { + count := 0 + for _, w := range in.Season.Same(n.week, baseloadMinYears) { + if w.BaseW > 0 { + count++ + } + } + if count < baseloadMinYears { + return false + } + } + return true +} + // baseloadDevice returns the device whose average night power rose by at least // half of the shift from the nights before at to the nights from at on, the one // with the largest rise. The empty string when no device qualifies. diff --git a/dashboard/internal/autolearn/detect_baseload_test.go b/dashboard/internal/autolearn/detect_baseload_test.go index 523ce83f..cbf9a592 100644 --- a/dashboard/internal/autolearn/detect_baseload_test.go +++ b/dashboard/internal/autolearn/detect_baseload_test.go @@ -2,6 +2,7 @@ package autolearn import ( "context" + "fmt" "testing" "time" ) @@ -213,3 +214,35 @@ func TestBaseLoadCUSUMFindsSustainedRiseOnly(t *testing.T) { t.Errorf("fall gave a drift") } } + +// blSeason is a season store with the night base load of the fixture weeks in +// the three years before the current year. +func blSeason(baseW float64) *SeasonStore { + s := LoadSeasonStore("", func(string, ...any) {}) + year := time.Now().Year() + for k := 1; k <= 3; k++ { + for w := 30; w <= 45; w++ { + s.Put(Week{Key: fmt.Sprintf("%d-W%02d", year-k, w), Source: seasonSourceDays, Days: 7, BaseW: baseW}) + } + } + return s +} + +func TestBaseLoadDriftWithSeasonNeedsOnlyFourteenNights(t *testing.T) { + in := blInput(20, func(i int) float64 { + if i < 10 { + return 180 + } + return 260 + }, nil) + in.Devices = map[string]DeviceInfo{} + in.Season = blSeason(180) + findings, _ := blSplit(in) + if len(findings) != 1 { + t.Fatalf("20 nights with a season expectation gave %d findings, want 1", len(findings)) + } + in.Season = nil + if findings, _ := blSplit(in); len(findings) != 0 { + t.Fatalf("20 nights without a season gave %d findings, want none", len(findings)) + } +} From 478916842687e0b30a1891f5b4f182b7f2843f60 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:17:32 +0100 Subject: [PATCH 26/37] feat(autolearn): seed earlier years instead of doubling the demo days Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/autolearn/demo.go | 39 +++++++++++-------- dashboard/internal/autolearn/demo_test.go | 35 ++++++++++++++--- .../devices/demo/automation_rules.json | 2 +- 3 files changed, 52 insertions(+), 24 deletions(-) diff --git a/dashboard/internal/autolearn/demo.go b/dashboard/internal/autolearn/demo.go index 3915e6d9..422e4505 100644 --- a/dashboard/internal/autolearn/demo.go +++ b/dashboard/internal/autolearn/demo.go @@ -43,10 +43,13 @@ const ( // die Grundlast um demoRiseW hebt. TUNABLE demoRiseFrom = 12 // demoRiseW ist der Anstieg der Grundlast in W. TUNABLE - demoRiseW = 80.0 + demoRiseW = 200.0 // demoPriorWeeks ist die Zahl der Wochen vor now, für die das Vorjahr einen - // Anteil leerer Morgen trägt. Sie deckt die 42 Demo-Tage ab. - demoPriorWeeks = 8 + // Anteil leerer Morgen trägt. Sie deckt die 21 Demo-Tage plus die Nachbarwoche ab. + demoPriorWeeks = 5 + // demoSeasonBaseW ist die Grundlast der Vorjahreswochen in W, so hoch wie die + // Nächte der Demo vor dem Anstieg. TUNABLE + demoSeasonBaseW = 290.0 // demoPlugOffMin ist die Abschaltzeit der Balkonsteckdose, 22:30 in Minuten. demoPlugOffMin = 1350 @@ -110,8 +113,8 @@ var demoEntities = map[string]string{ // demoWatts ist die Leistung der Demo-Geräte, wenn sie laufen. var demoWatts = map[string]float64{demoPlugBalkon: 60, demoPlugDry: 300, demoRelais: 500, demoHeatPump: 1500, demoWasherDevice: 2000} -// SeedDemo schreibt die Tagesdateien der letzten 42 Tage vor now in dir (zweimal -// das 21-Tage-Muster), für die Geräte der Demo. Jede Datei trägt "fake": true, die Konsole der Demo entfernt +// SeedDemo schreibt die Tagesdateien der letzten 21 Tage vor now in dir, für die +// Geräte der Demo. Jede Datei trägt "fake": true, die Konsole der Demo entfernt // nur solche. Das Ergebnis ist fest, derselbe Aufruf schreibt dieselben Bytes. // Der Aufrufer prüft, ob dir leer ist. func SeedDemo(dir string, now time.Time, loc *time.Location) error { @@ -119,11 +122,7 @@ func SeedDemo(dir string, now time.Time, loc *time.Location) error { loc = time.Local } store := &DayStore{dir: dir} - // Vor den 21 Tagen liegt dasselbe Muster ein zweites Mal, ohne Anstieg. So hat - // die Grundlast genug Nächte für ihre Referenz. - days := demoDaysWith(now.In(loc).AddDate(0, 0, -demoSeedDays), loc, false) - days = append(days, demoDays(now.In(loc), loc)...) - for _, f := range days { + for _, f := range demoDays(now.In(loc), loc) { if err := store.writeFile(f.Day, f); err != nil { return fmt.Errorf("autolearn: demo seed: %w", err) } @@ -689,13 +688,19 @@ func DemoSeason(now time.Time) []Week { Learned: map[string]float64{demoBedtimeKey: demoBedtimeMin + 6*math.Sin(float64(k))}, }) } - // Dieselben Wochen ein Jahr früher: der Akku war damals selten leer. Damit - // meldet die Demo „Akku ist nachts leer“. - share := 0.1 - for k := 0; k <= demoPriorWeeks; k++ { - y, w := now.AddDate(0, 0, -7*k).ISOWeek() - s := share - out = append(out, Week{Key: fmt.Sprintf("%d-W%02d", y-1, w), Source: seasonSourceDays, Days: 7, EmptyShare: &s}) + // Dieselben Wochen in den zwei Jahren davor: der Akku war damals selten leer, + // und die Grundlast lag nachts bei demoSeasonBaseW. Damit meldet die Demo + // „Akku ist nachts leer“ und „Grundlast steigt“ schon nach 21 Tagen. + for back := 1; back <= 2; back++ { + for k := 0; k <= demoPriorWeeks; k++ { + y, w := now.AddDate(0, 0, -7*k).ISOWeek() + week := Week{Key: fmt.Sprintf("%d-W%02d", y-back, w), Source: seasonSourceDays, Days: 7, BaseW: demoSeasonBaseW} + if back == 1 { + share := 0.1 + week.EmptyShare = &share + } + out = append(out, week) + } } return out } diff --git a/dashboard/internal/autolearn/demo_test.go b/dashboard/internal/autolearn/demo_test.go index aa01b3f7..943a35ff 100644 --- a/dashboard/internal/autolearn/demo_test.go +++ b/dashboard/internal/autolearn/demo_test.go @@ -339,8 +339,8 @@ func TestDemoSeedWritesGzipDayFilesAndIsDeterministic(t *testing.T) { if err != nil { t.Fatal(err) } - if len(entries) != 2*demoSeedDays { - t.Fatalf("files = %d, want %d", len(entries), 2*demoSeedDays) + if len(entries) != demoSeedDays { + t.Fatalf("files = %d, want %d", len(entries), demoSeedDays) } for _, e := range entries { a, err := os.ReadFile(filepath.Join(dirA, e.Name())) @@ -450,8 +450,8 @@ func TestDemoOutdoorSensorIsInBrokerAndSettings(t *testing.T) { func TestDemoSeasonYearCourseOfBedtime(t *testing.T) { now := time.Date(2026, 11, 21, 9, 0, 0, 0, berlinLoc(t)) weeks := DemoSeason(now) - if len(weeks) != demoSeasonWeeks+demoPriorWeeks+1 || demoSeasonWeeks < 20 { - t.Fatalf("season weeks = %d, want %d (at least 20)", len(weeks), demoSeasonWeeks+demoPriorWeeks+1) + if len(weeks) != demoSeasonWeeks+2*(demoPriorWeeks+1) || demoSeasonWeeks < 20 { + t.Fatalf("season weeks = %d, want %d (at least 20)", len(weeks), demoSeasonWeeks+2*(demoPriorWeeks+1)) } count := 0 for _, w := range weeks { @@ -530,11 +530,10 @@ func TestDemoSeedClockAndSunHabitsContrast(t *testing.T) { codes[c.Finding.ID] = c.Finding.Summary.Code } } - // With 42 days the relay carries the sun habit of switching on, the balcony plug follows it by coupling. want := map[string]string{ "switch_time:" + demoRelais + ":off:0:1830": "switch_time.sun_off", "switch_time:" + demoPlugBalkon + ":off:0:2230": "switch_time.off", - "switch_time:" + demoRelais + ":on:0:1700": "switch_time.sun_on", + "switch_time:" + demoPlugBalkon + ":on:0:1700": "switch_time.sun_on", } for id, code := range want { if codes[id] != code { @@ -708,6 +707,30 @@ func TestDemoSeedYieldsEnergyFindings(t *testing.T) { t.Errorf("no %s finding in the demo pipeline, ids %v", id, ids) } } + for _, c := range demoEngineRun(t, t.TempDir(), now, loc).Candidates() { + if c.Finding.Kind == "baseload" && (c.Finding.Device != "" || c.Finding.Group != "check") { + t.Errorf("baseload finding device %q group %q, want no culprit and group check", c.Finding.Device, c.Finding.Group) + } + if c.Finding.ID == "battery:empty" && c.Finding.Group != "check" { + t.Errorf("battery:empty group %q, want check without culprit", c.Finding.Group) + } + } +} + +// TestDemoSeedKeepsTheHabitSuggestions checks the suggestions the demo had +// before the energy findings: run time of the dehumidifier and the away standby. +func TestDemoSeedKeepsTheHabitSuggestions(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 20, 9, 0, 0, 0, loc) + ids := map[string]bool{} + for _, c := range demoEngineRun(t, t.TempDir(), now, loc).Candidates() { + ids[c.Finding.ID] = true + } + for _, id := range []string{"runtime:plug_entfeuchter", "away_standby:waermepumpe"} { + if !ids[id] { + t.Errorf("no %s in the demo pipeline, ids %v", id, ids) + } + } } // TestDemoPVYearRestsTheFeedInRule checks that the demo year raster knows the diff --git a/demo/fixtures/devices/demo/automation_rules.json b/demo/fixtures/devices/demo/automation_rules.json index 936d11fd..996e5ee9 100644 --- a/demo/fixtures/devices/demo/automation_rules.json +++ b/demo/fixtures/devices/demo/automation_rules.json @@ -141,7 +141,7 @@ "enabled": true, "cooldown_seconds": 600, "conditions": [ - {"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 2200, "hysteresis": 100, "hold_seconds": 60} + {"type": "balance_threshold", "field": "grid_export", "comparison": "above", "threshold": 2600, "hysteresis": 100, "hold_seconds": 60} ], "actions": [ {"type": "publish", "topic": "plug/entfeuchter/output/set", "payload_source": "constant", "payload": "ON"} From c1014812f8f2c54b4aa8a62d7c331f38c651efc7 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:18:41 +0100 Subject: [PATCH 27/37] feat(demo): publish the automation state when the console starts Co-Authored-By: Claude Opus 5.5 --- demo/fakes/console_autolearn.py | 5 +++++ demo/fakes/fake_console.py | 12 ++++++++++-- demo/fakes/test_console_autolearn.py | 12 ++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/demo/fakes/console_autolearn.py b/demo/fakes/console_autolearn.py index 486e5a4a..305f11a5 100644 --- a/demo/fakes/console_autolearn.py +++ b/demo/fakes/console_autolearn.py @@ -471,6 +471,11 @@ def _publish_state(self) -> None: for rule in rules if "id" in rule}, }) + def publish_now(self) -> None: + """Veroeffentlicht den Zustand einmal, etwa kurz nach dem Start der Konsole.""" + with self._lock: + self._publish_state() + def _trigger(self, body: dict) -> str: scenario = BY_ID.get(body.get("scenario")) if scenario is None or not scenario.get("triggerable"): diff --git a/demo/fakes/fake_console.py b/demo/fakes/fake_console.py index a4995537..e18a6031 100644 --- a/demo/fakes/fake_console.py +++ b/demo/fakes/fake_console.py @@ -51,6 +51,7 @@ import json import os import sys +import threading import urllib.parse from pathlib import Path @@ -58,6 +59,8 @@ from fakelog import Log DEFAULT_PORT = 18102 +# Sekunden nach dem Start, bis die Konsole den Zustand der Automationen veröffentlicht. +AUTOLEARN_STATE_DELAY_S = 5.0 class Tab: @@ -243,9 +246,14 @@ def build_tabs(args: argparse.Namespace, log: Log) -> list[Tab]: tabs.append(PerformanceTab(log, Path(args.performance_state))) if args.automation_rules or args.data_dir: from console_autolearn import AutolearnTab - tabs.append(AutolearnTab(log, Path(args.automation_rules) if args.automation_rules else None, + autolearn = AutolearnTab(log, Path(args.automation_rules) if args.automation_rules else None, args.broker_control, - Path(args.data_dir) if args.data_dir else None)) + Path(args.data_dir) if args.data_dir else None) + tabs.append(autolearn) + # Die Regelprüfung kennt die Regeln erst mit ihrem Zustand: einmal kurz nach dem Start. + timer = threading.Timer(AUTOLEARN_STATE_DELAY_S, autolearn.publish_now) + timer.daemon = True + timer.start() if args.highlights_repo: from console_highlights import HighlightsTab installer = Path(args.installer_state) if args.installer_state else None diff --git a/demo/fakes/test_console_autolearn.py b/demo/fakes/test_console_autolearn.py index 7d29678e..d020228b 100644 --- a/demo/fakes/test_console_autolearn.py +++ b/demo/fakes/test_console_autolearn.py @@ -648,3 +648,15 @@ def test_pv_throttle_needs_a_bool_and_the_broker(rules_path, broker): AutolearnTab(Log(), rules_path, url).act("pv_throttle", {"on": "ja"}) with pytest.raises(ValueError): AutolearnTab(Log(), rules_path).act("pv_throttle", {"on": True}) + + +def test_publish_now_publishes_zero_counts_once(rules_path, broker): + url, posts = broker + tab = AutolearnTab(Log(), rules_path, url) + + tab.publish_now() + + doc = _document(rules_path) + states = _states(posts) + assert len(states) == 1 + assert states[0]["rules"] == {r["id"]: {"trigger_count": 0} for r in doc["rules"]} From 43ae2f6ce6a005835f8d41cb1591f939271aee6f Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:32:51 +0100 Subject: [PATCH 28/37] feat(autolearn): show the Soll charge of the battery findings Co-Authored-By: Claude Opus 5.5 --- .../internal/autolearn/detect_battery.go | 55 ++++++++++++++++--- .../internal/autolearn/detect_battery_test.go | 55 +++++++++++++++++++ 2 files changed, 103 insertions(+), 7 deletions(-) diff --git a/dashboard/internal/autolearn/detect_battery.go b/dashboard/internal/autolearn/detect_battery.go index b67e6696..b07f3e6f 100644 --- a/dashboard/internal/autolearn/detect_battery.go +++ b/dashboard/internal/autolearn/detect_battery.go @@ -318,7 +318,7 @@ func batteryFull(days []*batteryDay) []Candidate { "time": batteryClock(Median(at)), "kwh_after": round1(Median(kwh)), }}, - Evidence: batteryEvidence(days), + Evidence: batteryFullEvidence(hits[len(hits)-1]), } return []Candidate{{ Finding: finding, @@ -405,7 +405,7 @@ func batteryEmpty(in *Input, days []*batteryDay) []Candidate { "kwh_missing": round1(kwh), "candidates": strings.Join(names, ", "), }}, - Evidence: batteryEvidence(days), + Evidence: batteryEmptyEvidence(hits[len(hits)-1]), Apply: apply, Benefit: &Benefit{Unit: "kwh_week", Value: kwh * batteryWeekDays}, } @@ -538,16 +538,57 @@ func batteryLearned(in *Input, days []*batteryDay) []Candidate { return out } -// batteryEvidence shows the charge of the last day as the curve, in percent. -func batteryEvidence(days []*batteryDay) Evidence { - last := days[len(days)-1].f +// batteryCurve is the charge of a day per quarter, 0 where it is missing. +func batteryCurve(f *DayFile) []float32 { curve := make([]float32, dayQuarters) for q := 0; q < dayQuarters; q++ { - if v := last.Site.SoC[q]; v != nil { + if v := f.Site.SoC[q]; v != nil { curve[q] = *v } } - return Evidence{Shape: "curve", Quarters: curve, Unit: "%"} + return curve +} + +// batteryFullEvidence shows the charge of the last early full day as Ist. The +// Soll is the same day reaching full only at the highest sun: from the start +// of the charge it rises evenly and is full at noon, so the surplus of the +// morning can go to loads first. +func batteryFullEvidence(d *batteryDay) Evidence { + ist := batteryCurve(d.f) + soll := append([]float32(nil), ist...) + noonQ := int(math.Round((d.rise + d.set) / 2 / baseQuarterMin)) + if d.sunOK && d.fullQ > 0 && noonQ > d.fullQ && noonQ < dayQuarters { + start := d.fullQ + for start > 0 && ist[start-1] < ist[start] { + start-- + } + from, to := float64(ist[start]), float64(ist[d.fullQ]) + for q := start; q <= noonQ; q++ { + soll[q] = float32(from + (to-from)*float64(q-start)/float64(noonQ-start)) + } + } + return Evidence{Shape: "curve", Quarters: ist, SollQ: soll, Unit: "%"} +} + +// batteryEmptyEvidence shows the charge of the last night that ran empty as +// Ist. The Soll keeps the charge batteryEmptyMargin above the empty threshold +// until the charge rises again after sunrise. +func batteryEmptyEvidence(d *batteryDay) Evidence { + ist := batteryCurve(d.f) + soll := append([]float32(nil), ist...) + if d.hasThr && d.sunOK { + floor := float32(d.thr + batteryEmptyMargin) + riseQ := int(d.rise / baseQuarterMin) + for q := 0; q < dayQuarters; q++ { + if q >= riseQ && ist[q] >= floor { + break + } + if soll[q] < floor { + soll[q] = floor + } + } + } + return Evidence{Shape: "curve", Quarters: ist, SollQ: soll, Unit: "%"} } // batteryHalves reports whether the first and the second half of the days both diff --git a/dashboard/internal/autolearn/detect_battery_test.go b/dashboard/internal/autolearn/detect_battery_test.go index 19ef5240..25d3fa24 100644 --- a/dashboard/internal/autolearn/detect_battery_test.go +++ b/dashboard/internal/autolearn/detect_battery_test.go @@ -270,3 +270,58 @@ func TestEmptyShareOfNeedsFourDaysAndSun(t *testing.T) { t.Errorf("without a site gave a share, want none") } } + +// batteryTestDay is a day with the charge of soc(q) per quarter. +func batteryTestDay(soc func(q int) float32) *DayFile { + f := &DayFile{} + for q := 0; q < dayQuarters; q++ { + v := soc(q) + f.Site.SoC[q] = &v + } + return f +} + +func TestBatteryFullEvidenceIsFullOnlyAtNoon(t *testing.T) { + f := batteryTestDay(func(q int) float32 { + switch { + case q < 32: + return 10 + case q < 40: + return 10 + float32(q-32)*87/8 + default: + return 97 + } + }) + d := &batteryDay{f: f, sunOK: true, rise: 7 * 60, set: 17 * 60, fullQ: 40} + ev := batteryFullEvidence(d) + if len(ev.Quarters) != dayQuarters || len(ev.SollQ) != dayQuarters { + t.Fatalf("ist %d, soll %d quarters, want %d each", len(ev.Quarters), len(ev.SollQ), dayQuarters) + } + if ev.SollQ[48] != 97 { + t.Errorf("Soll at noon = %v, want full 97", ev.SollQ[48]) + } + if !(ev.SollQ[44] > 10 && ev.SollQ[44] < ev.Quarters[44]) { + t.Errorf("Soll at 11:00 = %v, want between 10 and the Ist %v", ev.SollQ[44], ev.Quarters[44]) + } + if ev.SollQ[0] != ev.Quarters[0] || ev.SollQ[60] != ev.Quarters[60] { + t.Errorf("Soll must follow the Ist before the charge and after noon") + } +} + +func TestBatteryEmptyEvidenceKeepsTheFloorUntilSunrise(t *testing.T) { + f := batteryTestDay(func(q int) float32 { + if q < 32 { + return 6 + } + return 6 + float32(q-32)*2 + }) + d := &batteryDay{f: f, sunOK: true, rise: 7*60 + 30, set: 17 * 60, hasThr: true, thr: 9} + ev := batteryEmptyEvidence(d) + floor := float32(9 + batteryEmptyMargin) + if ev.SollQ[10] != floor || ev.SollQ[31] != floor { + t.Errorf("Soll before sunrise = %v/%v, want the floor %v", ev.SollQ[10], ev.SollQ[31], floor) + } + if ev.SollQ[50] != ev.Quarters[50] { + t.Errorf("Soll after the charge rose = %v, want the Ist %v", ev.SollQ[50], ev.Quarters[50]) + } +} From a5ff2af4fc3030739f0c8ba1086b4ffc19d24123 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:33:04 +0100 Subject: [PATCH 29/37] feat(monitoring): list every suggestion as a notice The monitoring collects the visible suggestions of the band and turns each one into a notice whose step opens the suggestion on the automations page. Monitoring stays quiet while the pattern learning is off, as the endpoint does. Co-Authored-By: Claude Opus 5.5 --- dashboard/cmd/dashboard/main.go | 13 ++++++++ dashboard/internal/monitoring/notice.go | 31 ++++++++++++++++++++ dashboard/internal/monitoring/notice_test.go | 28 ++++++++++++++++++ 3 files changed, 72 insertions(+) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index fa6b9cb5..c048abf0 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -646,12 +646,18 @@ func main() { learnHub.AddSaver("learned", learnedStore) // 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 + // Vorschlagsbuch steht, und vor dem Start der Lernschleifen. + var monitoringSuggestions func() []autolearn.Finding collectMonitoring := func() monitoring.Input { in := monitoring.Input{Snapshot: energy.Aggregate(reg.Snapshot(), energyResolver, time.Now().UTC())} if value, err := settingsStore.LoadEnergy(); err == nil { in.Config = value } in.Findings = automationChecker.Findings(time.Now()) + if monitoringSuggestions != nil { + in.Suggestions = monitoringSuggestions() + } return in } monitoringStore := monitoring.OpenStore(filepath.Join(autolearnDir, "monitoring.json"), log.Printf) @@ -695,6 +701,13 @@ func main() { _, ok := reg.Get(device) return ok } + monitoringSuggestions = func() []autolearn.Finding { + // Wie der Vorschlags-Endpunkt: bei abgeschaltetem Muster-Lernen keine Vorschlaege. + if value, err := settingsStore.LoadSettings(); err == nil && value.AutomationPatternsDisabled { + return nil + } + return suggestions.Visible(time.Now(), suggestionExists) + } origin := newOriginLearner(originTracker, dayStore, reg, func() ([]byte, error) { return configManager.Read("automation_rules") }) origin.rebuild() diff --git a/dashboard/internal/monitoring/notice.go b/dashboard/internal/monitoring/notice.go index 9908c252..1d6394cc 100644 --- a/dashboard/internal/monitoring/notice.go +++ b/dashboard/internal/monitoring/notice.go @@ -45,6 +45,9 @@ type Input struct { Snapshot energy.Snapshot Config settings.EnergyConfig Findings []autolearn.Finding + // 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 } // Collect baut die Meldungen in fester Reihenfolge: energy, chain, learn. @@ -53,6 +56,7 @@ func Collect(in Input) []Notice { out = append(out, energyNotices(in)...) out = append(out, chainNotices(in.Snapshot)...) out = append(out, learnNotices(in.Findings)...) + out = append(out, suggestionNotices(in.Suggestions)...) return out } @@ -224,3 +228,30 @@ func learnNotices(findings []autolearn.Finding) []Notice { } return out } + +// suggestionNotices turns the visible suggestions into notices. The step opens +// the suggestion on the automations page. +func suggestionNotices(list []autolearn.Finding) []Notice { + var out []Notice + for _, f := range list { + params := make(map[string]any, len(f.Summary.Params)+1) + for k, v := range f.Summary.Params { + params[k] = v + } + params["kind"] = f.Kind + n := Notice{ + ID: "suggest:" + f.ID, + Source: "learn", + Severity: learnSeverity(f.Severity), + Code: f.Summary.Code, + Params: params, + Steps: []Step{{Code: "suggestion_open", Target: "suggestion", IDs: []string{f.ID}}}, + } + if f.Evidence.Shape != "" { + ev := f.Evidence + n.Evidence = &ev + } + out = append(out, n) + } + return out +} diff --git a/dashboard/internal/monitoring/notice_test.go b/dashboard/internal/monitoring/notice_test.go index 5a033637..176783aa 100644 --- a/dashboard/internal/monitoring/notice_test.go +++ b/dashboard/internal/monitoring/notice_test.go @@ -94,3 +94,31 @@ func TestCollectLearnOnlyRulelessWithoutApply(t *testing.T) { t.Errorf("steps = %v", codes) } } + +func TestSuggestionsBecomeNoticesThatOpenTheSuggestion(t *testing.T) { + in := Input{Suggestions: []autolearn.Finding{{ + ID: "runtime:plug", Kind: "runtime", Severity: "info", + Summary: autolearn.Text{Code: "runtime.long", Params: map[string]any{"device": "Plug"}}, + Evidence: autolearn.Evidence{Shape: "scale"}, + }}} + var got *Notice + for _, n := range Collect(in) { + if n.ID == "suggest:runtime:plug" { + n := n + got = &n + } + } + if got == nil { + t.Fatal("no notice for the suggestion") + } + if got.Source != "learn" || got.Code != "runtime.long" || got.Params["device"] != "Plug" || got.Params["kind"] != "runtime" { + t.Errorf("notice = %+v", got) + } + if len(got.Steps) != 1 || got.Steps[0].Code != "suggestion_open" || got.Steps[0].Target != "suggestion" || + len(got.Steps[0].IDs) != 1 || got.Steps[0].IDs[0] != "runtime:plug" { + t.Errorf("steps = %+v, want one suggestion_open step with the suggestion id", got.Steps) + } + if got.Evidence == nil || got.Evidence.Shape != "scale" { + t.Errorf("evidence = %+v, want the suggestion evidence", got.Evidence) + } +} From 5f880ad1a72b0f2a592768b733f58939f230ead6 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:33:36 +0100 Subject: [PATCH 30/37] feat(automations): draw Ist and Soll curves in one chart Co-Authored-By: Claude Opus 5.5 --- .../internal/webui/static/css/automations.css | 15 ++++++++++ .../webui/static/js/automation-evidence.js | 30 ++++++++++++++----- dashboard/test/automation-evidence.test.mjs | 30 +++++++++++++++++-- 3 files changed, 65 insertions(+), 10 deletions(-) diff --git a/dashboard/internal/webui/static/css/automations.css b/dashboard/internal/webui/static/css/automations.css index cf8c46c8..26bd3836 100644 --- a/dashboard/internal/webui/static/css/automations.css +++ b/dashboard/internal/webui/static/css/automations.css @@ -993,6 +993,19 @@ label.settings-toggle.auto-assist-check .settings-toggle-track { flex: none; wid .auto-learn-lane-svg .auto-learn-clear { fill: none; stroke: var(--accent); stroke-opacity: .45; stroke-width: 1.5; stroke-linejoin: round; } .auto-learn-lane-svg .auto-learn-best { fill: none; stroke: var(--accent); stroke-width: 2; stroke-linejoin: round; } .auto-learn-lane-svg .auto-learn-throttled { fill: var(--accent-bg); stroke: none; } +/* Kurven: Ist und Soll in einem Koordinatensystem, so hoch wie zwei Spuren samt Abstand */ +.auto-learn-plot { display: grid; grid-template-columns: 2.2rem minmax(0, 1fr); gap: .5rem; align-items: stretch; } +.auto-learn-plot-legend { display: flex; flex-direction: column; justify-content: center; gap: .35rem; } +.auto-learn-plot-key { font-size: .72rem; font-weight: 600; line-height: 1; color: var(--text-muted); } +.auto-learn-plot-key.is-soll { color: var(--accent-line); } +.auto-learn-plot-area { position: relative; min-width: 0; height: 40px; background: var(--sunken); border-radius: 5px; } +.auto-learn-plot-svg { position: absolute; inset: 0; display: block; width: 100%; height: 100%; } +.auto-learn-plot-svg .auto-learn-grid { stroke: var(--text-faint); stroke-opacity: .35; stroke-width: 1; } +.auto-learn-plot-svg .auto-learn-curve.auto-learn-ist { fill: none; stroke: var(--flow-rest); stroke-width: 2; stroke-linejoin: round; } +.auto-learn-plot-svg .auto-learn-soll-line { fill: none; stroke: var(--accent); stroke-width: 2; stroke-linejoin: round; } +.auto-learn-plot-svg .auto-learn-clear { fill: none; stroke: var(--accent); stroke-opacity: .45; stroke-width: 1.5; stroke-linejoin: round; } +.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; } .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; } @@ -1009,6 +1022,7 @@ label.settings-toggle.auto-assist-check .settings-toggle-track { flex: none; wid .auto-learn-target.is-missing { color: var(--bad); background: transparent; border: 1px dashed var(--bad-line); } /* Soll erscheint nach dem Ist: einmal beim Oeffnen, von links */ .auto-learn-lane.is-soll .auto-learn-lane-svg { animation: auto-learn-trace 280ms var(--ease-out) 120ms both; } +.auto-learn-plot-svg.is-soll { animation: auto-learn-trace 280ms var(--ease-out) 120ms both; } @keyframes auto-learn-trace { from { clip-path: inset(0 100% 0 0 round 5px); } to { clip-path: inset(0 0 0 0 round 5px); } } /* Neue Grafik nach dem Umschalten: blendet ein, ohne Bewegung bei reduzierter Bewegung */ @keyframes auto-learn-chart-in { from { opacity: 0; transform: scale(.985); } to { opacity: 1; transform: none; } } @@ -1027,6 +1041,7 @@ label.settings-toggle.auto-assist-check .settings-toggle-track { flex: none; wid .auto-learn-mark:active { transform: none; } .auto-learn-pop { animation-name: auto-learn-fade; } .auto-learn-lane.is-soll .auto-learn-lane-svg { animation: none; } + .auto-learn-plot-svg.is-soll { animation: none; } .auto-learn-is { animation-name: auto-learn-chart-fade; } .auto-learn-zoom-btn { transition: none; } .auto-learn-zoom-btn:active { transform: none; } diff --git a/dashboard/internal/webui/static/js/automation-evidence.js b/dashboard/internal/webui/static/js/automation-evidence.js index b640baa7..e2959320 100644 --- a/dashboard/internal/webui/static/js/automation-evidence.js +++ b/dashboard/internal/webui/static/js/automation-evidence.js @@ -62,8 +62,8 @@ } // Hilfslinien hinter den Balken, an den Hauptmarken der Achse. - function gridLines(xs) { - return xs.map((x) => '').join(''); + function gridLines(xs, height = 10) { + return xs.map((x) => '').join(''); } function spans(list, from, to, cls) { @@ -322,6 +322,7 @@ + axisHtml(ticks, labels); } + // Ist und Soll teilen eine Kurvenflaeche, die Soll-Ebene liegt ueber der Ist-Ebene. // Tageskurve aus 96 Viertelstunden in W. Ist als Linie, Soll-Spur mit Klarhimmel-Kurve, Bestkurve // gestrichelt und die abgeregelte Flaeche zwischen Best und Ist, wo die Bestkurve darueber liegt. const CURVE_N = 96; @@ -338,7 +339,13 @@ } const curveX = (i) => round((i / CURVE_N) * 100); - const curveY = (v, max) => round(9.5 - (Math.max(0, v) / max) * 9); + // Ist und Soll teilen ein Koordinatensystem, so hoch wie zwei Spuren. + const PLOT_H = 20; + const curveY = (v, max) => round(PLOT_H - 0.5 - (Math.max(0, v) / max) * (PLOT_H - 1)); + + function plotSvg(inner, soll) { + return ''; // i18n-ignore + } function curveShape(ev, t) { const ist = curveSeries(ev.ist_q); @@ -370,17 +377,24 @@ + r.map((i) => point(i, bestAt.get(i))).concat(r.slice().reverse().map((i) => point(i, istAt.get(i)))).join(' ') + '"/>').join(''); // i18n-ignore const hours = CURVE_HOURS.map((h) => h * 60); - const grid = gridLines(hours.map((m) => (m / DAY) * 100)); + const grid = gridLines(hours.map((m) => (m / DAY) * 100), PLOT_H); const istBody = grid + line(ist, 'auto-learn-ist auto-learn-curve', false); // i18n-ignore - const sollBody = grid + throttled + line(soll, 'auto-learn-clear', false) + line(best, 'auto-learn-best', true); // i18n-ignore + // Mit Bestkurve (Verschattung) ist Soll die Klarhimmel-Referenz, sonst die Sollkurve selbst. + const sollCls = best.length > 0 ? 'auto-learn-clear' : 'auto-learn-soll-line'; // i18n-ignore + const sollBody = throttled + line(soll, sollCls, false) + line(best, 'auto-learn-best', true); // i18n-ignore + const hasSoll = soll.length > 0 || best.length > 0; const ticks = []; for (let h = 0; h <= 24; h++) { ticks.push({ x: (h / 24) * 100, major: CURVE_HOURS.indexOf(h) >= 0 }); } const labels = hours.map((m) => ({ x: (m / DAY) * 100, text: clockText(m, true) })); - return lane(t('automations.learn.lane.ist'), laneSvg(istBody)) // i18n-ignore - + lane(t('automations.learn.lane.soll'), laneSvg(sollBody), true) - + axisHtml(ticks, labels); + const legend = '
' // i18n-ignore + + '' + esc(t('automations.learn.lane.ist')) + '' // i18n-ignore + + (hasSoll ? '' + esc(t('automations.learn.lane.soll')) + '' : '') // i18n-ignore + + '
'; + return '
' + legend + '
' // i18n-ignore + + plotSvg(istBody, false) + (hasSoll ? plotSvg(sollBody, true) : '') + + '
' + axisHtml(ticks, labels); } function chips(names) { diff --git a/dashboard/test/automation-evidence.test.mjs b/dashboard/test/automation-evidence.test.mjs index b7d17b25..9b8fd4a7 100644 --- a/dashboard/test/automation-evidence.test.mjs +++ b/dashboard/test/automation-evidence.test.mjs @@ -337,7 +337,7 @@ test('unknown shape or missing evidence renders an empty string', () => { const quarters = (fn) => Array.from({ length: 96 }, (_, i) => fn(i)); -test('curve shape draws exactly one dashed line, the best curve, in the Soll lane', () => { +test('curve shape draws exactly one dashed line, the best curve, in the Soll layer', () => { const { api, document } = load(); const html = api.render({ shape: 'curve', @@ -349,7 +349,7 @@ test('curve shape draws exactly one dashed line, the best curve, in the Soll lan const dashed = host.querySelectorAll('polyline[stroke-dasharray]'); assert.equal(dashed.length, 1); assert.equal(dashed[0].classList.contains('auto-learn-best'), true); - assert.equal(dashed[0].closest('.auto-learn-lane.is-soll') !== null, true); + assert.equal(dashed[0].closest('.auto-learn-plot-svg.is-soll') !== null, true); assert.equal(dashed[0].getAttribute('points').trim().split(/\s+/).length, 96); assert.equal(host.querySelectorAll('polyline.auto-learn-ist').length, 1); }); @@ -391,3 +391,29 @@ test('prototype keys are not shapes', () => { assert.equal(api.render({ shape }, t), '', shape); }); }); + +test('curve shape puts Ist and Soll into one plot as high as two lanes', () => { + const { api, document } = load(); + const host = mount(document, api.render({ + shape: 'curve', + unit: '%', + ist_q: quarters((i) => (i < 40 ? 10 : 97)), + soll_q: quarters((i) => (i < 48 ? 10 + i : 97)), + }, t)); + assert.equal(host.querySelectorAll('.auto-learn-plot').length, 1); + assert.equal(host.querySelectorAll('.auto-learn-lane').length, 0, 'no separate lanes'); + const svgs = host.querySelectorAll('.auto-learn-plot-area > svg.auto-learn-plot-svg'); + assert.equal(svgs.length, 2); + svgs.forEach((svg) => assert.equal(svg.getAttribute('viewBox'), '0 0 100 20')); + assert.equal(svgs[1].classList.contains('is-soll'), true); + assert.equal(svgs[1].querySelectorAll('polyline.auto-learn-soll-line').length, 1); + assert.equal(svgs[0].querySelectorAll('polyline.auto-learn-ist').length, 1); + assert.equal(host.querySelectorAll('.auto-learn-plot-key').length, 2); +}); + +test('curve shape without Soll draws only the Ist layer and one legend key', () => { + const { api, document } = load(); + const host = mount(document, api.render({ shape: 'curve', ist_q: quarters(() => 50) }, t)); + assert.equal(host.querySelectorAll('svg.auto-learn-plot-svg').length, 1); + assert.equal(host.querySelectorAll('.auto-learn-plot-key').length, 1); +}); From 9eaa37c2d8e76c1c93ed37dd58b2b932f829b3dc Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:35:09 +0100 Subject: [PATCH 31/37] feat(monitoring): open the suggestion from its notice A suggestion notice opens the suggestion on the automations page. The band opens the requested suggestion, widening its list when the suggestion is beyond the first rows. Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/webui/catalogs/de.json | 2 ++ dashboard/internal/webui/catalogs/en.json | 2 ++ .../webui/static/js/automation-suggestions.js | 19 +++++++++++++ .../webui/static/js/monitoring-model.js | 25 +++++++++++++---- .../webui/static/js/monitoring.page.js | 11 ++++++++ .../internal/webui/templates/automations.html | 1 + dashboard/internal/webui/templates/base.html | 2 +- .../test/automation-suggestions.test.mjs | 27 +++++++++++++++++++ dashboard/test/monitoring-model.test.mjs | 10 +++++++ 9 files changed, 93 insertions(+), 6 deletions(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 8b91075f..dffaf9de 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -3725,6 +3725,8 @@ "monitoring.step.set_role.button": "Rollen setzen", "monitoring.step.shade_accept": "Lässt sich der Schatten nicht beseitigen, ist nichts zu tun. Rest-Überschuss und Überschussfenster rechnen ihn schon heraus.", "monitoring.step.shade_look": "Vor Ort nach der Ursache schauen: Baum, Antenne, Nachbarhaus oder Schornstein in Richtung {direction}, etwa {height}° hoch.", + "monitoring.step.suggestion_open": "Der Vorschlag steht unter Automationen", + "monitoring.step.suggestion_open.button": "Vorschlag öffnen", "monitoring.steps.title": "Empfohlene Schritte", "monitoring.value.time": "{time} Uhr", "monitoring.view.label": "Ansicht", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index ad7345dc..cec48d76 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -3725,6 +3725,8 @@ "monitoring.step.set_role.button": "Set roles", "monitoring.step.shade_accept": "If the shade cannot be removed, there is nothing to do. The remaining surplus and the surplus window already leave it out.", "monitoring.step.shade_look": "Look for the cause on site: a tree, an antenna, a neighbouring house or a chimney towards the {direction}, about {height}° high.", + "monitoring.step.suggestion_open": "The suggestion is on the Automations page", + "monitoring.step.suggestion_open.button": "Open suggestion", "monitoring.steps.title": "Recommended steps", "monitoring.value.time": "{time}", "monitoring.view.label": "View", diff --git a/dashboard/internal/webui/static/js/automation-suggestions.js b/dashboard/internal/webui/static/js/automation-suggestions.js index f06afb71..650cd4a7 100644 --- a/dashboard/internal/webui/static/js/automation-suggestions.js +++ b/dashboard/internal/webui/static/js/automation-suggestions.js @@ -170,6 +170,7 @@ this.days = Number(body && body.learning && body.learning.days) || 0; this.devices = Number(body && body.learning && body.learning.devices) || 0; this.loaded = true; + this.openRequested(); } catch (error) { this.loaded = false; } @@ -181,6 +182,24 @@ this.tipOpen = false; if (this.open && tile) this.placeCaret(tile); }, + // Sprung aus dem Monitoring: der Vorschlag klappt auf und rueckt ins Bild. + openRequested() { + const id = window.__automationSuggestionRequest__; + if (!id || !this.items.some((s) => s.id === id)) return; + window.__automationSuggestionRequest__ = null; + if (!this.visible.some((s) => s.id === id)) this.all = true; + this.open = id; + this.fullDay = false; + this.tipOpen = false; + if (!this.$nextTick) return; + this.$nextTick(() => { + this.placeCaret(); + const tile = this.$root ? this.$root.querySelector('.auto-learn-tile[aria-expanded="true"]') : null; + if (!tile || typeof tile.scrollIntoView !== 'function') return; + const calm = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches; + tile.scrollIntoView({ block: 'center', behavior: calm ? 'auto' : 'smooth' }); + }); + }, // Die Karte zeigt mit ihrer Spitze auf die Kachel, aus der sie kommt. Ohne Kachel // (Groessenwechsel, mehr Kacheln) gilt die gerade aufgeklappte. placeCaret(tile = null) { diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index 72d1454b..cb9704a3 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -79,6 +79,14 @@ return p; } + // Code und Platzhalter eines Lernbefunds. Ist das Vorschlagsband geladen + // (automation-suggestions.js), gelten dieselben Umrechnungen wie dort. + function learnSummary(notice, t) { + const summary = { code: notice.code, params: learnParams(notice, t) }; + const band = typeof window !== 'undefined' ? window.AutomationSuggestions : null; + return band && typeof band.resolveSummary === 'function' ? band.resolveSummary(summary, t) : summary; + } + function shadeIdParts(id) { const m = SHADE_ID_RE.exec(id || ''); return m ? { az: Number(m[1]), el: Number(m[2]) } : null; @@ -106,15 +114,21 @@ } function title(notice, t) { - const key = sourceOf(notice) === 'learn' - ? 'automations.learn.' + notice.code + '.title' - : 'monitoring.notice.' + notice.code + '.title'; - return t(key, sourceOf(notice) === 'learn' ? learnParams(notice, t) : notice.params); + if (sourceOf(notice) === 'learn') { + const s = learnSummary(notice, t); + const key = 'automations.learn.' + s.code + '.title'; + return t(key, s.params); + } + const key = 'monitoring.notice.' + notice.code + '.title'; + return t(key, notice.params); } function text(notice, t) { const p = notice.params || {}; - if (sourceOf(notice) === 'learn') return t(`automations.learn.${notice.code}.text`, learnParams(notice, t)); + if (sourceOf(notice) === 'learn') { + const s = learnSummary(notice, t); + return t(`automations.learn.${s.code}.text`, s.params); + } if (notice.code === 'measured_no_meter') return t('energy.roles.notices.measured_warning'); if (notice.code === 'role_needed') return t('energy.chains.role_needed'); if (notice.code === 'chain') { @@ -142,6 +156,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; return false; } diff --git a/dashboard/internal/webui/static/js/monitoring.page.js b/dashboard/internal/webui/static/js/monitoring.page.js index 956d365f..70028dc2 100644 --- a/dashboard/internal/webui/static/js/monitoring.page.js +++ b/dashboard/internal/webui/static/js/monitoring.page.js @@ -113,6 +113,7 @@ view_efficiency: roles.includes('view_efficiency'), view_device_map: roles.includes('view_device_map'), edit_energy: roles.includes('edit_energy'), + view_automations: roles.includes('view_automations'), }; }, canAck() { return (this.sessionRoles || []).includes('edit_setup'); }, @@ -226,6 +227,7 @@ const step = this.stepsOf(notice)[index]; if (!step || !step.target) return; if (step.target === 'learned') { this.goLearned(); return; } + if (step.target === 'suggestion') { this.goSuggestion((step.ids || [])[0]); return; } if (step.target === 'action.role_keep') { this.roleKeep(step.ids); return; } const panel = panelFor(step.target); if (!panel) return; @@ -249,6 +251,15 @@ }); }, + // Sprung zum aufgeklappten Vorschlag. Ist die Automationen-Seite noch nicht + // geladen, nimmt ihr Band die Anfrage in load() entgegen. + goSuggestion(id) { + if (!id) return; + window.__automationSuggestionRequest__ = id; + window.dispatchEvent(new CustomEvent('automation-suggestion-open', { detail: { id } })); + openTab('automations-panel'); + }, + learnedGroups() { return window.MonitoringModel.learnedGroups(this.learned.values, nowSeconds(), t); }, diff --git a/dashboard/internal/webui/templates/automations.html b/dashboard/internal/webui/templates/automations.html index b6143767..2ffcf552 100644 --- a/dashboard/internal/webui/templates/automations.html +++ b/dashboard/internal/webui/templates/automations.html @@ -76,6 +76,7 @@

{{t "automations.list.title"}}

{{t "automations.learn.band.title"}}

diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index d534c9a5..5a3431ee 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -237,7 +237,7 @@

{{t "no_access.title"}}

{{if index .Can "view_history"}}

{{t "panel.history_loading"}}

{{end}} {{if index .Can "view_stats"}}

{{t "panel.stats_loading"}}

{{end}} {{if and .Manager (index .Can "view_efficiency")}}

{{t "panel.efficiency_loading"}}

{{end}} -{{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} +{{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} {{if .Manager}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} {{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} diff --git a/dashboard/test/automation-suggestions.test.mjs b/dashboard/test/automation-suggestions.test.mjs index 3b5af760..b22421d2 100644 --- a/dashboard/test/automation-suggestions.test.mjs +++ b/dashboard/test/automation-suggestions.test.mjs @@ -669,3 +669,30 @@ test('the rules texts keep their shape for a share and a sun code', () => { assert.equal(sun.code, 'switch_time.sun_on.before'); assert.equal(sun.params.minutes, 5); }); + +test('a monitoring request opens its suggestion even beyond the band, and clears the request', async () => { + const a = finding('a:1'); + const b = finding('b:2'); + const c = finding('c:3'); + const d = finding('d:4'); + const { band, window, close } = loadBand(listRoutes({ enabled: true, suggestions: [a, b, c, d], learning: { since: 1, devices: 1, days: 1 } })); + await band.load(); + assert.ok(!band.visible.some((s) => s.id === 'd:4'), 'd:4 is beyond BAND_MAX'); + window.__automationSuggestionRequest__ = 'd:4'; + band.openRequested(); + assert.equal(band.open, 'd:4'); + assert.equal(band.all, true); + assert.equal(window.__automationSuggestionRequest__, null); + close(); +}); + +test('an unknown monitoring request keeps the band as it is and the request', async () => { + const a = finding('a:1'); + const { band, window, close } = loadBand(listRoutes({ enabled: true, suggestions: [a], learning: { since: 1, devices: 1, days: 1 } })); + await band.load(); + window.__automationSuggestionRequest__ = 'zz:9'; + band.openRequested(); + assert.equal(band.open, ''); + assert.equal(window.__automationSuggestionRequest__, 'zz:9'); + close(); +}); diff --git a/dashboard/test/monitoring-model.test.mjs b/dashboard/test/monitoring-model.test.mjs index e6585c88..cb715def 100644 --- a/dashboard/test/monitoring-model.test.mjs +++ b/dashboard/test/monitoring-model.test.mjs @@ -195,3 +195,13 @@ test('learn findings without a culprit name the placeholder instead of the templ assert.ok(emptyText.includes('automations.learn.battery.candidate.none')); assert.ok(!emptyText.includes('{candidates}')); }); + +test('a suggestion step targets the automations page only with the view_automations right', () => { + const notice = { source: 'learn', code: 'runtime.long', steps: [{ code: 'suggestion_open', target: 'suggestion', ids: ['runtime:plug'] }] }; + const with_ = M.steps(notice, { view_automations: true }, t)[0]; + assert.equal(with_.target, 'suggestion'); + assert.ok(with_.label.length > 0); + const without = M.steps(notice, {}, t)[0]; + assert.equal(without.target, ''); + assert.equal(without.label, ''); +}); From e4c86cb1bae0a9ba5d7eacf1216cac539d325f90 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:35:25 +0100 Subject: [PATCH 32/37] chore(dashboard): bump the cache-bust marks for the curve chart and suggestion notices Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/webui/cache-bust-history.csv | 3 +++ dashboard/internal/webui/templates/base.html | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index cb01213d..21e16e60 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,9 +1,12 @@ version,date,asset,v,note +v0.11.22-pre.31,2026-11-22,css/automations.css,23, +v0.11.22-pre.31,2026-11-22,js/automation-evidence.js,5, v0.11.22-pre.31,2026-11-22,js/automation-learned.js,4, v0.11.22-pre.31,2026-11-22,js/automation-suggestions.js,4, v0.11.22-pre.31,2026-11-22,js/automation-templates.js,10, v0.11.22-pre.31,2026-11-22,js/automations.page.js,30, v0.11.22-pre.31,2026-11-22,js/monitoring-model.js,2, +v0.11.22-pre.31,2026-11-22,js/monitoring.page.js,2, v0.11.22-pre.31,2026-11-22,js/settings.page.js,42, v0.11.22-pre.30,2026-11-22,css/base.css,54, v0.11.22-pre.30,2026-11-22,css/manager.css,53, diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 5a3431ee..f8ce9322 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -237,14 +237,14 @@

{{t "no_access.title"}}

{{if index .Can "view_history"}}

{{t "panel.history_loading"}}

{{end}} {{if index .Can "view_stats"}}

{{t "panel.stats_loading"}}

{{end}} {{if and .Manager (index .Can "view_efficiency")}}

{{t "panel.efficiency_loading"}}

{{end}} -{{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} +{{if index .Can "view_monitoring"}}

{{t "panel.monitoring_loading"}}

{{end}} {{if .Manager}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} {{if index .Can "view_config"}}

{{t "panel.config_loading"}}

{{end}} {{if index .Can "view_energy"}}

{{t "panel.energy_loading"}}

{{end}} {{if index .Can "view_device_map"}}

{{t "panel.devicemap_loading"}}

{{end}}

{{t "panel.settings_loading"}}

-{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} +{{if index .Can "view_automations"}} {{if index .InstalledServices "automation"}}

{{t "panel.automations_loading"}}

{{end}}{{end}} {{else}} {{if index .Can "view_diagnostics"}}

{{t "panel.diagnostics_loading"}}

{{end}} {{end}} From add1bab003daa8d6eb8c7dddda4e72505d11111b Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:44:51 +0100 Subject: [PATCH 33/37] feat(monitoring): collect the suggestions under their own filter Co-Authored-By: Claude Opus 5.5 --- dashboard/internal/monitoring/notice.go | 5 +++-- dashboard/internal/monitoring/notice_test.go | 2 +- dashboard/internal/webui/catalogs/de.json | 2 ++ dashboard/internal/webui/catalogs/en.json | 2 ++ .../webui/static/js/monitoring-model.js | 19 ++++++++++++++----- .../webui/static/js/monitoring.page.js | 5 ++++- dashboard/test/monitoring-model.test.mjs | 12 ++++++++++++ docs/dashboard/monitoring.md | 3 ++- 8 files changed, 40 insertions(+), 10 deletions(-) diff --git a/dashboard/internal/monitoring/notice.go b/dashboard/internal/monitoring/notice.go index 1d6394cc..d8118d57 100644 --- a/dashboard/internal/monitoring/notice.go +++ b/dashboard/internal/monitoring/notice.go @@ -230,7 +230,8 @@ func learnNotices(findings []autolearn.Finding) []Notice { } // suggestionNotices turns the visible suggestions into notices. The step opens -// the suggestion on the automations page. +// the suggestion on the automations page. Their source is suggest, the page lists +// them under the filter Vorschläge. func suggestionNotices(list []autolearn.Finding) []Notice { var out []Notice for _, f := range list { @@ -241,7 +242,7 @@ func suggestionNotices(list []autolearn.Finding) []Notice { params["kind"] = f.Kind n := Notice{ ID: "suggest:" + f.ID, - Source: "learn", + Source: "suggest", Severity: learnSeverity(f.Severity), Code: f.Summary.Code, Params: params, diff --git a/dashboard/internal/monitoring/notice_test.go b/dashboard/internal/monitoring/notice_test.go index 176783aa..14621fed 100644 --- a/dashboard/internal/monitoring/notice_test.go +++ b/dashboard/internal/monitoring/notice_test.go @@ -111,7 +111,7 @@ func TestSuggestionsBecomeNoticesThatOpenTheSuggestion(t *testing.T) { if got == nil { t.Fatal("no notice for the suggestion") } - if got.Source != "learn" || got.Code != "runtime.long" || got.Params["device"] != "Plug" || got.Params["kind"] != "runtime" { + if got.Source != "suggest" || got.Code != "runtime.long" || got.Params["device"] != "Plug" || got.Params["kind"] != "runtime" { t.Errorf("notice = %+v", got) } if len(got.Steps) != 1 || got.Steps[0].Code != "suggestion_open" || got.Steps[0].Target != "suggestion" || diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index dffaf9de..dbb3bbf9 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -3657,6 +3657,7 @@ "monitoring.filter.energy": "Energie", "monitoring.filter.label": "Quelle", "monitoring.filter.learn": "Lernfunktionen", + "monitoring.filter.suggest": "Vorschläge", "monitoring.group.known": "Zur Kenntnis genommen", "monitoring.group.new": "Neu", "monitoring.learned.count": "{have} von {total}", @@ -3699,6 +3700,7 @@ "monitoring.source.chain": "Messketten", "monitoring.source.energy": "Energie-Bilanz", "monitoring.source.learn": "Lernfunktionen", + "monitoring.source.suggest": "Vorschläge", "monitoring.step.assign_roles": "Jedem Wert, der zur Bilanz gehört, eine Rolle geben", "monitoring.step.assign_roles.button": "Rollen setzen", "monitoring.step.chain_open": "Messkette ansehen", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index cec48d76..d29436ff 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -3657,6 +3657,7 @@ "monitoring.filter.energy": "Energy", "monitoring.filter.label": "Source", "monitoring.filter.learn": "Learning", + "monitoring.filter.suggest": "Suggestions", "monitoring.group.known": "Acknowledged", "monitoring.group.new": "New", "monitoring.learned.count": "{have} of {total}", @@ -3699,6 +3700,7 @@ "monitoring.source.chain": "Measurement chains", "monitoring.source.energy": "Energy balance", "monitoring.source.learn": "Learning", + "monitoring.source.suggest": "Suggestions", "monitoring.step.assign_roles": "Give every value that belongs to the balance a role", "monitoring.step.assign_roles.button": "Set roles", "monitoring.step.chain_open": "Look at the measurement chain", diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index cb9704a3..2a39581f 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -6,13 +6,21 @@ const SHADE_ID_RE = /^learn:shade:(\d+):(\d+)$/; const pad = (n) => String(n).padStart(2, '0'); - // Quelle für Filter und Gruppen: Energie-Bilanz und Messketten zusammen, sonst Lernfunktionen. + // Quelle für Filter und Gruppen: Energie-Bilanz und Messketten zusammen, Vorschläge + // für sich, sonst Lernfunktionen. function sourceOf(notice) { - return notice.source === 'energy' || notice.source === 'chain' ? 'energy' : 'learn'; + if (notice.source === 'energy' || notice.source === 'chain') return 'energy'; + return notice.source === 'suggest' ? 'suggest' : 'learn'; + } + + // Lernbefunde und Vorschläge teilen Texte und Belege der Automationen. + function isLearned(notice) { + const source = sourceOf(notice); + return source === 'learn' || source === 'suggest'; } function filterNotices(notices, filter) { - if (filter === 'energy' || filter === 'learn') { + if (filter === 'energy' || filter === 'learn' || filter === 'suggest') { return notices.filter((n) => sourceOf(n) === filter); } return notices.slice(); @@ -114,7 +122,7 @@ } function title(notice, t) { - if (sourceOf(notice) === 'learn') { + if (isLearned(notice)) { const s = learnSummary(notice, t); const key = 'automations.learn.' + s.code + '.title'; return t(key, s.params); @@ -125,7 +133,7 @@ function text(notice, t) { const p = notice.params || {}; - if (sourceOf(notice) === 'learn') { + if (isLearned(notice)) { const s = learnSummary(notice, t); return t(`automations.learn.${s.code}.text`, s.params); } @@ -304,6 +312,7 @@ valueText, spark, sourceOf, + isLearned, filterNotices, sortNotices, groups, diff --git a/dashboard/internal/webui/static/js/monitoring.page.js b/dashboard/internal/webui/static/js/monitoring.page.js index 70028dc2..22451b90 100644 --- a/dashboard/internal/webui/static/js/monitoring.page.js +++ b/dashboard/internal/webui/static/js/monitoring.page.js @@ -3,7 +3,8 @@ // mit dem CSRF-Token der Sitzung. Die Texte baut window.MonitoringModel. // // i18n-keys: monitoring.filter.all, monitoring.filter.energy, monitoring.filter.learn, -// monitoring.source.energy, monitoring.source.chain, monitoring.source.learn, +// monitoring.filter.suggest, monitoring.source.energy, monitoring.source.chain, +// monitoring.source.learn, monitoring.source.suggest, // 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, monitoring.learned.count @@ -19,11 +20,13 @@ { id: 'all', key: 'monitoring.filter.all' }, { id: 'energy', key: 'monitoring.filter.energy' }, { id: 'learn', key: 'monitoring.filter.learn' }, + { id: 'suggest', key: 'monitoring.filter.suggest' }, ]; const SOURCE_KEYS = { energy: 'monitoring.source.energy', chain: 'monitoring.source.chain', learn: 'monitoring.source.learn', + suggest: 'monitoring.source.suggest', }; 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. diff --git a/dashboard/test/monitoring-model.test.mjs b/dashboard/test/monitoring-model.test.mjs index cb715def..06a7e4c8 100644 --- a/dashboard/test/monitoring-model.test.mjs +++ b/dashboard/test/monitoring-model.test.mjs @@ -205,3 +205,15 @@ test('a suggestion step targets the automations page only with the view_automati assert.equal(without.target, ''); assert.equal(without.label, ''); }); + +test('suggestion notices have their own source and filter and use the learn texts', () => { + const learn = { id: 'learn:x', source: 'learn', code: 'battery.full_early', params: {} }; + const suggest = { id: 'suggest:y', source: 'suggest', code: 'runtime.long', params: { device: 'Plug', kind: 'runtime' } }; + const energy = { id: 'energy:z', source: 'energy', code: 'unassigned', params: {} }; + const all = [learn, suggest, energy]; + assert.equal(M.sourceOf(suggest), 'suggest'); + assert.deepEqual(M.filterNotices(all, 'suggest').map((n) => n.id), ['suggest:y']); + assert.deepEqual(M.filterNotices(all, 'learn').map((n) => n.id), ['learn:x']); + assert.equal(M.filterNotices(all, 'all').length, 3); + assert.ok(M.title(suggest, t).startsWith('automations.learn.runtime.long.title')); +}); diff --git a/docs/dashboard/monitoring.md b/docs/dashboard/monitoring.md index c36c53b2..4f482d32 100644 --- a/docs/dashboard/monitoring.md +++ b/docs/dashboard/monitoring.md @@ -17,7 +17,7 @@ Monitoring covers the energy side and what the system has learned. ## Notices The top left of the tab switches between **Notices** and **Learned values**. The -filter on the right limits the notices to **All**, **Energy** or **Learning**. +filter on the right limits the notices to **All**, **Energy**, **Learning** or **Suggestions**. The list has two groups, **New** and **Acknowledged**. Select a notice to see its card. The card has the text, the facts of the notice, the evidence if there is @@ -31,6 +31,7 @@ Notices come from three sources: | Energy balance | The house load is set to measured, but no meter has the role house meter. A battery level exists without a capacity in kWh. Power values have no role. Values were left without a role by a measurement chain. | | Measurement chains | A finding of a [measurement chain](energy.md#measurement-chains), such as a unit error, a frozen value, a contradiction or a sign error. The card shows the time since the finding started. | | Learning | A finding that belongs to no rule and to no suggestion, for example a fixed shade that reduces the PV power, a battery that is full early or empty before morning, or a rising base load without a switchable device. The card shows the direction and height of the shade, the calendar weeks, the loss per year and a daily curve. | +| Suggestions | Every suggestion of the [suggestion band](automations-rules.md#suggestions). **Open suggestion** opens it on the Automations page. The chip **Suggestions** lists only these, **All** includes them. | Findings that belong to a rule stay on the rule card in [Automations](automations-rules.md). Findings with a suggestion to apply stay in From ff6bf1b3f05a41c15c00e5cfa695b089a6d0d98e Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 22 Nov 2026 16:51:41 +0000 Subject: [PATCH 34/37] chore(release): bump component versions --- dashboard/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashboard/VERSION b/dashboard/VERSION index 9391c83d..66d3b7c5 100644 --- a/dashboard/VERSION +++ b/dashboard/VERSION @@ -1 +1 @@ -v0.11.22-pre.30 +v0.11.22-pre.31 From 2389914bbc13bbe7b685ce08717bb487a3183a86 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 22 Nov 2026 16:52:31 +0000 Subject: [PATCH 35/37] docs(changelog): update changelogs --- changelog/highlights/292.json | 8 ++++++++ dashboard/CHANGELOG.md | 37 ++++++++++++++++++++++++++++++++--- 2 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 changelog/highlights/292.json diff --git a/changelog/highlights/292.json b/changelog/highlights/292.json new file mode 100644 index 00000000..d8827f8a --- /dev/null +++ b/changelog/highlights/292.json @@ -0,0 +1,8 @@ +{ + "de": { + "*": "Die Regelprüfung erkennt Rückkopplung, Konkurrenz um den Überschuss, steigende Grundlast und einen zu früh vollen oder nachts leeren Akku" + }, + "en": { + "*": "The rule check finds feedback loops, competition for the surplus, a rising base load and a battery that is full too early or empty at night" + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index 9bf568fd..6f63575c 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.11.22-pre.30 (2026-11-06) +## v0.11.22-pre.31 (2026-11-06) ### Features @@ -30,6 +30,31 @@ - **automations:** Rules can follow learned values with bounds and react to a quiet or active house (#284) (8aae55b) - **automations:** Learning knows the seasons, the sun and the outdoor temperature (#287) (8812dc2) - **automations:** Learning knows device cycles, the PV reserve and the remaining surplus of the day (#289) (5d86b6b) +- **monitoring:** A Monitoring tab with notices, acknowledgement and all learned values (#291) (7ae50a9) +- **autolearn:** let a fix change several rules and estimate signal noise (80c444e) +- **autolearn:** flag rules whose own load flips their condition (67cbc32) +- **autolearn:** name feedback as the cause of flapping rules (f6ea384) +- **autolearn:** stagger rules that compete for the same surplus (d725acf) +- **autolearn:** say in which week a PV rule will fire again (3769fa6) +- **autolearn:** report a rising base load with the device behind it (b624fb6) +- **autolearn:** add the night off template with learned night bounds (20a221a) +- **autolearn:** report a battery that is full too early or empty before morning (aac68e4) +- **monitoring:** show base load, battery full time and night energy (e6e4e30) +- **autolearn:** store the empty battery share per season week (0fbf269) +- **autolearn:** seed energy findings in the demo (e00d60b) +- **autolearn:** seed a rising base load and an empty battery in the demo (5775d14) +- **autolearn:** keep the PV sky for a year and stop calling summer thresholds unreachable in winter (bb0ea79) +- **settings:** add the switch for a whole year of seasonal data (2a5c0aa) +- **autolearn:** seed a year of PV sky so the demo shows a seasonal rest (2c655b5) +- **autolearn:** send energy findings without a rule to Monitoring (d0e1298) +- **autolearn:** let the season expectation shorten the base load history (d87e3c1) +- **autolearn:** seed earlier years instead of doubling the demo days (4789168) +- **autolearn:** show the Soll charge of the battery findings (43ae2f6) +- **monitoring:** list every suggestion as a notice (a5ff2af) +- **automations:** draw Ist and Soll curves in one chart (5f880ad) +- **monitoring:** open the suggestion from its notice (9eaa37c) +- **monitoring:** collect the suggestions under their own filter (add1bab) +- **autolearn:** The rule check finds feedback loops, competition for the surplus, a rising base load and a battery that is full too early or empty at night (#292) - **i18n:** add the view_monitoring texts (0385648) - **auth:** add the view_monitoring right (44c40f9) - **monitoring:** collect notices from energy, chains and learning (e85d98c) @@ -44,7 +69,6 @@ - **i18n:** add the monitoring labels and load error (c5aa6b7) - **webui:** add the monitoring tab and panel (41562a2) - **energy:** point the energy page notices to monitoring (8c665f2) -- **monitoring:** A Monitoring tab with notices, acknowledgement and all learned values (#291) - **learnrec:** add the energy limits of each learning level (b74b813) - **autolearn:** track device cycles from minute power (0e10e79) - **autolearn:** store cycles and battery level in the day file (039e639) @@ -263,6 +287,10 @@ - **storage:** offer sticks with several partitions as a group and format single partitions (#243) (c4e6d33) - **storage:** wipe old file system signatures before formatting a stick (#245) (aeafa63) - **storage:** set up, back up and replug the additional drive reliably (#247) (b668394) +- **autolearn:** drop findings whose fix is saved and show an early full battery in Monitoring (cb2d65b) +- **automations:** keep learned findings while a fix sits in the draft (715cbfd) +- **automations:** preselect the switch of night off and quiet off suggestions (e3a0952) +- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **webui:** translate the time value of the monitoring model (d55ca28) - **webui:** add labels and load error to the monitoring panel (79ad0f3) - **energy:** keep monitoring jumps and refresh the summary line (9ad7b8a) @@ -270,7 +298,6 @@ - **webui:** match the monitoring skeleton to the page and bump marks (bd91d58) - **users:** label the monitoring right just Monitoring (35f718e) - **users:** list the view rights in the order of the tabs (de17776) -- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **autolearn:** pass the battery level into the learning frames (be60d22) - **autolearn:** harden cycle gap, runs and long cycles (a3b5f6f) - **autolearn:** count only the PV the house does not use as surplus (c9b33ff) @@ -375,6 +402,7 @@ ### Tests +- **webui:** follow the template cache-bust mark (c30a3db) - **smoke:** probe the live push on the house load (5382341) - **webui:** follow the new cache-bust marks (b06cc13) - **automations:** do not pin the cache-bust mark of the learned helper (2fd09ce) @@ -395,6 +423,9 @@ ### Chores +- **dashboard:** bump the cache-bust marks for energy findings (85a44b4) +- **dashboard:** bump the cache-bust mark of the settings page (a590474) +- **dashboard:** bump the cache-bust marks for the curve chart and suggestion notices (e4c86cb) - **webui:** bump the lazy asset marks of the monitoring page (79de377) - **dashboard:** bump the cache-bust marks for energy learning (8bd6f10) - **dashboard:** rebump the cache-bust marks after the rebase (c8480e9) From 1ff6d17e4fd8de591c5cbb392bedce30aed41831 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 22 Nov 2026 16:55:22 +0000 Subject: [PATCH 36/37] docs(changelog): update changelogs --- changelog/highlights/292.json | 2 +- dashboard/CHANGELOG.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/changelog/highlights/292.json b/changelog/highlights/292.json index d8827f8a..8bb524e4 100644 --- a/changelog/highlights/292.json +++ b/changelog/highlights/292.json @@ -1,6 +1,6 @@ { "de": { - "*": "Die Regelprüfung erkennt Rückkopplung, Konkurrenz um den Überschuss, steigende Grundlast und einen zu früh vollen oder nachts leeren Akku" + "*": "Die Regelprüfung erkennt Rückkopplung, Konkurrenz, steigende Grundlast und Akkuprobleme" }, "en": { "*": "The rule check finds feedback loops, competition for the surplus, a rising base load and a battery that is full too early or empty at night" diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index 6f63575c..3c987b36 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -54,7 +54,7 @@ - **automations:** draw Ist and Soll curves in one chart (5f880ad) - **monitoring:** open the suggestion from its notice (9eaa37c) - **monitoring:** collect the suggestions under their own filter (add1bab) -- **autolearn:** The rule check finds feedback loops, competition for the surplus, a rising base load and a battery that is full too early or empty at night (#292) +- **autolearn:** The rule check finds feedback, competition for the surplus, a rising base load and battery problems (#292) - **i18n:** add the view_monitoring texts (0385648) - **auth:** add the view_monitoring right (44c40f9) - **monitoring:** collect notices from energy, chains and learning (e85d98c) From a26ec0dd9dd3d1170481af3edde823d28d9ef6ca Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 22 Nov 2026 17:54:06 +0000 Subject: [PATCH 37/37] docs(changelog): update changelogs --- changelog/highlights/292.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog/highlights/292.json b/changelog/highlights/292.json index 8bb524e4..3894ad14 100644 --- a/changelog/highlights/292.json +++ b/changelog/highlights/292.json @@ -3,6 +3,6 @@ "*": "Die Regelprüfung erkennt Rückkopplung, Konkurrenz, steigende Grundlast und Akkuprobleme" }, "en": { - "*": "The rule check finds feedback loops, competition for the surplus, a rising base load and a battery that is full too early or empty at night" + "*": "The rule check finds feedback, competition for the surplus, a rising base load and battery problems" } }