From 25d731e8c011f741930be8754de6ffcc14507abe Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:52:33 +0100 Subject: [PATCH 01/30] feat(autolearn): expose forecast days and the rules that read a learned value Add ForecastWindow, ForecastDay and ForecastCheck.Days for the finished forecast days, and RuleRef and LearnedReaders to list the rules whose conditions read a learned key. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/forecast.go | 22 +++++++++++++ dashboard/internal/autolearn/forecast_test.go | 25 +++++++++++++++ dashboard/internal/autolearn/rules.go | 31 +++++++++++++++++++ dashboard/internal/autolearn/rules_test.go | 16 ++++++++++ 4 files changed, 94 insertions(+) diff --git a/dashboard/internal/autolearn/forecast.go b/dashboard/internal/autolearn/forecast.go index 1ecf759b..21542d7f 100644 --- a/dashboard/internal/autolearn/forecast.go +++ b/dashboard/internal/autolearn/forecast.go @@ -24,6 +24,8 @@ const ( forecastFileVersion = 1 // forecastDays is the number of finished days the check keeps. forecastDays = 14 + // ForecastWindow is the number of finished days the check keeps. + ForecastWindow = forecastDays // forecastHour is the local hour of the forecast. forecastHour = 10 // forecastQuarter is the quarter of the forecast, 10:00 local time. @@ -39,6 +41,15 @@ type forecastEntry struct { Season float64 `json:"season_wh"` } +// ForecastDay is one finished day of the check: the forecast of the rest of the +// day from 10:00, the measured rest and the season median of the rest, in Wh. +type ForecastDay struct { + Day string `json:"day"` + ForecastWh float64 `json:"forecast_wh"` + ActualWh float64 `json:"actual_wh"` + SeasonWh float64 `json:"season_wh"` +} + // forecastFile is the content of forecast.json. type forecastFile struct { Version int `json:"version"` @@ -150,6 +161,17 @@ func (c *ForecastCheck) Close(day string, actualRestWh float64, seasonMedianRest } } +// Days returns a copy of the finished days, oldest first. It is never nil. +func (c *ForecastCheck) Days() []ForecastDay { + c.mu.Lock() + defer c.mu.Unlock() + out := make([]ForecastDay, 0, len(c.days)) + for _, e := range c.days { + out = append(out, ForecastDay{Day: e.Day, ForecastWh: e.Forecast, ActualWh: e.Actual, SeasonWh: e.Season}) + } + return out +} + // UseSeasonMedian tells whether the season median should replace the forecast. // It needs forecastDays finished days, and the mean absolute error of the // forecast must not be smaller than the mean absolute error of the season diff --git a/dashboard/internal/autolearn/forecast_test.go b/dashboard/internal/autolearn/forecast_test.go index 64522388..a4e4618a 100644 --- a/dashboard/internal/autolearn/forecast_test.go +++ b/dashboard/internal/autolearn/forecast_test.go @@ -5,6 +5,7 @@ import ( "math" "os" "path/filepath" + "reflect" "testing" "time" @@ -264,3 +265,27 @@ func TestSurplusSelfCheckRecordsAndClosesDays(t *testing.T) { t.Errorf("actual = %.0f, want %.0f from 10:00", check.days[0].Actual, wantActual) } } + +func TestForecastDaysCopiesOldestFirst(t *testing.T) { + c := LoadForecastCheck(filepath.Join(t.TempDir(), "f.json"), nil) + c.Record("2026-11-20", 3000) + c.Close("2026-11-20", 2500, 2800) + c.Record("2026-11-21", 1000) + c.Close("2026-11-21", 1200, 2700) + got := c.Days() + want := []ForecastDay{{"2026-11-20", 3000, 2500, 2800}, {"2026-11-21", 1000, 1200, 2700}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("Days = %+v", got) + } + got[0].ActualWh = 0 + if c.Days()[0].ActualWh != 2500 { + t.Fatal("Days must return a copy") + } +} + +func TestForecastDaysEmptyIsNotNil(t *testing.T) { + c := LoadForecastCheck("", nil) + if d := c.Days(); d == nil || len(d) != 0 { + t.Fatalf("Days = %#v", d) + } +} diff --git a/dashboard/internal/autolearn/rules.go b/dashboard/internal/autolearn/rules.go index a8de9204..7f97721f 100644 --- a/dashboard/internal/autolearn/rules.go +++ b/dashboard/internal/autolearn/rules.go @@ -63,6 +63,37 @@ type LearnedRef struct { MaxAgeS float64 } +// RuleRef names a rule by its ID and Name. +type RuleRef struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// LearnedReaders returns the rules whose conditions read the learned key in +// Learned, in the order of doc.Rules, each rule once. It is never nil. +func LearnedReaders(doc Doc, key string) []RuleRef { + out := []RuleRef{} + for _, r := range doc.Rules { + for _, c := range r.Conditions { + if learnedReads(c, key) { + out = append(out, RuleRef{ID: r.ID, Name: r.Name}) + break + } + } + } + return out +} + +// learnedReads tells whether a learned reference of the condition has the key. +func learnedReads(c Condition, key string) bool { + for _, ref := range c.Learned { + if ref.Key == key { + return true + } + } + return false +} + // Action is one action of a rule, a publish or a notification. type Action struct { Type string diff --git a/dashboard/internal/autolearn/rules_test.go b/dashboard/internal/autolearn/rules_test.go index 10b2f934..a68e472a 100644 --- a/dashboard/internal/autolearn/rules_test.go +++ b/dashboard/internal/autolearn/rules_test.go @@ -481,3 +481,19 @@ func TestParseDocReadsTheRegulatorTuning(t *testing.T) { t.Fatalf("defaults = %+v, want gain 0.8, no max change, base last", b) } } + +func TestLearnedReadersFindsRulesOnce(t *testing.T) { + doc := Doc{Rules: []Rule{ + {ID: "a", Name: "Wallbox", Conditions: []Condition{{Learned: map[string]LearnedRef{"threshold": {Key: "site/surplus_left_wh"}, "value": {Key: "site/surplus_left_wh"}}}}}, + {ID: "b", Name: "Licht", Conditions: []Condition{{Learned: map[string]LearnedRef{"value": {Key: "site/day_start"}}}}}, + {ID: "c", Name: "Boiler", Conditions: []Condition{{}, {Learned: map[string]LearnedRef{"threshold": {Key: "site/surplus_left_wh"}}}}}, + }} + got := LearnedReaders(doc, "site/surplus_left_wh") + want := []RuleRef{{"a", "Wallbox"}, {"c", "Boiler"}} + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %+v", got) + } + if got := LearnedReaders(Doc{}, "site/surplus_left_wh"); got == nil || len(got) != 0 { + t.Fatalf("empty doc: %#v", got) + } +} From 4a39a7765b17627673a16ae28a39fec0034c6e3b Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:54:58 +0100 Subject: [PATCH 02/30] feat(demo): seed a forecast check and a year of season weeks Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 10 +- dashboard/internal/autolearn/demo.go | 113 ++++++++++++++++++++-- dashboard/internal/autolearn/demo_test.go | 37 +++++++ 3 files changed, 149 insertions(+), 11 deletions(-) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 6ee99d98..f6e8b7aa 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -598,6 +598,10 @@ func main() { forecastCheck := autolearn.LoadForecastCheck(filepath.Join(autolearnDir, "forecast.json"), log.Printf) learnHub.AddSaver("forecast", forecastCheck) learnHub.AddResetter("forecast", forecastCheck) + // Demo: ohne Prognosetage bekommt die Selbstpruefung die vierzehn Demo-Tage. + if strings.TrimSpace(os.Getenv("ENERGY_NODE_AUTOLEARN_FAST")) == "1" && len(forecastCheck.Days()) == 0 { + autolearn.DemoForecast(time.Now(), forecastCheck) + } registerEnergyDetectors(automationEngine, pvReserve.Current, pvReserve.DayCount, forecastCheck) automationEngine.Register(autolearn.BaseLoadDetector) automationEngine.Register(autolearn.BatteryDetector) @@ -710,8 +714,12 @@ func main() { } } automationEngine.SetSeason(seasonStore) - // Demo: ohne Wochenwerte bekommt das Saisongedaechtnis die acht Demo-Wochen. + // Demo: ohne Wochenwerte bekommt das Saisongedaechtnis das Jahr davor und die Demo-Wochen. + // Die Demo-Wochen kommen zuletzt, damit sie die Tageswochen des Jahres davor ueberschreiben. if strings.TrimSpace(os.Getenv("ENERGY_NODE_AUTOLEARN_FAST")) == "1" && len(seasonStore.Weeks("0000-W00", "9999-W99")) == 0 { + for _, w := range autolearn.DemoSeasonHistory(time.Now()) { + seasonStore.Put(w) + } for _, w := range autolearn.DemoSeason(time.Now()) { seasonStore.Put(w) } diff --git a/dashboard/internal/autolearn/demo.go b/dashboard/internal/autolearn/demo.go index 04f91437..aca1e739 100644 --- a/dashboard/internal/autolearn/demo.go +++ b/dashboard/internal/autolearn/demo.go @@ -724,21 +724,64 @@ func (b *demoBuilder) fill(rng *rand.Rand) { } } +// demoSeasonSeed, demoHistorySeed und demoForecastSeed sind die festen Seeds der +// Wochenwerte, des Jahres davor und der Prognose der Demo. +const ( + demoSeasonSeed = demoSeed + 2 + demoHistorySeed = demoSeed + 3 + demoForecastSeed = demoSeed + 4 + // demoHistoryWeeks ist die Zahl der Statistikwochen vor dem Saisongedächtnis. + demoHistoryWeeks = 64 + // demoForecastErrW ist die größte Abweichung der Prognose vom Tagesrest in Wh. + demoForecastErrW = 900.0 +) + +// demoSummer ist der Sommeranteil der ISO-Woche, 0 im Januar und 1 Ende Juni. +func demoSummer(week int) float64 { + return math.Pow(math.Sin(math.Pi*(float64(week)-0.5)/52), 2) +} + +// demoNoise ist ein Zufallswert in [-amp, amp] aus dem festen Strom rng. +func demoNoise(rng *rand.Rand, amp float64) float64 { + return (rng.Float64() - 0.5) * 2 * amp +} + +// demoWeekEnergy liefert PV, Last, Einspeisung in kWh, die Grundlast in W und die +// Außentemperatur der ISO-Woche week. Die Werte folgen dem Jahresverlauf der +// Referenz, das Rauschen kommt aus rng. +func demoWeekEnergy(rng *rand.Rand, week int) (pv, load, export, base, temp float64) { + s := demoSummer(week) + pv = math.Max(8, 26+205*s+demoNoise(rng, 24)) + load = 92 + 58*(1-s) + demoNoise(rng, 9) + export = math.Max(0, pv*0.52-12+demoNoise(rng, 6)) + base = 178 + 52*(1-s) + demoNoise(rng, 7) + temp = 1.5 + 17.5*s + demoNoise(rng, 2.2) + return pv, load, export, base, temp +} + // DemoSeason liefert das Saisongedächtnis der Demo: die zwanzig Wochen vor now, -// die älteste zuerst. Jede Woche trägt ihre Außentemperatur, fünf Auslösungen -// der Demo-Regeln, damit der Temperaturvorschlag warme Wochen findet, und die -// gelernte Abschaltzeit der Balkonsteckdose, damit die Jahreslinie erscheint. +// die älteste zuerst. Jede Woche trägt ihre Energiewerte und Außentemperatur, fünf +// Auslösungen der Demo-Regeln, damit der Temperaturvorschlag warme Wochen findet, +// und die gelernte Abschaltzeit der Balkonsteckdose, damit die Jahreslinie erscheint. func DemoSeason(now time.Time) []Week { + rng := rand.New(rand.NewSource(demoSeasonSeed)) out := make([]Week, 0, demoSeasonWeeks) for k := demoSeasonWeeks; k >= 1; k-- { + at := now.AddDate(0, 0, -7*k) + _, w := at.ISOWeek() + pv, load, export, base, _ := demoWeekEnergy(rng, w) temp := demoWeekTempC[k-1] out = append(out, Week{ - Key: isoWeekKey(now.AddDate(0, 0, -7*k)), - Source: seasonSourceDays, - Days: 7, - TempC: &temp, - Triggers: map[string]float64{demoRuleID: 5, demoPVRuleID: 5}, - Learned: map[string]float64{demoBedtimeKey: demoBedtimeMin + 6*math.Sin(float64(k))}, + Key: isoWeekKey(at), + Source: seasonSourceDays, + Days: 7, + ExportKWh: export, + PVKWh: pv, + LoadKWh: load, + BaseW: base, + TempC: &temp, + Triggers: map[string]float64{demoRuleID: 5, demoPVRuleID: 5}, + Learned: map[string]float64{demoBedtimeKey: demoBedtimeMin + 6*math.Sin(float64(k))}, }) } // Dieselben Wochen in den zwei Jahren davor: der Akku war damals selten leer, @@ -747,7 +790,16 @@ func DemoSeason(now time.Time) []Week { 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} + pv, load, export, _, _ := demoWeekEnergy(rng, w) + week := Week{ + Key: fmt.Sprintf("%d-W%02d", y-back, w), + Source: seasonSourceDays, + Days: 7, + ExportKWh: export, + PVKWh: pv, + LoadKWh: load, + BaseW: demoSeasonBaseW, + } if back == 1 { share := 0.1 week.EmptyShare = &share @@ -758,6 +810,47 @@ func DemoSeason(now time.Time) []Week { return out } +// DemoSeasonHistory liefert die demoHistoryWeeks Statistikwochen vor den Wochen +// von DemoSeason, die älteste zuerst. Sie tragen Energiewerte und Temperatur, aber +// keine Auslösungen und keine gelernten Werte. +func DemoSeasonHistory(now time.Time) []Week { + rng := rand.New(rand.NewSource(demoHistorySeed)) + out := make([]Week, 0, demoHistoryWeeks) + for k := demoSeasonWeeks + demoHistoryWeeks; k > demoSeasonWeeks; k-- { + at := now.AddDate(0, 0, -7*k) + _, w := at.ISOWeek() + pv, load, export, base, temp := demoWeekEnergy(rng, w) + out = append(out, Week{ + Key: isoWeekKey(at), + Source: seasonSourceStats, + Days: 7, + ExportKWh: export, + PVKWh: pv, + LoadKWh: load, + BaseW: base, + TempC: &temp, + }) + } + return out +} + +// DemoForecast schreibt die vierzehn Tage vor now in die Prognose-Selbstprüfung c. +// Jeder Tag bekommt eine Prognose des Tagesrests ab 10:00, den gemessenen Rest und +// den Saisonmedian. Die Prognose liegt meist näher am Rest als der Median, daher +// bleibt die Prognose im Einsatz. +func DemoForecast(now time.Time, c *ForecastCheck) { + rng := rand.New(rand.NewSource(demoForecastSeed)) + y, m, d := now.Local().Date() + for k := ForecastWindow; k >= 1; k-- { + day := time.Date(y, m, d-k, 0, 0, 0, 0, time.Local).Format(dayLayout) + actual := math.Max(300, 2600+demoNoise(rng, 1900)) + forecast := math.Max(0, actual+demoNoise(rng, demoForecastErrW)) + season := 2750 + demoNoise(rng, 260) + c.Record(day, forecast) + c.Close(day, actual, season) + } +} + // DemoDailyShare liefert den Tagesanteil der Lernlast für die letzten // demoShareDays Tage vor now, den der Lernstand der Demo beim ersten Start // bekommt. Der Anteil liegt unter der Hälfte des Ziels der Stufe eco. diff --git a/dashboard/internal/autolearn/demo_test.go b/dashboard/internal/autolearn/demo_test.go index 0bc9bb13..aa0ee7c2 100644 --- a/dashboard/internal/autolearn/demo_test.go +++ b/dashboard/internal/autolearn/demo_test.go @@ -947,3 +947,40 @@ func TestSeedDemoMinutesAndSteps(t *testing.T) { t.Fatal("second seed changed an existing minute file") } } + +// TestDemoSeasonHistoryIsOlderStatsWeeks checks that the year before the demo +// season is filled with statistics weeks that carry their energy values. +func TestDemoSeasonHistoryIsOlderStatsWeeks(t *testing.T) { + now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + hist, recent := DemoSeasonHistory(now), DemoSeason(now) + if len(hist) != 64 { + t.Fatalf("len %d", len(hist)) + } + if hist[len(hist)-1].Key >= recent[0].Key { + t.Fatalf("history %s not before %s", hist[len(hist)-1].Key, recent[0].Key) + } + for _, w := range hist { + if w.Source != seasonSourceStats || w.PVKWh <= 0 || w.LoadKWh <= 0 || w.TempC == nil { + t.Fatalf("week %+v", w) + } + } + for _, w := range recent { + if w.PVKWh <= 0 || w.BaseW <= 0 { + t.Fatalf("recent week without energy %+v", w) + } + } +} + +// TestDemoForecastFillsFourteenDays checks that the demo forecast fills the +// check with the fourteen days before today and beats the season median. +func TestDemoForecastFillsFourteenDays(t *testing.T) { + c := LoadForecastCheck("", nil) + DemoForecast(time.Date(2026, 11, 23, 12, 0, 0, 0, time.Local), c) + d := c.Days() + if len(d) != ForecastWindow || d[len(d)-1].Day != "2026-11-22" { + t.Fatalf("days %+v", d) + } + if c.UseSeasonMedian() { + t.Fatal("demo forecast should beat the median") + } +} From d11383fde2fcf3bbeb7e976eb3ffb1334a5e1b88 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:56:39 +0100 Subject: [PATCH 03/30] feat(monitoring): serve the forecast check and the season weeks from the api Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/httpapi/access.go | 1 + dashboard/internal/httpapi/access_test.go | 5 +- dashboard/internal/httpapi/httpapi.go | 1 + dashboard/internal/httpapi/monitoring.go | 86 ++++++++++++++- dashboard/internal/httpapi/monitoring_test.go | 101 ++++++++++++++++++ 5 files changed, 190 insertions(+), 4 deletions(-) diff --git a/dashboard/internal/httpapi/access.go b/dashboard/internal/httpapi/access.go index defaeb08..07ece621 100644 --- a/dashboard/internal/httpapi/access.go +++ b/dashboard/internal/httpapi/access.go @@ -174,6 +174,7 @@ var routeTable = map[string]routeAccess{ "/api/v1/automations/learned": {group: groupPage, view: auth.RoleViewAutomations}, "/api/v1/monitoring": {group: groupPage, view: auth.RoleViewMonitoring}, "/api/v1/monitoring/ack": {group: groupPage, view: auth.RoleViewMonitoring}, + "/api/v1/monitoring/forecast": {group: groupPage, view: auth.RoleViewMonitoring}, "/api/v1/learning/status": {group: groupPage, view: auth.RoleViewAutomations}, "/api/v1/energy/": {group: groupPage, view: auth.RoleViewEnergy}, "/api/v1/energy/stats/chains": {group: groupPage, view: auth.RoleViewStats}, diff --git a/dashboard/internal/httpapi/access_test.go b/dashboard/internal/httpapi/access_test.go index 4e1785cb..573726f5 100644 --- a/dashboard/internal/httpapi/access_test.go +++ b/dashboard/internal/httpapi/access_test.go @@ -114,8 +114,9 @@ func TestEfficiencyRoutesNeedTheirOwnView(t *testing.T) { func TestMonitoringRoutesNeedViewMonitoring(t *testing.T) { cases := map[string]string{ - "/api/v1/monitoring": auth.RoleViewMonitoring, - "/api/v1/monitoring/ack": auth.RoleViewMonitoring, + "/api/v1/monitoring": auth.RoleViewMonitoring, + "/api/v1/monitoring/ack": auth.RoleViewMonitoring, + "/api/v1/monitoring/forecast": auth.RoleViewMonitoring, } for path, view := range cases { access, ok := routeTable[path] diff --git a/dashboard/internal/httpapi/httpapi.go b/dashboard/internal/httpapi/httpapi.go index f22259d6..12a7db6b 100644 --- a/dashboard/internal/httpapi/httpapi.go +++ b/dashboard/internal/httpapi/httpapi.go @@ -421,6 +421,7 @@ func NewRouterWithDependencies(reg *registry.Registry, configs *config.Manager, g.HandleFunc("/api/v1/automations/learned", handleAutomationLearned(dependencies.Learning, dependencies.LearnedValues, suggestionDeviceExists, dependencies.LearnedSeason)) g.HandleFunc("/api/v1/monitoring", handleMonitoring(dependencies.Monitoring)) g.HandleFunc("/api/v1/monitoring/ack", handleMonitoringAck(dependencies.Auth, dependencies.Monitoring)) + g.HandleFunc("/api/v1/monitoring/forecast", handleMonitoringForecast(dependencies.Monitoring)) g.HandleFunc("/api/v1/learning/status", handleLearningStatus(dependencies.Learning)) g.HandleFunc("/api/v1/learning/reset", handleLearningReset(dependencies.Auth, dependencies.Learning)) g.HandleFunc("/api/v1/energy/interpretation", handleEnergyInterpretation(store, resolver, dependencies.Auth)) diff --git a/dashboard/internal/httpapi/monitoring.go b/dashboard/internal/httpapi/monitoring.go index ab0c04d7..7895f162 100644 --- a/dashboard/internal/httpapi/monitoring.go +++ b/dashboard/internal/httpapi/monitoring.go @@ -6,14 +6,68 @@ import ( "time" "github.com/Developer-Simon/energy-node-dashboard/internal/auth" + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" "github.com/Developer-Simon/energy-node-dashboard/internal/monitoring" ) const ( - monitoringPath = "/api/v1/monitoring" - monitoringAckPath = "/api/v1/monitoring/ack" + monitoringPath = "/api/v1/monitoring" + monitoringAckPath = "/api/v1/monitoring/ack" + monitoringForecastPath = "/api/v1/monitoring/forecast" ) +// MonitoringForecast is the answer of GET /api/v1/monitoring/forecast. +type MonitoringForecast struct { + Forecast MonitoringForecastCheck `json:"forecast"` + Season MonitoringSeason `json:"season"` +} + +// MonitoringForecastCheck is the forecast check of the monitoring page. +// Days and Readers are never null. +type MonitoringForecastCheck struct { + Needed int `json:"needed"` + UseMedian bool `json:"use_median"` + Days []autolearn.ForecastDay `json:"days"` + Readers []autolearn.RuleRef `json:"readers"` +} + +// MonitoringSeason is the season view of the monitoring page. +type MonitoringSeason struct { + Year int `json:"year"` + Week int `json:"week"` + Weeks []MonitoringSeasonWeek `json:"weeks"` +} + +// MonitoringSeasonWeek is one week of the season view, without the rule fields. +type MonitoringSeasonWeek struct { + Key string `json:"key"` + Source string `json:"source"` + Days int `json:"days"` + ExportKWh float64 `json:"export_kwh"` + PVKWh float64 `json:"pv_kwh"` + LoadKWh float64 `json:"load_kwh"` + BaseW float64 `json:"base_w"` + TempC *float64 `json:"temp_c,omitempty"` +} + +// SeasonView keeps the shown fields of the season weeks. Weeks is never null. +func SeasonView(year, week int, weeks []autolearn.Week) MonitoringSeason { + view := MonitoringSeason{Year: year, Week: week, Weeks: []MonitoringSeasonWeek{}} + for _, item := range weeks { + view.Weeks = append(view.Weeks, MonitoringSeasonWeek{ + Key: item.Key, + Source: item.Source, + Days: item.Days, + ExportKWh: item.ExportKWh, + PVKWh: item.PVKWh, + LoadKWh: item.LoadKWh, + BaseW: item.BaseW, + TempC: item.TempC, + }) + } + return view +} + // MonitoringDeps verbindet die Routen mit Sammeln, Speicher und Lernwerten. // Nil heißt 501. type MonitoringDeps struct { @@ -24,6 +78,8 @@ type MonitoringDeps struct { // Learned liefert die Lernwerte wie GET /api/v1/automations/learned, // ergänzt um Gerätename und Icon. Learned func() MonitoringLearned + // Forecast liefert die Prognoseprüfung und die Saisonwochen, now ist die Zeit der Anfrage. + Forecast func(now time.Time) MonitoringForecast } // MonitoringLearned sind die Lernwerte der Überwachung. @@ -68,6 +124,32 @@ func handleMonitoring(deps *MonitoringDeps) http.HandlerFunc { } } +// handleMonitoringForecast serves GET /api/v1/monitoring/forecast. Without the +// Forecast dep the answer is 501. Days, Readers and Weeks are never null. +func handleMonitoringForecast(deps *MonitoringDeps) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + methodNotAllowed(w, http.MethodGet) + return + } + if deps == nil || deps.Forecast == nil { + writeError(w, http.StatusNotImplemented, "monitoring_unavailable", "Monitoring ist auf dieser Instanz nicht verfügbar.") + return + } + answer := deps.Forecast(time.Now()) + if answer.Forecast.Days == nil { + answer.Forecast.Days = []autolearn.ForecastDay{} + } + if answer.Forecast.Readers == nil { + answer.Forecast.Readers = []autolearn.RuleRef{} + } + if answer.Season.Weeks == nil { + answer.Season.Weeks = []MonitoringSeasonWeek{} + } + writeJSON(w, answer) + } +} + // handleMonitoringAck serves POST /api/v1/monitoring/ack. It needs the edit // setup role, and answers the monitoring page like GET after the change. func handleMonitoringAck(manager *auth.Manager, deps *MonitoringDeps) http.HandlerFunc { diff --git a/dashboard/internal/httpapi/monitoring_test.go b/dashboard/internal/httpapi/monitoring_test.go index 135859ff..eeab4ea3 100644 --- a/dashboard/internal/httpapi/monitoring_test.go +++ b/dashboard/internal/httpapi/monitoring_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Developer-Simon/energy-node-dashboard/internal/auth" + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" "github.com/Developer-Simon/energy-node-dashboard/internal/config" "github.com/Developer-Simon/energy-node-dashboard/internal/monitoring" "github.com/Developer-Simon/energy-node-dashboard/internal/registry" @@ -193,3 +194,103 @@ func TestMonitoringAckNeedsCSRF(t *testing.T) { t.Fatalf("POST with CSRF: %d %s", recorder.Code, recorder.Body.String()) } } + +// monitoringForecastGet reads the forecast check with the cookie. +func monitoringForecastGet(router http.Handler, cookie *http.Cookie) *httptest.ResponseRecorder { + request := httptest.NewRequest(http.MethodGet, monitoringForecastPath, nil) + request.AddCookie(cookie) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + return recorder +} + +func TestMonitoringForecastAnswers(t *testing.T) { + deps := &MonitoringDeps{ + Forecast: func(time.Time) MonitoringForecast { + return MonitoringForecast{ + Forecast: MonitoringForecastCheck{Needed: autolearn.ForecastWindow}, + Season: SeasonView(2026, 47, nil), + } + }, + } + router, manager := monitoringRouter(t, deps) + cookie, _ := guestCookie(t, router, manager, []string{auth.RoleViewMonitoring}) + + recorder := monitoringForecastGet(router, cookie) + if recorder.Code != http.StatusOK { + t.Fatalf("GET status %d: %s", recorder.Code, recorder.Body.String()) + } + var body struct { + Forecast struct { + Needed int `json:"needed"` + } `json:"forecast"` + Season struct { + Weeks []any `json:"weeks"` + } `json:"season"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body.Forecast.Needed != 14 { + t.Fatalf("needed = %d, want 14", body.Forecast.Needed) + } + if body.Season.Weeks == nil { + t.Fatalf("season.weeks is null: %s", recorder.Body.String()) + } +} + +func TestMonitoringForecastWithoutDepsIs501(t *testing.T) { + for name, deps := range map[string]*MonitoringDeps{"nil deps": nil, "no forecast": {}} { + router, manager := monitoringRouter(t, deps) + cookie, _ := guestCookie(t, router, manager, []string{auth.RoleViewMonitoring}) + + recorder := monitoringForecastGet(router, cookie) + if recorder.Code != http.StatusNotImplemented { + t.Fatalf("%s: status %d, want 501", name, recorder.Code) + } + if !strings.Contains(recorder.Body.String(), "monitoring_unavailable") { + t.Fatalf("%s: body %s, want code monitoring_unavailable", name, recorder.Body.String()) + } + } +} + +func TestMonitoringForecastPostIs405(t *testing.T) { + deps := &MonitoringDeps{ + Forecast: func(time.Time) MonitoringForecast { return MonitoringForecast{} }, + } + router, manager := monitoringRouter(t, deps) + cookie, csrf := guestCookie(t, router, manager, []string{auth.RoleViewMonitoring}) + + request := httptest.NewRequest(http.MethodPost, monitoringForecastPath, nil) + request.Header.Set("X-CSRF-Token", csrf) + request.AddCookie(cookie) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + if recorder.Code != http.StatusMethodNotAllowed { + t.Fatalf("POST status %d, want 405", recorder.Code) + } +} + +func TestSeasonViewDropsRuleFields(t *testing.T) { + weeks := []autolearn.Week{{ + Key: "2026-W46", + Source: "day", + Days: 7, + Triggers: map[string]float64{"a": 1}, + RunMin: map[string]float64{"b": 2}, + }} + season := SeasonView(2026, 47, weeks) + raw, err := json.Marshal(season) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), "triggers") || strings.Contains(string(raw), "run_min") { + t.Fatalf("SeasonView carries rule fields: %s", raw) + } + if len(season.Weeks) != 1 || season.Weeks[0].Key != "2026-W46" { + t.Fatalf("weeks = %+v, want the one week", season.Weeks) + } + if empty := SeasonView(2026, 47, nil); empty.Weeks == nil || len(empty.Weeks) != 0 { + t.Fatalf("empty weeks = %#v, want an empty list", empty.Weeks) + } +} From e135dccae02001dbcfefa150f5675be32b4c381c Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:57:33 +0100 Subject: [PATCH 04/30] feat(monitoring): collect the forecast check and season weeks for the endpoint Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 3 ++ dashboard/cmd/dashboard/monitoring.go | 25 ++++++++++++++ dashboard/cmd/dashboard/monitoring_test.go | 39 ++++++++++++++++++++++ 3 files changed, 67 insertions(+) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index f6e8b7aa..16a1b448 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -1487,6 +1487,9 @@ func main() { snap := energy.Aggregate(devices, energyResolver, time.Now().UTC()) return monitoringLearned(learned, devices, snap, energyResolver) }, + Forecast: func(now time.Time) httpapi.MonitoringForecast { + return monitoringForecast(forecastCheck, seasonStore, suggestions.currentDoc, now) + }, }, CommandObserver: origin.observeCommand, StorageFallback: storageFallback, diff --git a/dashboard/cmd/dashboard/monitoring.go b/dashboard/cmd/dashboard/monitoring.go index 5ef1d690..d593d349 100644 --- a/dashboard/cmd/dashboard/monitoring.go +++ b/dashboard/cmd/dashboard/monitoring.go @@ -1,10 +1,12 @@ package main import ( + "fmt" "strings" "sync" "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/httpapi" "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" @@ -101,3 +103,26 @@ func monitoringLearned(learned httpapi.MonitoringLearned, devices []registry.Dev } return learned } + +// monitoringForecast collects the forecast check and the season weeks for +// GET /api/v1/monitoring/forecast. The weeks run from the first ISO week two +// years back up to the ISO week of now. Without a readable rule document the +// readers stay empty. +func monitoringForecast(check *autolearn.ForecastCheck, season *autolearn.SeasonStore, doc func() (autolearn.Doc, bool), now time.Time) httpapi.MonitoringForecast { + year, week := now.ISOWeek() + from := fmt.Sprintf("%04d-W01", year-2) + to := fmt.Sprintf("%04d-W%02d", year, week) + readers := []autolearn.RuleRef{} + if d, ok := doc(); ok { + readers = autolearn.LearnedReaders(d, "site/surplus_left_wh") + } + return httpapi.MonitoringForecast{ + Forecast: httpapi.MonitoringForecastCheck{ + Needed: autolearn.ForecastWindow, + UseMedian: check.UseSeasonMedian(), + Days: check.Days(), + Readers: readers, + }, + Season: httpapi.SeasonView(year, week, season.Weeks(from, to)), + } +} diff --git a/dashboard/cmd/dashboard/monitoring_test.go b/dashboard/cmd/dashboard/monitoring_test.go index 22e9a116..2d9a9ed5 100644 --- a/dashboard/cmd/dashboard/monitoring_test.go +++ b/dashboard/cmd/dashboard/monitoring_test.go @@ -1,6 +1,8 @@ package main import ( + "path/filepath" + "reflect" "testing" "time" @@ -57,3 +59,40 @@ func findMonitoringNotice(notices []monitoring.Notice, id string) *monitoring.No } return nil } + +func TestMonitoringForecastCollects(t *testing.T) { + now := time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) + season := autolearn.LoadSeasonStore(filepath.Join(t.TempDir(), "season.json"), t.Logf) + season.Put(autolearn.Week{Key: "2024-W01", Source: "days", Days: 7}) + season.Put(autolearn.Week{Key: "2022-W10", Source: "days", Days: 7}) + check := autolearn.LoadForecastCheck(filepath.Join(t.TempDir(), "forecast.json"), t.Logf) + + doc := func() (autolearn.Doc, bool) { + return autolearn.Doc{Rules: []autolearn.Rule{{ + ID: "a", + Name: "Wallbox", + Conditions: []autolearn.Condition{{Learned: map[string]autolearn.LearnedRef{"threshold": {Key: "site/surplus_left_wh"}}}}, + }}}, true + } + got := monitoringForecast(check, season, doc, now) + + if got.Forecast.Needed != autolearn.ForecastWindow { + t.Errorf("Needed = %d, want %d", got.Forecast.Needed, autolearn.ForecastWindow) + } + if got.Season.Year != 2026 { + t.Errorf("Season.Year = %d, want 2026", got.Season.Year) + } + if len(got.Season.Weeks) != 1 || got.Season.Weeks[0].Key != "2024-W01" { + t.Fatalf("Season.Weeks = %+v, want only 2024-W01", got.Season.Weeks) + } + want := []autolearn.RuleRef{{ID: "a", Name: "Wallbox"}} + if !reflect.DeepEqual(got.Forecast.Readers, want) { + t.Errorf("Readers = %+v, want %+v", got.Forecast.Readers, want) + } + + none := func() (autolearn.Doc, bool) { return autolearn.Doc{}, false } + got = monitoringForecast(check, season, none, now) + if got.Forecast.Readers == nil || len(got.Forecast.Readers) != 0 { + t.Errorf("without document Readers = %#v, want empty", got.Forecast.Readers) + } +} From c8b003e21c95b1933329453f331e58494b99f855 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:57:53 +0100 Subject: [PATCH 05/30] feat(monitoring): add texts for forecast, season and the usual day Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 86 +++++++++++++++++++++++ dashboard/internal/webui/catalogs/en.json | 86 +++++++++++++++++++++++ 2 files changed, 172 insertions(+) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 5d31264b..53f5da30 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -3733,6 +3733,38 @@ "monitoring.compass.se": "Südost", "monitoring.compass.sw": "Südwest", "monitoring.compass.w": "West", + "monitoring.day.allday": "läuft fast den ganzen Tag, {duration}", + "monitoring.day.allday_short": "fast ganztags", + "monitoring.day.fact.ago": "vor {age}", + "monitoring.day.fact.changed": "Zuletzt geändert", + "monitoring.day.fact.days": "{n} Tagen", + "monitoring.day.fact.learned": "Gelernt aus", + "monitoring.day.fact.prev": "Vorher", + "monitoring.day.fact.prev_value": "{prev} statt {value}", + "monitoring.day.fact.runs": "{n} Läufen", + "monitoring.day.fact.sure": "Sicherheit", + "monitoring.day.fact.sure_no": "lernt noch, ab 10 Tagen sicher", + "monitoring.day.fact.sure_yes": "sicher", + "monitoring.day.free": "{duration} am Stück, keine feste Uhrzeit", + "monitoring.day.free_short": "{duration}, frei", + "monitoring.day.house": "Haus", + "monitoring.day.label": "Üblicher Tag, Pfeiltasten verschieben die Uhrzeit", + "monitoring.day.legend.night": "Nachtruhe", + "monitoring.day.legend.on": "üblich an", + "monitoring.day.night": "Nachtruhe {from} bis {to}", + "monitoring.day.now": "jetzt", + "monitoring.day.picked": "gewählte Zeit", + "monitoring.day.point": "üblich um {time}", + "monitoring.day.read.night": "Nachtruhe, kein Gerät üblich an", + "monitoring.day.read.night_on": "Nachtruhe. Üblich an: {names}", + "monitoring.day.read.none": "Kein Gerät üblich an", + "monitoring.day.read.on": "Üblich an: {names}", + "monitoring.day.state.active": "Haus aktiv", + "monitoring.day.state.quiet": "Haus ruhig", + "monitoring.day.sub": "Gelernt aus {n} Tagen. Tippe auf eine Zeile für den Verlauf übers Jahr.", + "monitoring.day.title": "Ein üblicher Tag", + "monitoring.day.unsure": "lernt noch", + "monitoring.day.window": "{from} bis {to}", "monitoring.empty.text": "Keine offenen Meldungen. Neue erscheinen hier, der Reiter bekommt dann einen Punkt.", "monitoring.empty.title": "Alles ruhig", "monitoring.energy_line.count.one": "{count} Meldung zur Energie", @@ -3754,6 +3786,31 @@ "monitoring.filter.label": "Quelle", "monitoring.filter.learn": "Lernfunktionen", "monitoring.filter.suggest": "Vorschläge", + "monitoring.forecast.chart.label": "Prognose und Messung der letzten Tage, Pfeiltasten wählen den Tag", + "monitoring.forecast.days.sub": "Rest-Überschuss ab 10 Uhr in kWh", + "monitoring.forecast.days.title": "Die letzten {n} Tage", + "monitoring.forecast.legend.actual": "Gemessen", + "monitoring.forecast.legend.forecast": "Prognose um 10 Uhr", + "monitoring.forecast.legend.median": "Saisonmedian", + "monitoring.forecast.legend.near": "Prognose war näher", + "monitoring.forecast.load_failed": "Die Prognose konnte nicht geladen werden.", + "monitoring.forecast.mae.caption": "Mittlere Abweichung vom gemessenen Rest des Tages. Die Prognose war an {hits} von {days} Tagen näher.", + "monitoring.forecast.mae.forecast": "Prognose", + "monitoring.forecast.mae.median": "Saisonmedian", + "monitoring.forecast.progress": "{have} von {needed} Tagen", + "monitoring.forecast.read.actual": "Gemessen", + "monitoring.forecast.read.forecast": "Prognose", + "monitoring.forecast.read.median": "Median", + "monitoring.forecast.status.forecast.text": "Die Prognose lag in den letzten {days} Tagen im Mittel {forecast} neben dem gemessenen Rest des Tages. Der Saisonmedian lag {median} daneben.", + "monitoring.forecast.status.forecast.title": "Die Node folgt ihrer Prognose", + "monitoring.forecast.status.learning.text": "Nach {needed} Tagen vergleicht sie die Prognose mit dem Saisonmedian. Bis dahin gilt die Prognose. Noch {left} Tage.", + "monitoring.forecast.status.learning.title": "Die Node prüft ihre Prognose noch", + "monitoring.forecast.status.median.text": "Die Prognose lag in den letzten {days} Tagen im Mittel {forecast} daneben, der Saisonmedian nur {median}. Sobald die Prognose wieder genauer ist, wechselt die Node zurück.", + "monitoring.forecast.status.median.title": "Die Node folgt gerade dem Saisonmedian", + "monitoring.forecast.use": "Um 10 Uhr schätzt die Node, wie viel Überschuss der Rest des Tages noch bringt. Diesen Wert nutzen {rules}.", + "monitoring.forecast.use_none": "Um 10 Uhr schätzt die Node, wie viel Überschuss der Rest des Tages noch bringt. Noch keine Regel nutzt diesen Wert.", + "monitoring.forecast.verdict.forecast": "Prognose {forecast} daneben, Median {median}. Die Prognose war näher.", + "monitoring.forecast.verdict.median": "Prognose {forecast} daneben, Median {median}. Der Median war näher.", "monitoring.group.known": "Zur Kenntnis genommen", "monitoring.group.new": "Neu", "monitoring.learned.count": "{have} von {total}", @@ -3790,9 +3847,37 @@ "monitoring.notice.soc_capacity.title": "Akkustand ohne Kapazität", "monitoring.notice.unassigned.text": "Leistungswerte ohne Rolle sind oft die eigentliche Ursache einer Bilanzlücke.", "monitoring.notice.unassigned.title": "{count} Leistungswerte ohne Rolle", + "monitoring.run.power_for": "{power} für {duration}", + "monitoring.run.sub": "Energie je Lauf, erkannte Programme als Marken", + "monitoring.run.title": "Ein Lauf", + "monitoring.season.chart.label": "Jahresvergleich {metric}, Pfeiltasten wählen die Woche", + "monitoring.season.empty": "Das Saisongedächtnis ist noch leer oder hat kein Vorjahr. Es füllt sich jede Woche.", + "monitoring.season.legend.gap": "keine Daten", + "monitoring.season.metric.base": "Grundlast", + "monitoring.season.metric.export": "Einspeisung", + "monitoring.season.metric.label": "Kennzahl", + "monitoring.season.metric.load": "Verbrauch", + "monitoring.season.metric.pv": "PV", + "monitoring.season.metric.temp": "Außentemperatur", + "monitoring.season.note.later": "kommt noch", + "monitoring.season.note.off": "Node war aus", + "monitoring.season.note.stats": "aus der Energiestatistik", + "monitoring.season.range": "{from} bis {to}", + "monitoring.season.sub": "Wochenwerte aus dem Saisongedächtnis. Daraus kommt auch der Saisonmedian.", + "monitoring.season.sum.lead": "Bis KW {week}", + "monitoring.season.sum.lead_mean": "Mittel bis KW {week}", + "monitoring.season.sum.prev": "Vorjahr {value}", + "monitoring.season.sum.skipped": "Ohne {n} Wochen, die in einem der Jahre fehlen", + "monitoring.season.title": "Jahresvergleich", + "monitoring.season.week": "KW {week}", "monitoring.since.days": "seit {n} Tagen", "monitoring.since.today": "seit heute", "monitoring.since.yesterday": "seit gestern", + "monitoring.site.reserve": "aus Minutenwerten", + "monitoring.site.reserve_est": "Schätzung, wird aus Minutenwerten genauer", + "monitoring.site.sub": "Werte, die Regeln direkt lesen", + "monitoring.site.surplus_note": "Prognose von 10 Uhr", + "monitoring.site.to_forecast": "Zur Prognose", "monitoring.source.chain": "Messketten", "monitoring.source.energy": "Energie-Bilanz", "monitoring.source.learn": "Lernfunktionen", @@ -3827,6 +3912,7 @@ "monitoring.step.suggestion_open.button": "Vorschlag öffnen", "monitoring.steps.title": "Empfohlene Schritte", "monitoring.value.time": "{time} Uhr", + "monitoring.view.forecast": "Prognose", "monitoring.view.label": "Ansicht", "monitoring.view.learned": "Lernwerte", "monitoring.view.notices": "Meldungen", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 83f36f4d..e4806815 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -3733,6 +3733,38 @@ "monitoring.compass.se": "southeast", "monitoring.compass.sw": "southwest", "monitoring.compass.w": "west", + "monitoring.day.allday": "runs almost all day, {duration}", + "monitoring.day.allday_short": "almost all day", + "monitoring.day.fact.ago": "{age} ago", + "monitoring.day.fact.changed": "Last changed", + "monitoring.day.fact.days": "{n} days", + "monitoring.day.fact.learned": "Learned from", + "monitoring.day.fact.prev": "Before", + "monitoring.day.fact.prev_value": "{prev} instead of {value}", + "monitoring.day.fact.runs": "{n} runs", + "monitoring.day.fact.sure": "Certainty", + "monitoring.day.fact.sure_no": "still learning, certain from 10 days", + "monitoring.day.fact.sure_yes": "certain", + "monitoring.day.free": "{duration} at a time, no fixed time", + "monitoring.day.free_short": "{duration}, any time", + "monitoring.day.house": "House", + "monitoring.day.label": "Usual day, arrow keys move the time", + "monitoring.day.legend.night": "night rest", + "monitoring.day.legend.on": "usually on", + "monitoring.day.night": "Night rest {from} to {to}", + "monitoring.day.now": "now", + "monitoring.day.picked": "chosen time", + "monitoring.day.point": "usually at {time}", + "monitoring.day.read.night": "Night rest, no device usually on", + "monitoring.day.read.night_on": "Night rest. Usually on: {names}", + "monitoring.day.read.none": "No device usually on", + "monitoring.day.read.on": "Usually on: {names}", + "monitoring.day.state.active": "House active", + "monitoring.day.state.quiet": "House quiet", + "monitoring.day.sub": "Learned from {n} days. Tap a row for the course over the year.", + "monitoring.day.title": "A usual day", + "monitoring.day.unsure": "still learning", + "monitoring.day.window": "{from} to {to}", "monitoring.empty.text": "No open notices. New ones appear here and the tab gets a dot.", "monitoring.empty.title": "All quiet", "monitoring.energy_line.count.one": "{count} notice about energy", @@ -3754,6 +3786,31 @@ "monitoring.filter.label": "Source", "monitoring.filter.learn": "Learning", "monitoring.filter.suggest": "Suggestions", + "monitoring.forecast.chart.label": "Forecast and measurement of the last days, arrow keys choose the day", + "monitoring.forecast.days.sub": "Remaining surplus from 10:00 in kWh", + "monitoring.forecast.days.title": "The last {n} days", + "monitoring.forecast.legend.actual": "Measured", + "monitoring.forecast.legend.forecast": "Forecast at 10:00", + "monitoring.forecast.legend.median": "Season median", + "monitoring.forecast.legend.near": "Forecast was closer", + "monitoring.forecast.load_failed": "The forecast could not be loaded.", + "monitoring.forecast.mae.caption": "Mean deviation from the measured rest of the day. The forecast was closer on {hits} of {days} days.", + "monitoring.forecast.mae.forecast": "Forecast", + "monitoring.forecast.mae.median": "Season median", + "monitoring.forecast.progress": "{have} of {needed} days", + "monitoring.forecast.read.actual": "Measured", + "monitoring.forecast.read.forecast": "Forecast", + "monitoring.forecast.read.median": "Median", + "monitoring.forecast.status.forecast.text": "Over the last {days} days the forecast was off by {forecast} on average from the measured rest of the day. The season median was off by {median}.", + "monitoring.forecast.status.forecast.title": "The node follows its forecast", + "monitoring.forecast.status.learning.text": "After {needed} days it compares the forecast with the season median. Until then the forecast applies. {left} days to go.", + "monitoring.forecast.status.learning.title": "The node is still checking its forecast", + "monitoring.forecast.status.median.text": "Over the last {days} days the forecast was off by {forecast} on average, the season median only by {median}. Once the forecast is more accurate again, the node switches back.", + "monitoring.forecast.status.median.title": "The node currently follows the season median", + "monitoring.forecast.use": "At 10:00 the node estimates how much surplus the rest of the day will bring. This value is used by {rules}.", + "monitoring.forecast.use_none": "At 10:00 the node estimates how much surplus the rest of the day will bring. No rule uses this value yet.", + "monitoring.forecast.verdict.forecast": "Forecast off by {forecast}, median by {median}. The forecast was closer.", + "monitoring.forecast.verdict.median": "Forecast off by {forecast}, median by {median}. The median was closer.", "monitoring.group.known": "Acknowledged", "monitoring.group.new": "New", "monitoring.learned.count": "{have} of {total}", @@ -3790,9 +3847,37 @@ "monitoring.notice.soc_capacity.title": "Battery level without capacity", "monitoring.notice.unassigned.text": "Power values without a role are often the real cause of a gap in the balance.", "monitoring.notice.unassigned.title": "{count} power values without a role", + "monitoring.run.power_for": "{power} for {duration}", + "monitoring.run.sub": "Energy per run, detected programs as marks", + "monitoring.run.title": "One run", + "monitoring.season.chart.label": "Year comparison {metric}, arrow keys choose the week", + "monitoring.season.empty": "The season memory is still empty or has no previous year. It fills up every week.", + "monitoring.season.legend.gap": "no data", + "monitoring.season.metric.base": "Base load", + "monitoring.season.metric.export": "Feed-in", + "monitoring.season.metric.label": "Figure", + "monitoring.season.metric.load": "Consumption", + "monitoring.season.metric.pv": "PV", + "monitoring.season.metric.temp": "Outdoor temperature", + "monitoring.season.note.later": "still to come", + "monitoring.season.note.off": "Node was off", + "monitoring.season.note.stats": "from the energy statistics", + "monitoring.season.range": "{from} to {to}", + "monitoring.season.sub": "Weekly values from the season memory. The season median comes from here too.", + "monitoring.season.sum.lead": "Up to week {week}", + "monitoring.season.sum.lead_mean": "Average up to week {week}", + "monitoring.season.sum.prev": "Previous year {value}", + "monitoring.season.sum.skipped": "Without {n} weeks missing in one of the years", + "monitoring.season.title": "Year comparison", + "monitoring.season.week": "Week {week}", "monitoring.since.days": "for {n} days", "monitoring.since.today": "since today", "monitoring.since.yesterday": "since yesterday", + "monitoring.site.reserve": "from minute values", + "monitoring.site.reserve_est": "Estimate, gets more accurate from minute values", + "monitoring.site.sub": "Values that rules read directly", + "monitoring.site.surplus_note": "Forecast from 10:00", + "monitoring.site.to_forecast": "To the forecast", "monitoring.source.chain": "Measurement chains", "monitoring.source.energy": "Energy balance", "monitoring.source.learn": "Learning", @@ -3827,6 +3912,7 @@ "monitoring.step.suggestion_open.button": "Open suggestion", "monitoring.steps.title": "Recommended steps", "monitoring.value.time": "{time}", + "monitoring.view.forecast": "Forecast", "monitoring.view.label": "View", "monitoring.view.learned": "Learned values", "monitoring.view.notices": "Notices", From 8e5f7211bae5f95908129aba04fc272b7bc706b2 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:59:44 +0100 Subject: [PATCH 06/30] feat(monitoring): add the insight model for season and forecast Co-Authored-By: Claude Sonnet 5.5 --- .../static/js/monitoring-insight-model.js | 196 ++++++++++++++++++ .../test/monitoring-insight-model.test.mjs | 112 ++++++++++ 2 files changed, 308 insertions(+) create mode 100644 dashboard/internal/webui/static/js/monitoring-insight-model.js create mode 100644 dashboard/test/monitoring-insight-model.test.mjs diff --git a/dashboard/internal/webui/static/js/monitoring-insight-model.js b/dashboard/internal/webui/static/js/monitoring-insight-model.js new file mode 100644 index 00000000..f2f7aac2 --- /dev/null +++ b/dashboard/internal/webui/static/js/monitoring-insight-model.js @@ -0,0 +1,196 @@ +// Modell der Monitoring-Seite fuer Prognose und Saison: reine Funktionen ohne DOM, Alpine und Intl. +// Die Monatsnamen kommen als monthLabels herein, Zahlen am Rand werden hier ganzzahlig gruppiert. +(() => { + const METRICS = [ + { id: 'pv', key: 'pv_kwh', unit: 'kWh', color: 'var(--flow-pv)', sum: true, d: 0, good: 1, area: true }, + { id: 'load', key: 'load_kwh', unit: 'kWh', color: 'var(--flow-load)', sum: true, d: 0, good: -1, area: true }, + { id: 'export', key: 'export_kwh', unit: 'kWh', color: 'var(--flow-grid)', sum: true, d: 0, good: 1, area: true }, + { id: 'base', key: 'base_w', unit: 'W', color: 'var(--flow-heatpump)', sum: false, d: 0, good: -1, area: true }, + { id: 'temp', key: 'temp_c', unit: '°C', color: 'var(--accent)', sum: false, d: 1, good: 0, area: false }, + ]; + // erste ISO-Woche jedes Monats, fuer die Achse + const MONTH_WEEKS = [1, 5, 9, 14, 18, 23, 27, 31, 36, 40, 44, 49]; + const FORECAST_NEEDED = 14; + + const metricOf = (id) => METRICS.find((m) => m.id === id) || METRICS[0]; + + // Ganzzahl mit Punkt als Tausendertrenner, wie de-DE, ohne Intl. + function intText(v) { + const r = Math.round(v); + const digits = String(Math.abs(r)).replace(/\B(?=(\d{3})+(?!\d))/g, '.'); + return (r < 0 ? '-' : '') + digits; + } + + function niceStep(raw) { + const p = Math.pow(10, Math.floor(Math.log10(raw || 1))); + for (const f of [1, 2, 2.5, 5, 10]) if (f * p >= raw) return f * p; + return 10 * p; + } + + // Index = ISO-Woche (1..53), Eintrag { v, src } oder null fuer eine Luecke. + function seasonSeries(weeks, year, metricId) { + const m = metricOf(metricId); + // Index = ISO-Woche, 1..52 wie im Entwurf (ISO-Woche 53 wird nicht gezeichnet). + const out = new Array(53).fill(null); + for (const w of weeks || []) { + const [yy, ww] = String(w.key).split('-W').map(Number); + if (yy !== year || !(ww >= 1 && ww <= 52)) continue; + const v = w[m.key]; + if (typeof v !== 'number' || !isFinite(v)) continue; + out[ww] = { v, src: w.source }; + } + return out; + } + + // Kopfzahl: bis zur aktuellen Woche, nur Wochen, die in beiden Jahren da sind. + function seasonSummary(season, metricId) { + const m = metricOf(metricId); + const a = seasonSeries(season.weeks, season.year, metricId); + const b = seasonSeries(season.weeks, season.year - 1, metricId); + let sa = 0; let sb = 0; let n = 0; + for (let w = 1; w <= season.week; w++) if (a[w] && b[w]) { sa += a[w].v; sb += b[w].v; n++; } + if (!n) return null; + const cur = m.sum ? sa : sa / n; + const prev = m.sum ? sb : sb / n; + const diff = m.id === 'temp' ? cur - prev : (prev ? (cur - prev) / prev * 100 : 0); + const g = m.good * Math.sign(cur - prev); + return { cur, prev, diff, tone: g > 0 ? 'is-up' : g < 0 ? 'is-down' : '', skipped: season.week - n }; + } + + // Linienstuecke, ein neuer Lauf beginnt bei jeder Quellenwechsel oder Luecke. + function runs(s) { + const out = []; let cur = null; + for (let w = 1; w <= 52; w++) { + const p = s[w]; + if (!p) { cur = null; continue; } + if (!cur || cur.src !== p.src) { + cur = { src: p.src, pts: [] }; + // naechster Lauf beginnt am letzten Punkt des vorigen, damit die Flaeche durchgeht + const prev = out[out.length - 1]; + if (prev && s[w - 1]) cur.pts.push(prev.pts[prev.pts.length - 1]); + out.push(cur); + } + cur.pts.push([w, p.v]); + } + return out; + } + + // Jahresdiagramm: years ist 2 oder 3 (wie viele Jahre gezeigt werden, das aktuelle zuerst). + function seasonChart(season, metricId, years, width, narrow, monthLabels) { + const m = metricOf(metricId); + const y = season.year; + const yearList = years === 3 ? [y, y - 1, y - 2] : [y, y - 1]; + const W = width || 600; const H = narrow ? 168 : 212; + const pad = { l: 38, r: 10, t: 10, b: 24 }; + const series = (yr) => seasonSeries(season.weeks, yr, metricId); + let lo = Infinity; let hi = -Infinity; + for (const yr of yearList) for (const p of series(yr)) if (p) { lo = Math.min(lo, p.v); hi = Math.max(hi, p.v); } + if (!isFinite(lo)) { lo = 0; hi = 1; } + const step = niceStep((hi - Math.min(0, lo)) / 3); + const y0 = lo < 0 || m.id === 'temp' ? Math.floor(Math.min(0, lo) / step) * step : 0; + const y1 = Math.ceil(hi / step) * step; + const x = (w) => pad.l + (w - 1) / 51 * (W - pad.l - pad.r); + const yv = (v) => pad.t + (1 - (v - y0) / (y1 - y0)) * (H - pad.t - pad.b); + const geo = { W, H, pad, x, y: yv, y0, y1, step }; + + const line = (pts) => pts.map((p, i) => (i ? 'L' : 'M') + x(p[0]).toFixed(1) + ' ' + yv(p[1]).toFixed(1)).join(' '); + const area = (pts) => line(pts) + ' L' + x(pts[pts.length - 1][0]).toFixed(1) + ' ' + yv(y0).toFixed(1) + ' L' + x(pts[0][0]).toFixed(1) + ' ' + yv(y0).toFixed(1) + ' Z'; + + let s = ''; + return { svg: s, geo }; + } + + // Ergebnis der Prognose: Lernphase, Median oder Prognose, mit den mittleren Fehlern. + function forecastState(check) { + const days = check.days || []; + const needed = check.needed != null ? check.needed : FORECAST_NEEDED; + const n = days.length; + const maeF = days.reduce((sum, d) => sum + Math.abs(d.forecast_wh - d.actual_wh), 0) / Math.max(1, n); + const maeM = days.reduce((sum, d) => sum + Math.abs(d.season_wh - d.actual_wh), 0) / Math.max(1, n); + const hits = days.filter((d) => Math.abs(d.forecast_wh - d.actual_wh) < Math.abs(d.season_wh - d.actual_wh)).length; + let kind = 'forecast'; + if (n < needed) kind = 'learning'; + else if (maeF >= maeM) kind = 'median'; + return { kind, maeF, maeM, hits, have: n, needed }; + } + + // Tagesbalken Prognose gegen Messung, leere Plaetze bis needed. + function forecastChart(days, needed, width, narrow) { + const W = width || 600; const H = narrow ? 150 : 176; + const pad = { l: 34, r: 6, t: 8, b: 36 }; + const n = needed != null ? needed : FORECAST_NEEDED; + const cw = (W - pad.l - pad.r) / n; + const max = days.reduce((top, d) => Math.max(top, d.forecast_wh, d.actual_wh, d.season_wh), 4000); + const top = Math.ceil(max / 2000) * 2000; + const yv = (wh) => pad.t + (1 - wh / top) * (H - pad.t - pad.b); + const bw = Math.min(14, cw * 0.28); + const geo = { W, H, pad, cw }; + + let s = ''; + return { svg: s, geo }; + } + + window.MonitoringInsight = { + METRICS, + seasonSeries, + seasonSummary, + seasonChart, + forecastState, + forecastChart, + }; +})(); diff --git a/dashboard/test/monitoring-insight-model.test.mjs b/dashboard/test/monitoring-insight-model.test.mjs new file mode 100644 index 00000000..0fea136c --- /dev/null +++ b/dashboard/test/monitoring-insight-model.test.mjs @@ -0,0 +1,112 @@ +// Tests for the monitoring insight model (season and forecast): series, summary, charts, forecast state. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { JSDOM } from 'jsdom'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const jsDir = path.join(here, '..', 'internal', 'webui', 'static', 'js'); +const source = fs.readFileSync(path.join(jsDir, 'monitoring-insight-model.js'), 'utf8'); + +function load() { + const dom = new JSDOM('', { runScripts: 'outside-only' }); + vm.runInContext(source, dom.getInternalVMContext()); + return dom.window.MonitoringInsight; +} + +// Results come from the vm realm, so they are copied into this realm before strict comparison. +const plain = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v))); +const raw = load(); +const M = Object.fromEntries(Object.entries(raw).map(([name, fn]) => [name, typeof fn === 'function' ? (...args) => plain(fn(...args)) : plain(fn)])); + +const MONTHS = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']; + +test('seasonSeries keeps gaps as null and sources', () => { + const weeks = [ + { key: '2026-W01', source: 'stats', pv_kwh: 10 }, + { key: '2026-W03', source: 'days', pv_kwh: 30 }, + ]; + const s = M.seasonSeries(weeks, 2026, 'pv'); + assert.equal(s.length, 53); + assert.equal(s[1].src, 'stats'); + assert.equal(s[2], null); + assert.equal(s[3].src, 'days'); +}); + +test('seasonSummary compares only common weeks', () => { + const weeks = [ + { key: '2026-W01', source: 'days', pv_kwh: 10, load_kwh: 10, temp_c: 4 }, + { key: '2026-W02', source: 'days', pv_kwh: 20, load_kwh: 20, temp_c: 6 }, + { key: '2026-W03', source: 'days', pv_kwh: 30, load_kwh: 30, temp_c: 8 }, + { key: '2025-W01', source: 'days', pv_kwh: 10, load_kwh: 10, temp_c: 2 }, + { key: '2025-W03', source: 'days', pv_kwh: 20, load_kwh: 20, temp_c: 3 }, + ]; + const season = { year: 2026, week: 3, weeks }; + const pv = M.seasonSummary(season, 'pv'); + assert.equal(pv.cur, 40); + assert.equal(pv.prev, 30); + assert.equal(pv.skipped, 1); + assert.ok(Math.abs(pv.diff - 33.3) < 0.1, String(pv.diff)); + assert.equal(pv.tone, 'is-up'); + assert.equal(M.seasonSummary(season, 'load').tone, 'is-down'); + // temp: Mittel 2026 (4 und 8) gegen Mittel 2025 (2 und 3), Gradunterschied + const temp = M.seasonSummary(season, 'temp'); + assert.equal(temp.tone, ''); + assert.ok(Math.abs(temp.diff - (6 - 2.5)) < 0.01, String(temp.diff)); +}); + +test('seasonSummary is null without a common week', () => { + const onlyCurrent = { year: 2026, week: 3, weeks: [{ key: '2026-W01', source: 'days', pv_kwh: 10 }] }; + assert.equal(M.seasonSummary(onlyCurrent, 'pv'), null); + assert.equal(M.seasonSummary({ year: 2026, week: 3, weeks: [] }, 'pv'), null); +}); + +test('forecastState learning with zero days', () => { + const s = M.forecastState({ days: [], needed: 14 }); + assert.equal(s.kind, 'learning'); + assert.equal(s.have, 0); + assert.equal(s.needed, 14); + assert.equal(s.maeF, 0); + assert.equal(s.maeM, 0); + assert.equal(s.hits, 0); +}); + +test('forecastState picks the median when it is not worse', () => { + const days = Array.from({ length: 14 }, (_, i) => ({ + day: `2026-11-${String(i + 1).padStart(2, '0')}`, + actual_wh: 5000, + forecast_wh: 6000, + season_wh: 6000, + })); + const s = M.forecastState({ days, needed: 14 }); + assert.equal(s.kind, 'median'); + assert.equal(s.maeF, 1000); + assert.equal(s.maeM, 1000); + assert.equal(s.hits, 0); + assert.equal(s.have, 14); +}); + +test('seasonChart returns an svg without NaN, also for an empty season', () => { + const weeks = [{ key: '2026-W01', source: 'days', pv_kwh: 10 }, { key: '2026-W02', source: 'days', pv_kwh: 20 }]; + const full = M.seasonChart({ year: 2026, week: 2, weeks }, 'pv', 2, 600, false, MONTHS.map((m) => m.slice(0, 3))); + assert.ok(full.svg.startsWith(' m.slice(0, 3))); + assert.ok(empty.svg.startsWith(' { + const days = [{ day: '2026-11-01', actual_wh: 3000, forecast_wh: 3500, season_wh: 2000 }]; + const out = M.forecastChart(days, 14, 600, false); + assert.ok(out.svg.startsWith(' Date: Mon, 23 Nov 2026 21:01:19 +0100 Subject: [PATCH 07/30] feat(monitoring): add the usual day to the insight model Add dayRows, onAt, runRows and yearBand to window.MonitoringInsight, ported from psLearned in the draft. Covers windows over midnight, point and free rows, the duration from the cycle and power values, and the year band that needs four common weeks. Co-Authored-By: Claude Sonnet 5.5 --- .../static/js/monitoring-insight-model.js | 126 ++++++++++++++++++ .../test/monitoring-insight-model.test.mjs | 81 +++++++++++ 2 files changed, 207 insertions(+) diff --git a/dashboard/internal/webui/static/js/monitoring-insight-model.js b/dashboard/internal/webui/static/js/monitoring-insight-model.js index f2f7aac2..642c0f55 100644 --- a/dashboard/internal/webui/static/js/monitoring-insight-model.js +++ b/dashboard/internal/webui/static/js/monitoring-insight-model.js @@ -185,6 +185,128 @@ return { svg: s, geo }; } + // Uhrzeit HH:MM in Minuten seit Mitternacht, sonst null. + function clock(v) { + const m = /^(\d\d):(\d\d)$/.exec(String(v)); + return m ? Number(m[1]) * 60 + Number(m[2]) : null; + } + + // Intervall [a, b) auf der 24-h-Achse in Prozent, ueber Mitternacht in zwei Teilen. + const DAY_STEP = 14.4; + const EPS = 1e-6; + function segs(a, b) { + const parts = b > a ? [[a, b]] : [[a, 1440], [0, b]]; + return parts.filter(([x, y]) => y > x).map(([x, y]) => ({ left: x / DAY_STEP, width: (y - x) / DAY_STEP })); + } + + // Geraete aus den gelernten Werten, nach Name sortiert (Sprache aus I18n). + function collectDevices(values) { + const by = new Map(); + for (const v of values || []) { + if (!v.key || !v.key.startsWith('device/')) continue; + const [, id, field] = v.key.split('/'); + if (!by.has(id)) by.set(id, { id, name: id, icon: 'ico-device', f: {} }); + const d = by.get(id); + if (v.device_name) d.name = v.device_name; + if (v.device_icon) d.icon = v.device_icon; + d.f[field] = v; + } + const locale = (window.I18n && window.I18n.locale) || 'de'; + return [...by.values()].sort((a, b) => a.name.localeCompare(b.name, locale)); + } + + // Zeilen des ueblichen Tages: erst das Haus (Nachtruhe), dann Geraete. + // kind: night (Haus), on (Fenster), point (nur Beginn oder Ende, 15 Minuten), free (nur Laufzeit). + function dayRows(values) { + const by = new Map(); + for (const v of values || []) by.set(v.key, v); + const nr = by.get('site/night_rest'); const ds = by.get('site/day_start'); + const rows = []; + const a = nr ? clock(nr.value) : null; const b = ds ? clock(ds.value) : null; + if (nr && ds && a != null && b != null) { + const n = Math.min(nr.n || 0, ds.n || 0); + rows.push({ id: 'house', kind: 'night', name: 'Haus', icon: 'ico-user', segs: segs(a, b), from: nr.value, to: ds.value, + minutes: (b - a + 1440) % 1440, sure: n >= 10, n, keys: ['site/night_rest', 'site/day_start'], year: [nr, ds], entries: [nr, ds] }); + } else { + const present = [nr, ds].filter(Boolean); + rows.push({ id: 'house', kind: 'free', name: 'Haus', icon: 'ico-user', segs: [], from: null, to: null, minutes: null, + sure: false, n: 0, keys: present.map((v) => v.key), year: null, entries: present }); + } + for (const d of collectDevices(values)) { + const on = d.f.usual_on; const off = d.f.usual_off; const rt = d.f.usual_runtime_s; + const base = { id: d.id, name: d.name, icon: d.icon }; + if (on && off) { + const s = clock(on.value); const e = clock(off.value); + const n = Math.min(on.n || 0, off.n || 0); + rows.push({ ...base, kind: 'on', segs: segs(s, e), from: on.value, to: off.value, minutes: (e - s + 1440) % 1440, + sure: n >= 10, n, keys: [on.key, off.key], year: [on, off], entries: [on, off] }); + } else if (on || off) { + const only = on || off; const t = clock(only.value); + const s = on ? t : (t - 15 + 1440) % 1440; + rows.push({ ...base, kind: 'point', segs: segs(s, (s + 15) % 1440), from: on ? only.value : null, to: off ? only.value : null, + minutes: null, sure: (only.n || 0) >= 10, n: only.n || 0, keys: [only.key], year: null, entries: [only] }); + } else if (rt) { + rows.push({ ...base, kind: 'free', segs: [], from: null, to: null, minutes: Math.round(rt.value / 60), + sure: (rt.n || 0) >= 10, n: rt.n || 0, keys: [rt.key], year: null, entries: [rt] }); + } + } + return rows; + } + + // Welche Zeilen laufen zu einer Minute: Nachtruhe und die Namen der on-Zeilen. + function onAt(rows, minute) { + const inSeg = (r) => (r.segs || []).some((g) => minute >= g.left * DAY_STEP - EPS && minute < (g.left + g.width) * DAY_STEP - EPS); + const list = rows || []; + const house = list.find((r) => r.id === 'house'); + return { + night: !!house && house.kind === 'night' && inSeg(house), + on: list.filter((r) => r.kind === 'on' && inSeg(r)).map((r) => r.name), + }; + } + + // Laufzeiten der Geraete mit Zyklus oder Leistung, relativ zum groessten Wert. + function runRows(values) { + const list = []; + for (const d of collectDevices(values)) { + const e = d.f.cycle_wh; const p = d.f.op_power_w; const rt = d.f.usual_runtime_s; + if (!e && !p) continue; + const wh = e ? e.value : null; + const seconds = rt ? rt.value : (e && p && p.value ? e.value / p.value * 3600 : null); + list.push({ id: d.id, name: d.name, icon: d.icon, wh, powerW: p ? p.value : null, seconds, + programs: (e && e.programs) || [], sure: ((e || p).n || 0) >= 10 }); + } + const max = Math.max(1, ...list.flatMap((r) => [r.wh || 0, ...r.programs])); + return list.map((r) => ({ id: r.id, name: r.name, icon: r.icon, wh: r.wh, powerW: r.powerW, seconds: r.seconds, + pct: r.wh ? r.wh / max * 100 : 0, ticks: r.programs.map((x) => x / max * 100), sure: r.sure })); + } + + // Jahreslauf eines Fensters: je Woche das uebliche Band zwischen Beginn und Ende, nur gemeinsame Wochen. + function yearBand(onEntry, offEntry, night) { + const weekMap = (entry) => new Map(((entry && entry.year) || []).map((y) => [y.week, y.value])); + const on = weekMap(onEntry); const off = weekMap(offEntry); + const weeks = [...on.keys()].filter((k) => off.has(k)).sort(); + const pts = []; + for (const k of weeks) { + const x = clock(on.get(k)); const y = clock(off.get(k)); + if (x == null || y == null) continue; + pts.push({ k, x, y: y < x ? y + 1440 : y }); + } + const n = pts.length; + if (n < 4) return null; + const W = 300; const H = 64; const P = 4; + const lo = Math.floor((Math.min(...pts.map((p) => p.x)) - 30) / 60) * 60; + const hi = Math.ceil((Math.max(...pts.map((p) => p.y)) + 30) / 60) * 60; + const X = (i) => P + i / (n - 1) * (W - 2 * P); + const Y = (m) => P + (m - lo) / (hi - lo) * (H - 2 * P); + const top = pts.map((p, i) => (i ? 'L' : 'M') + X(i).toFixed(1) + ' ' + Y(p.x).toFixed(1)).join(' '); + const bot = pts.slice().reverse().map((p, j) => 'L' + X(n - 1 - j).toFixed(1) + ' ' + Y(p.y).toFixed(1)).join(' '); + const line = (useEnd) => pts.map((p, i) => (i ? 'L' : 'M') + X(i).toFixed(1) + ' ' + Y(useEnd ? p.y : p.x).toFixed(1)).join(' '); + const svg = ''; + return { svg, from: pts[0].k, to: pts[n - 1].k, lo, hi }; + } + window.MonitoringInsight = { METRICS, seasonSeries, @@ -192,5 +314,9 @@ seasonChart, forecastState, forecastChart, + dayRows, + onAt, + runRows, + yearBand, }; })(); diff --git a/dashboard/test/monitoring-insight-model.test.mjs b/dashboard/test/monitoring-insight-model.test.mjs index 0fea136c..d6a707f5 100644 --- a/dashboard/test/monitoring-insight-model.test.mjs +++ b/dashboard/test/monitoring-insight-model.test.mjs @@ -110,3 +110,84 @@ test('forecastChart returns an svg without NaN and fills empty slots', () => { assert.ok(none.svg.startsWith(' ({ key, value, n, ...extra }); + +test('dayRows splits windows over midnight', () => { + const values = [ + lv('site/night_rest', '23:15', 12), + lv('site/day_start', '06:30', 12), + lv('device/w1/usual_on', '22:00', 12, { device_name: 'Waschmaschine', device_icon: 'ico-wash' }), + lv('device/w1/usual_off', '02:00', 12, { device_name: 'Waschmaschine', device_icon: 'ico-wash' }), + ]; + const rows = M.dayRows(values); + assert.equal(rows[0].id, 'house'); + assert.equal(rows[0].kind, 'night'); + assert.equal(rows[0].sure, true); + const dev = rows.find((r) => r.id === 'w1'); + assert.equal(dev.kind, 'on'); + assert.equal(dev.name, 'Waschmaschine'); + assert.equal(dev.icon, 'ico-wash'); + assert.equal(dev.segs.length, 2); + assert.equal(dev.sure, true); + assert.equal(M.onAt(rows, 60).on.includes('Waschmaschine'), true); + assert.equal(M.onAt(rows, 600).on.includes('Waschmaschine'), false); + assert.equal(M.onAt(rows, 0).night, true); + assert.equal(M.onAt(rows, 600).night, false); +}); + +test('dayRows point and free rows', () => { + const point = M.dayRows([lv('device/p1/usual_on', '07:00', 4, { device_name: 'Kaffee' })]); + const pr = point.find((r) => r.id === 'p1'); + assert.equal(pr.kind, 'point'); + assert.equal(pr.sure, false); + assert.ok(Math.abs(pr.segs[0].width - 15 / 14.4) < 1e-9, String(pr.segs[0].width)); + + const offOnly = M.dayRows([lv('device/p2/usual_off', '18:00', 12, { device_name: 'Pumpe' })]); + assert.equal(offOnly.find((r) => r.id === 'p2').kind, 'point'); + + const free = M.dayRows([lv('device/f1/usual_runtime_s', 2400, 12, { device_name: 'Rasenmäher' })]); + const fr = free.find((r) => r.id === 'f1'); + assert.equal(fr.kind, 'free'); + assert.equal(fr.minutes, 40); + assert.deepEqual(fr.segs, []); +}); + +test('dayRows with empty values returns one free house row without minutes', () => { + const rows = M.dayRows([]); + assert.equal(rows.length, 1); + assert.equal(rows[0].id, 'house'); + assert.equal(rows[0].kind, 'free'); + assert.equal(rows[0].minutes, null); +}); + +test('runRows derives the duration', () => { + const values = [ + lv('device/d1/cycle_wh', 900, 12, { device_name: 'Spülmaschine', programs: [490, 1350] }), + lv('device/d1/op_power_w', 1800, 12, { device_name: 'Spülmaschine' }), + ]; + const rows = M.runRows(values); + assert.equal(rows.length, 1); + const r = rows[0]; + assert.equal(r.seconds, 1800); + assert.equal(r.wh, 900); + assert.equal(r.powerW, 1800); + assert.equal(r.sure, true); + assert.ok(Math.abs(r.ticks[0] - 490 / 1350 * 100) < 0.01, String(r.ticks[0])); + assert.equal(r.ticks[1], 100); +}); + +test('yearBand needs four weeks', () => { + const week = (w, v) => ({ week: `2026-W${String(w).padStart(2, '0')}`, value: v }); + const on3 = [week(1, '22:00'), week(2, '22:00'), week(3, '22:00')]; + const off3 = [week(1, '02:00'), week(2, '02:00'), week(3, '02:00')]; + assert.equal(M.yearBand({ year: on3 }, { year: off3 }), null); + const on4 = [...on3, week(4, '22:00')]; + const off4 = [...off3, week(4, '02:00')]; + const band = M.yearBand({ year: on4 }, { year: off4 }); + assert.ok(band); + assert.ok(band.svg.includes('mi-yr-band')); + assert.ok(band.svg.includes('mi-yr-line')); + assert.ok(!band.svg.includes('NaN')); +}); From fe3631f8877a5866576bb36a6cb36b91bb057f40 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:04:50 +0100 Subject: [PATCH 08/30] feat(monitoring): add the forecast and year comparison components Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/monitoring-insight.js | 372 ++++++++++++++++++ dashboard/test/monitoring-insight.test.mjs | 103 +++++ 2 files changed, 475 insertions(+) create mode 100644 dashboard/internal/webui/static/js/monitoring-insight.js create mode 100644 dashboard/test/monitoring-insight.test.mjs diff --git a/dashboard/internal/webui/static/js/monitoring-insight.js b/dashboard/internal/webui/static/js/monitoring-insight.js new file mode 100644 index 00000000..b7bf554b --- /dev/null +++ b/dashboard/internal/webui/static/js/monitoring-insight.js @@ -0,0 +1,372 @@ +// Ueberwachung: Prognose und Jahresvergleich. Die Daten kommen aus +// GET /api/v1/monitoring/forecast (forecast und season), die Zahlen und Zeichnungen +// baut window.MonitoringInsight, die Texte kommen aus dem Katalog. +// +// i18n-keys: monitoring.forecast.load_failed, monitoring.forecast.progress, +// monitoring.forecast.use, monitoring.forecast.use_none, monitoring.forecast.mae.caption, +// monitoring.forecast.mae.forecast, monitoring.forecast.mae.median, +// monitoring.forecast.status.learning.title, monitoring.forecast.status.learning.text, +// monitoring.forecast.status.median.title, monitoring.forecast.status.median.text, +// monitoring.forecast.status.forecast.title, monitoring.forecast.status.forecast.text, +// monitoring.forecast.verdict.forecast, monitoring.forecast.verdict.median, +// monitoring.season.note.off, monitoring.season.note.later, +// monitoring.season.note.stats, monitoring.season.range, monitoring.season.week, +// monitoring.season.sum.lead, monitoring.season.sum.lead_mean, monitoring.season.sum.prev, +// monitoring.season.sum.skipped, monitoring.season.metric.pv, monitoring.season.metric.load, +// monitoring.season.metric.export, monitoring.season.metric.base, monitoring.season.metric.temp +(() => { + const EASE_OUT = 'cubic-bezier(0.23, 1, 0.32, 1)'; + const FORECAST_PATH = '/api/v1/monitoring/forecast'; + const METRIC_KEY = 'monitoring.season.metric'; + const DEFAULT_METRIC = 'pv'; + const FORECAST_ICONS = { learning: 'ico-history', median: 'ico-calendar', forecast: 'ico-learning' }; + const FORECAST_TONES = { learning: 'wait', median: 'warn', forecast: 'ok' }; + const STATUS_KEYS = { + learning: { title: 'monitoring.forecast.status.learning.title', text: 'monitoring.forecast.status.learning.text' }, + median: { title: 'monitoring.forecast.status.median.title', text: 'monitoring.forecast.status.median.text' }, + forecast: { title: 'monitoring.forecast.status.forecast.title', text: 'monitoring.forecast.status.forecast.text' }, + }; + const METRIC_LABEL_KEYS = { + pv: 'monitoring.season.metric.pv', + load: 'monitoring.season.metric.load', + export: 'monitoring.season.metric.export', + base: 'monitoring.season.metric.base', + temp: 'monitoring.season.metric.temp', + }; + + const t = (key, params) => (window.I18n ? window.I18n.t(key, params) : key); + const base = () => window.__DASHBOARD_BASE_PATH__ || ''; + const reduced = () => Boolean(window.matchMedia) && window.matchMedia('(prefers-reduced-motion: reduce)').matches; + const narrow = () => Boolean(window.matchMedia) && window.matchMedia('(max-width: 640px)').matches; + const num = (v, d) => (window.I18n && window.I18n.formatNumber ? window.I18n.formatNumber(v, d) : Number(v).toFixed(d)); + const locale = () => (window.I18n && window.I18n.locale) || undefined; + const fmtDate = (date, opts) => (window.I18n && window.I18n.formatDate + ? window.I18n.formatDate(date, opts) + : date.toLocaleDateString(locale(), opts)); + const metricList = () => window.MonitoringInsight.METRICS; + + // Monatsnamen kurz, aus der Sprache der Oberflaeche + function monthLabels() { + const f = new Intl.DateTimeFormat(locale(), { month: 'short' }); + return Array.from({ length: 12 }, (_, m) => f.format(new Date(2026, m, 15))); + } + + // ISO-Woche: Montag der Woche w im Jahr y + function weekMonday(y, w) { + const jan4 = new Date(y, 0, 4); + const mon = new Date(jan4); + mon.setDate(jan4.getDate() - ((jan4.getDay() + 6) % 7) + (w - 1) * 7); + return mon; + } + + function reveal(el) { + if (!el || !el.animate || reduced()) return; + el.animate([{ clipPath: 'inset(0 100% 0 0)' }, { clipPath: 'inset(0 0 0 0)' }], { duration: 280, easing: EASE_OUT }); + } + function crossfade(el) { + if (!el || !el.animate) return; + const frames = reduced() + ? [{ opacity: 0.35 }, { opacity: 1 }] + : [{ opacity: 0.35, transform: 'translateY(4px)' }, { opacity: 1, transform: 'translateY(0)' }]; + el.animate(frames, { duration: 160, easing: EASE_OUT }); + } + function onFirstView(el, fn) { + if (!el) return; + if (!('IntersectionObserver' in window)) { fn(); return; } + const io = new IntersectionObserver((entries) => { + if (entries.some((e) => e.isIntersecting)) { io.disconnect(); fn(); } + }, { threshold: 0.4 }); + io.observe(el); + } + // Zeiger auf eine Spalte abbilden, mit Zeiger-Capture. touch-action: pan-y laesst + // senkrechtes Scrollen beim Browser, dann kommt pointercancel und die Auswahl bleibt. + function scrubber(el, pick) { + let down = false; + el.addEventListener('pointerdown', (e) => { down = true; try { el.setPointerCapture(e.pointerId); } catch (err) { /* egal */ } pick(e.clientX); }); + el.addEventListener('pointermove', (e) => { if (down || e.pointerType === 'mouse') pick(e.clientX); }); + const up = () => { down = false; }; + el.addEventListener('pointerup', up); + el.addEventListener('pointercancel', up); + } + + // Prognose: Tagesbalken gegen Messung, Lernphase, Median oder Prognose. + function monitoringForecast() { + return { + data: null, + failed: false, + loaded: false, + loading: false, + sel: -1, + width: 0, + geo: null, + get check() { return (this.data && this.data.forecast) || null; }, + get days() { return (this.check && this.check.days) || []; }, + get readers() { return (this.check && this.check.readers) || []; }, + get state() { return this.check ? window.MonitoringInsight.forecastState(this.check) : null; }, + get learning() { return Boolean(this.state) && this.state.kind === 'learning'; }, + get failedText() { return t('monitoring.forecast.load_failed'); }, + kwh(wh) { return num(wh / 1000, 1) + ' kWh'; }, + get status() { + const s = this.state; if (!s) return null; + const params = s.kind === 'learning' + ? { needed: s.needed, left: s.needed - s.have } + : { days: s.have, forecast: this.kwh(s.maeF), median: this.kwh(s.maeM) }; + return { + kind: s.kind, + icon: FORECAST_ICONS[s.kind], + tone: FORECAST_TONES[s.kind], + title: t(STATUS_KEYS[s.kind].title), + text: t(STATUS_KEYS[s.kind].text, params), + }; + }, + get bars() { + const s = this.state; if (!s) return []; + const max = Math.max(s.maeF, s.maeM) || 1; + const winF = s.kind !== 'median'; + return [ + { id: 'f', label: t('monitoring.forecast.mae.forecast'), value: this.kwh(s.maeF), pct: s.maeF / max * 100, win: winF }, + { id: 'm', label: t('monitoring.forecast.mae.median'), value: this.kwh(s.maeM), pct: s.maeM / max * 100, win: !winF }, + ]; + }, + get caption() { + const s = this.state; if (!s) return ''; + return t('monitoring.forecast.mae.caption', { hits: s.hits, days: s.have }); + }, + get useText() { + const names = this.readers.map((r) => r.name || r.id); + return names.length ? t('monitoring.forecast.use', { rules: names.join(', ') }) : t('monitoring.forecast.use_none'); + }, + get progress() { + const s = this.state; if (!s) return ''; + return t('monitoring.forecast.progress', { have: s.have, needed: s.needed }); + }, + get selIndex() { return this.sel < 0 ? this.days.length - 1 : this.sel; }, + get selDay() { return this.days[this.selIndex]; }, + get readTitle() { + const d = this.selDay; if (!d) return ''; + return fmtDate(new Date(d.day + 'T12:00:00'), { weekday: 'short', day: 'numeric', month: 'short' }); + }, + get readVerdict() { + const d = this.selDay; if (!d) return ''; + const ef = Math.abs(d.forecast_wh - d.actual_wh); + const em = Math.abs(d.season_wh - d.actual_wh); + return t(ef < em ? 'monitoring.forecast.verdict.forecast' : 'monitoring.forecast.verdict.median', + { forecast: this.kwh(ef), median: this.kwh(em) }); + }, + + async load() { + if (this.loaded || this.loading) return; + this.loading = true; + this.failed = false; + try { + const res = await fetch(base() + FORECAST_PATH, { credentials: 'same-origin', headers: { Accept: 'application/json' } }); + if (!res.ok) throw new Error('status ' + res.status); + this.data = await res.json(); + this.loaded = true; + } catch (e) { + this.failed = true; + } finally { + this.loading = false; + } + }, + + init() { + const el = this.$refs.plot; + if ('ResizeObserver' in window) { + new ResizeObserver(() => { const w = el.clientWidth; if (w && w !== this.width) { this.width = w; this.draw(); } }).observe(el); + } + onFirstView(el, () => reveal(el.querySelector('.mi-cols'))); + this.$watch('data', () => { this.sel = -1; this.draw(); }); + scrubber(el, (x) => this.pickX(x)); + }, + draw() { + const el = this.$refs && this.$refs.plot; if (!el) return; + const s = this.state; + if (!s) { el.innerHTML = ''; this.geo = null; return; } + const chart = window.MonitoringInsight.forecastChart(this.days, s.needed, this.width || 600, narrow()); + el.innerHTML = chart.svg; + this.geo = chart.geo; + this.mark(); + }, + // Ohne Wahl tritt nichts zurueck, die Lesezeile zeigt den letzten Tag + mark() { + const el = this.$refs && this.$refs.plot; const svg = el && el.firstChild; + if (!svg || !svg.querySelectorAll) return; + svg.querySelectorAll('.mi-col').forEach((c) => c.classList.toggle('is-dim', this.sel >= 0 && Number(c.dataset.i) !== this.selIndex)); + }, + pickX(clientX) { + if (!this.geo) return; + const r = this.$refs.plot.getBoundingClientRect(); + this.setDay(Math.floor((clientX - r.left - this.geo.pad.l) / this.geo.cw)); + }, + setDay(i) { + if (!this.days.length) return; + i = Math.max(0, Math.min(this.days.length - 1, i)); + if (i === this.selIndex) return; + this.sel = i; + this.mark(); + }, + key(e) { + const map = { ArrowLeft: -1, ArrowRight: 1 }; + if (map[e.key]) { e.preventDefault(); this.setDay(this.selIndex + map[e.key]); } + }, + }; + } + + // Jahresvergleich: Kennzahl, Kopfzahl, Lesezeile und Diagramm. getSeason liefert data.season. + function monitoringYear(getSeason) { + const storedMetric = () => { + try { + const v = window.localStorage.getItem(METRIC_KEY); + return metricList().some((m) => m.id === v) ? v : DEFAULT_METRIC; + } catch (e) { + return DEFAULT_METRIC; + } + }; + return { + metric: storedMetric(), + sel: null, + width: 0, + geo: null, + get season() { return (typeof getSeason === 'function' && getSeason()) || null; }, + get metrics() { return metricList().map((m) => ({ id: m.id, label: t(METRIC_LABEL_KEYS[m.id]) })); }, + get m() { return metricList().find((x) => x.id === this.metric) || metricList()[0]; }, + get years() { + const s = this.season; if (!s) return []; + const old = s.year - 2; + const three = (s.weeks || []).some((w) => String(w.key).startsWith(old + '-W')); + return three ? [s.year, s.year - 1, s.year - 2] : [s.year, s.year - 1]; + }, + get selWeek() { return this.sel != null ? this.sel : (this.season ? this.season.week : 1); }, + get empty() { return this.summary === null; }, + fmt(v) { + const m = this.m; + return m.sum && v >= 1000 ? num(v / 1000, 2) + ' MWh' : num(v, m.d) + ' ' + m.unit; + }, + // Temperatur als Gradunterschied, sonst als Prozent + diffText(v) { + const sign = v >= 0 ? '+' : '−'; + return this.m.id === 'temp' ? sign + num(Math.abs(v), 1) + ' °C' : sign + num(Math.abs(v), 0) + ' %'; + }, + diffPair(a, b) { + if (this.m.id === 'temp') return this.diffText(a - b); + return b ? this.diffText((a - b) / b * 100) : ''; + }, + tone(a, b) { + const g = this.m.good * Math.sign(a - b); + return g > 0 ? 'is-up' : g < 0 ? 'is-down' : ''; + }, + get summary() { + const s = this.season; if (!s) return null; + const r = window.MonitoringInsight.seasonSummary(s, this.metric); + if (!r) return null; + return { + lead: t(this.m.sum ? 'monitoring.season.sum.lead' : 'monitoring.season.sum.lead_mean', { week: s.week }), + cur: this.fmt(r.cur), + prev: t('monitoring.season.sum.prev', { value: this.fmt(r.prev) }), + diff: this.diffText(r.diff), + tone: r.tone, + skipped: r.skipped > 0 ? t('monitoring.season.sum.skipped', { n: r.skipped }) : '', + }; + }, + get readTitle() { return t('monitoring.season.week', { week: this.selWeek }); }, + get readRange() { + const s = this.season; if (!s) return ''; + const a = weekMonday(s.year, this.selWeek); + const b = new Date(a); b.setDate(a.getDate() + 6); + const opts = { day: 'numeric', month: 'short' }; + return t('monitoring.season.range', { from: fmtDate(a, opts), to: fmtDate(b, opts) }); + }, + get readRows() { + const s = this.season; if (!s) return []; + const ys = this.years; const cur = this.selWeek; + const series = (yr) => window.MonitoringInsight.seasonSeries(s.weeks, yr, this.metric); + const base = series(ys[1])[cur]; + return ys.map((yr, i) => { + const p = series(yr)[cur]; + let note = ''; + if (!p && yr === s.year && cur < s.week) note = t('monitoring.season.note.off'); + else if (!p && yr === s.year) note = t('monitoring.season.note.later'); + else if (p && p.src === 'stats') note = t('monitoring.season.note.stats'); + const compare = i === 0 && p && base; + return { + yr, + i, + value: p ? this.fmt(p.v) : '', + note, + diff: compare ? this.diffPair(p.v, base.v) : '', + tone: compare ? this.tone(p.v, base.v) : '', + }; + }); + }, + + setMetric(id) { + if (id === this.metric || !metricList().some((m) => m.id === id)) return; + this.metric = id; + try { window.localStorage.setItem(METRIC_KEY, id); } catch (e) { /* ohne Speicher */ } + this.draw(true); + }, + init() { + const el = this.$refs.plot; + if ('ResizeObserver' in window) { + new ResizeObserver(() => { const w = el.clientWidth; if (w && w !== this.width) { this.width = w; this.draw(false); } }).observe(el); + } + onFirstView(el, () => reveal(el.querySelector('.mi-cur'))); + this.$watch('season', () => this.draw(false)); + scrubber(el, (x) => this.pickX(x)); + }, + draw(fade) { + const el = this.$refs && this.$refs.plot; if (!el) return; + const s = this.season; + if (!s || !this.years.length) { el.innerHTML = ''; this.geo = null; return; } + const chart = window.MonitoringInsight.seasonChart(s, this.metric, this.years.length, this.width || 600, narrow(), monthLabels()); + el.innerHTML = chart.svg; + this.geo = chart.geo; + this.moveCursor(); + if (fade) crossfade(el.firstChild); + }, + moveCursor() { + const g = this.geo; const el = this.$refs && this.$refs.plot; const svg = el && el.firstChild; const s = this.season; + if (!g || !svg || !s || !svg.querySelector) return; + const w = this.selWeek; + const X = g.x(w).toFixed(1); + const hair = svg.querySelector('.mi-hair'); hair.setAttribute('x1', X); hair.setAttribute('x2', X); + this.years.forEach((yr, i) => { + const p = window.MonitoringInsight.seasonSeries(s.weeks, yr, this.metric)[w]; + const dot = svg.querySelector('.mi-dot-' + i); + if (!p) { dot.setAttribute('visibility', 'hidden'); return; } + dot.setAttribute('visibility', 'visible'); + dot.setAttribute('cx', X); + dot.setAttribute('cy', g.y(p.v).toFixed(1)); + }); + }, + pickX(clientX) { + if (!this.geo) return; + const r = this.$refs.plot.getBoundingClientRect(); + const g = this.geo; + this.setWeek(Math.round((clientX - r.left - g.pad.l) / (g.W - g.pad.l - g.pad.r) * 51) + 1); + }, + setWeek(w) { + const s = this.season; if (!s) return; + w = Math.max(1, Math.min(52, w)); + if (w === this.selWeek) return; + this.sel = w; + this.moveCursor(); + }, + key(e) { + const s = this.season; if (!s) return; + const map = { ArrowLeft: -1, ArrowRight: 1 }; + if (map[e.key]) { e.preventDefault(); this.setWeek(this.selWeek + map[e.key]); } + if (e.key === 'Home') { e.preventDefault(); this.setWeek(1); } + if (e.key === 'End') { e.preventDefault(); this.setWeek(s.week); } + }, + }; + } + + const register = () => { + if (!window.Alpine) return; + window.Alpine.data('monitoringForecast', monitoringForecast); + window.Alpine.data('monitoringYear', monitoringYear); + }; + if (window.Alpine) register(); else document.addEventListener('alpine:init', register, { once: true }); +})(); diff --git a/dashboard/test/monitoring-insight.test.mjs b/dashboard/test/monitoring-insight.test.mjs new file mode 100644 index 00000000..536c631f --- /dev/null +++ b/dashboard/test/monitoring-insight.test.mjs @@ -0,0 +1,103 @@ +// Tests for the monitoring forecast and year components (window.MonitoringInsight drives the numbers). +// Alpine is a stub that only captures the factories, fetch is faked, storage can be made to throw. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { JSDOM } from 'jsdom'; +import { installI18n } from './helpers/i18n.mjs'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const jsDir = path.join(here, '..', 'internal', 'webui', 'static', 'js'); +const modelSource = fs.readFileSync(path.join(jsDir, 'monitoring-insight-model.js'), 'utf8'); +const componentSource = fs.readFileSync(path.join(jsDir, 'monitoring-insight.js'), 'utf8'); + +const FORECAST_PATH = '/api/v1/monitoring/forecast'; + +function response(body) { + return { ok: true, status: 200, json: async () => JSON.parse(JSON.stringify(body)) }; +} + +function create({ forecast = { needed: 14, days: [], readers: [] }, season = null, fail = false, throwStorage = false } = {}) { + const dom = new JSDOM('', { runScripts: 'outside-only', url: 'http://localhost/' }); + const context = dom.getInternalVMContext(); + installI18n(dom.window); + if (throwStorage) { + Object.defineProperty(dom.window, 'localStorage', { configurable: true, get() { throw new Error('storage denied'); } }); + } + const factories = {}; + dom.window.Alpine = { data: (name, fn) => { factories[name] = fn; } }; + const calls = []; + dom.window.fetch = async (url, options) => { + calls.push({ url, options }); + if (fail) return { ok: false, status: 500, json: async () => ({}) }; + return response({ forecast, season }); + }; + vm.runInContext(modelSource, context); + vm.runInContext(componentSource, context); + return { dom, factories, calls }; +} + +function forecastComponent(options) { + const { dom, factories, calls } = create(options); + const component = factories.monitoringForecast(); + component.$refs = {}; + return { component, calls, dom }; +} + +test('monitoringForecast loads once', async () => { + const { component, calls } = forecastComponent(); + await component.load(); + await component.load(); + assert.equal(calls.length, 1); + assert.equal(calls[0].url, FORECAST_PATH); + assert.equal(component.loaded, true); +}); + +test('monitoringForecast shows the learning status for a fresh node', async () => { + const { component } = forecastComponent({ forecast: { needed: 14, days: [], readers: [] } }); + await component.load(); + assert.equal(component.status.kind, 'learning'); + assert.equal(component.learning, true); + assert.ok(component.status.text.includes('14'), component.status.text); +}); + +test('monitoringForecast lists the readers and says so when there are none', async () => { + const readers = [{ id: 'a', name: 'Garage Speicher' }, { id: 'b', name: 'Warmwasser' }]; + const withReaders = forecastComponent({ forecast: { needed: 14, days: [], readers } }); + await withReaders.component.load(); + assert.ok(withReaders.component.useText.includes('Garage Speicher')); + assert.ok(withReaders.component.useText.includes('Warmwasser')); + + const none = forecastComponent({ forecast: { needed: 14, days: [], readers: [] } }); + await none.component.load(); + assert.equal(none.component.useText, none.dom.window.I18n.t('monitoring.forecast.use_none')); +}); + +test('monitoringForecast reports a load error', async () => { + const { component } = forecastComponent({ fail: true }); + await component.load(); + assert.equal(component.failed, true); + assert.equal(component.loaded, false); + assert.ok(component.failedText.length > 0); +}); + +test('monitoringYear keeps the metric in storage', () => { + const { dom, factories } = create(); + const component = factories.monitoringYear(() => null); + component.$refs = {}; + component.setMetric('base'); + assert.equal(component.metric, 'base'); + assert.equal(dom.window.localStorage.getItem('monitoring.season.metric'), 'base'); +}); + +test('monitoringYear works with a throwing storage', () => { + const { factories } = create({ throwStorage: true }); + const component = factories.monitoringYear(() => null); + component.$refs = {}; + assert.equal(component.metric, 'pv'); + assert.doesNotThrow(() => component.setMetric('base')); + assert.equal(component.metric, 'base'); +}); From 57e2a44f1c0f41f8b660e7c9f144fe5de1b58ae9 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:05:29 +0100 Subject: [PATCH 09/30] fix(monitoring): keep texts and locale out of the insight model The house row carries a name key instead of a fixed German name. The sort locale is an optional argument instead of read from I18n. Equal on and off minutes give a 15 minute point, not a full day. Co-Authored-By: Claude Sonnet 5.5 --- .../static/js/monitoring-insight-model.js | 26 +++++++------- .../test/monitoring-insight-model.test.mjs | 35 +++++++++++++++++++ 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/dashboard/internal/webui/static/js/monitoring-insight-model.js b/dashboard/internal/webui/static/js/monitoring-insight-model.js index 642c0f55..0ce26c04 100644 --- a/dashboard/internal/webui/static/js/monitoring-insight-model.js +++ b/dashboard/internal/webui/static/js/monitoring-insight-model.js @@ -199,8 +199,8 @@ return parts.filter(([x, y]) => y > x).map(([x, y]) => ({ left: x / DAY_STEP, width: (y - x) / DAY_STEP })); } - // Geraete aus den gelernten Werten, nach Name sortiert (Sprache aus I18n). - function collectDevices(values) { + // Geraete aus den gelernten Werten, nach Name sortiert (locale optional, sonst Standard der Umgebung). + function collectDevices(values, locale) { const by = new Map(); for (const v of values || []) { if (!v.key || !v.key.startsWith('device/')) continue; @@ -211,13 +211,12 @@ if (v.device_icon) d.icon = v.device_icon; d.f[field] = v; } - const locale = (window.I18n && window.I18n.locale) || 'de'; return [...by.values()].sort((a, b) => a.name.localeCompare(b.name, locale)); } // Zeilen des ueblichen Tages: erst das Haus (Nachtruhe), dann Geraete. // kind: night (Haus), on (Fenster), point (nur Beginn oder Ende, 15 Minuten), free (nur Laufzeit). - function dayRows(values) { + function dayRows(values, locale) { const by = new Map(); for (const v of values || []) by.set(v.key, v); const nr = by.get('site/night_rest'); const ds = by.get('site/day_start'); @@ -225,17 +224,18 @@ const a = nr ? clock(nr.value) : null; const b = ds ? clock(ds.value) : null; if (nr && ds && a != null && b != null) { const n = Math.min(nr.n || 0, ds.n || 0); - rows.push({ id: 'house', kind: 'night', name: 'Haus', icon: 'ico-user', segs: segs(a, b), from: nr.value, to: ds.value, + rows.push({ id: 'house', kind: 'night', name: null, nameKey: 'monitoring.day.house', icon: 'ico-user', segs: segs(a, b), from: nr.value, to: ds.value, minutes: (b - a + 1440) % 1440, sure: n >= 10, n, keys: ['site/night_rest', 'site/day_start'], year: [nr, ds], entries: [nr, ds] }); } else { const present = [nr, ds].filter(Boolean); - rows.push({ id: 'house', kind: 'free', name: 'Haus', icon: 'ico-user', segs: [], from: null, to: null, minutes: null, + rows.push({ id: 'house', kind: 'free', name: null, nameKey: 'monitoring.day.house', icon: 'ico-user', segs: [], from: null, to: null, minutes: null, sure: false, n: 0, keys: present.map((v) => v.key), year: null, entries: present }); } - for (const d of collectDevices(values)) { + for (const d of collectDevices(values, locale)) { const on = d.f.usual_on; const off = d.f.usual_off; const rt = d.f.usual_runtime_s; const base = { id: d.id, name: d.name, icon: d.icon }; - if (on && off) { + // Gleiche Minute fuer Beginn und Ende ist ein Punkt, kein volles Fenster. + if (on && off && clock(on.value) !== clock(off.value)) { const s = clock(on.value); const e = clock(off.value); const n = Math.min(on.n || 0, off.n || 0); rows.push({ ...base, kind: 'on', segs: segs(s, e), from: on.value, to: off.value, minutes: (e - s + 1440) % 1440, @@ -243,8 +243,10 @@ } else if (on || off) { const only = on || off; const t = clock(only.value); const s = on ? t : (t - 15 + 1440) % 1440; - rows.push({ ...base, kind: 'point', segs: segs(s, (s + 15) % 1440), from: on ? only.value : null, to: off ? only.value : null, - minutes: null, sure: (only.n || 0) >= 10, n: only.n || 0, keys: [only.key], year: null, entries: [only] }); + const ents = [on, off].filter(Boolean); + const n = Math.min(...ents.map((x) => x.n || 0)); + rows.push({ ...base, kind: 'point', segs: segs(s, (s + 15) % 1440), from: on ? on.value : null, to: off ? off.value : null, + minutes: null, sure: n >= 10, n, keys: ents.map((x) => x.key), year: null, entries: ents }); } else if (rt) { rows.push({ ...base, kind: 'free', segs: [], from: null, to: null, minutes: Math.round(rt.value / 60), sure: (rt.n || 0) >= 10, n: rt.n || 0, keys: [rt.key], year: null, entries: [rt] }); @@ -265,9 +267,9 @@ } // Laufzeiten der Geraete mit Zyklus oder Leistung, relativ zum groessten Wert. - function runRows(values) { + function runRows(values, locale) { const list = []; - for (const d of collectDevices(values)) { + for (const d of collectDevices(values, locale)) { const e = d.f.cycle_wh; const p = d.f.op_power_w; const rt = d.f.usual_runtime_s; if (!e && !p) continue; const wh = e ? e.value : null; diff --git a/dashboard/test/monitoring-insight-model.test.mjs b/dashboard/test/monitoring-insight-model.test.mjs index d6a707f5..abf35ea3 100644 --- a/dashboard/test/monitoring-insight-model.test.mjs +++ b/dashboard/test/monitoring-insight-model.test.mjs @@ -125,6 +125,8 @@ test('dayRows splits windows over midnight', () => { assert.equal(rows[0].id, 'house'); assert.equal(rows[0].kind, 'night'); assert.equal(rows[0].sure, true); + assert.equal(rows[0].name, null); + assert.equal(rows[0].nameKey, 'monitoring.day.house'); const dev = rows.find((r) => r.id === 'w1'); assert.equal(dev.kind, 'on'); assert.equal(dev.name, 'Waschmaschine'); @@ -191,3 +193,36 @@ test('yearBand needs four weeks', () => { assert.ok(band.svg.includes('mi-yr-line')); assert.ok(!band.svg.includes('NaN')); }); + +test('dayRows house row without locale keeps the name key and no name', () => { + const rows = M.dayRows([lv('site/night_rest', '23:15'), lv('site/day_start', '06:30')]); + assert.equal(rows[0].kind, 'night'); + assert.equal(rows[0].name, null); + assert.equal(rows[0].nameKey, 'monitoring.day.house'); + const free = M.dayRows([]); + assert.equal(free[0].name, null); + assert.equal(free[0].nameKey, 'monitoring.day.house'); +}); + +test('dayRows sorts devices by name with the given locale', () => { + const values = [ + lv('device/b/usual_runtime_s', 600, 12, { device_name: 'Zisterne' }), + lv('device/a/usual_runtime_s', 600, 12, { device_name: 'Ahorn' }), + ]; + const withLocale = M.dayRows(values, 'de').slice(1).map((r) => r.name); + assert.deepEqual(withLocale, ['Ahorn', 'Zisterne']); + const noLocale = M.dayRows(values).slice(1).map((r) => r.name); + assert.deepEqual(noLocale, ['Ahorn', 'Zisterne']); +}); + +test('dayRows with equal on and off minute is a point, not a full day', () => { + const rows = M.dayRows([ + lv('device/e1/usual_on', '12:00', 12, { device_name: 'Gleich' }), + lv('device/e1/usual_off', '12:00', 12, { device_name: 'Gleich' }), + ]); + const r = rows.find((x) => x.id === 'e1'); + assert.equal(r.kind, 'point'); + assert.equal(r.segs.length, 1); + assert.ok(Math.abs(r.segs[0].width - 15 / 14.4) < 1e-9, String(r.segs[0].width)); + assert.equal(M.onAt(rows, 12 * 60 + 5).on.includes('Gleich'), false); +}); From bc67258b3143bea3069a561e63016eb85f9c618e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:07:37 +0100 Subject: [PATCH 10/30] feat(monitoring): add the forecast view and tab to the monitoring template Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/monitoring.page.js | 2 +- dashboard/internal/webui/templates/base.html | 2 +- .../internal/webui/templates/monitoring.html | 106 ++++++++++++++++++ 3 files changed, 108 insertions(+), 2 deletions(-) diff --git a/dashboard/internal/webui/static/js/monitoring.page.js b/dashboard/internal/webui/static/js/monitoring.page.js index 22451b90..b4c9d674 100644 --- a/dashboard/internal/webui/static/js/monitoring.page.js +++ b/dashboard/internal/webui/static/js/monitoring.page.js @@ -125,7 +125,7 @@ setView(view) { if (this.view === view) return; this.view = view; - this.$nextTick(() => this.fadeIn(this.$el && this.$el.querySelector(view === 'learned' ? '.monitoring-learned' : '.monitoring-split'), 6)); + this.$nextTick(() => this.fadeIn(this.$el && this.$el.querySelector(view === 'learned' ? '.monitoring-learned' : view === 'forecast' ? '.mi-fview' : '.monitoring-split'), 6)); }, setFilter(id) { this.filter = id; this.pick = ''; }, diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 63966485..fdc7a42d 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/internal/webui/templates/monitoring.html b/dashboard/internal/webui/templates/monitoring.html index 203d659a..b59569e5 100644 --- a/dashboard/internal/webui/templates/monitoring.html +++ b/dashboard/internal/webui/templates/monitoring.html @@ -13,6 +13,9 @@ {{t "monitoring.view.learned"}} +
@@ -220,7 +220,7 @@

-

+

{{t "monitoring.forecast.days.sub"}}

diff --git a/dashboard/test/monitoring-insight-model.test.mjs b/dashboard/test/monitoring-insight-model.test.mjs index 60e29dce..44ad8f80 100644 --- a/dashboard/test/monitoring-insight-model.test.mjs +++ b/dashboard/test/monitoring-insight-model.test.mjs @@ -229,3 +229,35 @@ test('dayRows with equal on and off minute is a point, not a full day', () => { assert.ok(Math.abs(r.segs[0].width - 15 / 14.4) < 1e-9, String(r.segs[0].width)); assert.equal(M.onAt(rows, 12 * 60 + 5).on.includes('Gleich'), false); }); + +test('seasonChart keeps a range when all exported values are 0', () => { + const weeks = [1, 2, 3].map((w) => ({ key: '2026-W0' + w, export_kwh: 0, source: 'live' })); + const out = M.seasonChart({ year: 2026, week: 3, weeks }, 'export', 2, 600, false, MONTHS.map((m) => m.slice(0, 3))); + assert.equal(out.svg.includes('NaN'), false); + assert.ok(out.geo.y1 > out.geo.y0); +}); + +test('seasonChart keeps a range when all temperatures are equal and negative', () => { + const weeks = [1, 2, 3].map((w) => ({ key: '2026-W0' + w, temp_c: -5, source: 'live' })); + const out = M.seasonChart({ year: 2026, week: 3, weeks }, 'temp', 2, 600, false, MONTHS.map((m) => m.slice(0, 3))); + assert.equal(out.svg.includes('NaN'), false); + assert.ok(out.geo.y1 > out.geo.y0); +}); + +test('seasonChart uses the given fmt for the axis labels', () => { + const weeks = [{ key: '2026-W01', pv_kwh: 10, source: 'live' }]; + const out = M.seasonChart({ year: 2026, week: 1, weeks }, 'pv', 2, 600, false, MONTHS.map((m) => m.slice(0, 3)), (n) => 'X' + n); + assert.ok(out.svg.includes('>X0<'), 'custom fmt on the first tick'); +}); + +test('forecastChart keeps the svg free of NaN when all days are 0 Wh', () => { + const days = [0, 1, 2].map((i) => ({ day: '2026-11-0' + (i + 1), forecast_wh: 0, actual_wh: 0, season_wh: 0 })); + const out = M.forecastChart(days, 14, 600, false); + assert.equal(out.svg.includes('NaN'), false); +}); + +test('forecastChart uses the given fmt for the axis labels', () => { + const days = [{ day: '2026-11-01', forecast_wh: 1000, actual_wh: 1000, season_wh: 1000 }]; + const out = M.forecastChart(days, 14, 600, false, (n) => 'X' + n); + assert.ok(out.svg.includes('>X0<'), 'custom fmt on the first tick'); +}); diff --git a/dashboard/test/monitoring-insight.test.mjs b/dashboard/test/monitoring-insight.test.mjs index c5093ffd..7ee70728 100644 --- a/dashboard/test/monitoring-insight.test.mjs +++ b/dashboard/test/monitoring-insight.test.mjs @@ -144,11 +144,11 @@ test('monitoringYear shows the gap legend only when the current year misses a we // monitoringDay: getValues and getFocus stand in for learned.values and learnedFocus. function dayComponent(values, initialFocus = '') { - const { factories } = create(); + const { dom, factories } = create(); let focus = initialFocus; const component = factories.monitoringDay(() => values, () => focus); component.$refs = {}; - return { component, setFocus: (value) => { focus = value; } }; + return { component, dom, setFocus: (value) => { focus = value; } }; } const PLUG_VALUES = [ @@ -207,3 +207,76 @@ test('monitoringDay shows the window as a label', () => { const plug = component.rows.find((row) => row.id === 'plug'); assert.equal(plug.label, '16:45 bis 22:30'); }); + +test('monitoringDay clears a swipe after the click that follows pointerup', async () => { + const { component, dom } = dayComponent(PLUG_VALUES); + const rows = dom.window.document.createElement('div'); + component.$refs = { rows }; + component.$watch = () => {}; + component.init(); + component.moved = true; + rows.dispatchEvent(new dom.window.Event('pointerup')); + assert.equal(component.moved, true, 'still set in the same task, so the click is ignored'); + await new Promise((resolve) => setTimeout(resolve, 5)); + assert.equal(component.moved, false); + component.toggle('plug'); + assert.equal(component.open, 'plug'); +}); + +test('monitoringDay reads the rows once for the same values array', () => { + const { component, dom } = dayComponent(PLUG_VALUES); + const M = dom.window.MonitoringInsight; + const original = M.dayRows; + let calls = 0; + M.dayRows = (...args) => { calls += 1; return original(...args); }; + component.rows; + component.rows; + component.readText; + assert.equal(calls, 1); +}); + +// Fake observer and listener spies, to see what destroy() releases. +function fakeResizeObserver(dom) { + const log = { disconnects: 0 }; + dom.window.ResizeObserver = class { + observe() {} + disconnect() { log.disconnects += 1; } + }; + return log; +} +function spyListeners(el) { + const log = { added: 0, removed: 0 }; + const add = el.addEventListener.bind(el); + const remove = el.removeEventListener.bind(el); + el.addEventListener = (type, fn, opts) => { log.added += 1; add(type, fn, opts); }; + el.removeEventListener = (type, fn, opts) => { log.removed += 1; remove(type, fn, opts); }; + return log; +} + +test('monitoringDay destroy disconnects the observer and removes its listeners', () => { + const { component, dom } = dayComponent(PLUG_VALUES); + const observer = fakeResizeObserver(dom); + const rows = dom.window.document.createElement('div'); + const listeners = spyListeners(rows); + component.$refs = { rows }; + component.$watch = () => {}; + component.init(); + assert.equal(listeners.added, 4); + component.destroy(); + assert.equal(observer.disconnects, 1); + assert.equal(listeners.removed, 4); +}); + +test('monitoringForecast destroy disconnects the observer and removes its listeners', () => { + const { component, dom } = forecastComponent(); + const observer = fakeResizeObserver(dom); + const plot = dom.window.document.createElement('div'); + const listeners = spyListeners(plot); + component.$refs = { plot }; + component.$watch = () => {}; + component.init(); + assert.equal(listeners.added, 4); + component.destroy(); + assert.equal(observer.disconnects, 1); + assert.equal(listeners.removed, 4); +}); From 7751f73528772e5c99e7b2ef3faef52f5c995bb3 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:30:15 +0100 Subject: [PATCH 20/30] fix(monitoring): keep the forecast view inside the screen and polish the usual day Co-Authored-By: Claude Sonnet 5.5 --- .../internal/webui/static/css/monitoring.css | 5 +++ .../webui/static/js/monitoring-insight.js | 24 ++++++----- .../internal/webui/templates/monitoring.html | 6 +-- dashboard/test/monitoring-insight.test.mjs | 40 +++++++++++++++++++ 4 files changed, 61 insertions(+), 14 deletions(-) diff --git a/dashboard/internal/webui/static/css/monitoring.css b/dashboard/internal/webui/static/css/monitoring.css index 08c4bf56..1bdbddbe 100644 --- a/dashboard/internal/webui/static/css/monitoring.css +++ b/dashboard/internal/webui/static/css/monitoring.css @@ -354,3 +354,8 @@ .mi-day-acc, .mi-day-item.is-open .mi-day-acc { transition: opacity 150ms ease, visibility 0s; } .mi-day-chev { transition: none; } } + +/* Schmale Bildschirme: die Grid-Spalten duerfen schrumpfen, die Diagramme passen sich der Breite an */ +.mi-fview, .mi-lw { grid-template-columns: minmax(0, 1fr); } +.mi-card, .mi-status, .mi-plot, .mi-day { min-width: 0; } +.mi-plot .mi-svg { max-width: 100%; height: auto; } diff --git a/dashboard/internal/webui/static/js/monitoring-insight.js b/dashboard/internal/webui/static/js/monitoring-insight.js index 55e33d83..e6de888d 100644 --- a/dashboard/internal/webui/static/js/monitoring-insight.js +++ b/dashboard/internal/webui/static/js/monitoring-insight.js @@ -14,7 +14,7 @@ // monitoring.season.sum.lead, monitoring.season.sum.lead_mean, monitoring.season.sum.prev, // monitoring.season.sum.skipped, monitoring.season.metric.pv, monitoring.season.metric.load, // monitoring.season.metric.export, monitoring.season.metric.base, monitoring.season.metric.temp -// i18n-keys (Tagesbild): monitoring.day.fact.days, monitoring.day.fact.ago, monitoring.day.fact.changed, monitoring.day.fact.learned, monitoring.day.fact.prev, monitoring.day.fact.prev_value, monitoring.day.fact.runs, monitoring.day.fact.sure, monitoring.day.fact.sure_no, monitoring.day.fact.sure_yes, monitoring.day.allday, monitoring.day.allday_short, monitoring.day.free, monitoring.day.free_short, monitoring.day.house, monitoring.day.night, monitoring.day.point, monitoring.day.read.night, monitoring.day.read.night_on, monitoring.day.read.none, monitoring.day.read.on, monitoring.day.state.active, monitoring.day.state.quiet, monitoring.day.unsure, monitoring.day.window, monitoring.run.power_for, monitoring.site.reserve, monitoring.site.reserve_est, monitoring.site.surplus_note, monitoring.site.to_forecast, monitoring.learned.short.pv_reserve_w, monitoring.learned.short.surplus_left_wh, status.uptime.hours_minutes, status.uptime.minutes +// i18n-keys (Tagesbild): monitoring.day.fact.days, monitoring.day.fact.changed, monitoring.day.fact.learned, monitoring.day.fact.prev, monitoring.day.fact.prev_value, monitoring.day.fact.runs, monitoring.day.fact.sure, monitoring.day.fact.sure_no, monitoring.day.fact.sure_yes, monitoring.day.allday, monitoring.day.allday_short, monitoring.day.free, monitoring.day.free_short, monitoring.day.house, monitoring.day.night, monitoring.day.point, monitoring.day.read.night, monitoring.day.read.night_on, monitoring.day.read.none, monitoring.day.read.on, monitoring.day.state.active, monitoring.day.state.quiet, monitoring.day.unsure, monitoring.day.window, monitoring.run.power_for, monitoring.site.reserve, monitoring.site.reserve_est, monitoring.site.surplus_note, monitoring.site.to_forecast, monitoring.learned.short.pv_reserve_w, monitoring.learned.short.surplus_left_wh, status.uptime.hours_minutes, status.uptime.minutes (() => { const EASE_OUT = 'cubic-bezier(0.23, 1, 0.32, 1)'; const FORECAST_PATH = '/api/v1/monitoring/forecast'; @@ -269,7 +269,14 @@ for (let w = 1; w <= s.week; w++) if (!cur[w]) return true; return false; }, - get selWeek() { return this.sel != null ? this.sel : (this.season ? this.season.week : 1); }, + // Vorgabe: die letzte Woche mit Daten im laufenden Jahr, sonst die aktuelle Woche + get defaultWeek() { + const s = this.season; if (!s) return 1; + const cur = window.MonitoringInsight.seasonSeries(s.weeks, s.year, this.metric); + for (let w = s.week; w >= 1; w--) if (cur[w]) return w; + return s.week; + }, + get selWeek() { return this.sel != null ? this.sel : this.defaultWeek; }, get empty() { return this.summary === null; }, fmt(v) { const m = this.m; @@ -401,7 +408,6 @@ // getFocus liefert learnedFocus (Schluessel aus dem Lernwert-Reiter, z. B. device//usual_on). const pad2 = (v) => String(v).padStart(2, '0'); const hhmm = (m) => pad2(Math.floor(m / 60)) + ':' + pad2(m % 60); - const DAY_SECONDS = 86400; const LONG_RUN_SECONDS = 20 * 3600; // Dauer aus Sekunden, Einheiten aus dem Katalog (status.uptime) function durText(seconds) { @@ -416,13 +422,9 @@ if (parts[0] === 'device' && parts[1]) return parts[1]; return SITE_HOUSE_KEYS.includes(key) ? 'house' : ''; } - // Alter eines Lernwerts: Tage als Zahl, sonst das Datum der Aenderung - function agoText(changedAt) { - const days = Math.floor((Date.now() / 1000 - changedAt) / DAY_SECONDS); - const age = days >= 1 - ? t('monitoring.day.fact.days', { n: num(days, 0) }) - : fmtDate(new Date(changedAt * 1000), { day: 'numeric', month: 'short' }); - return t('monitoring.day.fact.ago', { age }); + // Datum der letzten Aenderung eines Lernwerts, nur das Datum + function changedText(changedAt) { + return fmtDate(new Date(changedAt * 1000), { day: 'numeric', month: 'short' }); } const valueText = (entry, v) => (entry.kind === 'duration' ? durText(Number(v)) : String(v)); @@ -436,7 +438,7 @@ } out.push([t('monitoring.day.fact.sure'), t(row.sure ? 'monitoring.day.fact.sure_yes' : 'monitoring.day.fact.sure_no')]); const changed = Math.max(0, ...entries.map((e) => e.changed_at || 0)); - if (changed) out.push([t('monitoring.day.fact.changed'), agoText(changed)]); + if (changed) out.push([t('monitoring.day.fact.changed'), changedText(changed)]); entries.filter((e) => e.prev != null).forEach((e) => { out.push([t('monitoring.day.fact.prev'), t('monitoring.day.fact.prev_value', { prev: valueText(e, e.prev), value: valueText(e, e.value) })]); }); diff --git a/dashboard/internal/webui/templates/monitoring.html b/dashboard/internal/webui/templates/monitoring.html index b7a02628..6ccaa6f1 100644 --- a/dashboard/internal/webui/templates/monitoring.html +++ b/dashboard/internal/webui/templates/monitoring.html @@ -85,7 +85,7 @@

{{t "monitoring.day.title"}}

-

+

@@ -135,7 +135,7 @@

{{t "monitoring.day.title"}}

-
+

{{t "monitoring.run.title"}}

@@ -157,7 +157,7 @@

{{t "monitoring.run.title"}}

-
+

{{t "monitoring.learned.site"}}

diff --git a/dashboard/test/monitoring-insight.test.mjs b/dashboard/test/monitoring-insight.test.mjs index 7ee70728..088ab30a 100644 --- a/dashboard/test/monitoring-insight.test.mjs +++ b/dashboard/test/monitoring-insight.test.mjs @@ -280,3 +280,43 @@ test('monitoringForecast destroy disconnects the observer and removes its listen assert.equal(observer.disconnects, 1); assert.equal(listeners.removed, 4); }); + +test('monitoringDay shows only the date of the last change', () => { + const changed = Math.floor(Date.now() / 1000) - 3 * 86400; + const values = [ + { key: 'device/plug/usual_on', value: '16:45', n: 12, device_name: 'Steckdose', changed_at: changed }, + { key: 'device/plug/usual_off', value: '22:30', n: 12, device_name: 'Steckdose', changed_at: changed }, + ]; + const { component, dom } = dayComponent(values); + const label = dom.window.I18n.t('monitoring.day.fact.changed'); + const fact = component.rows.find((row) => row.id === 'plug').facts.find(([name]) => name === label); + assert.ok(fact, 'the changed fact is listed'); + assert.equal(fact[1].includes('vor'), false, fact[1]); +}); + +test('monitoringDay has no runs, site tiles or house count without values', () => { + const { component } = dayComponent([]); + assert.equal(component.runs.length, 0); + assert.equal(component.site.length, 0); + assert.equal(component.house.n, 0); +}); + +test('monitoringYear starts at the last week with data in the current year', () => { + const { factories } = create(); + const year = factories.monitoringYear(() => ({ + year: 2026, week: 5, + weeks: [ + { key: '2026-W01', pv_kwh: 5, source: 'live' }, + { key: '2026-W03', pv_kwh: 7, source: 'live' }, + ], + })); + year.$refs = {}; + assert.equal(year.selWeek, 3); +}); + +test('monitoringYear falls back to the current week without data', () => { + const { factories } = create(); + const year = factories.monitoringYear(() => ({ year: 2026, week: 5, weeks: [] })); + year.$refs = {}; + assert.equal(year.selWeek, 5); +}); From 372f5aa62d5e66c20de920df9c76aa351e957aa1 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:34:31 +0100 Subject: [PATCH 21/30] docs(monitoring): describe the forecast view, the year comparison and the usual day Co-Authored-By: Claude Sonnet 5.5 --- docs/dashboard/monitoring.md | 104 +++++++++++++++++++++++++++++++---- 1 file changed, 94 insertions(+), 10 deletions(-) diff --git a/docs/dashboard/monitoring.md b/docs/dashboard/monitoring.md index 4f482d32..a104f3d8 100644 --- a/docs/dashboard/monitoring.md +++ b/docs/dashboard/monitoring.md @@ -6,18 +6,20 @@ title: "Monitoring" The **Monitoring** tab collects what the node wants you to look at. It shows notices about the energy balance, the measurement chains and the learning -functions, and it lists every value the system has learned. The tab sits before -[Diagnostics](diagnostics.md). It needs the permission `view_monitoring`, see -[Settings, Users](settings-users.md#permissions). While a notice is new, the tab -shows a dot. +functions, it shows the forecast the node uses for the surplus, the comparison +with the previous year, and it lists every value the system has learned. The tab +sits before [Diagnostics](diagnostics.md). It needs the permission +`view_monitoring`, see [Settings, Users](settings-users.md#permissions). While a +notice is new, the tab shows a dot. Diagnostics stays a separate tab. It covers devices, services and the broker. 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**, **Learning** or **Suggestions**. +The top left of the tab switches between **Notices**, **Forecast** and **Learned +values**. The 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 @@ -65,12 +67,94 @@ shade notice names the direction and the height. It also says that nothing needs to be done when the shade cannot be removed, because the remaining surplus and the surplus window already leave it out. +## Forecast + +The **Forecast** view shows how well the node estimates the surplus. At 10:00 +each day the node estimates the remaining surplus of the day, the value +`site/surplus_left_wh`. The status card names the rules that use this value. If +no rule uses it yet, the card says so. + +The status card tells which estimate the node currently follows. It shows one of +three states: + +- **The node follows its forecast** +- **The node currently follows the season median** +- **The node is still checking its forecast** + +Below the title, the card shows the mean deviation of the forecast and of the +season median from the measured rest of the day as two bars. It also says on how +many of the last 14 days the forecast was closer. + +Below the status card, the last 14 days appear as pairs. The forecast is drawn +hollow, the measured value filled, and the season median as a dashed mark. A dot +marks each day on which the forecast was closer. Arrow keys choose a day. + +After 14 finished days the node compares the forecast with the season median, +until then the forecast applies. If the median has been at least as accurate as +the forecast over the last 14 days, the median is published instead, marked as an +estimate. + +## Year comparison + +The **Year comparison** sits under the Forecast view. It shows weekly values from +the season memory: PV, consumption, feed-in, base load and outdoor temperature. +Choose the value with the selector **Figure**. + +The current year is drawn as an area, the previous year dashed, and a third year +dotted. Weeks taken from the energy statistics are hatched. A gap appears as a +band, marked as no data. + +The headline figure compares the weeks up to now with the same weeks of the +previous year. Only weeks that are present in both years count. If weeks are +missing in one of the years, the headline says how many were left out. Moving the +pointer or finger over the chart shows one week with all years. Arrow keys choose +the week as well. + +The view needs the permission `view_monitoring`. A young node shows a note until +a previous year exists, because the season memory fills up week by week. + ## Learned values -The second view lists all values the system has learned. Each value shows its -origin, for example from 14 days, from 3 runs, changed 2 days ago or before a -previous value, and whether it is an estimate. When the seasonal memory covers -at least four weeks, a yearly line shows the curve. +The third view lists all values the system has learned. It opens with **A usual +day**, a picture of one day on a 24 hour axis. + +- The house row shows the night rest as a band. +- Each device with a usual on and off time shows a bar from on to off. A bar with + fewer than 10 learned days is hatched and marked as still learning. +- A device that only has a run length shows a dashed row, for example + "40 min at a time, no fixed time". +- A dashed line marks the current time. +- Moving the pointer or finger over the axis shows which devices are usually on at + that time. The arrow keys move the time by 15 minutes. +- Tapping a row opens the course over the year, the band between on and off per + week. It also shows the origin: learned from N days or runs, the certainty, when + the value last changed and the value before. + +Two more cards follow the picture: + +- **One run** shows the energy per run on one scale. Detected programs appear as + marks, and the power and the run time are shown below. +- **Plant** shows the PV reserve and the remaining surplus of today. A link leads + to the Forecast view. + +Each value shows its origin, for example from 14 days, from 3 runs, changed 2 days +ago or before a previous value, and whether it is an estimate. When the seasonal +memory covers at least four weeks, a yearly line shows the curve. + +Below the picture, this table explains the values: + +| Name | Meaning | Unit | +|---|---|---| +| Start of day | The learned start of the day, the point at which the usual day begins. | time of day | +| Night rest | The night rest of the house, shown as a band in the house row. | time span | +| House state | Whether the house is usually active or quiet. | active or quiet | +| PV reserve | The PV power still available, from the minute values. | W | +| Remaining surplus today | The surplus the rest of the day is expected to bring, see the Forecast view. | kWh | +| Usual switch-on time | The time at which the device is usually switched on. | time of day | +| Usual switch-off time | The time at which the device is usually switched off. | time of day | +| Usual runtime | How long the device usually runs at a time. | min | +| Typical operating power | The power the device usually draws while it runs. | W | +| Typical cycle energy | The energy the device usually takes per run, see One run. | kWh | The first group, **System**, always lists the five system values: start of day, night rest, house state, PV reserve and remaining surplus today. A value that is From b29e7397e6941e964c3cc68936872883c14512fb Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:34:54 +0100 Subject: [PATCH 22/30] chore(webui): bump cache marks for the monitoring assets Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/cache-bust-history.csv | 5 +++++ dashboard/internal/webui/templates/base.html | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index 134854c6..92992c44 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.36,2026-11-23,css/monitoring.css,2, +v0.11.22-pre.36,2026-11-23,js/monitoring-insight-model.js,1, +v0.11.22-pre.36,2026-11-23,js/monitoring-insight.js,1, +v0.11.22-pre.36,2026-11-23,js/monitoring-model.js,4, +v0.11.22-pre.36,2026-11-23,js/monitoring.page.js,3, v0.11.22-pre.35,2026-11-23,css/automations.css,25, v0.11.22-pre.35,2026-11-23,js/automation-suggestions.js,6, v0.11.22-pre.35,2026-11-23,js/automations.page.js,32, diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index fdc7a42d..ccdff669 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}} From ca4f7a05dba1715fa06eda44a812d6290b77c53f Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:46:36 +0100 Subject: [PATCH 23/30] feat(monitoring): add a tour target to the forecast tab Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/templates/monitoring.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashboard/internal/webui/templates/monitoring.html b/dashboard/internal/webui/templates/monitoring.html index 6ccaa6f1..0dd05529 100644 --- a/dashboard/internal/webui/templates/monitoring.html +++ b/dashboard/internal/webui/templates/monitoring.html @@ -13,7 +13,7 @@ {{t "monitoring.view.learned"}} -
From ab438d5db2175c4f3e3e2880f64a5a81caa6a141 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:44:02 +0100 Subject: [PATCH 24/30] test(autolearn): keep the cycle test window open until today The day store files new cycles under the running day, so a fixed window stops holding them once that day lies behind it. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_cycles_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dashboard/cmd/dashboard/learn_cycles_test.go b/dashboard/cmd/dashboard/learn_cycles_test.go index 65ea78f3..81b31b58 100644 --- a/dashboard/cmd/dashboard/learn_cycles_test.go +++ b/dashboard/cmd/dashboard/learn_cycles_test.go @@ -73,7 +73,8 @@ func TestCycleRunnerCollectsCyclesAndSurvivesRestart(t *testing.T) { // ends a cycle starts at 15 minutes). at = feedRun(t, r, at, []block{{true, 20}, {false, 20}, {true, 20}, {false, 20}}) - to := at.Add(48 * time.Hour) + // AddCycles schreibt in den laufenden Tag des Speichers, also reicht das Fenster bis heute. + to := time.Now().Add(48 * time.Hour) if got := countCycles(t, days, start, to); got != 2 { t.Fatalf("cycles before restart = %d, want 2", got) } From da980a57427a67f748d7a4db2ba878d8d47993cf Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Wed, 25 Nov 2026 21:51:27 +0000 Subject: [PATCH 25/30] chore(release): bump component versions --- dashboard/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashboard/VERSION b/dashboard/VERSION index d1772c1b..6c762875 100644 --- a/dashboard/VERSION +++ b/dashboard/VERSION @@ -1 +1 @@ -v0.11.22-pre.35 +v0.11.22-pre.36 From eb3e44d3b5b5151f581d4f189c594c51b46a5af4 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Wed, 25 Nov 2026 21:52:16 +0000 Subject: [PATCH 26/30] docs(changelog): update changelogs --- changelog/highlights/297.json | 48 ++++++++++++++++++++++++++++++++ dashboard/CHANGELOG.md | 30 ++++++++++++++++++-- services/automation/CHANGELOG.md | 2 +- 3 files changed, 76 insertions(+), 4 deletions(-) create mode 100644 changelog/highlights/297.json diff --git a/changelog/highlights/297.json b/changelog/highlights/297.json new file mode 100644 index 00000000..97b99bd9 --- /dev/null +++ b/changelog/highlights/297.json @@ -0,0 +1,48 @@ +{ + "de": { + "dashboard": "Monitoring zeigt die Prognoseprüfung, einen Jahresvergleich und die Lernwerte als üblichen Tag" + }, + "en": { + "*": "Monitoring shows the forecast check, a year comparison and the learned values as a usual day" + }, + "tour": { + "*": { + "steps": [ + { + "device": "any", + "need": "view_monitoring", + "open": [ + "monitoring-forecast" + ], + "panel": "monitoring-panel", + "target": "monitoring-forecast", + "text": { + "de": "Die neue Ansicht Prognose zeigt, ob die Node ihrer Überschussprognose oder dem Saisonmedian folgt, und vergleicht beide über die letzten 14 Tage. Darunter vergleichst du Erzeugung, Verbrauch und mehr Woche für Woche mit den Vorjahren.", + "en": "The new Forecast view shows whether the node follows its surplus forecast or the season median, and compares the two over the last 14 days. Below it you compare production, consumption and more with the previous years, week by week." + }, + "title": { + "de": "Prognose und Jahresvergleich", + "en": "Forecast and year comparison" + } + }, + { + "device": "any", + "need": "view_monitoring", + "open": [ + "monitoring-learned" + ], + "panel": "monitoring-panel", + "target": "monitoring-learned", + "text": { + "de": "Die Lernwerte erscheinen jetzt als üblicher Tag auf einer Zeitachse, mit Nachtruhe und den üblichen Zeiten deiner Geräte. Tippe auf eine Zeile, um den Verlauf übers Jahr zu sehen.", + "en": "The learned values now appear as a usual day on a time axis, with night rest and the usual times of your devices. Tap a row to see how it changes over the year." + }, + "title": { + "de": "Ein üblicher Tag", + "en": "A usual day" + } + } + ] + } + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index 7dfad156..a8c6b3e0 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.11.22-pre.35 (2026-11-06) +## v0.11.22-pre.36 (2026-11-06) ### Features @@ -35,6 +35,21 @@ - **autolearn:** The node records minute values and keeps every regulator step as a base for learning (#293) (19e65e7) - **autolearn:** Automation suggestions for surplus and load shifts are checked against your data (#295) (6c255ad) - **autolearn:** Learning functions can take minute values from Home Assistant (#294) (7aa657e) +- **autolearn:** expose forecast days and the rules that read a learned value (25d731e) +- **demo:** seed a forecast check and a year of season weeks (4a39a77) +- **monitoring:** serve the forecast check and the season weeks from the api (d11383f) +- **monitoring:** collect the forecast check and season weeks for the endpoint (e135dcc) +- **monitoring:** add texts for forecast, season and the usual day (c8b003e) +- **monitoring:** add the insight model for season and forecast (8e5f721) +- **monitoring:** add the usual day to the insight model (80bb7d0) +- **monitoring:** add the forecast and year comparison components (fe3631f) +- **monitoring:** add the forecast view and tab to the monitoring template (bc67258) +- **monitoring:** style the forecast view (1d8f4c8) +- **monitoring:** add the usual day component (5e9d157) +- **monitoring:** show learned values as a usual day (1749c86) +- **monitoring:** style the usual day (72d192a) +- **monitoring:** add a tour target to the forecast tab (ca4f7a0) +- **monitoring:** Monitoring shows the forecast check, a year comparison and the learned values as a usual day (#297) - **learnrec:** fetch minute values from Home Assistant through the companion (97e2665) - **learnrec:** pause the own recording while Home Assistant delivers minutes (4086c45) - **learnrec:** read own minutes first, then Home Assistant, and fetch gaps before the heavy run (44ee05d) @@ -334,6 +349,14 @@ - **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) +- **automations:** correct the learning feature after the full review (#296) (88f3c75) +- **monitoring:** keep texts and locale out of the insight model (57e2a44) +- **monitoring:** show the legend items for statistics weeks and gaps (82cde6e) +- **monitoring:** route locale formatting through I18n (a664db2) +- **monitoring:** link the surplus tile to the forecast and follow repeated focus (ebf5e84) +- **monitoring:** harden the insight charts and components (a1eb3a9) +- **monitoring:** keep the forecast view inside the screen and polish the usual day (7751f73) +- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **learning:** reset every learned state through one registry (594282c) - **autolearn:** survive a detector panic and keep results of finished devices (102cad0) - **autolearn:** keep harm first, cap open suggestions and give every value a spread (bde4c6a) @@ -352,8 +375,6 @@ - **automations:** read the resolve section of the learned vectors in the JS test (2405fe4) - **webui:** animate the band card and soften the popover close (ae782ae) - **autolearn:** list findings without a fix only in Monitoring (2e4acd0) -- **automations:** correct the learning feature after the full review (#296) -- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **autolearn:** harden the replay against unsupported fields and absent keys (f762aae) - **automations:** prefill the surplus templates from a suggestion (d977098) - **automations:** prefill the shift start template from a suggestion (d1b835a) @@ -491,6 +512,7 @@ ### Tests +- **autolearn:** keep the cycle test window open until today (ab438d5) - **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) @@ -512,6 +534,8 @@ ### Chores +- **monitoring:** drop the texts of the old learned values list (d6da484) +- **webui:** bump cache marks for the monitoring assets (b29e739) - **webui:** bump the cache-bust marks for the learning review fixes (6c82592) - **dashboard:** bump the cache-bust marks for the Home Assistant source (8b3bb59) - **dashboard:** refresh the cache-bust history after the rebase (33c7bcb) diff --git a/services/automation/CHANGELOG.md b/services/automation/CHANGELOG.md index 01d6f264..d27e4532 100644 --- a/services/automation/CHANGELOG.md +++ b/services/automation/CHANGELOG.md @@ -19,8 +19,8 @@ ### Fixes +- **automations:** correct the learning feature after the full review (#296) (88f3c75) - **automations:** reject learned bounds on save that the service would reject (15cd9c7) -- **automations:** correct the learning feature after the full review (#296) - **automation:** keep resolving learned values exception free and allow hold_seconds on all conditions (081dfed) - **automation:** reject malformed learned references consistently (934c418) From 3168e41ca9c2c297ee8be9135101975ebe9bc837 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:09:29 +0100 Subject: [PATCH 27/30] fix(monitoring): keep one gap between the cards of the forecast and learned views Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/static/css/monitoring.css | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/dashboard/internal/webui/static/css/monitoring.css b/dashboard/internal/webui/static/css/monitoring.css index 1bdbddbe..d63f7aa6 100644 --- a/dashboard/internal/webui/static/css/monitoring.css +++ b/dashboard/internal/webui/static/css/monitoring.css @@ -125,11 +125,11 @@ /* Ueberwachung: Prognose und Jahresvergleich (mi-*, ported from the ps draft) */ /* Gemeinsam */ -.mi-card { box-sizing: border-box; display: grid; gap: .9rem; margin: 0 0 1rem; padding: 1rem 1rem .8rem; border: 1px solid var(--border-soft); border-radius: 12px; background: var(--panel); } +.mi-card { box-sizing: border-box; display: grid; gap: .9rem; margin: 0; padding: 1rem 1rem .8rem; border: 1px solid var(--border-soft); border-radius: 12px; background: var(--panel); } .mi-head { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: .3rem 1rem; } .mi-title { margin: 0; font-size: 1.05rem; font-weight: 600; letter-spacing: -0.01em; color: var(--text-strong); } .mi-sub { margin: .15rem 0 0; font-size: .84rem; color: var(--text-muted); line-height: 1.45; } -.mi-error { margin: 0 0 1rem; color: var(--warn); line-height: 1.5; } +.mi-error { margin: 0; color: var(--warn); line-height: 1.5; } .mi-empty { margin: 0; color: var(--text-muted); line-height: 1.5; } .mi-plot { position: relative; min-height: 150px; touch-action: pan-y; user-select: none; -webkit-user-select: none; cursor: crosshair; border-radius: 8px; } .mi-plot:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } @@ -267,7 +267,6 @@ /* ---------- Ueberwachung: Lernwerte als Tagesbild ---------- */ .mi-lw { display: grid; gap: 1rem; } .mi-lw-grid { display: grid; grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); gap: 1rem; align-items: start; } -.mi-lw-grid > .mi-card { margin: 0; } .mi-day { --mi-lab: 9.5rem; position: relative; display: grid; touch-action: pan-y; user-select: none; -webkit-user-select: none; border-radius: 8px; } .mi-day:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } .mi-day-item { min-width: 0; } From 1b52e7c5f34ffbfc941d7b4ddcca10e0412da676 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:09:37 +0100 Subject: [PATCH 28/30] docs(monitoring): drop the description of the old learned values list Co-Authored-By: Claude Sonnet 5.5 --- docs/dashboard/monitoring.md | 34 ++++++++++++---------------------- 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/docs/dashboard/monitoring.md b/docs/dashboard/monitoring.md index a104f3d8..8d503169 100644 --- a/docs/dashboard/monitoring.md +++ b/docs/dashboard/monitoring.md @@ -7,8 +7,8 @@ title: "Monitoring" The **Monitoring** tab collects what the node wants you to look at. It shows notices about the energy balance, the measurement chains and the learning functions, it shows the forecast the node uses for the surplus, the comparison -with the previous year, and it lists every value the system has learned. The tab -sits before [Diagnostics](diagnostics.md). It needs the permission +with the previous year, and the values the system has learned. The tab sits +before [Diagnostics](diagnostics.md). It needs the permission `view_monitoring`, see [Settings, Users](settings-users.md#permissions). While a notice is new, the tab shows a dot. @@ -17,8 +17,8 @@ Monitoring covers the energy side and what the system has learned. ## Notices -The top left of the tab switches between **Notices**, **Forecast** and **Learned -values**. The filter on the right limits the notices to **All**, **Energy**, +The top left of the tab switches between **Notices**, **Learned values** and +**Forecast**. The 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 @@ -115,8 +115,9 @@ a previous year exists, because the season memory fills up week by week. ## Learned values -The third view lists all values the system has learned. It opens with **A usual -day**, a picture of one day on a 24 hour axis. +The **Learned values** view shows what the system has learned. It opens with **A +usual day**, a picture of one day on a 24 hour axis. A label at the top says +whether the house is usually active or quiet. - The house row shows the night rest as a band. - Each device with a usual on and off time shows a bar from on to off. A bar with @@ -134,21 +135,17 @@ Two more cards follow the picture: - **One run** shows the energy per run on one scale. Detected programs appear as marks, and the power and the run time are shown below. -- **Plant** shows the PV reserve and the remaining surplus of today. A link leads - to the Forecast view. +- **System** shows the PV reserve and the remaining surplus of today, each once + it is learned. A link leads to the Forecast view. -Each value shows its origin, for example from 14 days, from 3 runs, changed 2 days -ago or before a previous value, and whether it is an estimate. When the seasonal -memory covers at least four weeks, a yearly line shows the curve. - -Below the picture, this table explains the values: +The view shows these values: | Name | Meaning | Unit | |---|---|---| | Start of day | The learned start of the day, the point at which the usual day begins. | time of day | | Night rest | The night rest of the house, shown as a band in the house row. | time span | | House state | Whether the house is usually active or quiet. | active or quiet | -| PV reserve | The PV power still available, from the minute values. | W | +| PV reserve | The PV power still available. It is marked as an estimate until it comes from the minute values. | W | | Remaining surplus today | The surplus the rest of the day is expected to bring, see the Forecast view. | kWh | | Usual switch-on time | The time at which the device is usually switched on. | time of day | | Usual switch-off time | The time at which the device is usually switched off. | time of day | @@ -156,14 +153,7 @@ Below the picture, this table explains the values: | Typical operating power | The power the device usually draws while it runs. | W | | Typical cycle energy | The energy the device usually takes per run, see One run. | kWh | -The first group, **System**, always lists the five system values: start of day, -night rest, house state, PV reserve and remaining surplus today. A value that is -not learned yet shows its reason, such as needing PV minutes by day or more days. -Below that, each device has its own group with the usual switch-on time, the -usual switch-off time, the usual runtime, the typical operating power and the -typical cycle energy. - -If pattern learning is off, a hint above the list links to the learning settings +If pattern learning is off, the view only shows a note that you can turn it on under *Settings, Learning*. ## Energy line From 2d6749e6f7bcc6cd495c7840a5a83288b2789788 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:12:17 +0100 Subject: [PATCH 29/30] fix(monitoring): let the forecast view use the full tab width Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/static/css/monitoring.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashboard/internal/webui/static/css/monitoring.css b/dashboard/internal/webui/static/css/monitoring.css index d63f7aa6..3e940479 100644 --- a/dashboard/internal/webui/static/css/monitoring.css +++ b/dashboard/internal/webui/static/css/monitoring.css @@ -190,7 +190,7 @@ .mi-sw-gap { width: 10px; height: 10px; border-radius: 2px; background: var(--sunken, var(--panel-alt)); box-shadow: inset 0 0 0 1px var(--border-soft); } /* Ueberwachung: Prognose */ -.mi-fview { display: grid; gap: 1rem; max-width: 60rem; } +.mi-fview { display: grid; gap: 1rem; } .mi-status { box-sizing: border-box; display: grid; grid-template-columns: auto 1fr; gap: .2rem .85rem; padding: 1.1rem 1.2rem; border-radius: 14px; background: var(--panel); box-shadow: 0 0 0 1px var(--border-soft), 0 8px 24px -16px rgb(0 0 0 / .45); } .mi-status-badge { grid-row: span 2; display: grid; place-items: center; width: 40px; height: 40px; border-radius: 12px; background: var(--ok-bg); } From f54424ff2043d9418ba4b6579fb2713793a15704 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Wed, 25 Nov 2026 22:20:28 +0000 Subject: [PATCH 30/30] docs(changelog): update changelogs --- dashboard/CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index a8c6b3e0..3c231ef2 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -356,6 +356,8 @@ - **monitoring:** link the surplus tile to the forecast and follow repeated focus (ebf5e84) - **monitoring:** harden the insight charts and components (a1eb3a9) - **monitoring:** keep the forecast view inside the screen and polish the usual day (7751f73) +- **monitoring:** keep one gap between the cards of the forecast and learned views (3168e41) +- **monitoring:** let the forecast view use the full tab width (2d6749e) - **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **learning:** reset every learned state through one registry (594282c) - **autolearn:** survive a detector panic and keep results of finished devices (102cad0)