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..3c231ef2 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,16 @@ - **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) +- **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) - **autolearn:** keep harm first, cap open suggestions and give every value a spread (bde4c6a) @@ -352,8 +377,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 +514,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 +536,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/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 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) } diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 6ee99d98..16a1b448 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) } @@ -1479,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) + } +} 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") + } +} 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) + } +} 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) + } +} 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/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 5d31264b..e1ecc0fe 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,33 +3786,36 @@ "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}", - "monitoring.learned.missing": "Noch nicht gelernt", - "monitoring.learned.missing_days": "braucht mehr Tage", - "monitoring.learned.missing_pv": "braucht PV-Minuten am Tag", "monitoring.learned.off": "Muster lernen ist aus. Einschalten unter Einstellungen, Lernfunktionen.", - "monitoring.learned.origin.changed": "geändert vor {age}", - "monitoring.learned.origin.days": "aus {n} Tagen", - "monitoring.learned.origin.days_one": "aus 1 Tag", - "monitoring.learned.origin.minute": "Wert der letzten Minute", - "monitoring.learned.origin.prev": "vorher {value}", - "monitoring.learned.origin.runs": "aus {n} Läufen", - "monitoring.learned.origin.runs_one": "aus 1 Lauf", - "monitoring.learned.short.base_w": "Grundlast", - "monitoring.learned.short.battery_full_at": "Akku voll um", - "monitoring.learned.short.cycle_wh": "Typische Zyklusenergie", - "monitoring.learned.short.day_start": "Tagesbeginn", - "monitoring.learned.short.house_state": "Hauszustand", - "monitoring.learned.short.night_rest": "Nachtruhe", - "monitoring.learned.short.night_wh": "Nachtverbrauch", - "monitoring.learned.short.op_power_w": "Typische Betriebsleistung", "monitoring.learned.short.pv_reserve_w": "PV-Reserve", "monitoring.learned.short.surplus_left_wh": "Rest-Überschuss heute", - "monitoring.learned.short.usual_off": "Übliche Ausschaltzeit", - "monitoring.learned.short.usual_on": "Übliche Einschaltzeit", - "monitoring.learned.short.usual_runtime_s": "Übliche Laufzeit", "monitoring.learned.site": "Anlage", "monitoring.load_failed": "Monitoring konnte nicht geladen werden.", "monitoring.notice.chain.title": "{chain}: Messkette auffällig", @@ -3790,9 +3825,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 +3890,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..ccdcae79 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,33 +3786,36 @@ "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}", - "monitoring.learned.missing": "Not learned yet", - "monitoring.learned.missing_days": "needs more days", - "monitoring.learned.missing_pv": "needs PV minutes by day", "monitoring.learned.off": "Pattern learning is off. Turn it on under settings, learning.", - "monitoring.learned.origin.changed": "changed {age} ago", - "monitoring.learned.origin.days": "from {n} days", - "monitoring.learned.origin.days_one": "from 1 day", - "monitoring.learned.origin.minute": "value of the last minute", - "monitoring.learned.origin.prev": "before {value}", - "monitoring.learned.origin.runs": "from {n} runs", - "monitoring.learned.origin.runs_one": "from 1 run", - "monitoring.learned.short.base_w": "Base load", - "monitoring.learned.short.battery_full_at": "Battery full at", - "monitoring.learned.short.cycle_wh": "Typical cycle energy", - "monitoring.learned.short.day_start": "Start of day", - "monitoring.learned.short.house_state": "House state", - "monitoring.learned.short.night_rest": "Night rest", - "monitoring.learned.short.night_wh": "Night consumption", - "monitoring.learned.short.op_power_w": "Typical operating power", "monitoring.learned.short.pv_reserve_w": "PV reserve", "monitoring.learned.short.surplus_left_wh": "Remaining surplus today", - "monitoring.learned.short.usual_off": "Usual switch-off time", - "monitoring.learned.short.usual_on": "Usual switch-on time", - "monitoring.learned.short.usual_runtime_s": "Usual runtime", "monitoring.learned.site": "System", "monitoring.load_failed": "Monitoring could not be loaded.", "monitoring.notice.chain.title": "{chain}: measurement chain looks wrong", @@ -3790,9 +3825,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 +3890,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", diff --git a/dashboard/internal/webui/static/css/monitoring.css b/dashboard/internal/webui/static/css/monitoring.css index f1bff0c9..3e940479 100644 --- a/dashboard/internal/webui/static/css/monitoring.css +++ b/dashboard/internal/webui/static/css/monitoring.css @@ -95,37 +95,12 @@ .monitoring-empty-badge svg { width: 26px; height: 26px; fill: none; stroke: var(--ok); stroke-width: 2.4; } .monitoring-empty-title { margin: 0; font-size: 1.1rem; font-weight: 600; color: var(--text-strong); } -/* Lernwerte: Gruppenkarten in zwei Spalten */ -.monitoring-learned { column-count: 2; column-gap: 1.25rem; } -.monitoring-lgroup { break-inside: avoid; margin: 0 0 1.25rem; border-radius: 14px; background: var(--panel); - box-shadow: 0 0 0 1px var(--border-soft), 0 8px 24px -18px rgb(0 0 0 / .5); overflow: hidden; } -.monitoring-lgroup-head { display: flex; align-items: center; gap: .6rem; padding: .8rem 1rem .7rem; border-bottom: 1px solid var(--border-soft); } -.monitoring-lgroup-icon { display: grid; place-items: center; width: 30px; height: 30px; border-radius: 9px; background: var(--accent-bg); flex: none; } -.monitoring-lgroup-icon svg { width: 17px; height: 17px; fill: none; stroke: var(--accent); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } -.monitoring-lgroup-name { flex: 1; min-width: 0; font-weight: 600; color: var(--text-strong); letter-spacing: -0.005em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.monitoring-lrows { display: grid; } -.monitoring-lrow { display: flex; align-items: center; gap: .75rem; padding: .7rem 1rem; border-top: 1px solid var(--border-soft); - transition: background-color 600ms ease; } -.monitoring-lrow:first-child { border-top: 0; } -.monitoring-lrow.is-flash { background: var(--accent-bg); transition-duration: 160ms; } -.monitoring-lrow-icon { display: grid; place-items: center; width: 26px; height: 26px; border-radius: 8px; background: var(--panel-alt); flex: none; } -.monitoring-lrow-icon svg { width: 15px; height: 15px; fill: none; stroke: var(--text-muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } -.monitoring-lrow-main { flex: 1; min-width: 0; display: grid; gap: .1rem; } -.monitoring-lrow-label { color: var(--text); } -.monitoring-lrow-meta { font-size: .78rem; color: var(--text-muted); } -.monitoring-lrow-value { display: grid; justify-items: end; gap: .2rem; flex: none; text-align: right; } -.monitoring-lrow-num { font-size: 1.05rem; font-weight: 600; color: var(--text-strong); font-variant-numeric: tabular-nums; letter-spacing: -0.01em; } -.monitoring-lrow.is-missing .monitoring-lrow-num { font-size: .88rem; font-weight: 400; color: var(--text-faint); } -.monitoring-lrow.is-missing .monitoring-lrow-label { color: var(--text-muted); } -.monitoring-lrow.is-missing .monitoring-lrow-icon { opacity: .55; } -.monitoring-est { padding: 0 .45rem; border-radius: 999px; background: var(--warn-bg); color: var(--warn); font-size: .72rem; line-height: 1.6; } -.monitoring-spark { width: 64px; height: 18px; } -.monitoring-spark polyline { fill: none; stroke: var(--accent); stroke-width: 1.6; vector-effect: non-scaling-stroke; stroke-linejoin: round; stroke-linecap: round; } +/* Lernwerte: Wrapper, die Karten stehen in mi-lw */ +.monitoring-learned { display: grid; gap: 1rem; } /* Schmal: Liste mit aufklappendem Detail (Akkordeon über grid-template-rows) */ @media (max-width: 720px) { - .monitoring-bar > .auto-segment { width: 100%; display: grid; grid-template-columns: 1fr 1fr; } - .monitoring-learned { column-count: 1; } + .monitoring-bar > .auto-segment { width: 100%; display: grid; grid-template-columns: repeat(3, 1fr); } .monitoring-split { grid-template-columns: 1fr; } .monitoring-detail { display: none; } .monitoring-row-chev { display: block; } @@ -138,8 +113,6 @@ .monitoring-facts { grid-template-columns: 1fr; gap: 0; } .monitoring-facts dd { margin-bottom: .4rem; } .monitoring-steps li > span { display: block; margin: 0 0 .35rem; } - .monitoring-lrow { gap: .6rem; padding: .7rem .85rem; } - .monitoring-spark { display: none; } } @media (prefers-reduced-motion: reduce) { @@ -148,3 +121,240 @@ .monitoring-row:active, .monitoring-btn:active, .monitoring-chip:active { transform: none; } .monitoring-acked { animation: none; } } + +/* Ueberwachung: Prognose und Jahresvergleich (mi-*, ported from the ps draft) */ + +/* Gemeinsam */ +.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; 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; } +.mi-svg { display: block; overflow: visible; } +.mi-grid { stroke: var(--border-soft); stroke-width: 1; } +.mi-ylab { fill: var(--text-faint); font-size: 10.5px; text-anchor: end; font-variant-numeric: tabular-nums; } +.mi-xlab { fill: var(--text-muted); font-size: 10.5px; text-anchor: middle; font-variant-numeric: tabular-nums; } +.mi-legend { display: flex; flex-wrap: wrap; gap: .3rem 1.1rem; margin: 0; padding: 0; list-style: none; font-size: .8rem; color: var(--text-muted); } +.mi-legend li { display: inline-flex; align-items: center; gap: .4rem; } +.mi-sw { display: inline-block; flex: none; } + +/* Lesezeile: feste Stelle ueber dem Diagramm, Text springt ohne Animation (wird oft gelesen) */ +.mi-read { display: flex; flex-wrap: wrap; align-items: baseline; gap: .2rem 1.1rem; min-height: 2.6rem; padding: .5rem .75rem; border-radius: 10px; background: var(--sunken, var(--panel-alt)); font-variant-numeric: tabular-nums; } +.mi-read-when { display: grid; gap: .05rem; margin-right: auto; } +.mi-read-title { font-weight: 600; color: var(--text-strong); } +.mi-read-range { font-size: .78rem; color: var(--text-muted); } +.mi-read-val { display: inline-flex; align-items: baseline; gap: .4rem; } +.mi-read-val b { font-weight: 600; color: var(--text-strong); } +.mi-read-yr { font-size: .78rem; color: var(--text-muted); } +.mi-read-note { font-size: .78rem; color: var(--text-faint); } +.mi-pill { display: inline-block; padding: 0 .45rem; border-radius: 999px; font-size: .75rem; line-height: 1.6; font-weight: 600; background: var(--panel-alt); color: var(--text-subtle); } +.mi-pill.is-up { background: var(--ok-bg); color: var(--ok); } +.mi-pill.is-down { background: var(--warn-bg); color: var(--warn); } + +/* Statistik: Jahresvergleich */ +.mi-metrics { display: flex; flex-wrap: wrap; gap: .35rem; } +.mi-chip { display: inline-flex; align-items: center; gap: .4rem; height: 1.9rem; padding: 0 .75rem; border-radius: 999px; border: 1px solid var(--border-soft); background: none; color: var(--text-muted); font: inherit; font-size: .88rem; cursor: pointer; + transition: background-color 160ms ease, color 160ms ease, border-color 160ms ease, transform 120ms var(--ease-out); } +.mi-chip i { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .9; } +.mi-chip.is-on { background: var(--accent-bg); border-color: var(--accent-line); color: var(--text-strong); } +.mi-chip:active { transform: scale(.97); } +.mi-chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +@media (hover: hover) and (pointer: fine) { .mi-chip:not(.is-on):hover { color: var(--text); border-color: var(--border); } } + +.mi-sum { display: flex; flex-wrap: wrap; align-items: baseline; gap: .2rem .9rem; } +.mi-sum-lead { width: 100%; font-size: .78rem; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--text-subtle); } +.mi-sum-cur { font-size: 1.7rem; line-height: 1.1; font-weight: 650; letter-spacing: -0.02em; color: var(--text-strong); font-variant-numeric: tabular-nums; } +.mi-sum-prev { color: var(--text-muted); font-variant-numeric: tabular-nums; } +.mi-sum-skip { width: 100%; font-size: .78rem; color: var(--text-faint); } + +.mi-area { fill: color-mix(in srgb, currentColor 22%, transparent); } +.mi-area.is-stats { fill: url(#mi-hatch); } +.mi-area.is-band { opacity: .6; } +.mi-line { fill: none; stroke: currentColor; stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; } +.mi-line.is-stats { stroke-opacity: .7; } +.mi-prev { fill: none; stroke: var(--text-muted); stroke-width: 1.5; stroke-dasharray: 4 3; stroke-linejoin: round; } +.mi-prev-2 { stroke-dasharray: 1 3; stroke-linecap: round; opacity: .7; } +.mi-gap { fill: var(--sunken, var(--panel-alt)); } +.mi-end { fill: currentColor; stroke: var(--panel); stroke-width: 2; } +.mi-hair { stroke: var(--text-subtle); stroke-width: 1; } +.mi-dot { fill: var(--panel); stroke: var(--text-muted); stroke-width: 1.5; } +.mi-dot-0 { fill: currentColor; stroke: var(--panel); stroke-width: 2; } + +.mi-sw-cur { width: 14px; height: 10px; border-radius: 2px; border-top: 2px solid var(--mi-c); background: color-mix(in srgb, var(--mi-c) 22%, transparent); } +.mi-sw-stats { width: 14px; height: 10px; border-radius: 2px; background: repeating-linear-gradient(45deg, color-mix(in srgb, var(--mi-c) 55%, transparent) 0 1.5px, transparent 1.5px 4px); } +.mi-sw-prev { width: 16px; border-top: 1.5px dashed var(--text-muted); } +.mi-sw-prev2 { width: 16px; border-top: 2px dotted var(--text-muted); opacity: .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; } +.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); } +.mi-status-badge svg { width: 21px; height: 21px; fill: none; stroke: var(--ok); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.mi-status[data-tone="warn"] .mi-status-badge { background: var(--warn-bg); } +.mi-status[data-tone="warn"] .mi-status-badge svg { stroke: var(--warn); } +.mi-status[data-tone="wait"] .mi-status-badge { background: var(--accent-bg); } +.mi-status[data-tone="wait"] .mi-status-badge svg { stroke: var(--accent); } +.mi-status-title { margin: 0; font-size: 1.15rem; line-height: 1.25; letter-spacing: -0.01em; color: var(--text-strong); } +.mi-status-text { margin: 0; color: var(--text); line-height: 1.55; max-width: 46rem; } +.mi-status-body { grid-column: 1 / -1; display: grid; gap: .75rem; margin-top: .6rem; } + +.mi-mae { display: grid; grid-template-columns: max-content 1fr max-content; align-items: center; gap: .45rem .8rem; max-width: 34rem; font-size: .9rem; } +.mi-mae-label { color: var(--text-muted); } +.mi-mae-track { height: 8px; border-radius: 999px; background: var(--sunken, var(--panel-alt)); overflow: hidden; } +.mi-mae-bar { display: block; height: 100%; border-radius: inherit; background: var(--flow-rest); } +.mi-mae-row.is-win .mi-mae-bar { background: var(--accent); } +.mi-mae-row.is-win .mi-mae-label, .mi-mae-row.is-win .mi-mae-val { color: var(--text-strong); font-weight: 600; } +.mi-mae-row { display: contents; } +.mi-mae-val { font-variant-numeric: tabular-nums; color: var(--text-muted); text-align: right; } +.mi-mae-cap { grid-column: 1 / -1; margin: 0; font-size: .78rem; color: var(--text-faint); } + +.mi-progress { display: flex; gap: 5px; align-items: center; } +.mi-progress i { width: 9px; height: 9px; border-radius: 50%; border: 1.5px dashed var(--border); } +.mi-progress i.is-on { border: 0; background: var(--accent); } +.mi-progress span { margin-left: .5rem; font-size: .84rem; color: var(--text-muted); font-variant-numeric: tabular-nums; } + +.mi-use { margin: 0; font-size: .84rem; color: var(--text-muted); line-height: 1.5; } +.mi-use b { font-weight: 600; color: var(--text); } + +.mi-col { transition: opacity 160ms ease; } +.mi-col.is-dim { opacity: .38; } +.mi-cursor { pointer-events: none; } +.mi-hit { fill: transparent; } +.mi-fc { fill: color-mix(in srgb, var(--accent) 10%, transparent); stroke: var(--accent); stroke-width: 1.5; } +.mi-act { fill: var(--flow-pv); } +.mi-med { stroke: var(--text-strong); stroke-width: 1.5; stroke-dasharray: 3 2; opacity: .75; } +.mi-near { fill: none; stroke: var(--flow-rest); stroke-width: 1.5; } +.mi-near.is-fc { fill: var(--accent); stroke: none; } +.mi-slot { fill: none; stroke: var(--border); stroke-width: 1; stroke-dasharray: 3 3; } + +.mi-sw-fc { width: 10px; height: 12px; border-radius: 2px; box-shadow: inset 0 0 0 1.5px var(--accent); background: color-mix(in srgb, var(--accent) 10%, transparent); } +.mi-sw-act { width: 10px; height: 12px; border-radius: 2px; background: var(--flow-pv); } +.mi-sw-med { width: 14px; border-top: 1.5px dashed var(--text-strong); opacity: .75; } +.mi-sw-near { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); } + +/* Tagesband (Jahresband im Tagesdetail) */ +.mi-yr { display: block; width: 100%; height: 64px; } +.mi-yr-band { fill: color-mix(in srgb, var(--accent) 20%, transparent); } +.mi-yr-band.is-night { fill: color-mix(in srgb, var(--text-muted) 24%, transparent); } +.mi-yr-line { fill: none; stroke: var(--accent); stroke-width: 1.5; vector-effect: non-scaling-stroke; stroke-linejoin: round; } +.mi-yr-band.is-night + .mi-yr-line, .mi-yr-band.is-night ~ .mi-yr-line { stroke: var(--text-muted); } + +/* Dritter Reiter im Segment */ +@media (max-width: 720px) { + .monitoring-bar > .auto-segment:has(.mi-seg) { grid-template-columns: repeat(3, 1fr); } +} + +@media (max-width: 640px) { + .mi-card { padding: .85rem .8rem .7rem; } + .mi-sum-cur { font-size: 1.45rem; } + .mi-status { padding: 1rem; align-items: center; } + .mi-status-badge { grid-row: auto; width: 34px; height: 34px; border-radius: 10px; } + .mi-status-text { grid-column: 1 / -1; margin-top: .4rem; } + .mi-mae { grid-template-columns: max-content 1fr; } + .mi-mae-val { grid-column: 2; text-align: left; margin-top: -.3rem; font-size: .82rem; } +} + +@media (prefers-reduced-motion: reduce) { + .mi-chip, .mi-col { transition: opacity 120ms ease; } + .mi-chip:active { transform: none; } +} + +/* ---------- 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-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; } +.mi-day-row { box-sizing: border-box; display: grid; grid-template-columns: var(--mi-lab) minmax(0, 1fr) 4.8rem 14px; align-items: center; gap: .6rem; width: 100%; min-height: 2.5rem; + padding: 0 .35rem; border: 0; border-radius: 8px; background: none; color: var(--text); font: inherit; text-align: left; cursor: pointer; } +.mi-day-row:active { background: var(--panel-alt); } +.mi-day-row:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +@media (hover: hover) and (pointer: fine) { .mi-day-row:hover { background: color-mix(in srgb, var(--panel-alt) 60%, transparent); } } +.mi-day-name { display: inline-flex; align-items: center; gap: .5rem; min-width: 0; font-size: .9rem; } +.mi-day-name span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.mi-day-name svg { flex: none; width: 16px; height: 16px; fill: none; stroke: var(--text-muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.mi-track { position: relative; height: 14px; border-radius: 7px; background: var(--sunken, var(--panel-alt)); } +.mi-bar { position: absolute; top: 0; bottom: 0; border-radius: 7px; background: var(--accent); } +.mi-track.is-night .mi-bar { background: color-mix(in srgb, var(--text-muted) 38%, transparent); } +.mi-bar.is-unsure { background: repeating-linear-gradient(45deg, color-mix(in srgb, var(--accent) 70%, transparent) 0 2px, color-mix(in srgb, var(--accent) 22%, transparent) 2px 5px); } +.mi-free { position: absolute; inset: -3px 0; display: flex; align-items: center; padding: 0 .55rem; border: 1px dashed var(--border); border-radius: 9px; background: var(--panel); + color: var(--text-muted); font-size: .76rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; z-index: 2; } +.mi-free-short { display: none; } +.mi-day-side { font-size: .8rem; color: var(--text-muted); text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; } +.mi-day-chev { width: 14px; height: 14px; fill: none; stroke: var(--text-faint); stroke-width: 2.2; transition: transform 220ms var(--ease-out); } +.mi-day-item.is-open .mi-day-chev { transform: rotate(90deg); } +.mi-day-hair, .mi-day-now { position: absolute; top: 0; bottom: 1.5rem; left: 0; width: 1px; pointer-events: none; z-index: 1; } +.mi-day-hair { background: var(--text-subtle); } +.mi-day-now { width: 2px; margin-left: -.5px; background: repeating-linear-gradient(to bottom, var(--accent) 0 3px, transparent 3px 6px); opacity: .75; } +.mi-day-axis { display: grid; grid-template-columns: var(--mi-lab) minmax(0, 1fr) 4.8rem 14px; gap: .6rem; padding: .2rem .35rem 0; } +.mi-day-ticks { position: relative; height: 1rem; } +.mi-day-ticks i { position: absolute; top: 0; transform: translateX(-50%); font-style: normal; font-size: .72rem; color: var(--text-faint); font-variant-numeric: tabular-nums; } +.mi-day-ticks i:nth-child(1) { left: 0; transform: none; } .mi-day-ticks i:nth-child(2) { left: 25%; } .mi-day-ticks i:nth-child(3) { left: 50%; } .mi-day-ticks i:nth-child(4) { left: 75%; } .mi-day-ticks i:nth-child(5) { left: 100%; transform: translateX(-100%); } + +/* Aufklappen: Transition auf grid-template-rows, unterbrechbar */ +.mi-day-acc { display: grid; grid-template-rows: 0fr; opacity: 0; visibility: hidden; + transition: grid-template-rows 240ms var(--ease-out), opacity 200ms var(--ease-out), visibility 0s linear 240ms; } +.mi-day-item.is-open .mi-day-acc { grid-template-rows: 1fr; opacity: 1; visibility: visible; transition: grid-template-rows 240ms var(--ease-out), opacity 200ms var(--ease-out), visibility 0s; } +.mi-day-acc-inner { overflow: hidden; min-height: 0; } +.mi-day-detail { position: relative; z-index: 2; box-sizing: border-box; display: grid; grid-template-columns: minmax(0, 1fr) 15rem; gap: .6rem 1.2rem; margin: .25rem 0 .6rem calc(var(--mi-lab) + .95rem); padding: .8rem .9rem; border-radius: 10px; background: var(--panel-alt); } +.mi-day-main { min-width: 0; } +.mi-day-lead { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; margin: 0 0 .4rem; color: var(--text-strong); } +.mi-day-unsure { padding: 0 .45rem; border-radius: 999px; background: var(--warn-bg); color: var(--warn); font-size: .72rem; line-height: 1.6; font-weight: 600; } +.mi-day-year { min-width: 0; } +.mi-day-facts { display: grid; gap: .3rem; margin: 0; font-size: .84rem; align-content: start; } +.mi-day-facts div { display: flex; justify-content: space-between; gap: .8rem; } +.mi-day-facts dt { color: var(--text-muted); } +.mi-day-facts dd { margin: 0; color: var(--text); text-align: right; font-variant-numeric: tabular-nums; } + +.mi-sw-bar { width: 14px; height: 8px; border-radius: 4px; background: var(--accent); } +.mi-sw-unsure { width: 14px; height: 8px; border-radius: 4px; background: repeating-linear-gradient(45deg, color-mix(in srgb, var(--accent) 70%, transparent) 0 2px, color-mix(in srgb, var(--accent) 22%, transparent) 2px 5px); } +.mi-sw-night { width: 14px; height: 8px; border-radius: 4px; background: color-mix(in srgb, var(--text-muted) 38%, transparent); } +.mi-sw-now { width: 2px; height: 12px; background: repeating-linear-gradient(to bottom, var(--accent) 0 3px, transparent 3px 6px); } + +/* Ein Lauf */ +.mi-runs { display: grid; gap: .85rem; } +.mi-run { display: grid; grid-template-columns: 8.5rem minmax(0, 1fr) 4.6rem; grid-template-areas: "name track val" ". sub ."; align-items: center; gap: .15rem .7rem; } +.mi-run > .mi-day-name { grid-area: name; } +.mi-run-track { grid-area: track; position: relative; height: 10px; border-radius: 5px; background: var(--sunken, var(--panel-alt)); } +.mi-run-bar { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 5px; background: var(--flow-load); } +.mi-run-bar.is-unsure { background: repeating-linear-gradient(45deg, color-mix(in srgb, var(--flow-load) 75%, transparent) 0 2px, color-mix(in srgb, var(--flow-load) 25%, transparent) 2px 5px); } +.mi-run-tick { position: absolute; top: -3px; bottom: -3px; width: 2px; margin-left: -1px; border-radius: 1px; background: var(--text-strong); opacity: .7; } +.mi-run-val { grid-area: val; white-space: nowrap; text-align: right; font-weight: 600; color: var(--text-strong); font-variant-numeric: tabular-nums; } +.mi-run-sub { grid-area: sub; font-size: .78rem; color: var(--text-muted); } + +/* Anlage */ +.mi-tiles { display: grid; gap: .6rem; } +.mi-tile { display: grid; gap: .15rem; justify-items: start; padding: .75rem .85rem; border-radius: 10px; background: var(--panel-alt); } +.mi-tile-label { display: inline-flex; align-items: center; gap: .4rem; font-size: .8rem; color: var(--text-muted); } +.mi-tile-label svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.mi-tile-val { font-size: 1.4rem; line-height: 1.15; font-weight: 650; letter-spacing: -0.02em; color: var(--text-strong); font-variant-numeric: tabular-nums; } +.mi-tile-note { font-size: .78rem; color: var(--text-muted); } +.mi-tile .monitoring-btn-link { margin-top: .35rem; } + +@media (max-width: 720px) { + .mi-lw-grid { grid-template-columns: 1fr; } +} +@media (max-width: 640px) { + .mi-day { --mi-lab: 6.4rem; } + .mi-day-row, .mi-day-axis { grid-template-columns: var(--mi-lab) minmax(0, 1fr) 14px; gap: .5rem; } + .mi-day-side, .mi-day-axis > :nth-child(3) { display: none; } + .mi-day-name svg { display: none; } + .mi-day-detail { grid-template-columns: 1fr; margin-left: 0; } + .mi-run { grid-template-columns: minmax(0, 1fr) max-content; grid-template-areas: "name val" "track track" "sub sub"; gap: .3rem .7rem; } + .mi-free-long { display: none; } + .mi-free-short { display: inline; } +} +@media (prefers-reduced-motion: reduce) { + .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-model.js b/dashboard/internal/webui/static/js/monitoring-insight-model.js new file mode 100644 index 00000000..1380ddc3 --- /dev/null +++ b/dashboard/internal/webui/static/js/monitoring-insight-model.js @@ -0,0 +1,329 @@ +// 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, fmt) { + 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; + // Gleiche Werte (alle 0 oder alle gleich): der Bereich bleibt mindestens einen Schritt hoch + const y1 = Math.max(Math.ceil(hi / step) * step, y0 + 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, fmt) { + 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.max(2000, 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 }; + } + + // 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 })); + } + + // Vergleich fuer Namen, standardmaessig einfach nach Zeichen. Die Sortierung der Oberflaeche kommt von I18n.compare. + const plainCompare = (a, b) => (a < b ? -1 : a > b ? 1 : 0); + + // Geraete aus den gelernten Werten, nach Name sortiert. + function collectDevices(values, compare) { + 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 cmp = typeof compare === 'function' ? compare : plainCompare; + return [...by.values()].sort((a, b) => cmp(a.name, b.name)); + } + + // 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, compare) { + 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: 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: 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, compare)) { + 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 }; + // 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, + 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; + 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] }); + } + } + 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, compare) { + const list = []; + for (const d of collectDevices(values, compare)) { + 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, + seasonSummary, + seasonChart, + forecastState, + forecastChart, + dayRows, + onAt, + runRows, + yearBand, + }; +})(); 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..e6de888d --- /dev/null +++ b/dashboard/internal/webui/static/js/monitoring-insight.js @@ -0,0 +1,611 @@ +// 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.legend.gap, 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 +// 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'; + 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; + // Achsenzahlen ueber I18n, ohne I18n bleibt der Standard der Modelle + const axisFmt = () => (window.I18n && window.I18n.formatNumber ? (n) => window.I18n.formatNumber(n, 0) : undefined); + const num = (v, d) => (window.I18n && window.I18n.formatNumber ? window.I18n.formatNumber(v, d) : Number(v).toFixed(d)); + // Datum und Monatsnamen nur ueber I18n, damit Sprache und Zahlenformat der Oberflaeche gelten. + // Ohne I18n bleibt ein schlichter Text (Jahr-Monat-Tag, Monatsnummer), kein eigenes Format. + const fmtDate = (date, opts) => { + if (window.I18n && window.I18n.formatDate) return window.I18n.formatDate(date, opts); + const p2 = (v) => String(v).padStart(2, '0'); + return date.getFullYear() + '-' + p2(date.getMonth() + 1) + '-' + p2(date.getDate()); + }; + const metricList = () => window.MonitoringInsight.METRICS; + + // Monatsnamen kurz, aus der Sprache der Oberflaeche + function monthLabels() { + if (!(window.I18n && window.I18n.formatDate)) return Array.from({ length: 12 }, (_, m) => String(m + 1).padStart(2, '0')); + return Array.from({ length: 12 }, (_, m) => fmtDate(new Date(2026, m, 15), { month: 'short' })); + } + + // 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, w) { + 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); + if (w) w.observe(io); + } + // Beobachter und Zuhoerer merken, damit destroy() sie loest + function watchers() { + const undo = []; + return { + observe(obs) { undo.push(() => obs.disconnect()); return obs; }, + listen(el, type, fn) { el.addEventListener(type, fn); undo.push(() => el.removeEventListener(type, fn)); }, + release() { undo.splice(0).forEach((f) => f()); }, + }; + } + // 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, w) { + let down = false; + const on = (type, fn) => { if (w) w.listen(el, type, fn); else el.addEventListener(type, fn); }; + on('pointerdown', (e) => { down = true; try { el.setPointerCapture(e.pointerId); } catch (err) { /* egal */ } pick(e.clientX); }); + on('pointermove', (e) => { if (down || e.pointerType === 'mouse') pick(e.clientX); }); + const up = () => { down = false; }; + on('pointerup', up); + on('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 needed() { return (this.data && this.data.forecast && this.data.forecast.needed) || 14; }, + 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; + const w = (this._w = watchers()); + if ('ResizeObserver' in window) { + w.observe(new ResizeObserver(() => { const width = el.clientWidth; if (width && width !== this.width) { this.width = width; this.draw(); } })).observe(el); + } + onFirstView(el, () => reveal(el.querySelector('.mi-cols')), w); + this.$watch('data', () => { this.sel = -1; this.draw(); }); + scrubber(el, (x) => this.pickX(x), w); + }, + destroy() { if (this._w) this._w.release(); this._w = null; }, + 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(), axisFmt()); + 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]; + }, + // Mindestens eine Woche der gezeigten Jahre stammt aus der Energiestatistik + get hasStats() { + const s = this.season; if (!s) return false; + return this.years.some((yr) => window.MonitoringInsight.seasonSeries(s.weeks, yr, this.metric).some((p) => p && p.src === 'stats')); + }, + // Im aktuellen Jahr fehlt mindestens eine Woche zwischen KW 1 und der aktuellen Woche + get hasGaps() { + const s = this.season; if (!s) return false; + const cur = window.MonitoringInsight.seasonSeries(s.weeks, s.year, this.metric); + for (let w = 1; w <= s.week; w++) if (!cur[w]) return true; + return false; + }, + // 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; + 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; + const w = (this._w = watchers()); + if ('ResizeObserver' in window) { + w.observe(new ResizeObserver(() => { const width = el.clientWidth; if (width && width !== this.width) { this.width = width; this.draw(false); } })).observe(el); + } + onFirstView(el, () => reveal(el.querySelector('.mi-cur')), w); + this.$watch('season', () => this.draw(false)); + scrubber(el, (x) => this.pickX(x), w); + }, + destroy() { if (this._w) this._w.release(); this._w = null; }, + 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(), axisFmt()); + 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); } + }, + }; + } + + // Ein ueblicher Tag: Zeilen aus dem Modell, Lesezeile und Anlagewerte. getValues liefert learned.values, + // 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 LONG_RUN_SECONDS = 20 * 3600; + // Dauer aus Sekunden, Einheiten aus dem Katalog (status.uptime) + function durText(seconds) { + const min = Math.round(seconds / 60); + if (min >= 60) return t('status.uptime.hours_minutes', { hours: num(Math.floor(min / 60), 0), minutes: num(min % 60, 0) }); + return t('status.uptime.minutes', { minutes: num(min, 0) }); + } + // Zeile zu einem Fokus: device//... oeffnet , die Anlagewerte oeffnen das Haus + const SITE_HOUSE_KEYS = ['site/night_rest', 'site/day_start', 'site/house_state']; + function rowForFocus(key) { + const parts = String(key || '').split('/'); + if (parts[0] === 'device' && parts[1]) return parts[1]; + return SITE_HOUSE_KEYS.includes(key) ? 'house' : ''; + } + // 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)); + + function factsOf(row) { + const out = []; + const entries = row.entries || []; + const n = row.n || 0; + if (n) { + const runs = entries.some((e) => e.kind === 'duration'); + out.push([t('monitoring.day.fact.learned'), t(runs ? 'monitoring.day.fact.runs' : 'monitoring.day.fact.days', { n: num(n, 0) })]); + } + 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'), 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) })]); + }); + return out; + } + + // Zeile aus dem Modell mit Anzeigetexten, dazu der Jahreslauf als SVG (yr) wo es ein Fenster gibt + function decorateRow(r, band) { + const out = { id: r.id, kind: r.kind, name: r.name || t(r.nameKey), icon: r.icon, segs: r.segs, sure: r.sure, + minutes: r.minutes, label: '', short: '', side: '', facts: factsOf(r), yr: null }; + const duration = r.minutes != null ? durText(r.minutes * 60) : ''; + if (r.kind === 'night') { + out.label = t('monitoring.day.night', { from: r.from, to: r.to }); + out.side = duration; + } else if (r.kind === 'on') { + out.label = t('monitoring.day.window', { from: r.from, to: r.to }); + out.side = duration; + } else if (r.kind === 'point') { + out.label = t('monitoring.day.point', { time: r.from || r.to }); + } else if (r.kind === 'free' && r.id !== 'house') { + const long = r.minutes * 60 > LONG_RUN_SECONDS; + out.label = t(long ? 'monitoring.day.allday' : 'monitoring.day.free', { duration }); + out.short = long ? t('monitoring.day.allday_short') : t('monitoring.day.free_short', { duration }); + } else { + out.label = t('monitoring.day.unsure'); + } + if (r.year) out.yr = band(r.year[0], r.year[1], r.kind === 'night'); + return out; + } + + function monitoringDay(getValues, getFocus) { + const EMPTY = []; + const values = () => (typeof getValues === 'function' && getValues()) || EMPTY; + // Ergebnisse je Werte-Array, damit Lesen ohne neue Werte nichts neu rechnet + const cache = { rowsSrc: null, rows: null, runsSrc: null, runs: null }; + const focusKey = () => (typeof getFocus === 'function' && getFocus()) || ''; + const compare = () => (window.I18n && window.I18n.compare) || undefined; + const find = (key) => values().find((v) => v.key === key); + return { + open: '', + t: null, + moved: false, + revealed: false, + get nowMin() { const d = new Date(); return d.getHours() * 60 + d.getMinutes(); }, + get at() { return this.t == null ? this.nowMin : this.t; }, + get readTime() { return hhmm(this.at); }, + get rows() { + const src = values(); + if (src !== cache.rowsSrc) { + const M = window.MonitoringInsight; + cache.rowsSrc = src; + cache.rows = M.dayRows(src, compare()).map((r) => decorateRow(r, M.yearBand)); + } + return cache.rows; + }, + get house() { + const nr = find('site/night_rest'); const st = find('site/house_state'); + const active = Boolean(st) && st.value === 'active'; + return { + n: nr ? nr.n || 0 : 0, + state: active ? 'active' : 'quiet', + stateText: t(active ? 'monitoring.day.state.active' : 'monitoring.day.state.quiet'), + }; + }, + get runs() { + const src = values(); + if (src === cache.runsSrc) return cache.runs; + cache.runsSrc = src; + cache.runs = window.MonitoringInsight.runRows(src, compare()).map((r) => { + const power = r.powerW ? num(r.powerW / 1000, 1) + ' kW' : ''; + const time = r.seconds ? durText(r.seconds) : ''; + const sub = power && time ? t('monitoring.run.power_for', { power, duration: time }) : (power || time); + const value = r.wh ? num(r.wh / 1000, r.wh < 1000 ? 2 : 1) + ' kWh' : ''; + return { ...r, value, sub }; + }); + return cache.runs; + }, + get site() { + const reserve = find('site/pv_reserve_w'); const left = find('site/surplus_left_wh'); + const tiles = []; + if (reserve) tiles.push({ id: 'r', label: t('monitoring.learned.short.pv_reserve_w'), value: num(reserve.value, 0) + ' W', + note: t(reserve.estimate ? 'monitoring.site.reserve_est' : 'monitoring.site.reserve'), icon: 'ico-gauge' }); + if (left) tiles.push({ id: 's', label: t('monitoring.learned.short.surplus_left_wh'), value: num(left.value / 1000, 1) + ' kWh', + note: t('monitoring.site.surplus_note'), icon: 'ico-flash', link: true }); + return tiles; + }, + get readText() { + const o = window.MonitoringInsight.onAt(this.rows, this.at); + if (o.on.length) return t(o.night ? 'monitoring.day.read.night_on' : 'monitoring.day.read.on', { names: o.on.join(', ') }); + return t(o.night ? 'monitoring.day.read.night' : 'monitoring.day.read.none'); + }, + + // Ein Tipp ohne Bewegung klappt auf, nach einem Wisch ist der naechste Klick kein Tipp + toggle(id) { + if (this.moved) { this.moved = false; return; } + this.open = this.open === id ? '' : id; + }, + // Fokus aus dem Lernwert-Reiter: Zeile oeffnen und zur Zeile scrollen + follow() { + const id = rowForFocus(focusKey()); + if (!id) return; + this.open = id; + const go = () => { + const rows = this.$refs && this.$refs.rows; + const el = rows && rows.querySelector('[data-row="' + id + '"]'); + if (el && el.scrollIntoView) el.scrollIntoView({ block: 'nearest', behavior: reduced() ? 'auto' : 'smooth' }); + }; + if (this.$nextTick) this.$nextTick(go); else go(); + }, + // Balken einmal je Seitenaufruf aufziehen + reveal() { + if (this.revealed) return; + this.revealed = true; + const rows = this.$refs && this.$refs.rows; if (!rows) return; + rows.querySelectorAll('.mi-track').forEach((tr) => reveal(tr)); + }, + pick(clientX) { + const rows = this.$refs && this.$refs.rows; + const tr = rows && rows.querySelector('.mi-track'); if (!tr) return; + const r = tr.getBoundingClientRect(); + const f = Math.max(0, Math.min(0.9999, (clientX - r.left) / r.width)); + this.t = Math.round(f * 1440 / 15) * 15 % 1440; + this.place(); + }, + place() { + const rows = this.$refs && this.$refs.rows; const hair = this.$refs && this.$refs.hair; const nowl = this.$refs && this.$refs.now; + const tr = rows && rows.querySelector('.mi-track'); + if (!tr || !hair || !nowl) return; + const box = rows.getBoundingClientRect(); const r = tr.getBoundingClientRect(); + hair.style.transform = 'translateX(' + (r.left - box.left + this.at / 1440 * r.width).toFixed(1) + 'px)'; + nowl.style.transform = 'translateX(' + (r.left - box.left + this.nowMin / 1440 * r.width).toFixed(1) + 'px)'; + }, + key(e) { + const map = { ArrowLeft: -15, ArrowRight: 15 }; + if (map[e.key]) { e.preventDefault(); this.t = (this.at + map[e.key] + 1440) % 1440; this.place(); } + }, + init() { + const el = this.$refs.rows; + const w = (this._w = watchers()); + onFirstView(el, () => this.reveal(), w); + this.$watch(() => focusKey(), () => this.follow()); + this.follow(); + let down = false; let x0 = 0; + w.listen(el, 'pointerdown', (e) => { down = true; x0 = e.clientX; this.moved = false; this.pick(e.clientX); }); + w.listen(el, 'pointermove', (e) => { + if (down && !this.moved && Math.abs(e.clientX - x0) > 6) { + this.moved = true; + try { el.setPointerCapture(e.pointerId); } catch (err) { /* egal */ } + } + if (down || e.pointerType === 'mouse') this.pick(e.clientX); + }); + // Der Klick nach dem Loslassen kommt noch vor dem Timer, danach ist der Wisch vorbei + const up = () => { down = false; window.setTimeout(() => { this.moved = false; }, 0); }; + w.listen(el, 'pointerup', up); + w.listen(el, 'pointercancel', up); + if ('ResizeObserver' in window) w.observe(new ResizeObserver(() => this.place())).observe(el); + if (this.$nextTick) this.$nextTick(() => this.place()); else this.place(); + }, + destroy() { if (this._w) this._w.release(); this._w = null; }, + }; + } + + const register = () => { + if (!window.Alpine) return; + window.Alpine.data('monitoringForecast', monitoringForecast); + window.Alpine.data('monitoringYear', monitoringYear); + window.Alpine.data('monitoringDay', monitoringDay); + }; + if (window.Alpine) register(); else document.addEventListener('alpine:init', register, { once: true }); +})(); diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index 59391949..a8484694 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -196,130 +196,7 @@ }); } - // Lernwerte: Anlage mit festen Schlüsseln, Geräte nach Name, feste Reihenfolge der Gerätewerte. - const SITE_KEYS = ['day_start', 'night_rest', 'house_state', 'pv_reserve_w', 'surplus_left_wh', 'base_w', 'battery_full_at', 'night_wh']; - const RUN_KEYS = ['usual_runtime_s', 'op_power_w', 'cycle_wh']; - const ORDER = ['usual_on', 'usual_off', 'usual_runtime_s', 'op_power_w', 'cycle_wh']; - // Icons aus dem Sprite (base.html), keine neuen Zeichnungen. - const VALUE_ICON = { - usual_on: 'ico-power-on', usual_off: 'ico-power-off', usual_runtime_s: 'ico-history', - op_power_w: 'ico-gauge', cycle_wh: 'ico-flash', - day_start: 'ico-sun', night_rest: 'ico-clock', house_state: 'ico-user', - pv_reserve_w: 'ico-gauge', surplus_left_wh: 'ico-flash', - base_w: 'ico-gauge', battery_full_at: 'ico-clock', night_wh: 'ico-flash', - }; - - const isFiniteNumber = (v) => typeof v === 'number' && Number.isFinite(v); - const clockMin = (v) => { - const m = /^(\d\d):(\d\d)$/.exec(String(v)); - return m ? Number(m[1]) * 60 + Number(m[2]) : null; - }; - const numberText = (v) => (window.I18n && window.I18n.formatNumber ? window.I18n.formatNumber(v) : String(v)); - - function durationText(sec) { - const min = Math.round(Number(sec) / 60); - if (min < 60) return min + ' min'; - const h = Math.floor(min / 60); - const rest = min % 60; - return rest ? h + ' h ' + rest + ' min' : h + ' h'; - } - - // Wert eines Lernwerts als Text: Uhrzeit, Dauer, Zahl mit Einheit oder Zustand. - function valueText(entry, t) { - if (entry.kind === 'time') return t('monitoring.value.time', { time: entry.value }); - if (entry.kind === 'duration') return durationText(entry.value); - if (entry.kind === 'state') return t(entry.value === 'active' ? 'automations.learned.state.active' : 'automations.learned.state.quiet'); - return numberText(entry.value) + (entry.unit ? ' ' + entry.unit : ''); - } - - // Alter als kurze Angabe, gleiche Einheiten wie die Lernwerte-Ansicht. - function ageText(sec) { - const v = isFiniteNumber(sec) ? Math.max(0, sec) : 0; - if (v < 60) return Math.round(v) + ' s'; - if (v < 3600) return Math.round(v / 60) + ' min'; - if (v < 86400) return Math.round(v / 3600) + ' h'; - return Math.round(v / 86400) + ' d'; - } - - // Herkunft: Tage oder Läufe, Änderungszeit und vorheriger Wert, mit Trennzeichen. - function metaText(entry, name, now, t) { - const parts = []; - if (name === 'pv_reserve_w') { - parts.push(t('monitoring.learned.origin.minute')); - } else if (entry.n) { - const kind = RUN_KEYS.includes(name) ? 'runs' : 'days'; - parts.push(entry.n === 1 - ? t(`monitoring.learned.origin.${kind}_one`) - : t(`monitoring.learned.origin.${kind}`, { n: entry.n })); - } - const since = entry.changed_at || entry.at; - if (since) parts.push(t('monitoring.learned.origin.changed', { age: ageText(now - since) })); - if (entry.prev !== undefined && entry.prev !== null) { - parts.push(t('monitoring.learned.origin.prev', { value: valueText(Object.assign({}, entry, { value: entry.prev }), t) })); - } - return parts.join(' · '); - } - - // Jahreslinie als Polyline in einem 100 x 24 Feld. - function spark(entry) { - const pts = (entry.year || []) - .map((p) => (entry.kind === 'time' ? clockMin(p.value) : Number(p.value))) - .filter((x) => x !== null && Number.isFinite(x)); - if (pts.length < 4) return ''; - const lo = Math.min(...pts); - const hi = Math.max(...pts); - const span = hi - lo || 1; - return pts.map((x, i) => (i / (pts.length - 1) * 100).toFixed(1) + ',' + (21 - (x - lo) / span * 18).toFixed(1)).join(' '); - } - - function learnedRow(key, name, entry, now, t) { - return { - key, - label: t(`monitoring.learned.short.${name}`), - icon: VALUE_ICON[name] || 'ico-learning', - have: !!entry, - value: entry ? valueText(entry, t) : t('monitoring.learned.missing'), - meta: entry ? metaText(entry, name, now, t) : t(name === 'pv_reserve_w' ? 'monitoring.learned.missing_pv' : 'monitoring.learned.missing_days'), - estimate: !!(entry && entry.estimate), - spark: entry ? spark(entry) : '', - }; - } - - function learnedGroups(values, now, t) { - const list = values || []; - const byKey = new Map(list.map((v) => [v.key, v])); - const siteRows = SITE_KEYS.map((n) => learnedRow('site/' + n, n, byKey.get('site/' + n), now, t)); - const site = { - id: 'site', - label: t('monitoring.learned.site'), - icon: 'ico-learning', - have: siteRows.filter((r) => r.have).length, - total: siteRows.length, - rows: siteRows, - }; - - const devices = new Map(); - list.filter((v) => String(v.key).startsWith('device/')).forEach((v) => { - const [, dev, name] = String(v.key).split('/'); - if (!devices.has(dev)) devices.set(dev, { dev, entries: [], name: v.device_name || dev, icon: v.device_icon || 'ico-device' }); - devices.get(dev).entries.push({ name, entry: v }); - }); - const compare = (a, b) => (window.I18n && window.I18n.compare ? window.I18n.compare(a, b) : (a < b ? -1 : (a > b ? 1 : 0))); - const deviceGroups = [...devices.values()] - .sort((a, b) => compare(a.name, b.name)) - .map((d) => { - const rows = d.entries - .sort((a, b) => ORDER.indexOf(a.name) - ORDER.indexOf(b.name)) - .map((r) => learnedRow('device/' + d.dev + '/' + r.name, r.name, r.entry, now, t)); - return { id: 'device/' + d.dev, label: d.name, icon: d.icon, have: rows.filter((r) => r.have).length, total: rows.length, rows }; - }); - return [site].concat(deviceGroups); - } - window.MonitoringModel = { - learnedGroups, - valueText, - spark, sourceOf, isLearned, filterNotices, diff --git a/dashboard/internal/webui/static/js/monitoring.page.js b/dashboard/internal/webui/static/js/monitoring.page.js index 22451b90..382786ad 100644 --- a/dashboard/internal/webui/static/js/monitoring.page.js +++ b/dashboard/internal/webui/static/js/monitoring.page.js @@ -7,7 +7,7 @@ // monitoring.source.learn, monitoring.source.suggest, // monitoring.group.new, monitoring.group.known, monitoring.steps.title, // monitoring.ack.button, monitoring.ack.done, monitoring.ack.undo, monitoring.ack.no_right, -// monitoring.badge.new, monitoring.learned.count +// monitoring.badge.new (() => { const t = (key, params) => (window.I18n ? window.I18n.t(key, params) : key); const base = () => window.__DASHBOARD_BASE_PATH__ || ''; @@ -61,7 +61,8 @@ view: 'notices', filter: 'all', pick: '', - flashKey: '', + // Schluessel aus dem Lernwert-Reiter (z. B. device//usual_on), das Tagesbild oeffnet die Zeile + learnedFocus: '', init() { // Eine Anfrage, die vor dem Laden der Seite kam, liegt auf window. @@ -125,7 +126,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 = ''; }, @@ -229,7 +230,7 @@ runStep(notice, index) { const step = this.stepsOf(notice)[index]; if (!step || !step.target) return; - if (step.target === 'learned') { this.goLearned(); return; } + if (step.target === 'learned') { this.goLearned(step.key); return; } if (step.target === 'suggestion') { this.goSuggestion((step.ids || [])[0]); return; } if (step.target === 'action.role_keep') { this.roleKeep(step.ids); return; } const panel = panelFor(step.target); @@ -246,8 +247,15 @@ openTab(panel); }, - goLearned() { + // Mit Schluessel oeffnet das Tagesbild die Zeile und scrollt dorthin, ohne Schluessel zur Lernwert-Karte + goLearned(key) { + // Erst leeren, dann setzen: so folgt das Tagesbild auch einem wiederholten Schluessel + this.learnedFocus = ''; this.setView('learned'); + if (key) { + this.$nextTick(() => { this.learnedFocus = key; }); + return; + } this.$nextTick(() => { const el = this.$el && this.$el.querySelector('.monitoring-learned'); if (el && el.scrollIntoView) el.scrollIntoView({ block: 'start', behavior: reduced() ? 'auto' : 'smooth' }); @@ -263,13 +271,6 @@ openTab('automations-panel'); }, - learnedGroups() { - return window.MonitoringModel.learnedGroups(this.learned.values, nowSeconds(), t); - }, - countText(group) { - return t('monitoring.learned.count', { have: group.have, total: group.total }); - }, - titleOf(notice) { return window.MonitoringModel.title(notice, t); }, rowMeta(notice) { return [this.sourceLabel(notice.source), window.MonitoringModel.sinceText(notice.first_seen, nowSeconds(), t)].join(' · '); diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 63966485..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}} diff --git a/dashboard/internal/webui/templates/monitoring.html b/dashboard/internal/webui/templates/monitoring.html index 203d659a..0dd05529 100644 --- a/dashboard/internal/webui/templates/monitoring.html +++ b/dashboard/internal/webui/templates/monitoring.html @@ -13,6 +13,9 @@ {{t "monitoring.view.learned"}} +