From 972c4aab1b492aaa239d634f4481ce492cf05def Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:50:51 +0100 Subject: [PATCH 01/21] feat(learnrec): resolve where the minute recording lives Add learning_minutes_mode, learning_minutes_location and learning_minutes_days to the settings, with schema, defaults, and RoleEditSetup access. Add the per-stage RAM budget for minute recording (eco 4 MiB, balanced 16 MiB, full 64 MiB), ResolveMinutes for mode and location, and RAMDays to cap the RAM days by that budget. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/httpapi/settings_access.go | 3 + dashboard/internal/learnrec/level.go | 7 +- dashboard/internal/learnrec/level_test.go | 12 ++-- dashboard/internal/learnrec/minutes_config.go | 72 +++++++++++++++++++ .../internal/learnrec/minutes_config_test.go | 62 ++++++++++++++++ dashboard/internal/settings/settings.go | 22 ++++++ .../internal/settings/settings.schema.json | 24 ++++++- dashboard/internal/settings/settings_test.go | 37 ++++++++++ 8 files changed, 229 insertions(+), 10 deletions(-) create mode 100644 dashboard/internal/learnrec/minutes_config.go create mode 100644 dashboard/internal/learnrec/minutes_config_test.go diff --git a/dashboard/internal/httpapi/settings_access.go b/dashboard/internal/httpapi/settings_access.go index 398a9b27..d76fe69b 100644 --- a/dashboard/internal/httpapi/settings_access.go +++ b/dashboard/internal/httpapi/settings_access.go @@ -37,6 +37,9 @@ var settingsFieldRoles = map[string]string{ "learning_profile_days": auth.RoleEditSetup, "learning_acknowledged": auth.RoleEditSetup, "learning_level": auth.RoleEditSetup, + "learning_minutes_mode": auth.RoleEditSetup, + "learning_minutes_location": auth.RoleEditSetup, + "learning_minutes_days": auth.RoleEditSetup, "energy_stats_recording": auth.RoleEditSetup, "changelog_history": auth.RoleEditSetup, "update_check_disabled": auth.RoleEditSetup, diff --git a/dashboard/internal/learnrec/level.go b/dashboard/internal/learnrec/level.go index 152b32ce..fb778cc6 100644 --- a/dashboard/internal/learnrec/level.go +++ b/dashboard/internal/learnrec/level.go @@ -25,6 +25,7 @@ type Limits struct { LightEvery time.Duration MaxDevices int RAMMinuteDays int + RAMMinuteBytes int64 PVCellAzDeg float64 PVCellElDeg float64 GeoStepDeg float64 @@ -40,13 +41,13 @@ func LimitsFor(l Level, cores int) Limits { workers := max(1, cores-1) switch l { case LevelEco: - return Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, + return Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, RAMMinuteBytes: 4 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false} case LevelFull: - return Limits{Workers: workers, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, + return Limits{Workers: workers, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, RAMMinuteBytes: 64 << 20, PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true} default: - return Limits{Workers: workers, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, + return Limits{Workers: workers, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, RAMMinuteBytes: 16 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true} } } diff --git a/dashboard/internal/learnrec/level_test.go b/dashboard/internal/learnrec/level_test.go index 9b1731fc..218771dc 100644 --- a/dashboard/internal/learnrec/level_test.go +++ b/dashboard/internal/learnrec/level_test.go @@ -12,12 +12,12 @@ func TestLimitsForLevels(t *testing.T) { cores int want Limits }{ - {"eco 1 core", LevelEco, 1, Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false}}, - {"eco 4 cores", LevelEco, 4, Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false}}, - {"balanced 1 core", LevelBalanced, 1, Limits{Workers: 1, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true}}, - {"balanced 4 cores", LevelBalanced, 4, Limits{Workers: 3, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true}}, - {"full 1 core", LevelFull, 1, Limits{Workers: 1, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true}}, - {"full 4 cores", LevelFull, 4, Limits{Workers: 3, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true}}, + {"eco 1 core", LevelEco, 1, Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, RAMMinuteBytes: 4 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false}}, + {"eco 4 cores", LevelEco, 4, Limits{Workers: 1, Budget: 2 * time.Second, LightEvery: 15 * time.Minute, MaxDevices: 64, RAMMinuteDays: 3, RAMMinuteBytes: 4 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 5, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: false}}, + {"balanced 1 core", LevelBalanced, 1, Limits{Workers: 1, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, RAMMinuteBytes: 16 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true}}, + {"balanced 4 cores", LevelBalanced, 4, Limits{Workers: 3, Budget: 10 * time.Second, LightEvery: 5 * time.Minute, MaxDevices: 128, RAMMinuteDays: 7, RAMMinuteBytes: 16 << 20, PVCellAzDeg: 5, PVCellElDeg: 3, GeoStepDeg: 2, GeoSurfaces: 2, SimilarDays: 7, SimilarPoolDays: 56, SimilarLastYear: true}}, + {"full 1 core", LevelFull, 1, Limits{Workers: 1, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, RAMMinuteBytes: 64 << 20, PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true}}, + {"full 4 cores", LevelFull, 4, Limits{Workers: 3, Budget: 60 * time.Second, LightEvery: 1 * time.Minute, MaxDevices: 256, RAMMinuteDays: 14, RAMMinuteBytes: 64 << 20, PVCellAzDeg: 2, PVCellElDeg: 1, GeoStepDeg: 1, GeoSurfaces: 3, SimilarDays: 15, SimilarPoolDays: 0, SimilarLastYear: true}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/dashboard/internal/learnrec/minutes_config.go b/dashboard/internal/learnrec/minutes_config.go new file mode 100644 index 00000000..e9df8bba --- /dev/null +++ b/dashboard/internal/learnrec/minutes_config.go @@ -0,0 +1,72 @@ +package learnrec + +import "strings" + +// MinuteLocation ist der Ort, an dem die Minutenaufzeichnung liegt. +type MinuteLocation string + +const ( + LocRAM MinuteLocation = "ram" + LocDrive MinuteLocation = "drive" + LocSystem MinuteLocation = "system" +) + +// MinuteDaysDefault ist die Zahl der Tage, die die Minutenaufzeichnung behaelt, +// wenn die Einstellung 0 ist. +const MinuteDaysDefault = 60 + +// MinuteSettings sind die gespeicherten Einstellungen der Minutenaufzeichnung. +// Mode ist auto, always oder off. Location ist auto, ram, drive oder system. +type MinuteSettings struct { + Mode string + Location string + Days int +} + +// MinutePlan ist die aufgeloeste Form der Einstellungen. AutoLocation meldet, +// dass der Ort der Lage folgt und nicht gewaehlt wurde. +type MinutePlan struct { + On bool + Location MinuteLocation + AutoLocation bool + Days int +} + +// ResolveMinutes uebersetzt die Einstellungen. Modus auto wird zu always, +// Ort auto wird zu drive, wenn ein Laufwerk eingerichtet ist, sonst zu ram. +// Unbekannte Werte rechnen wie auto. Tage 0 heisst MinuteDaysDefault. +func ResolveMinutes(s MinuteSettings, driveConfigured bool) MinutePlan { + plan := MinutePlan{Days: s.Days} + if plan.Days <= 0 { + plan.Days = MinuteDaysDefault + } + switch strings.TrimSpace(s.Mode) { + case "off": + plan.On = false + default: + plan.On = true + } + switch MinuteLocation(strings.TrimSpace(s.Location)) { + case LocRAM, LocDrive, LocSystem: + plan.Location = MinuteLocation(strings.TrimSpace(s.Location)) + default: + plan.AutoLocation = true + plan.Location = LocRAM + if driveConfigured { + plan.Location = LocDrive + } + } + return plan +} + +// RAMDays ist die Zahl der Tage, die im RAM bleiben: die Tage der Stufe, aber +// hoechstens das RAM-Budget durch die Bytes eines vollen Tages. Mindestens 1. +func RAMDays(l Limits, bytesPerDay int64) int { + days := l.RAMMinuteDays + if bytesPerDay > 0 { + if fit := int(l.RAMMinuteBytes / bytesPerDay); fit < days { + days = fit + } + } + return max(1, days) +} diff --git a/dashboard/internal/learnrec/minutes_config_test.go b/dashboard/internal/learnrec/minutes_config_test.go new file mode 100644 index 00000000..2cb3dba1 --- /dev/null +++ b/dashboard/internal/learnrec/minutes_config_test.go @@ -0,0 +1,62 @@ +package learnrec + +import "testing" + +func TestLimitsMinuteBudgetPerLevel(t *testing.T) { + tests := []struct { + level Level + want int64 + }{ + {LevelEco, 4 << 20}, + {LevelBalanced, 16 << 20}, + {LevelFull, 64 << 20}, + } + for _, tt := range tests { + if got := LimitsFor(tt.level, 4).RAMMinuteBytes; got != tt.want { + t.Errorf("LimitsFor(%s).RAMMinuteBytes = %d, want %d", tt.level, got, tt.want) + } + } +} + +func TestResolveMinutes(t *testing.T) { + tests := []struct { + name string + settings MinuteSettings + drive bool + want MinutePlan + }{ + {"auto mode, auto location, no drive", MinuteSettings{Mode: "auto", Location: "auto", Days: 60}, false, + MinutePlan{On: true, Location: LocRAM, AutoLocation: true, Days: 60}}, + {"auto mode, auto location, drive", MinuteSettings{Mode: "auto", Location: "auto", Days: 60}, true, + MinutePlan{On: true, Location: LocDrive, AutoLocation: true, Days: 60}}, + {"explicit ram beats drive", MinuteSettings{Mode: "auto", Location: "ram", Days: 60}, true, + MinutePlan{On: true, Location: LocRAM, AutoLocation: false, Days: 60}}, + {"explicit system", MinuteSettings{Mode: "always", Location: "system", Days: 30}, false, + MinutePlan{On: true, Location: LocSystem, AutoLocation: false, Days: 30}}, + {"mode off", MinuteSettings{Mode: "off", Location: "drive", Days: 60}, true, + MinutePlan{On: false, Location: LocDrive, AutoLocation: false, Days: 60}}, + {"unknown location counts as auto", MinuteSettings{Mode: "always", Location: "turbo", Days: 60}, false, + MinutePlan{On: true, Location: LocRAM, AutoLocation: true, Days: 60}}, + {"unknown mode counts as auto", MinuteSettings{Mode: "", Location: "", Days: 60}, false, + MinutePlan{On: true, Location: LocRAM, AutoLocation: true, Days: 60}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := ResolveMinutes(tt.settings, tt.drive); got != tt.want { + t.Errorf("ResolveMinutes(%+v, %v) = %+v, want %+v", tt.settings, tt.drive, got, tt.want) + } + }) + } +} + +func TestRAMDaysCapsByBudget(t *testing.T) { + const dayRAM64 = 368 << 10 + const dayRAM512 = 2944 << 10 + eco := LimitsFor(LevelEco, 4) + if got := RAMDays(eco, dayRAM64); got != 3 { + t.Errorf("RAMDays(eco, 64 entities) = %d, want 3", got) + } + if got := RAMDays(eco, dayRAM512); got != 1 { + t.Errorf("RAMDays(eco, 512 entities) = %d, want 1", got) + } +} diff --git a/dashboard/internal/settings/settings.go b/dashboard/internal/settings/settings.go index 35c77a0e..61a63f8f 100644 --- a/dashboard/internal/settings/settings.go +++ b/dashboard/internal/settings/settings.go @@ -125,6 +125,12 @@ type Settings struct { LearningProfileDays int `json:"learning_profile_days"` LearningAcknowledged []string `json:"learning_acknowledged"` LearningLevel string `json:"learning_level"` + // LearningMinutesMode, LearningMinutesLocation und LearningMinutesDays + // steuern die Minutenaufzeichnung. Modus auto folgt dem Lernen, Ort auto + // folgt der Lage (Laufwerk, wenn eingerichtet, sonst RAM). Leer heisst auto. + LearningMinutesMode string `json:"learning_minutes_mode"` + LearningMinutesLocation string `json:"learning_minutes_location"` + LearningMinutesDays int `json:"learning_minutes_days"` // AutomationOutdoorEntity ist die unique_id der Aussentemperatur-Entitaet // fuers Saisonlernen. Leer heisst: keine Temperatur wird gesammelt. AutomationOutdoorEntity string `json:"automation_outdoor_entity"` @@ -214,6 +220,10 @@ const ( LearningProfileDaysMin = 14 LearningProfileDaysMax = 365 LearningLevelAuto = "auto" + LearningMinutesAuto = "auto" + LearningMinutesDaysDefault = 60 + LearningMinutesDaysMin = 1 + LearningMinutesDaysMax = 365 ChangelogHistoryRecent = "recent" ChangelogHistoryExtended = "extended" @@ -654,6 +664,9 @@ func Default() Settings { LearningProfileDays: LearningProfileDaysDefault, LearningAcknowledged: []string{}, LearningLevel: LearningLevelAuto, + LearningMinutesMode: LearningMinutesAuto, + LearningMinutesLocation: LearningMinutesAuto, + LearningMinutesDays: LearningMinutesDaysDefault, } } @@ -2114,6 +2127,15 @@ func normalizeSettings(value Settings) Settings { if value.LearningLevel == "" { value.LearningLevel = LearningLevelAuto } + if value.LearningMinutesMode == "" { + value.LearningMinutesMode = LearningMinutesAuto + } + if value.LearningMinutesLocation == "" { + value.LearningMinutesLocation = LearningMinutesAuto + } + if value.LearningMinutesDays == 0 { + value.LearningMinutesDays = LearningMinutesDaysDefault + } if value.LearningExcludedDevices == nil { value.LearningExcludedDevices = []string{} } diff --git a/dashboard/internal/settings/settings.schema.json b/dashboard/internal/settings/settings.schema.json index 3c44562e..bef6f5e8 100644 --- a/dashboard/internal/settings/settings.schema.json +++ b/dashboard/internal/settings/settings.schema.json @@ -3,7 +3,7 @@ "description": "Operational settings for the Energy Node dashboard.", "type": "object", "additionalProperties": false, - "required": ["health_score_threshold", "sweep_interval_seconds", "show_runtime_status", "device_view_mode", "theme", "number_format", "number_grouping", "show_config_entities_on_tile", "show_diagnostic_entities_on_tile", "live_update_interval_seconds", "wide_panels", "status_bar_items", "history_sample_interval_seconds", "history_retention_mode", "history_retention_hours", "history_budget_mb", "history_raw_window_hours", "history_minute_window_days", "history_extra_entities", "history_exchange_disabled", "history_views", "energy_stats_recording", "changelog_history", "update_check_disabled", "language_switch_hidden", "dashboard_title", "dashboard_subtitle", "dashboard_title_hidden", "dashboard_subtitle_hidden", "performance_target_pct", "automation_patterns_disabled", "automation_habits_disabled", "automation_reliability_disabled", "automation_energy_disabled", "learning_season_year_disabled", "learning_excluded_devices", "learning_profile_days", "learning_acknowledged", "learning_level", "automation_outdoor_entity"], + "required": ["health_score_threshold", "sweep_interval_seconds", "show_runtime_status", "device_view_mode", "theme", "number_format", "number_grouping", "show_config_entities_on_tile", "show_diagnostic_entities_on_tile", "live_update_interval_seconds", "wide_panels", "status_bar_items", "history_sample_interval_seconds", "history_retention_mode", "history_retention_hours", "history_budget_mb", "history_raw_window_hours", "history_minute_window_days", "history_extra_entities", "history_exchange_disabled", "history_views", "energy_stats_recording", "changelog_history", "update_check_disabled", "language_switch_hidden", "dashboard_title", "dashboard_subtitle", "dashboard_title_hidden", "dashboard_subtitle_hidden", "performance_target_pct", "automation_patterns_disabled", "automation_habits_disabled", "automation_reliability_disabled", "automation_energy_disabled", "learning_season_year_disabled", "learning_excluded_devices", "learning_profile_days", "learning_acknowledged", "learning_level", "learning_minutes_mode", "learning_minutes_location", "learning_minutes_days", "automation_outdoor_entity"], "properties": { "health_score_threshold": { "type": "integer", @@ -223,6 +223,28 @@ "title": "Lernstufe", "description": "Wie viel Last das Lernen erzeugen darf. auto waehlt die Stufe nach der Kernzahl des Geraets." }, + "learning_minutes_mode": { + "type": "string", + "enum": ["auto", "always", "off"], + "default": "auto", + "title": "Minutenaufzeichnung", + "description": "Ob die Minutenwerte aufgezeichnet werden. auto folgt dem Lernen." + }, + "learning_minutes_location": { + "type": "string", + "enum": ["auto", "ram", "drive", "system"], + "default": "auto", + "title": "Ort der Minutenaufzeichnung", + "description": "Wo die Minutenwerte liegen. auto nimmt das Laufwerk, wenn eines eingerichtet ist, sonst den Arbeitsspeicher." + }, + "learning_minutes_days": { + "type": "integer", + "minimum": 1, + "maximum": 365, + "default": 60, + "title": "Tage der Minutenaufzeichnung", + "description": "Wie viele Tage die Minutenwerte behalten werden. Gilt fuer Laufwerk und Systemlaufwerk." + }, "history_views": { "type": "array", "default": [], diff --git a/dashboard/internal/settings/settings_test.go b/dashboard/internal/settings/settings_test.go index 434dfb99..c23a5898 100644 --- a/dashboard/internal/settings/settings_test.go +++ b/dashboard/internal/settings/settings_test.go @@ -3229,6 +3229,43 @@ func TestLearningLevelInvalidIsRejected(t *testing.T) { } } +func TestLearningMinutesDefaultsWhenMissing(t *testing.T) { + got := normalizeSettings(Settings{}) + if got.LearningMinutesMode != "auto" || got.LearningMinutesLocation != "auto" || got.LearningMinutesDays != 60 { + t.Fatalf("learning minutes = %q, %q, %d, want auto, auto, 60", got.LearningMinutesMode, got.LearningMinutesLocation, got.LearningMinutesDays) + } +} + +func TestLearningMinutesOutOfRangeIsRejected(t *testing.T) { + value := Default() + value.LearningMinutesDays = 366 + if err := validateSettings(value); err == nil { + t.Fatal("learning_minutes_days 366 accepted, want rejection") + } + // normalizeSettings maps 0 to the default, so the schema only sees 0 when + // the raw document is validated. + raw, err := json.Marshal(Settings{LearningMinutesMode: "auto", LearningMinutesLocation: "auto", LearningMinutesDays: 0}) + if err != nil { + t.Fatal(err) + } + if err := config.ValidateDocument(raw, settingsSchema); err == nil { + t.Fatal("learning_minutes_days 0 accepted by the schema, want rejection") + } +} + +func TestLearningMinutesInvalidEnumIsRejected(t *testing.T) { + for _, mutate := range []func(*Settings){ + func(v *Settings) { v.LearningMinutesMode = "pause_with_companion" }, + func(v *Settings) { v.LearningMinutesLocation = "cloud" }, + } { + value := Default() + mutate(&value) + if err := validateSettings(value); err == nil { + t.Fatalf("invalid learning minutes value accepted: %+v", value) + } + } +} + func TestLearningAcknowledgedDropsDuplicatesAndKeepsUnknown(t *testing.T) { got := normalizeSettings(Settings{LearningAcknowledged: []string{"auto_patterns", "future_x", "auto_patterns"}}).LearningAcknowledged if !reflect.DeepEqual(got, []string{"auto_patterns", "future_x"}) { From f0e0eec245c4ef50cb921b6adf6ae5d560d364ea Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:53:14 +0100 Subject: [PATCH 02/21] feat(learnrec): add the binary day format of the minute recording Day file with header ENM1, key blocks and value blocks, each framed by length and CRC32. Gaps are NaN. An incomplete or invalid last block is dropped on read, and OpenAppend cuts the file to the end of the last valid block. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/learnrec/minutefile.go | 348 ++++++++++++++++++ .../internal/learnrec/minutefile_test.go | 248 +++++++++++++ 2 files changed, 596 insertions(+) create mode 100644 dashboard/internal/learnrec/minutefile.go create mode 100644 dashboard/internal/learnrec/minutefile_test.go diff --git a/dashboard/internal/learnrec/minutefile.go b/dashboard/internal/learnrec/minutefile.go new file mode 100644 index 00000000..6f852157 --- /dev/null +++ b/dashboard/internal/learnrec/minutefile.go @@ -0,0 +1,348 @@ +package learnrec + +import ( + "encoding/binary" + "errors" + "fmt" + "hash/crc32" + "io" + "math" + "os" +) + +// Binary day format of the minute recording. +// +// A day file starts with the header "ENM1", a u16 length and the day. +// Blocks follow. Each block is a u32 body length, the body and the u32 +// CRC32 (IEEE) of the body. The first body byte is the block type: +// +// - 'K' key block: u16 count, then per key u16 length and the key name. +// New keys get the next indices of the file's key table. +// - 'V' value block: u16 first minute, u16 minute count, u16 key count, +// then per key of the table (indices 0 to key count minus 1) the minute +// count of float32 values, little endian. Keys without a value in the +// block are written as gaps (NaN). +// +// A block that is incomplete or fails its CRC ends the valid part of the +// file. Reading stops there, and OpenAppend cuts the file at that point. + +const ( + minuteMagic = "ENM1" + minutesPerDay = 1440 + minuteKeys = 'K' + minuteValues = 'V' +) + +var ( + minuteGap = float32(math.NaN()) + + errShortHeader = errors.New("minute file: header incomplete") + errBadHeader = errors.New("minute file: bad header") +) + +// MinuteBlock holds the values of several keys for consecutive minutes. +// First is the minute of the day (0 to 1439), Values[k][i] is the value of +// Keys[k] at minute First+i. +type MinuteBlock struct { + First int + Keys []string + Values [][]float32 +} + +// AppendBlock writes b to w. The first call for a file also writes the +// header. Keys that are not yet in known get a key block first. known maps +// each key to its index in the file and is extended on success. +func AppendBlock(w io.Writer, day string, b MinuteBlock, known map[string]int) (int64, error) { + if known == nil { + return 0, errors.New("minute block: known map is nil") + } + if len(b.Keys) == 0 { + return 0, errors.New("minute block: no keys") + } + if len(b.Values) != len(b.Keys) { + return 0, fmt.Errorf("minute block: %d keys but %d value rows", len(b.Keys), len(b.Values)) + } + count := len(b.Values[0]) + if count == 0 || b.First < 0 || b.First+count > minutesPerDay { + return 0, fmt.Errorf("minute block: %d minutes from %d outside the day", count, b.First) + } + seen := make(map[string]bool, len(b.Keys)) + for k, key := range b.Keys { + if key == "" || len(key) > math.MaxUint16 { + return 0, fmt.Errorf("minute block: key %q has an invalid length", key) + } + if seen[key] { + return 0, fmt.Errorf("minute block: key %q twice", key) + } + seen[key] = true + if len(b.Values[k]) != count { + return 0, fmt.Errorf("minute block: key %q has %d values, want %d", key, len(b.Values[k]), count) + } + } + + var newKeys []string + for _, key := range b.Keys { + if _, ok := known[key]; !ok { + newKeys = append(newKeys, key) + } + } + base := len(known) + if base+len(newKeys) > math.MaxUint16 { + return 0, errors.New("minute block: too many keys for one day file") + } + + var out []byte + if base == 0 { + if len(day) > math.MaxUint16 { + return 0, errors.New("minute block: day name too long") + } + out = append(out, minuteMagic...) + out = binary.LittleEndian.AppendUint16(out, uint16(len(day))) + out = append(out, day...) + } + if len(newKeys) > 0 { + body := []byte{minuteKeys} + body = binary.LittleEndian.AppendUint16(body, uint16(len(newKeys))) + for _, key := range newKeys { + body = binary.LittleEndian.AppendUint16(body, uint16(len(key))) + body = append(body, key...) + } + out = appendFrame(out, body) + } + + // The value block covers the whole key table in index order. + order := make([]string, base+len(newKeys)) + for key, idx := range known { + if idx < 0 || idx >= base { + return 0, fmt.Errorf("minute block: key %q has index %d of %d", key, idx, base) + } + order[idx] = key + } + for i, key := range newKeys { + order[base+i] = key + } + rows := make(map[string][]float32, len(b.Keys)) + for k, key := range b.Keys { + rows[key] = b.Values[k] + } + body := []byte{minuteValues} + body = binary.LittleEndian.AppendUint16(body, uint16(b.First)) + body = binary.LittleEndian.AppendUint16(body, uint16(count)) + body = binary.LittleEndian.AppendUint16(body, uint16(len(order))) + for _, key := range order { + row, ok := rows[key] + for i := 0; i < count; i++ { + v := minuteGap + if ok { + v = row[i] + } + body = binary.LittleEndian.AppendUint32(body, math.Float32bits(v)) + } + } + out = appendFrame(out, body) + + n, err := w.Write(out) + if err != nil { + return int64(n), err + } + if n != len(out) { + return int64(n), io.ErrShortWrite + } + for i, key := range newKeys { + known[key] = base + i + } + return int64(len(out)), nil +} + +// ReadDay decodes a day file. Gaps are NaN. An incomplete or invalid last +// block is dropped without error. A bad header is an error. +func ReadDay(r io.Reader) (keys []string, values map[string]*[1440]float32, err error) { + data, err := io.ReadAll(r) + if err != nil { + return nil, nil, err + } + p, err := parseMinuteDay(data) + if err != nil { + return nil, nil, err + } + return p.keys, p.values, nil +} + +// OpenAppend reads the keys of the day file at path and cuts the file to the +// end of its last valid block, so that new blocks can be appended. A missing +// file counts as empty. A header cut short by an interrupted first write +// empties the file, and so does a file without keys. +func OpenAppend(path string) (known map[string]int, size int64, err error) { + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return map[string]int{}, 0, nil + } + if err != nil { + return nil, 0, err + } + p, err := parseMinuteDay(data) + switch { + case errors.Is(err, errShortHeader): + p = minuteParse{} + case err != nil: + return nil, 0, err + } + if len(p.keys) == 0 { + p.end = 0 + } + if p.end < len(data) { + if err := os.Truncate(path, int64(p.end)); err != nil { + return nil, 0, err + } + } + known = make(map[string]int, len(p.keys)) + for i, key := range p.keys { + known[key] = i + } + return known, int64(p.end), nil +} + +// minuteParse is the valid part of a day file. +type minuteParse struct { + keys []string + values map[string]*[1440]float32 + end int // offset after the last valid block +} + +func parseMinuteDay(data []byte) (minuteParse, error) { + headerEnd, err := checkMinuteHeader(data) + if err != nil { + return minuteParse{}, err + } + p := minuteParse{values: map[string]*[1440]float32{}, end: headerEnd} + for pos := headerEnd; pos < len(data); { + body, next, ok := nextMinuteFrame(data, pos) + if !ok || !p.apply(body) { + break + } + pos = next + p.end = pos + } + return p, nil +} + +func checkMinuteHeader(data []byte) (int, error) { + n := len(data) + if n > len(minuteMagic) { + n = len(minuteMagic) + } + if string(data[:n]) != minuteMagic[:n] { + return 0, errBadHeader + } + if len(data) < 6 { + return 0, errShortHeader + } + end := 6 + int(binary.LittleEndian.Uint16(data[4:6])) + if len(data) < end { + return 0, errShortHeader + } + return end, nil +} + +// nextMinuteFrame returns the body of the frame at pos and the offset after +// it. It reports false for an incomplete frame or a CRC mismatch. +func nextMinuteFrame(data []byte, pos int) ([]byte, int, bool) { + if len(data)-pos < 8 { + return nil, 0, false + } + n := uint64(binary.LittleEndian.Uint32(data[pos:])) + if uint64(len(data)-pos-8) < n { + return nil, 0, false + } + bodyEnd := pos + 4 + int(n) + body := data[pos+4 : bodyEnd] + if crc32.ChecksumIEEE(body) != binary.LittleEndian.Uint32(data[bodyEnd:]) { + return nil, 0, false + } + return body, bodyEnd + 4, true +} + +// apply adds one block to p. It validates the whole block before it changes +// anything and reports false for an invalid block. +func (p *minuteParse) apply(body []byte) bool { + if len(body) == 0 { + return false + } + switch body[0] { + case minuteKeys: + return p.applyKeys(body[1:]) + case minuteValues: + return p.applyValues(body[1:]) + } + return false +} + +func (p *minuteParse) applyKeys(payload []byte) bool { + if len(payload) < 2 { + return false + } + n := int(binary.LittleEndian.Uint16(payload)) + rest := payload[2:] + names := make([]string, 0, n) + fresh := make(map[string]bool, n) + for i := 0; i < n; i++ { + if len(rest) < 2 { + return false + } + l := int(binary.LittleEndian.Uint16(rest)) + rest = rest[2:] + if l == 0 || len(rest) < l { + return false + } + name := string(rest[:l]) + rest = rest[l:] + if _, exists := p.values[name]; exists || fresh[name] { + return false + } + fresh[name] = true + names = append(names, name) + } + if len(rest) != 0 { + return false + } + for _, name := range names { + arr := new([minutesPerDay]float32) + for i := range arr { + arr[i] = minuteGap + } + p.keys = append(p.keys, name) + p.values[name] = arr + } + return true +} + +func (p *minuteParse) applyValues(payload []byte) bool { + if len(payload) < 6 { + return false + } + first := int(binary.LittleEndian.Uint16(payload)) + count := int(binary.LittleEndian.Uint16(payload[2:])) + nkeys := int(binary.LittleEndian.Uint16(payload[4:])) + rest := payload[6:] + if count == 0 || first+count > minutesPerDay || nkeys > len(p.keys) { + return false + } + if len(rest) != nkeys*count*4 { + return false + } + for k := 0; k < nkeys; k++ { + arr := p.values[p.keys[k]] + for i := 0; i < count; i++ { + arr[first+i] = math.Float32frombits(binary.LittleEndian.Uint32(rest)) + rest = rest[4:] + } + } + return true +} + +// appendFrame appends a block frame: u32 body length, body, u32 CRC32. +func appendFrame(dst, body []byte) []byte { + dst = binary.LittleEndian.AppendUint32(dst, uint32(len(body))) + dst = append(dst, body...) + return binary.LittleEndian.AppendUint32(dst, crc32.ChecksumIEEE(body)) +} diff --git a/dashboard/internal/learnrec/minutefile_test.go b/dashboard/internal/learnrec/minutefile_test.go new file mode 100644 index 00000000..ec1fef88 --- /dev/null +++ b/dashboard/internal/learnrec/minutefile_test.go @@ -0,0 +1,248 @@ +package learnrec + +import ( + "bytes" + "fmt" + "math" + "os" + "path/filepath" + "testing" +) + +const testMinuteDay = "2026-11-21" + +var testGap = float32(math.NaN()) + +// appendMinuteBlock appends one block to path the way the recorder does. +func appendMinuteBlock(t *testing.T, path string, b MinuteBlock, known map[string]int) int64 { + t.Helper() + f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + t.Fatal(err) + } + defer f.Close() + n, err := AppendBlock(f, testMinuteDay, b, known) + if err != nil { + t.Fatal(err) + } + return n +} + +func readMinuteFile(t *testing.T, path string) ([]string, map[string]*[1440]float32) { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + keys, values, err := ReadDay(bytes.NewReader(data)) + if err != nil { + t.Fatalf("ReadDay: %v", err) + } + return keys, values +} + +func requireMinuteValue(t *testing.T, values map[string]*[1440]float32, key string, minute int, want float32) { + t.Helper() + arr, ok := values[key] + if !ok { + t.Fatalf("key %q missing", key) + } + got := arr[minute] + if math.IsNaN(float64(want)) { + if !math.IsNaN(float64(got)) { + t.Fatalf("%s at minute %d: got %v, want gap", key, minute, got) + } + return + } + if got != want { + t.Fatalf("%s at minute %d: got %v, want %v", key, minute, got, want) + } +} + +func TestBlockRoundTripWithNewKeysMidDay(t *testing.T) { + path := filepath.Join(t.TempDir(), testMinuteDay+".enm") + known := map[string]int{} + appendMinuteBlock(t, path, MinuteBlock{First: 0, Keys: []string{"e:a"}, Values: [][]float32{{1, 2, 3}}}, known) + appendMinuteBlock(t, path, MinuteBlock{First: 3, Keys: []string{"e:a", "t:outdoor"}, Values: [][]float32{{4, 5}, {-2, -3}}}, known) + // b:grid starts at minute 720, so its minutes before that stay gaps. + appendMinuteBlock(t, path, MinuteBlock{First: 720, Keys: []string{"b:grid"}, Values: [][]float32{{7}}}, known) + + keys, values := readMinuteFile(t, path) + if want := []string{"e:a", "t:outdoor", "b:grid"}; fmt.Sprint(keys) != fmt.Sprint(want) { + t.Fatalf("keys: got %v, want %v", keys, want) + } + if known["t:outdoor"] != 1 || known["b:grid"] != 2 { + t.Fatalf("known: got %v", known) + } + requireMinuteValue(t, values, "e:a", 0, 1) + requireMinuteValue(t, values, "e:a", 4, 5) + requireMinuteValue(t, values, "e:a", 5, testGap) + requireMinuteValue(t, values, "e:a", 719, testGap) + requireMinuteValue(t, values, "t:outdoor", 2, testGap) + requireMinuteValue(t, values, "t:outdoor", 3, -2) + requireMinuteValue(t, values, "t:outdoor", 4, -3) + requireMinuteValue(t, values, "b:grid", 719, testGap) + requireMinuteValue(t, values, "b:grid", 720, 7) + requireMinuteValue(t, values, "b:grid", 721, testGap) +} + +func TestBlockTruncatedTailIsDroppedAndAppendResumes(t *testing.T) { + path := filepath.Join(t.TempDir(), testMinuteDay+".enm") + known := map[string]int{} + appendMinuteBlock(t, path, MinuteBlock{First: 0, Keys: []string{"e:a"}, Values: [][]float32{{1, 2}}}, known) + appendMinuteBlock(t, path, MinuteBlock{First: 3, Keys: []string{"t:outdoor"}, Values: [][]float32{{-2}}}, known) + fi, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + sizeAfterTwo := fi.Size() + // The last block is a value block only, so cutting into it leaves the + // key table of the first two blocks intact. + appendMinuteBlock(t, path, MinuteBlock{First: 10, Keys: []string{"e:a", "t:outdoor"}, Values: [][]float32{{9}, {8}}}, known) + + fi, err = os.Stat(path) + if err != nil { + t.Fatal(err) + } + if err := os.Truncate(path, fi.Size()-7); err != nil { + t.Fatal(err) + } + + keys, values := readMinuteFile(t, path) + if want := []string{"e:a", "t:outdoor"}; fmt.Sprint(keys) != fmt.Sprint(want) { + t.Fatalf("keys after cut: got %v, want %v", keys, want) + } + requireMinuteValue(t, values, "e:a", 1, 2) + requireMinuteValue(t, values, "t:outdoor", 3, -2) + requireMinuteValue(t, values, "e:a", 10, testGap) + + known, size, err := OpenAppend(path) + if err != nil { + t.Fatalf("OpenAppend: %v", err) + } + if size != sizeAfterTwo { + t.Fatalf("size after OpenAppend: got %d, want %d", size, sizeAfterTwo) + } + if fi, _ := os.Stat(path); fi.Size() != sizeAfterTwo { + t.Fatalf("file size on disk: got %d, want %d", fi.Size(), sizeAfterTwo) + } + if len(known) != 2 || known["e:a"] != 0 || known["t:outdoor"] != 1 { + t.Fatalf("known: got %v", known) + } + + appendMinuteBlock(t, path, MinuteBlock{First: 20, Keys: []string{"e:a"}, Values: [][]float32{{5}}}, known) + keys, values = readMinuteFile(t, path) + if want := []string{"e:a", "t:outdoor"}; fmt.Sprint(keys) != fmt.Sprint(want) { + t.Fatalf("keys after resume: got %v, want %v", keys, want) + } + requireMinuteValue(t, values, "e:a", 1, 2) + requireMinuteValue(t, values, "e:a", 20, 5) +} + +func TestBlockFlippedCRCBitDropsBlock(t *testing.T) { + path := filepath.Join(t.TempDir(), testMinuteDay+".enm") + known := map[string]int{} + appendMinuteBlock(t, path, MinuteBlock{First: 0, Keys: []string{"e:a"}, Values: [][]float32{{1, 2}}}, known) + appendMinuteBlock(t, path, MinuteBlock{First: 2, Keys: []string{"e:a"}, Values: [][]float32{{3}}}, known) + + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + data[len(data)-1] ^= 0x01 // last byte is the CRC of the last block + if err := os.WriteFile(path, data, 0o644); err != nil { + t.Fatal(err) + } + + _, values := readMinuteFile(t, path) + requireMinuteValue(t, values, "e:a", 1, 2) + requireMinuteValue(t, values, "e:a", 2, testGap) +} + +func TestBlockFullDayWith64KeysStaysUnder400KiB(t *testing.T) { + path := filepath.Join(t.TempDir(), testMinuteDay+".enm") + known := map[string]int{} + keys := make([]string, 64) + for i := range keys { + keys[i] = fmt.Sprintf("e:dev%02d", i) + } + for block := 0; block < 288; block++ { + values := make([][]float32, len(keys)) + for k := range keys { + values[k] = []float32{float32(k), float32(k) + 0.5, 1, 2, 3} + } + appendMinuteBlock(t, path, MinuteBlock{First: block * 5, Keys: keys, Values: values}, known) + } + + fi, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if fi.Size() >= 400<<10 { + t.Fatalf("file size %d bytes, want under 400 KiB", fi.Size()) + } + _, values := readMinuteFile(t, path) + requireMinuteValue(t, values, "e:dev63", 1439, 3) + requireMinuteValue(t, values, "e:dev05", 5, 5) +} + +func TestBlockRejectsInvalidInput(t *testing.T) { + tests := map[string]MinuteBlock{ + "no keys": {First: 0}, + "row count": {First: 0, Keys: []string{"e:a"}, Values: nil}, + "row length": {First: 0, Keys: []string{"e:a", "e:b"}, Values: [][]float32{{1}, {1, 2}}}, + "outside the day": {First: 1439, Keys: []string{"e:a"}, Values: [][]float32{{1, 2}}}, + "duplicate key": {First: 0, Keys: []string{"e:a", "e:a"}, Values: [][]float32{{1}, {2}}}, + "empty key": {First: 0, Keys: []string{""}, Values: [][]float32{{1}}}, + } + for name, b := range tests { + var buf bytes.Buffer + if _, err := AppendBlock(&buf, testMinuteDay, b, map[string]int{}); err == nil { + t.Errorf("%s: want error", name) + } + if buf.Len() != 0 { + t.Errorf("%s: wrote %d bytes before failing", name, buf.Len()) + } + } +} + +func TestReadDayRejectsBadHeader(t *testing.T) { + if _, _, err := ReadDay(bytes.NewReader(nil)); err == nil { + t.Error("empty input: want error") + } + if _, _, err := ReadDay(bytes.NewReader([]byte("XXXX\x00\x00"))); err == nil { + t.Error("wrong magic: want error") + } + + path := filepath.Join(t.TempDir(), testMinuteDay+".enm") + foreign := []byte("XXXX\x00\x00 not a minute file") + if err := os.WriteFile(path, foreign, 0o644); err != nil { + t.Fatal(err) + } + if _, _, err := OpenAppend(path); err == nil { + t.Fatal("OpenAppend on a foreign file: want error") + } + if data, _ := os.ReadFile(path); !bytes.Equal(data, foreign) { + t.Fatalf("foreign file was changed: %q", data) + } +} + +func TestOpenAppendRecoversFromPartialHeader(t *testing.T) { + path := filepath.Join(t.TempDir(), testMinuteDay+".enm") + if err := os.WriteFile(path, []byte("ENM"), 0o644); err != nil { + t.Fatal(err) + } + known, size, err := OpenAppend(path) + if err != nil { + t.Fatalf("OpenAppend: %v", err) + } + if size != 0 || len(known) != 0 { + t.Fatalf("got size %d, known %v, want empty", size, known) + } + if fi, _ := os.Stat(path); fi.Size() != 0 { + t.Fatalf("file size %d, want 0", fi.Size()) + } + appendMinuteBlock(t, path, MinuteBlock{First: 4, Keys: []string{"e:a"}, Values: [][]float32{{1}}}, known) + _, values := readMinuteFile(t, path) + requireMinuteValue(t, values, "e:a", 4, 1) +} From 64aff3402e4a395beccb96d99d3d70ffd185f24c Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:56:51 +0100 Subject: [PATCH 03/21] feat(learnrec): keep minute values in RAM and append them to the chosen drive The MinuteStore collects the minute values of entities, balance and outdoor temperature in RAM and writes them at Flush to the day files of the chosen location. While a drive is down, the values stay in RAM and are appended once it is back, without gaps or duplicates. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/learnrec/minutestore.go | 522 ++++++++++++++++++ .../internal/learnrec/minutestore_test.go | 285 ++++++++++ 2 files changed, 807 insertions(+) create mode 100644 dashboard/internal/learnrec/minutestore.go create mode 100644 dashboard/internal/learnrec/minutestore_test.go diff --git a/dashboard/internal/learnrec/minutestore.go b/dashboard/internal/learnrec/minutestore.go new file mode 100644 index 00000000..d8e6cda9 --- /dev/null +++ b/dashboard/internal/learnrec/minutestore.go @@ -0,0 +1,522 @@ +package learnrec + +import ( + "errors" + "math" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" +) + +// MinuteDirs sind die Basisverzeichnisse der Laufwerke. Leer heisst nicht verfuegbar. +type MinuteDirs struct { + Drive string + System string +} + +// MinuteUsage beschreibt den Stand der Minutenaufzeichnung. Bytes sind die seit +// Since geschriebenen Bytes. Since ist der Zeitpunkt der ersten Minute in Unix-Sekunden. +type MinuteUsage struct { + Bytes int64 + WrittenPerDay int64 + Since int64 + Keys int + RAMDays int + FileDays int + Location MinuteLocation + DriveDown bool +} + +const minuteDayLayout = "2006-01-02" + +// minuteDay ist ein Tag im RAM. observed sind die Minuten mit Werten, pending +// die, die noch nicht in der Datei des Ziels (target) stehen. +type minuteDay struct { + values map[string]*[minutesPerDay]float32 + observed [minutesPerDay]bool + pending [minutesPerDay]bool + target string + onDisk bool +} + +// minuteFileState ist die zwischengespeicherte Lage einer Tagesdatei. +type minuteFileState struct { + known map[string]int + have [minutesPerDay]bool +} + +type minuteJob struct { + day string + path string + d *minuteDay +} + +type minuteRun struct { + block MinuteBlock + count int +} + +// MinuteStore sammelt die Minutenwerte im RAM und schreibt sie beim Flush an +// den gewaehlten Ort. Der Minutenweg beruehrt nur das RAM. Dateien entstehen +// nur in Flush und Reset, ausserhalb des Hub-Mutex. +type MinuteStore struct { + flushMu sync.Mutex // serialisiert Flush und Reset, schuetzt files + loc *time.Location + plan func() MinutePlan + dirs func() MinuteDirs + driveUp func() bool + limits func() Limits + logf func(string, ...any) + files map[string]*minuteFileState + + mu sync.Mutex // schuetzt die Felder darunter + days map[string]*minuteDay + keys map[string]bool + since time.Time + written int64 + lastNow time.Time + curKey string + curDir string + prevDir string +} + +var _ MinuteConsumer = (*MinuteStore)(nil) + +// NewMinuteStore legt einen Store an. plan, dirs, driveUp und limits werden bei +// jedem Aufruf gelesen. +func NewMinuteStore(loc *time.Location, plan func() MinutePlan, dirs func() MinuteDirs, driveUp func() bool, limits func() Limits, logf func(string, ...any)) *MinuteStore { + if logf == nil { + logf = func(string, ...any) {} + } + return &MinuteStore{ + loc: loc, + plan: plan, + dirs: dirs, + driveUp: driveUp, + limits: limits, + logf: logf, + files: map[string]*minuteFileState{}, + days: map[string]*minuteDay{}, + keys: map[string]bool{}, + } +} + +// ObserveMinute legt die Werte des Rahmens im RAM ab. Schluessel sind e: +// fuer Leistung, b: fuer die Bilanz und t:outdoor fuer die Aussentemperatur. +func (s *MinuteStore) ObserveMinute(f Frame) { + if !s.plan().On { + return + } + vals := map[string]float64{} + for _, dev := range f.Devices { + for uid, w := range dev.Power { + vals["e:"+uid] = w + } + } + for field, v := range f.Balance { + vals["b:"+field] = v + } + if f.OutdoorC != nil { + vals["t:outdoor"] = *f.OutdoorC + } + if len(vals) == 0 { + return + } + + local := f.Minute.In(s.loc) + day := local.Format(minuteDayLayout) + m := local.Hour()*60 + local.Minute() + + s.mu.Lock() + defer s.mu.Unlock() + d := s.days[day] + if d == nil { + d = &minuteDay{values: map[string]*[minutesPerDay]float32{}} + s.days[day] = d + } + for key, v := range vals { + arr := d.values[key] + if arr == nil { + arr = new([minutesPerDay]float32) + for i := range arr { + arr[i] = minuteGap + } + d.values[key] = arr + s.keys[key] = true + } + arr[m] = float32(v) + } + d.observed[m] = true + d.pending[m] = true + if s.since.IsZero() { + s.since = local + } +} + +// place liefert den Schluessel des Orts, das Basisverzeichnis und ob der Ort +// jetzt beschreibbar ist. Der Ort ram hat kein Verzeichnis. +func (s *MinuteStore) place(pl MinutePlan, dirs MinuteDirs, up bool) (key, dir string, writable bool) { + switch pl.Location { + case LocDrive: + dir = dirs.Drive + writable = dir != "" && up + case LocSystem: + dir = dirs.System + writable = dir != "" + default: + return "ram|", "", false + } + return string(pl.Location) + "|" + dir, dir, writable +} + +// Flush schreibt die ausstehenden Minuten an den Ort. Ist das Laufwerk nicht +// da, bleibt alles im RAM. Danach kommen Tage aus dem RAM, die aelter als die +// Aufbewahrung sind oder ueber die RAM-Tage hinausgehen. +func (s *MinuteStore) Flush(now time.Time) error { + s.flushMu.Lock() + defer s.flushMu.Unlock() + + pl := s.plan() + dirs := s.dirs() + up := s.driveUp() + lim := s.limits() + key, dir, writable := s.place(pl, dirs, up) + cutoff := now.In(s.loc).AddDate(0, 0, -pl.Days).Format(minuteDayLayout) + + s.mu.Lock() + s.lastNow = now + if key != s.curKey { + s.curKey = key + if s.curDir != "" && s.curDir != dir { + s.prevDir = s.curDir + } + s.curDir = dir + s.files = map[string]*minuteFileState{} + } + if !writable { + s.files = map[string]*minuteFileState{} + } + + // RAM-Tage: aelter als die Aufbewahrung oder hinter den neuesten RAM-Tagen. + keep := RAMDays(lim, int64(len(s.keys))*minutesPerDay*4) + names := make([]string, 0, len(s.days)) + for k := range s.days { + names = append(names, k) + } + sort.Sort(sort.Reverse(sort.StringSlice(names))) + for i, k := range names { + if i >= keep || k <= cutoff { + delete(s.days, k) + } + } + + days := make([]string, 0, len(s.days)) + for k := range s.days { + days = append(days, k) + } + sort.Strings(days) + var jobs []minuteJob + for _, k := range days { + d := s.days[k] + path := "" + if writable { + path = minuteFileName(dir, k) + } + tgt := key + "|" + path + if d.target != tgt { + d.target = tgt + d.pending = d.observed + } + if path != "" { + jobs = append(jobs, minuteJob{day: k, path: path, d: d}) + } + } + s.mu.Unlock() + + if !writable { + return nil + } + var errs []error + for _, j := range jobs { + if err := s.writeDay(j); err != nil { + errs = append(errs, err) + } + } + if err := s.pruneFiles(dir, cutoff); err != nil { + errs = append(errs, err) + } + for _, err := range errs { + s.logf("learnrec: Minuten schreiben fehlgeschlagen: %v", err) + } + return errors.Join(errs...) +} + +// writeDay haengt die ausstehenden Minuten eines Tages an seine Datei an. Die +// Minuten, die die Datei schon hat, werden uebersprungen. +func (s *MinuteStore) writeDay(j minuteJob) error { + st, err := s.fileState(j.path) + if err != nil { + return err + } + runs := s.pendingRuns(j.d, st) + if len(runs) == 0 { + return nil + } + if err := os.MkdirAll(filepath.Dir(j.path), 0o755); err != nil { + return err + } + f, err := os.OpenFile(j.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + return err + } + defer f.Close() + for _, r := range runs { + n, err := AppendBlock(f, j.day, r.block, st.known) + if err != nil { + delete(s.files, j.path) + return err + } + s.mu.Lock() + s.written += n + j.d.onDisk = true + for m := r.block.First; m < r.block.First+r.count; m++ { + j.d.pending[m] = false + st.have[m] = true + } + s.mu.Unlock() + } + return nil +} + +// pendingRuns sammelt die ausstehenden Minuten zu zusammenhaengenden Bloecken. +// Minuten, die die Datei schon hat, gelten als erledigt. +func (s *MinuteStore) pendingRuns(d *minuteDay, st *minuteFileState) []minuteRun { + s.mu.Lock() + defer s.mu.Unlock() + var runs []minuteRun + for m := 0; m < minutesPerDay; { + if !d.pending[m] { + m++ + continue + } + if st.have[m] { + d.pending[m] = false + m++ + continue + } + start := m + for m < minutesPerDay && d.pending[m] && !st.have[m] { + m++ + } + count := m - start + b := MinuteBlock{First: start} + for key, arr := range d.values { + vals := make([]float32, count) + hasValue := false + for i := range vals { + vals[i] = arr[start+i] + if !math.IsNaN(float64(vals[i])) { + hasValue = true + } + } + if hasValue { + b.Keys = append(b.Keys, key) + b.Values = append(b.Values, vals) + } + } + if len(b.Keys) == 0 { + for i := start; i < m; i++ { + d.pending[i] = false + } + continue + } + runs = append(runs, minuteRun{block: b, count: count}) + } + return runs +} + +// fileState liefert die Lage der Datei aus dem Cache oder liest sie ein. Die +// Datei wird dabei auf ihren letzten gueltigen Block gekuerzt. +func (s *MinuteStore) fileState(path string) (*minuteFileState, error) { + if st := s.files[path]; st != nil { + return st, nil + } + known, _, err := OpenAppend(path) + if err != nil { + return nil, err + } + st := &minuteFileState{known: known} + if len(known) > 0 { + f, err := os.Open(path) + if err != nil { + return nil, err + } + _, values, err := ReadDay(f) + f.Close() + if err != nil { + return nil, err + } + for _, arr := range values { + for m := range arr { + if !math.IsNaN(float64(arr[m])) { + st.have[m] = true + } + } + } + } + s.files[path] = st + return st, nil +} + +// pruneFiles loescht die Tagesdateien im Verzeichnis dir, deren Tag nicht nach cutoff liegt. +func (s *MinuteStore) pruneFiles(dir, cutoff string) error { + sub := minuteDirOf(dir) + entries, err := os.ReadDir(sub) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + var errs []error + for _, e := range entries { + day, ok := strings.CutSuffix(e.Name(), ".enm") + if !ok || e.IsDir() || !isMinuteDay(day) || day > cutoff { + continue + } + path := filepath.Join(sub, e.Name()) + delete(s.files, path) + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +// Usage liefert den Stand der Aufzeichnung. +func (s *MinuteStore) Usage() MinuteUsage { + pl := s.plan() + up := s.driveUp() + + s.mu.Lock() + defer s.mu.Unlock() + u := MinuteUsage{ + Bytes: s.written, + Keys: len(s.keys), + RAMDays: len(s.days), + Location: pl.Location, + DriveDown: pl.Location == LocDrive && !up, + } + if !s.since.IsZero() { + u.Since = s.since.Unix() + } + days := 1.0 + if !s.since.IsZero() && s.lastNow.After(s.since) { + if d := s.lastNow.Sub(s.since).Hours() / 24; d > days { + days = d + } + } + u.WrittenPerDay = int64(float64(s.written) / days) + for _, d := range s.days { + if d.onDisk { + u.FileDays++ + } + } + return u +} + +// Reset leert das RAM und loescht die Tagesdateien des aktuellen und des vorigen Orts. +func (s *MinuteStore) Reset() error { + s.flushMu.Lock() + defer s.flushMu.Unlock() + + _, placeDir, _ := s.place(s.plan(), s.dirs(), true) + + s.mu.Lock() + dirSet := map[string]bool{} + for _, d := range []string{s.curDir, s.prevDir, placeDir} { + if d != "" { + dirSet[d] = true + } + } + s.days = map[string]*minuteDay{} + s.keys = map[string]bool{} + s.written = 0 + s.since = time.Time{} + s.lastNow = time.Time{} + s.prevDir = "" + s.files = map[string]*minuteFileState{} + s.mu.Unlock() + + var errs []error + for d := range dirSet { + sub := minuteDirOf(d) + entries, err := os.ReadDir(sub) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + errs = append(errs, err) + continue + } + for _, e := range entries { + if e.IsDir() || !strings.HasSuffix(e.Name(), ".enm") { + continue + } + if err := os.Remove(filepath.Join(sub, e.Name())); err != nil && !errors.Is(err, os.ErrNotExist) { + errs = append(errs, err) + } + } + } + return errors.Join(errs...) +} + +// Day liefert die Werte eines Tages, aus dem RAM oder sonst aus der Datei am Ort. +// Die Werte sind Kopien. Luecken sind NaN. +func (s *MinuteStore) Day(day string) (map[string]*[minutesPerDay]float32, bool) { + if !isMinuteDay(day) { + return nil, false + } + s.mu.Lock() + if d := s.days[day]; d != nil { + out := make(map[string]*[minutesPerDay]float32, len(d.values)) + for k, arr := range d.values { + c := *arr + out[k] = &c + } + s.mu.Unlock() + return out, true + } + s.mu.Unlock() + + _, dir, writable := s.place(s.plan(), s.dirs(), s.driveUp()) + if !writable { + return nil, false + } + f, err := os.Open(minuteFileName(dir, day)) + if err != nil { + return nil, false + } + defer f.Close() + _, values, err := ReadDay(f) + if err != nil { + return nil, false + } + return values, true +} + +func minuteDirOf(base string) string { + return filepath.Join(base, "learnrec", "minutes") +} + +func minuteFileName(base, day string) string { + return filepath.Join(minuteDirOf(base), day+".enm") +} + +func isMinuteDay(day string) bool { + _, err := time.Parse(minuteDayLayout, day) + return err == nil +} diff --git a/dashboard/internal/learnrec/minutestore_test.go b/dashboard/internal/learnrec/minutestore_test.go new file mode 100644 index 00000000..9b413ffb --- /dev/null +++ b/dashboard/internal/learnrec/minutestore_test.go @@ -0,0 +1,285 @@ +package learnrec + +import ( + "encoding/binary" + "io/fs" + "os" + "path/filepath" + "testing" + "time" +) + +// msTime ist eine Minute am Testtag, in UTC. +func msTime(h, m int) time.Time { + return time.Date(2026, 11, 21, h, m, 0, 0, time.UTC) +} + +// msEnv ist die veraenderbare Umgebung eines Tests: Einstellungen, Laufwerk und Stufe. +type msEnv struct { + plan MinutePlan + dirs MinuteDirs + up bool + limits Limits +} + +func newMsEnv(t *testing.T, loc MinuteLocation) *msEnv { + t.Helper() + return &msEnv{ + plan: MinutePlan{On: true, Location: loc, Days: 60}, + dirs: MinuteDirs{Drive: t.TempDir(), System: t.TempDir()}, + up: true, + limits: Limits{RAMMinuteDays: 7, RAMMinuteBytes: 16 << 20}, + } +} + +func newMsStore(env *msEnv) *MinuteStore { + return NewMinuteStore(time.UTC, + func() MinutePlan { return env.plan }, + func() MinuteDirs { return env.dirs }, + func() bool { return env.up }, + func() Limits { return env.limits }, + func(string, ...any) {}, + ) +} + +// msFrame ist ein Minutenrahmen mit einem Geraet, einem Wert und einer Bilanz. +func msFrame(at time.Time, watts float64) Frame { + return Frame{ + Minute: at, + Devices: []DeviceMinute{{ID: "dev", Power: map[string]float64{"uid1": watts}}}, + Balance: map[string]float64{"grid": 42}, + } +} + +func msPath(base, day string) string { + return filepath.Join(base, "learnrec", "minutes", day+".enm") +} + +// msBlockMinutes zaehlt alle Minuten in den Wertbloecken der Datei. Doppelte +// Minuten wuerden hier auffallen. +func msBlockMinutes(t *testing.T, path string) int { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + pos, err := checkMinuteHeader(data) + if err != nil { + t.Fatal(err) + } + total := 0 + for pos < len(data) { + body, next, ok := nextMinuteFrame(data, pos) + if !ok { + t.Fatalf("invalid block at offset %d", pos) + } + if body[0] == minuteValues { + total += int(binary.LittleEndian.Uint16(body[3:5])) + } + pos = next + } + return total +} + +func msCountFiles(t *testing.T, dir string) int { + t.Helper() + n := 0 + err := filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if !d.IsDir() { + n++ + } + return nil + }) + if err != nil { + t.Fatal(err) + } + return n +} + +func TestMinuteStoreFlushWritesRAMMinutesToSystem(t *testing.T) { + env := newMsEnv(t, LocSystem) + s := newMsStore(env) + for i := 0; i < 10; i++ { + s.ObserveMinute(msFrame(msTime(10, i), float64(i))) + } + if err := s.Flush(msTime(10, 10)); err != nil { + t.Fatalf("Flush: %v", err) + } + path := msPath(env.dirs.System, testMinuteDay) + if got := msBlockMinutes(t, path); got != 10 { + t.Fatalf("minutes in blocks = %d, want 10", got) + } + _, values := readMinuteFile(t, path) + for i := 0; i < 10; i++ { + requireMinuteValue(t, values, "e:uid1", 600+i, float32(i)) + requireMinuteValue(t, values, "b:grid", 600+i, 42) + } +} + +func TestMinuteStoreRAMLocationWritesNoFile(t *testing.T) { + env := newMsEnv(t, LocRAM) + s := newMsStore(env) + for i := 0; i < 10; i++ { + s.ObserveMinute(msFrame(msTime(10, i), float64(i))) + } + if err := s.Flush(msTime(10, 10)); err != nil { + t.Fatalf("Flush: %v", err) + } + if n := msCountFiles(t, env.dirs.System) + msCountFiles(t, env.dirs.Drive); n != 0 { + t.Fatalf("files written on ram location: %d", n) + } + values, ok := s.Day(testMinuteDay) + if !ok { + t.Fatal("Day: no RAM day") + } + requireMinuteValue(t, values, "e:uid1", 609, 9) +} + +func TestMinuteStoreDriveOutageBackfillsWithoutGapOrDuplicate(t *testing.T) { + env := newMsEnv(t, LocDrive) + env.up = false + s := newMsStore(env) + const minutes = 180 // drei Stunden + for i := 0; i < minutes; i++ { + at := msTime(0, 0).Add(time.Duration(i) * time.Minute) + s.ObserveMinute(msFrame(at, float64(i))) + if i%5 == 4 { + if err := s.Flush(at); err != nil { + t.Fatalf("Flush during outage: %v", err) + } + } + } + path := msPath(env.dirs.Drive, testMinuteDay) + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("file written while drive is down: %v", err) + } + if !s.Usage().DriveDown { + t.Fatal("Usage().DriveDown = false during outage") + } + + env.up = true + if err := s.Flush(msTime(3, 0)); err != nil { + t.Fatalf("Flush after return: %v", err) + } + if got := msBlockMinutes(t, path); got != minutes { + t.Fatalf("minutes in blocks = %d, want %d (no gap, no duplicate)", got, minutes) + } + _, values := readMinuteFile(t, path) + for i := 0; i < minutes; i++ { + requireMinuteValue(t, values, "e:uid1", i, float32(i)) + } + if s.Usage().DriveDown { + t.Fatal("Usage().DriveDown = true after return") + } +} + +func TestMinuteStoreLimitsShrinkRAMDays(t *testing.T) { + env := newMsEnv(t, LocSystem) + env.limits = Limits{RAMMinuteDays: 14, RAMMinuteBytes: 64 << 20} + s := newMsStore(env) + for d := 0; d < 6; d++ { + at := time.Date(2026, 11, 10+d, 12, 0, 0, 0, time.UTC) + s.ObserveMinute(msFrame(at, 1)) + if err := s.Flush(at); err != nil { + t.Fatalf("Flush: %v", err) + } + } + if got := s.Usage().RAMDays; got != 6 { + t.Fatalf("RAMDays on full = %d, want 6", got) + } + + env.limits = Limits{RAMMinuteDays: 3, RAMMinuteBytes: 4 << 20} + if err := s.Flush(time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)); err != nil { + t.Fatalf("Flush: %v", err) + } + if got := s.Usage().RAMDays; got != 3 { + t.Fatalf("RAMDays on eco = %d, want 3", got) + } + if got := msCountFiles(t, filepath.Join(env.dirs.System, "learnrec", "minutes")); got != 6 { + t.Fatalf("files after shrink = %d, want 6", got) + } +} + +func TestMinuteStoreDaysPrunesOldFiles(t *testing.T) { + env := newMsEnv(t, LocSystem) + env.plan.Days = 2 + s := newMsStore(env) + + old := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC) + s.ObserveMinute(msFrame(old, 1)) + if err := s.Flush(old); err != nil { + t.Fatalf("Flush old: %v", err) + } + if _, err := os.Stat(msPath(env.dirs.System, "2026-11-18")); err != nil { + t.Fatalf("old file not written: %v", err) + } + + now := time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + s.ObserveMinute(msFrame(now, 1)) + if err := s.Flush(now); err != nil { + t.Fatalf("Flush now: %v", err) + } + if _, err := os.Stat(msPath(env.dirs.System, "2026-11-18")); !os.IsNotExist(err) { + t.Fatalf("file from three days ago still there: %v", err) + } + if _, err := os.Stat(msPath(env.dirs.System, "2026-11-21")); err != nil { + t.Fatalf("current file missing: %v", err) + } +} + +func TestMinuteStoreResetClearsRAMAndFiles(t *testing.T) { + env := newMsEnv(t, LocSystem) + s := newMsStore(env) + for i := 0; i < 10; i++ { + s.ObserveMinute(msFrame(msTime(10, i), float64(i))) + } + if err := s.Flush(msTime(10, 10)); err != nil { + t.Fatalf("Flush: %v", err) + } + + // Ortswechsel auf ram: das System-Verzeichnis ist jetzt der vorige Ort. + env.plan.Location = LocRAM + s.ObserveMinute(msFrame(msTime(10, 10), 1)) + if err := s.Flush(msTime(10, 11)); err != nil { + t.Fatalf("Flush ram: %v", err) + } + + if err := s.Reset(); err != nil { + t.Fatalf("Reset: %v", err) + } + if got := s.Usage().Bytes; got != 0 { + t.Fatalf("Usage().Bytes after Reset = %d, want 0", got) + } + if n := msCountFiles(t, filepath.Join(env.dirs.System, "learnrec", "minutes")); n != 0 { + t.Fatalf("files left after Reset: %d", n) + } + if _, ok := s.Day(testMinuteDay); ok { + t.Fatal("Day still returns data after Reset") + } +} + +func TestMinuteStoreWrittenPerDayMatchesBytesOverDays(t *testing.T) { + env := newMsEnv(t, LocSystem) + s := newMsStore(env) + start := msTime(12, 0) + for i := 0; i < 10; i++ { + s.ObserveMinute(msFrame(start.Add(time.Duration(i)*time.Minute), float64(i))) + } + end := start.Add(2 * 24 * time.Hour) + if err := s.Flush(end); err != nil { + t.Fatalf("Flush: %v", err) + } + u := s.Usage() + if u.Bytes <= 0 { + t.Fatalf("Usage().Bytes = %d, want > 0", u.Bytes) + } + if want := int64(float64(u.Bytes) / 2); u.WrittenPerDay != want { + t.Fatalf("WrittenPerDay = %d, want %d (Bytes over 2 days)", u.WrittenPerDay, want) + } + if u.Since != start.Unix() { + t.Fatalf("Since = %d, want %d", u.Since, start.Unix()) + } +} From cfb599f1e2bfd835022e7928ff98dc10e36b7aa6 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:58:34 +0100 Subject: [PATCH 04/21] feat(learnrec): read ranges from the minute recording and replay them to one consumer Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/learnrec/hub.go | 117 ++++++++++++++++++ dashboard/internal/learnrec/hub_test.go | 55 +++++++++ dashboard/internal/learnrec/reader.go | 131 +++++++++++++++++++++ dashboard/internal/learnrec/reader_test.go | 67 +++++++++++ 4 files changed, 370 insertions(+) create mode 100644 dashboard/internal/learnrec/reader.go create mode 100644 dashboard/internal/learnrec/reader_test.go diff --git a/dashboard/internal/learnrec/hub.go b/dashboard/internal/learnrec/hub.go index e8099c5e..35a0c697 100644 --- a/dashboard/internal/learnrec/hub.go +++ b/dashboard/internal/learnrec/hub.go @@ -1,6 +1,7 @@ package learnrec import ( + "math" "sort" "strings" "sync" @@ -16,6 +17,13 @@ type MinuteConsumer interface { ObserveMinute(f Frame) } +// ReplayConsumer ist ein Minutenverbraucher, der die Minuten ab ReplayFrom aus +// der Aufzeichnung nachlesen kann. Eine Zeit null heisst: nichts nachlesen. +type ReplayConsumer interface { + MinuteConsumer + ReplayFrom() time.Time +} + // TickConsumer erhaelt jede Beobachtung sofort. type TickConsumer interface { ObserveTick(at time.Time, snap energy.Snapshot) @@ -44,6 +52,11 @@ type namedMinute struct { c MinuteConsumer } +type namedReplay struct { + name string + c ReplayConsumer +} + type namedTick struct { name string c TickConsumer @@ -76,6 +89,7 @@ type Hub struct { limits func() Limits logf func(string, ...any) minutes []namedMinute + replays []namedReplay ticks []namedTick savers []*namedSaver minute time.Time @@ -115,6 +129,109 @@ func (h *Hub) AddMinute(name string, c MinuteConsumer) { h.minutes = append(h.minutes, namedMinute{name: name, c: c}) } +// AddReplay meldet einen Verbraucher an, der mit Replay die Minuten nachlesen +// kann. Er erhaelt nur die Rahmen aus Replay, nicht die Live-Minuten. +func (h *Hub) AddReplay(name string, c ReplayConsumer) { + h.mu.Lock() + defer h.mu.Unlock() + h.replays = append(h.replays, namedReplay{name: name, c: c}) +} + +// Replay gibt jedem Wiederholungsverbraucher die Minuten ab seinem ReplayFrom bis +// vor die Minute von now, aus r. Pro Minute entsteht ein Rahmen mit Leistung je +// Schluessel e: und Bilanz aus b:. Ohne Aufzeichnung passiert +// nichts. Die Verbraucher laufen ausserhalb des Hub-Mutex. +func (h *Hub) Replay(r Reader, now time.Time) { + if r == nil { + return + } + h.mu.Lock() + list := append([]namedReplay(nil), h.replays...) + h.mu.Unlock() + + for _, nr := range list { + from := nr.c.ReplayFrom() + if from.IsZero() { + continue + } + h.replayOne(r, nr.c, from, now) + } +} + +// replayOne gibt einem Verbraucher seine nachgelesenen Rahmen. Jeder Rahmen hat +// je Schluessel ein Geraet, dessen ID der unique_id entspricht. +func (h *Hub) replayOne(r Reader, c MinuteConsumer, from, now time.Time) { + start := minuteStart(from, h.loc) + end := minuteStart(now, h.loc) + if !end.After(start) { + return + } + kl, ok := r.(keyLister) + if !ok { + return + } + keys := kl.Keys(start, end) + if len(keys) == 0 { + return + } + + series := map[string]Series{} + var powerKeys, balanceKeys []string + for _, key := range keys { + switch { + case strings.HasPrefix(key, "e:"): + powerKeys = append(powerKeys, key) + case strings.HasPrefix(key, "b:"): + balanceKeys = append(balanceKeys, key) + default: + continue + } + series[key] = r.Range(key, start, end) + } + + n := 0 + for _, sr := range series { + if len(sr.Values) > n { + n = len(sr.Values) + } + } + for i := 0; i < n; i++ { + f := Frame{Minute: start.Add(time.Duration(i) * time.Minute)} + for _, key := range powerKeys { + v, ok := valueAt(series[key], i) + if !ok { + continue + } + uid := strings.TrimPrefix(key, "e:") + f.Devices = append(f.Devices, DeviceMinute{ + ID: uid, + Power: map[string]float64{uid: v}, + Switch: map[string]bool{}, + Reachable: true, + }) + } + for _, key := range balanceKeys { + v, ok := valueAt(series[key], i) + if !ok { + continue + } + if f.Balance == nil { + f.Balance = map[string]float64{} + } + f.Balance[strings.TrimPrefix(key, "b:")] = v + } + c.ObserveMinute(f) + } +} + +// valueAt liefert den Wert der Minute i, ohne Luecke. +func valueAt(sr Series, i int) (float64, bool) { + if i >= len(sr.Values) || math.IsNaN(float64(sr.Values[i])) { + return 0, false + } + return float64(sr.Values[i]), true +} + // AddTick meldet einen Taktverbraucher an. func (h *Hub) AddTick(name string, c TickConsumer) { h.mu.Lock() diff --git a/dashboard/internal/learnrec/hub_test.go b/dashboard/internal/learnrec/hub_test.go index 3ee73b30..903a1bc3 100644 --- a/dashboard/internal/learnrec/hub_test.go +++ b/dashboard/internal/learnrec/hub_test.go @@ -324,3 +324,58 @@ func TestOutdoorNoChoiceIsNil(t *testing.T) { t.Fatalf("frames = %+v, want one frame without OutdoorC", mc.frames) } } + +// replayRec ist ein Wiederholungsverbraucher mit fester Startzeit. +type replayRec struct { + fakeMinute + from time.Time +} + +func (r *replayRec) ReplayFrom() time.Time { return r.from } + +func TestHubReplayDeliversFramesToOneConsumer(t *testing.T) { + env := newMsEnv(t, LocRAM) + s := newMsStore(env) + now := time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC) + start := now.Add(-40 * time.Minute) + for i := 0; i < 40; i++ { + s.ObserveMinute(msFrame(start.Add(time.Duration(i)*time.Minute), 100)) + } + + h := newTestHub(t, Limits{MaxDevices: 128}) + other := &fakeMinute{} + h.AddMinute("live", other) + rec := &replayRec{from: start} + h.AddReplay("chain", rec) + + h.Replay(s, now) + + if len(rec.frames) != 40 { + t.Fatalf("replay frames = %d, want 40", len(rec.frames)) + } + if !rec.frames[0].Minute.Equal(start) { + t.Errorf("first frame minute = %v, want %v", rec.frames[0].Minute, start) + } + if got := rec.frames[0].Devices[0].Power["uid1"]; got != 100 { + t.Errorf("power = %v, want 100", got) + } + if !rec.frames[0].Devices[0].Reachable { + t.Errorf("device with a value must be reachable") + } + if got := rec.frames[0].Balance["grid"]; got != 42 { + t.Errorf("balance grid = %v, want 42", got) + } + if len(other.frames) != 0 { + t.Errorf("replay reached a live consumer: %d frames", len(other.frames)) + } +} + +func TestHubReplayWithoutRecordingDoesNothing(t *testing.T) { + h := newTestHub(t, Limits{MaxDevices: 128}) + rec := &replayRec{} + h.AddReplay("chain", rec) + h.Replay(newMsStore(newMsEnv(t, LocRAM)), time.Date(2026, 11, 21, 10, 0, 0, 0, time.UTC)) + if len(rec.frames) != 0 { + t.Fatalf("zero ReplayFrom: frames = %d, want 0", len(rec.frames)) + } +} diff --git a/dashboard/internal/learnrec/reader.go b/dashboard/internal/learnrec/reader.go new file mode 100644 index 00000000..9e55333a --- /dev/null +++ b/dashboard/internal/learnrec/reader.go @@ -0,0 +1,131 @@ +package learnrec + +import ( + "math" + "sort" + "time" +) + +// Series ist eine Reihe Minutenwerte ab From. Je Minute ein Wert, Luecken sind NaN. +type Series struct { + From time.Time + Values []float32 +} + +// Reader liest die Minutenaufzeichnung. Range liefert die Werte eines Schluessels +// im Zeitraum [from, to). Coverage zaehlt die Tage im Zeitraum, die zu mindestens +// 80 % Minuten mit Werten in b:load_total haben. +type Reader interface { + Range(key string, from, to time.Time) Series + Coverage(from, to time.Time) (days int) +} + +var _ Reader = (*MinuteStore)(nil) + +// keyLister ist optional. Ein Reader, der sie hat, nennt die Schluessel mit Werten +// im Zeitraum, damit das Nachlesen sie findet. +type keyLister interface { + Keys(from, to time.Time) []string +} + +var _ keyLister = (*MinuteStore)(nil) + +// coverageMinMinutes ist die Zahl der Minuten, ab der ein Tag als abgedeckt gilt. +const coverageMinMinutes = minutesPerDay * 80 / 100 + +// coverageKey ist der Schluessel, an dem Coverage einen Tag misst. +const coverageKey = "b:load_total" + +// minuteStart liefert den Beginn der lokalen Minute von t. +func minuteStart(t time.Time, loc *time.Location) time.Time { + l := t.In(loc) + return time.Date(l.Year(), l.Month(), l.Day(), l.Hour(), l.Minute(), 0, 0, loc) +} + +// dayStrings liefert die lokalen Tage, die den Zeitraum [from, to) beruehren. +func dayStrings(from, to time.Time, loc *time.Location) []string { + l := from.In(loc) + day := time.Date(l.Year(), l.Month(), l.Day(), 0, 0, 0, 0, loc) + var out []string + for day.Before(to) { + out = append(out, day.Format(minuteDayLayout)) + day = day.AddDate(0, 0, 1) + } + return out +} + +// Range liefert die Minutenwerte des Schluessels key ab der Minute von from bis +// vor to. Minuten ohne Wert sind NaN. +func (s *MinuteStore) Range(key string, from, to time.Time) Series { + start := minuteStart(from, s.loc) + n := 0 + if to.After(start) { + n = int((to.Sub(start) + time.Minute - 1) / time.Minute) + } + out := Series{From: start, Values: make([]float32, n)} + + cache := map[string]*[minutesPerDay]float32{} + loaded := map[string]bool{} + for i := range out.Values { + t := start.Add(time.Duration(i) * time.Minute).In(s.loc) + day := t.Format(minuteDayLayout) + if !loaded[day] { + loaded[day] = true + vals, _ := s.Day(day) + cache[day] = vals[key] + } + arr := cache[day] + if arr == nil { + out.Values[i] = minuteGap + continue + } + out.Values[i] = arr[t.Hour()*60+t.Minute()] + } + return out +} + +// Keys nennt die Schluessel, zu denen im Zeitraum [from, to) Werte liegen, sortiert. +func (s *MinuteStore) Keys(from, to time.Time) []string { + set := map[string]bool{} + for _, day := range dayStrings(from, to, s.loc) { + vals, ok := s.Day(day) + if !ok { + continue + } + for key := range vals { + set[key] = true + } + } + out := make([]string, 0, len(set)) + for key := range set { + out = append(out, key) + } + sort.Strings(out) + return out +} + +// Coverage zaehlt die Tage im Zeitraum [from, to), an denen mindestens 80 % der +// Minuten einen Wert in b:load_total haben. +func (s *MinuteStore) Coverage(from, to time.Time) int { + n := 0 + for _, day := range dayStrings(from, to, s.loc) { + vals, ok := s.Day(day) + if !ok { + continue + } + arr := vals[coverageKey] + if arr == nil { + continue + } + have := 0 + for _, v := range arr { + if !math.IsNaN(float64(v)) { + have++ + } + } + if have >= coverageMinMinutes { + n++ + } + } + return n +} diff --git a/dashboard/internal/learnrec/reader_test.go b/dashboard/internal/learnrec/reader_test.go new file mode 100644 index 00000000..04078875 --- /dev/null +++ b/dashboard/internal/learnrec/reader_test.go @@ -0,0 +1,67 @@ +package learnrec + +import ( + "math" + "testing" + "time" +) + +func rdFrame(at time.Time, watts float64) Frame { + return Frame{ + Minute: at, + Devices: []DeviceMinute{{ID: "dev", Power: map[string]float64{"uid1": watts}}}, + } +} + +func TestMinuteStoreRangeAcrossMidnight(t *testing.T) { + env := newMsEnv(t, LocRAM) + s := newMsStore(env) + base := time.Date(2026, 11, 20, 23, 58, 0, 0, time.UTC) + for i, w := range []float64{1, 2, 3, 4} { + s.ObserveMinute(rdFrame(base.Add(time.Duration(i)*time.Minute), w)) + } + + got := s.Range("e:uid1", base, base.Add(4*time.Minute)) + if !got.From.Equal(base) { + t.Fatalf("From = %v, want %v", got.From, base) + } + want := []float32{1, 2, 3, 4} + if len(got.Values) != len(want) { + t.Fatalf("len = %d, want %d", len(got.Values), len(want)) + } + for i := range want { + if got.Values[i] != want[i] { + t.Errorf("Values[%d] = %v, want %v", i, got.Values[i], want[i]) + } + } + + gap := s.Range("e:uid1", base.Add(4*time.Minute), base.Add(6*time.Minute)) + if len(gap.Values) != 2 || !math.IsNaN(float64(gap.Values[0])) { + t.Errorf("missing minutes must be NaN, got %v", gap.Values) + } +} + +func TestMinuteStoreCoverageNeedsEightyPercentOfDay(t *testing.T) { + env := newMsEnv(t, LocRAM) + s := newMsStore(env) + start := time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC) + for m := 0; m < 720; m++ { + s.ObserveMinute(Frame{ + Minute: start.Add(time.Duration(m) * time.Minute), + Balance: map[string]float64{"load_total": 10}, + }) + } + if got := s.Coverage(start, start.Add(24*time.Hour)); got != 0 { + t.Fatalf("half a day: Coverage = %d, want 0", got) + } + + for m := 720; m < 1440; m++ { + s.ObserveMinute(Frame{ + Minute: start.Add(time.Duration(m) * time.Minute), + Balance: map[string]float64{"load_total": 10}, + }) + } + if got := s.Coverage(start, start.Add(24*time.Hour)); got != 1 { + t.Fatalf("full day: Coverage = %d, want 1", got) + } +} From 9ca18437c74462032c278d0e73031317339099ad Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:00:55 +0100 Subject: [PATCH 05/21] feat(learnrec): let chain suggestions catch up from the recording The chain suggestion collector remembers the last counted minute, saves it with the day sums and reports the minute after it through ReplayFrom. Replayed frames do not change the device owner of an entity, since the recording has no device IDs. main.go registers the collector for replay and calls learnHub.Replay once before the energy loop starts. The reader is still nil until the MinuteStore is wired in, so Replay does nothing for now. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 9 ++ dashboard/internal/chainsuggest/collector.go | 33 +++++- .../internal/chainsuggest/replay_test.go | 102 ++++++++++++++++++ dashboard/internal/chainsuggest/store.go | 16 +++ dashboard/internal/learnrec/frame.go | 3 + dashboard/internal/learnrec/hub.go | 2 +- dashboard/internal/learnrec/hub_test.go | 3 + 7 files changed, 163 insertions(+), 5 deletions(-) create mode 100644 dashboard/internal/chainsuggest/replay_test.go diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index c048abf0..f8ca7525 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -472,6 +472,7 @@ func main() { return "" }) learnHub.AddMinute("chainsuggest", chainSuggest) + learnHub.AddReplay("chainsuggest", chainSuggest) learnHub.AddTick("chainwatch", learnrec.TickFunc(chainMonitor.Observe)) learnHub.AddTick("autolearn", learnrec.TickFunc(func(at time.Time, snap energy.Snapshot) { automationChecker.ObserveTick(at, automationState(), balanceRuleValues(snap.Balance), automationEntityValue) @@ -1466,6 +1467,14 @@ func main() { ReadHeaderTimeout: 5 * time.Second, } + // Nachlesen der Minuten nach dem Neustart, einmal und vor der ersten Live-Minute. + // Der MinuteStore als Reader kommt erst mit der Aufzeichnung (Task 7). Bis dahin + // ist minuteReader nil, und Replay passiert nichts. + var minuteReader learnrec.Reader + if minuteReader != nil { + learnHub.Replay(minuteReader, time.Now()) + } + go func() { // Eigene Monotonuhr: time.Since(monoStart) laeuft auch dann // gleichmaessig weiter, wenn NTP die Wanduhr stellt. Daran erkennt diff --git a/dashboard/internal/chainsuggest/collector.go b/dashboard/internal/chainsuggest/collector.go index 20c9e0fa..9cb9d62f 100644 --- a/dashboard/internal/chainsuggest/collector.go +++ b/dashboard/internal/chainsuggest/collector.go @@ -92,6 +92,9 @@ type Collector struct { owner map[string]string sums map[pairDay]*sums lastDay int + // lastMinute ist die letzte gezaehlte Minute, live oder nachgelesen. Ab der + // Minute danach liest Replay nach. Die Nullzeit heisst: noch nichts gezaehlt. + lastMinute time.Time // dismissed haelt verworfene Paare. dismissed map[pairKey]bool @@ -161,6 +164,20 @@ func (c *Collector) LearnedSpan() (since int64, entities int) { return int64(oldest) * 86400, len(seen) } +var _ learnrec.ReplayConsumer = (*Collector)(nil) + +// ReplayFrom liefert die erste Minute, die noch nicht gezaehlt ist. Ohne gezaehlte +// Minute, etwa bei einer Datei aus einer Version ohne diesen Stand, liefert sie +// die Nullzeit: dann wird nichts nachgelesen, damit nichts doppelt zaehlt. +func (c *Collector) ReplayFrom() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + if c.lastMinute.IsZero() { + return time.Time{} + } + return c.lastMinute.Add(time.Minute) +} + // ObserveMinute nimmt den abgeschlossenen Minutenrahmen des Hubs entgegen und // addiert die aktiven Paare dieser Minute zu den Tagessummen. func (c *Collector) ObserveMinute(f learnrec.Frame) { @@ -213,14 +230,22 @@ func (c *Collector) participants(f learnrec.Frame) map[string]participant { // addMinuteLocked addiert die aktiven Paare des Rahmens zu den Tagessummen. // Teilnehmer werden dabei als devices und owner vermerkt. func (c *Collector) addMinuteLocked(f learnrec.Frame) { + if !f.Minute.Equal(c.lastMinute) { + c.lastMinute = f.Minute + c.dirty = true + } parts := c.participants(f) c.devices = make(map[string]string, len(parts)) ids := make([]string, 0, len(parts)) for id, p := range parts { - c.devices[id] = p.device - if c.owner[id] != p.device { - c.owner[id] = p.device - c.dirty = true + // Nachgelesene Rahmen nennen die Entitaet als Geraet. Das wuerde die + // Geraetezuordnung der Live-Minuten ueberschreiben. + if !f.Replayed { + c.devices[id] = p.device + if c.owner[id] != p.device { + c.owner[id] = p.device + c.dirty = true + } } ids = append(ids, id) } diff --git a/dashboard/internal/chainsuggest/replay_test.go b/dashboard/internal/chainsuggest/replay_test.go new file mode 100644 index 00000000..fce134d6 --- /dev/null +++ b/dashboard/internal/chainsuggest/replay_test.go @@ -0,0 +1,102 @@ +package chainsuggest + +import ( + "path/filepath" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" +) + +// replayFrame macht den Rahmen einer nachgelesenen Minute wie der Hub ihn baut. +// Der Hub nennt in einem nachgelesenen Rahmen jede Entitaet ein Geraet mit ID = unique_id. +func replayFrame(minute time.Time, values map[string]float64) learnrec.Frame { + f := learnrec.Frame{Minute: minute, Replayed: true} + for id, w := range values { + f.Devices = append(f.Devices, learnrec.DeviceMinute{ + ID: id, + Power: map[string]float64{id: w}, + Reachable: true, + }) + } + return f +} + +func TestReplayFromIsMinuteAfterLastCounted(t *testing.T) { + start := time.Date(2026, 11, 2, 12, 0, 0, 0, time.UTC) + c := NewCollector(DefaultThresholds, time.UTC) + feed(c, start, 5, func(int) map[string]float64 { return map[string]float64{"a": 100, "b": 90} }) + + want := start.Add(4 * time.Minute).Add(time.Minute) + if got := c.ReplayFrom(); !got.Equal(want) { + t.Errorf("ReplayFrom = %v, want %v", got, want) + } +} + +func TestReplayFromZeroWithoutHistory(t *testing.T) { + c := NewCollector(DefaultThresholds, time.UTC) + if got := c.ReplayFrom(); !got.IsZero() { + t.Errorf("ReplayFrom = %v, want zero time", got) + } +} + +func TestReplaySurvivesRestartWithoutDoubleCount(t *testing.T) { + start := time.Date(2026, 11, 2, 12, 0, 0, 0, time.UTC) + path := filepath.Join(t.TempDir(), "suggest.json") + + first := Load(path, DefaultThresholds, time.UTC, noLog) + first.SetPersistence(path, noLog) + feed(first, start, 5, func(int) map[string]float64 { return map[string]float64{"a": 100, "b": 90} }) + if err := first.Save(); err != nil { + t.Fatal(err) + } + + second := Load(path, DefaultThresholds, time.UTC, noLog) + from := second.ReplayFrom() + if !from.Equal(start.Add(5 * time.Minute)) { + t.Fatalf("ReplayFrom after restart = %v, want %v", from, start.Add(5*time.Minute)) + } + for m := 5; m < 10; m++ { + second.ObserveMinute(replayFrame(start.Add(time.Duration(m)*time.Minute), map[string]float64{"a": 100, "b": 90})) + } + + s := second.sums[pairDay{a: "a", b: "b", day: dayIndex(start)}] + if s == nil || s.n != 10 { + t.Fatalf("active minutes after replay = %+v, want 10", s) + } +} + +func TestReplayKeepsDeviceOwner(t *testing.T) { + start := time.Date(2026, 11, 2, 12, 0, 0, 0, time.UTC) + c := NewCollector(DefaultThresholds, time.UTC) + feed(c, start, 1, func(int) map[string]float64 { return map[string]float64{"a": 100, "b": 90} }) + if got := c.owner["a"]; got != "dev-a" { + t.Fatalf("owner of a = %q, want dev-a", got) + } + + c.ObserveMinute(replayFrame(start.Add(time.Minute), map[string]float64{"a": 100, "b": 90})) + + if got := c.owner["a"]; got != "dev-a" { + t.Errorf("replay changed owner of a to %q, want dev-a", got) + } + if got := c.owner["b"]; got != "dev-b" { + t.Errorf("replay changed owner of b to %q, want dev-b", got) + } +} + +func TestReplayPersistsLastMinute(t *testing.T) { + start := time.Date(2026, 11, 2, 12, 0, 0, 0, time.UTC) + path := filepath.Join(t.TempDir(), "suggest.json") + c := Load(path, DefaultThresholds, time.UTC, noLog) + c.SetPersistence(path, noLog) + // Nur leere Minuten: die Summen bleiben leer, die Minute muss trotzdem gespeichert werden. + c.ObserveMinute(learnrec.Frame{Minute: start}) + if err := c.Save(); err != nil { + t.Fatal(err) + } + + reloaded := Load(path, DefaultThresholds, time.UTC, noLog) + if got := reloaded.ReplayFrom(); !got.Equal(start.Add(time.Minute)) { + t.Errorf("ReplayFrom after reload = %v, want %v", got, start.Add(time.Minute)) + } +} diff --git a/dashboard/internal/chainsuggest/store.go b/dashboard/internal/chainsuggest/store.go index 8fdaa49a..c92ce52a 100644 --- a/dashboard/internal/chainsuggest/store.go +++ b/dashboard/internal/chainsuggest/store.go @@ -23,6 +23,9 @@ type suggestFile struct { Days map[string][]suggestEntry `json:"days"` Devices map[string]string `json:"devices"` Dismissed [][2]string `json:"dismissed"` + // LastMinute ist die letzte gezaehlte Minute im RFC3339-Format. Fehlt sie, + // liest Replay nichts nach. + LastMinute string `json:"last_minute,omitempty"` } // suggestEntry ist ein Paar an einem Tag: s = [n, Σa, Σb, Σa², Σb², Σab, Σ|a−b|]. @@ -85,6 +88,15 @@ func (c *Collector) restore(data []byte) error { } } + var last time.Time + if f.LastMinute != "" { + t, err := time.Parse(time.RFC3339, f.LastMinute) + if err != nil { + return fmt.Errorf("last minute %q: %w", f.LastMinute, err) + } + last = t + } + dismissed := map[pairKey]bool{} for _, d := range f.Dismissed { if d[0] == "" || d[1] == "" || d[0] == d[1] { @@ -104,6 +116,7 @@ func (c *Collector) restore(data []byte) error { c.sums = totals c.dismissed = dismissed c.owner = owner + c.lastMinute = last return nil } @@ -212,6 +225,9 @@ func (c *Collector) saveLocked() error { for id, dev := range c.owner { f.Devices[id] = dev } + if !c.lastMinute.IsZero() { + f.LastMinute = c.lastMinute.UTC().Format(time.RFC3339) + } for key := range c.dismissed { f.Dismissed = append(f.Dismissed, [2]string{key.a, key.b}) } diff --git a/dashboard/internal/learnrec/frame.go b/dashboard/internal/learnrec/frame.go index 25da90f2..5ac0f791 100644 --- a/dashboard/internal/learnrec/frame.go +++ b/dashboard/internal/learnrec/frame.go @@ -18,6 +18,9 @@ type Frame struct { // OutdoorC ist das Minutenmittel der Aussentemperatur in Grad Celsius. // nil, wenn keine Entitaet gewaehlt ist oder sie keinen Wert liefert. OutdoorC *float64 + // Replayed ist gesetzt, wenn der Rahmen aus der Aufzeichnung kommt (Hub.Replay). + // Dort ist jede Entitaet ein eigenes Geraet mit ID = unique_id. + Replayed bool } // DeviceMinute enthaelt die Minutenwerte eines Geraets. diff --git a/dashboard/internal/learnrec/hub.go b/dashboard/internal/learnrec/hub.go index 35a0c697..aa998874 100644 --- a/dashboard/internal/learnrec/hub.go +++ b/dashboard/internal/learnrec/hub.go @@ -196,7 +196,7 @@ func (h *Hub) replayOne(r Reader, c MinuteConsumer, from, now time.Time) { } } for i := 0; i < n; i++ { - f := Frame{Minute: start.Add(time.Duration(i) * time.Minute)} + f := Frame{Minute: start.Add(time.Duration(i) * time.Minute), Replayed: true} for _, key := range powerKeys { v, ok := valueAt(series[key], i) if !ok { diff --git a/dashboard/internal/learnrec/hub_test.go b/dashboard/internal/learnrec/hub_test.go index 903a1bc3..b5ed55c2 100644 --- a/dashboard/internal/learnrec/hub_test.go +++ b/dashboard/internal/learnrec/hub_test.go @@ -362,6 +362,9 @@ func TestHubReplayDeliversFramesToOneConsumer(t *testing.T) { if !rec.frames[0].Devices[0].Reachable { t.Errorf("device with a value must be reachable") } + if !rec.frames[0].Replayed { + t.Errorf("replay frame must be marked Replayed") + } if got := rec.frames[0].Balance["grid"]; got != 42 { t.Errorf("balance grid = %v, want 42", got) } From b82ff94b01029a40f19747679a22badba59340fa Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:02:31 +0100 Subject: [PATCH 06/21] feat(automation): publish every regulator step of a scenario Each computed regulator step goes to /scenario//step, not retained, QoS 0, with err, net, from, to and why (sent, deadband, unchanged or limit). Steps are reported even when no setpoint is sent, and a blocked publish reports why sent with to equal from. The step is not written to the scenario state or the history. Co-Authored-By: Claude Sonnet 5.5 --- services/automation/automation_mqtt.py | 33 +++++++++- services/automation/regulator.py | 3 +- services/automation/tests/test_regulator.py | 10 +++ services/automation/tests/test_scenarios.py | 72 ++++++++++++++++++++- 4 files changed, 113 insertions(+), 5 deletions(-) diff --git a/services/automation/automation_mqtt.py b/services/automation/automation_mqtt.py index fff9e598..cbc32eb7 100644 --- a/services/automation/automation_mqtt.py +++ b/services/automation/automation_mqtt.py @@ -1407,6 +1407,10 @@ class ScenarioRuntime: _SCENARIO_ACTIVE_PHASES = ("active", "fallback") +def _one_decimal(value) -> Optional[float]: + return None if value is None else round(float(value), 1) + + def _finite_float(value) -> Optional[float]: if value is None or isinstance(value, bool): return None @@ -1440,11 +1444,13 @@ class ScenarioEngine: """Zustandsmaschine fuer Szenarien (idle, active, fallback, disabled). Der Zustand lebt nur im RAM, wie bei Engine.""" - def __init__(self, executor: ActionExecutor, *, started_at: float, event_sink, history_sink=None): + def __init__(self, executor: ActionExecutor, *, started_at: float, event_sink, history_sink=None, + step_sink=None): self.executor = executor self.started_at = started_at self.event_sink = event_sink self.history_sink = history_sink + self.step_sink = step_sink self._runtime: dict[str, ScenarioRuntime] = {} def tick(self, doc: RulesDocument, *, balance: Optional[dict], balance_age: Optional[float], @@ -1624,12 +1630,15 @@ def _regulate(self, sid: str, scenario: dict, rt: ScenarioRuntime, *, now_ts: fl chain_id = regulator_def["efficiency"]["chain_id"] rt.efficiency = ({"chain_id": chain_id, "from_w": best[0], "to_w": best[1]} if best is not None else {"chain_id": chain_id, "reason": best_reason}) + previous = rt.last_value step = regulator.compute_step(regulator_def, net=net, base=base, last_value=rt.last_value, best=best) rt.net = net rt.error = step.error rt.base = base rt.reason = step.reason if step.payload is None: + to_value = previous if step.reason == "unchanged" else None + self._emit_step(sid, now_ts, step, net, previous, to_value=to_value, why=step.reason) return outcomes = self._run_actions([{ @@ -1639,13 +1648,25 @@ def _regulate(self, sid: str, scenario: dict, rt: ScenarioRuntime, *, now_ts: fl outcome = outcomes[0] if outcome.get("blocked"): rt.reason = outcome.get("reason") + self._emit_step(sid, now_ts, step, net, previous, to_value=previous, why="sent") return rt.last_value = step.value rt.last_sent_at = now_ts + self._emit_step(sid, now_ts, step, net, previous, to_value=step.value, why=step.reason or "sent") deadband = regulator_def["deadband_w"] if deadband > 0 and abs(step.error) > 5 * deadband: self._record(sid, "jump", outcomes) + def _emit_step(self, sid: str, now_ts: float, step, net: float, previous: Optional[float], *, + to_value: Optional[float], why: str) -> None: + """Meldet jeden berechneten Reglerschritt auf dem Schritt-Topic. Der Zustand + und die Historie bleiben davon unberuehrt.""" + if self.step_sink is None: + return + self.step_sink(sid, {"at": _one_decimal(now_ts), "err": _one_decimal(step.error), + "net": _one_decimal(net), "from": _one_decimal(previous), + "to": _one_decimal(to_value), "why": why}) + def _run_actions(self, actions: list, *, balance, topic_values) -> list[dict]: outcomes = [] for action in actions: @@ -1850,6 +1871,10 @@ def scenario_state_topic(base_topic: str, scenario_id: str) -> str: return f"{base_topic}/scenario/{scenario_id}/state" +def scenario_step_topic(base_topic: str, scenario_id: str) -> str: + return f"{base_topic}/scenario/{scenario_id}/step" + + def scenario_discovery(device_id: str, base_topic: str, device_block: dict, scenario: dict) -> list: """Phase ist immer da, der Stellwert nur bei Szenarien mit Regler.""" sid = scenario["id"] @@ -1909,7 +1934,7 @@ def __init__(self, service_config, mqtt_config, config_store, app_config=None, s self.engine = Engine(self.executor, started_at=started_at, event_sink=self._on_event, history_sink=self._on_fired) self.scenario_engine = ScenarioEngine(self.executor, started_at=started_at, event_sink=self._on_event, - history_sink=self._on_fired) + history_sink=self._on_fired, step_sink=self._on_scenario_step) self.scenario_publishers: dict[str, ChangeGatedPublisher] = {} self._scenario_discovery: set[tuple[str, str]] = set() self._scenario_ids: set[str] = set() @@ -2001,6 +2026,10 @@ def _publish_action(self, topic: str, payload: str, retain: bool) -> None: def _publish_raw_json(self, topic: str, payload: str) -> None: self.client.publish(topic, payload, qos=0, retain=True) + def _on_scenario_step(self, sid: str, record: dict) -> None: + self.client.publish(scenario_step_topic(self.base_topic, sid), + json.dumps(record, separators=(",", ":")), qos=0, retain=False) + def _on_event(self, message: str) -> None: self.events.push(message, at=time.time()) diff --git a/services/automation/regulator.py b/services/automation/regulator.py index 925ecab7..58001caa 100644 --- a/services/automation/regulator.py +++ b/services/automation/regulator.py @@ -71,6 +71,7 @@ def compute_step(regulator: dict, *, net: float, base: float, last_value: Option if max_change is not None and last_value is not None: value = min(max(value, last_value - max_change), last_value + max_change) out = regulator["output"] + clamped = value < out["min"] or value > out["max"] value, payload = quantize( value, step=out.get("step"), @@ -80,4 +81,4 @@ def compute_step(regulator: dict, *, net: float, base: float, last_value: Option ) if last_value is not None and value == last_value: return RegulatorStep(error, None, None, "unchanged") - return RegulatorStep(error, value, payload, None) + return RegulatorStep(error, value, payload, "limit" if clamped else None) diff --git a/services/automation/tests/test_regulator.py b/services/automation/tests/test_regulator.py index 6b4f894e..fc16d386 100644 --- a/services/automation/tests/test_regulator.py +++ b/services/automation/tests/test_regulator.py @@ -82,3 +82,13 @@ def test_compute_step_below_the_range_falls_back_to_the_output_minimum(): def test_compute_step_without_range_is_unchanged(): args = dict(net=-470, base=800, last_value=800) assert regulator.compute_step(reg(), **args) == regulator.compute_step(reg(), **args, best=None) + + +def test_clamped_value_reports_limit_reason(): + step = regulator.compute_step(reg(), net=5000, base=800, last_value=None) + assert (step.payload, step.reason) == ("800", "limit") + + +def test_value_inside_the_range_has_no_reason(): + step = regulator.compute_step(reg(), net=-470, base=800, last_value=None) + assert (step.payload, step.reason) == ("400", None) diff --git a/services/automation/tests/test_scenarios.py b/services/automation/tests/test_scenarios.py index b15b135e..77523543 100644 --- a/services/automation/tests/test_scenarios.py +++ b/services/automation/tests/test_scenarios.py @@ -197,7 +197,7 @@ def normalized(raw): return result -def scenario_engine_with(scenarios, settings=None, started_at=0.0, history_sink=None): +def scenario_engine_with(scenarios, settings=None, started_at=0.0, history_sink=None, step_sink=None): doc = automation.RulesDocument(version=1, settings=settings or automation.Settings(settling_seconds=0), rules=[], scenarios=scenarios) published = [] @@ -205,7 +205,7 @@ def scenario_engine_with(scenarios, settings=None, started_at=0.0, history_sink= executor = automation.ActionExecutor(publish_fn=lambda t, p, r: published.append((t, p, r)), publish_allowed_prefixes=["werkstatt/"]) engine = automation.ScenarioEngine(executor, started_at=started_at, event_sink=events.append, - history_sink=history_sink) + history_sink=history_sink, step_sink=step_sink) return doc, engine, published, events @@ -1009,3 +1009,71 @@ def test_required_topics_includes_the_learned_topics_of_scenarios(): service = automation.AutomationService.__new__(automation.AutomationService) service.test_command_topic = "outstation/automation/test/set" assert "outstation/energy_node/learned/site/house_state" in service.required_topics(doc) + + +def step_recorder(): + steps = [] + return steps, lambda sid, record: steps.append((sid, record)) + + +def test_step_topic_is_scenario_step(): + assert automation.scenario_step_topic("werkstatt/automation", "nulleinspeisung") == \ + "werkstatt/automation/scenario/nulleinspeisung/step" + + +def test_every_regulator_step_is_reported_with_its_reason(): + steps, sink = step_recorder() + doc, engine, published, _ = scenario_engine_with([regulate_scenario()], settings=regulator_settings(), + step_sink=sink) + regulate_tick(engine, doc, 1000, grid_export=470) # 800 -> 400, sent + regulate_tick(engine, doc, 1010, grid_export=470) # 400 again, unchanged + regulate_tick(engine, doc, 1020, grid_import=30, grid_export=0) # net 30 inside the deadband + assert [record["why"] for _sid, record in steps] == ["sent", "unchanged", "deadband"] + assert payloads(published) == ["400"] + first = steps[0][1] + assert first == {"at": 1000.0, "err": -500.0, "net": -470.0, "from": None, "to": 400.0, "why": "sent"} + assert steps[1][1]["from"] == 400.0 and steps[1][1]["to"] == 400.0 + assert steps[2][1]["to"] is None + + +def test_clamped_setpoint_reports_limit(): + steps, sink = step_recorder() + doc, engine, published, _ = scenario_engine_with([regulate_scenario()], settings=regulator_settings(), + step_sink=sink) + regulate_tick(engine, doc, 1000, grid_import=5000, grid_export=0) + assert payloads(published) == ["800"] + assert steps[0][1]["why"] == "limit" + assert steps[0][1]["to"] == 800.0 + + +def test_blocked_publish_reports_sent_without_movement(): + steps, sink = step_recorder() + doc, engine, published, _ = scenario_engine_with([regulate_scenario()], settings=regulator_settings(), + step_sink=sink) + engine.executor.publish_allowed_prefixes = ["andere/"] + regulate_tick(engine, doc, 1000) + assert published == [] + record = steps[0][1] + assert record["why"] == "sent" + assert record["to"] == record["from"] + + +def test_step_payload_stays_under_120_bytes(): + steps, sink = step_recorder() + doc, engine, _, _ = scenario_engine_with([regulate_scenario()], settings=regulator_settings(), + step_sink=sink) + regulate_tick(engine, doc, 1000, grid_import=99999, grid_export=0) + regulate_tick(engine, doc, 1010, grid_export=470) + for _sid, record in steps: + assert len(json.dumps(record, separators=(",", ":")).encode()) < 120 + + +def test_service_publishes_steps_on_the_step_topic_not_retained(): + service = scenario_service([regulate_scenario()]) + service.topic_values["werkstatt/bkw/state"] = '{"power": 800}' + fresh_balance(service, grid_export=470) + service.poll_core() + topic, payload, retain = next(p for p in service.client.published if p[0].endswith("/scenario/nulleinspeisung/step")) + assert topic.endswith("/scenario/nulleinspeisung/step") + assert retain is False + assert json.loads(payload)["why"] == "sent" From cb5a5072a02af5e78f4c1ea47f807cde3d98b891 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:04:59 +0100 Subject: [PATCH 07/21] feat(autolearn): keep the regulator steps of each scenario StepLog holds the regulator steps of each scenario in RAM for the days the learning profile keeps, validates the payloads and derives the day figures (changes, sign flips, out-of-deadband energy). Day files gain an optional steps map, old files load unchanged. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/daystore.go | 5 +- dashboard/internal/autolearn/steplog.go | 291 +++++++++++++++++++ dashboard/internal/autolearn/steplog_test.go | 223 ++++++++++++++ 3 files changed, 518 insertions(+), 1 deletion(-) create mode 100644 dashboard/internal/autolearn/steplog.go create mode 100644 dashboard/internal/autolearn/steplog_test.go diff --git a/dashboard/internal/autolearn/daystore.go b/dashboard/internal/autolearn/daystore.go index 92ff693a..fb870838 100644 --- a/dashboard/internal/autolearn/daystore.go +++ b/dashboard/internal/autolearn/daystore.go @@ -39,6 +39,8 @@ type DayFile struct { Events []EventRec `json:"events"` Actions []ActionRec `json:"actions"` Cycles []CycleRec `json:"cycles,omitempty"` + // Steps sind die Reglerschritte je Szenario. Alte Dateien haben das Feld nicht. + Steps map[string]*StepDay `json:"steps,omitempty"` // Fake markiert die Demo-Profile. Die Konsole der Demo entfernt nur solche // Dateien. Echte Tage tragen das Feld nicht. Fake bool `json:"fake,omitempty"` @@ -750,7 +752,8 @@ func (s *DayStore) writeLocked() error { // gerundet. func (s *DayStore) snapshotLocked() DayFile { out := DayFile{V: dayFileVersion, Day: s.day, Devices: make(map[string]*DeviceDay, len(s.file.Devices)), - Site: s.file.Site, Events: s.file.Events, Actions: s.file.Actions, Cycles: s.file.Cycles} + Site: s.file.Site, Events: s.file.Events, Actions: s.file.Actions, Cycles: s.file.Cycles, + Steps: s.file.Steps} for id, dd := range s.file.Devices { c := *dd for q := range c.AvgW { diff --git a/dashboard/internal/autolearn/steplog.go b/dashboard/internal/autolearn/steplog.go new file mode 100644 index 00000000..49fb86cd --- /dev/null +++ b/dashboard/internal/autolearn/steplog.go @@ -0,0 +1,291 @@ +package autolearn + +import ( + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "math" + "regexp" + "sort" + "sync" + "time" +) + +// Why sind die Gruende eines Reglerschritts. Der Automations-Dienst meldet sie +// als Text, im Speicher stehen sie als Zahl. +const ( + StepSent uint8 = iota + StepDeadband + StepUnchanged + StepLimit +) + +// stepFutureSlack ist die Zeit, die ein Schritt vorab liegen darf, etwa bei +// einer nachgehenden Uhr des Dienstes. +const stepFutureSlack = 300 * time.Second + +// stepRecordSize ist die Laenge eines Satzes der Schrittdatei. +const stepRecordSize = 24 + +var stepScenarioRE = regexp.MustCompile(`^[a-z0-9_-]{1,64}$`) + +// Step ist ein berechneter Reglerschritt eines Szenarios. From und To sind nil, +// wenn kein Stellwert vorliegt. Err und Net sind in Watt. +type Step struct { + At int64 + Err, Net float32 + From, To *float32 + Why uint8 +} + +// StepDay sind die Tageskennzahlen eines Szenarios. OutWhImport und OutWhExport +// sind die Energie ausserhalb der Totzone, Fehler mal Abstand zum naechsten +// Schritt. Netz ueber null zaehlt als Bezug, unter null als Einspeisung. +type StepDay struct { + N int `json:"n"` + Changes int `json:"changes"` + SignFlips int `json:"flips"` + OutWhImport float32 `json:"out_imp"` + OutWhExport float32 `json:"out_exp"` +} + +// StepLog haelt die Reglerschritte je Szenario im RAM. Die Aufbewahrung folgt +// days, dir liefert das Basisverzeichnis der Schrittdateien. Leer heisst nur RAM. +type StepLog struct { + days func() int + dir func() string + now func() time.Time + + mu sync.Mutex + steps map[string][]Step +} + +// NewStepLog legt einen leeren Schrittspeicher an. days und dir werden bei +// jedem Aufruf gelesen. +func NewStepLog(days func() int, dir func() string) *StepLog { + return &StepLog{days: days, dir: dir, now: time.Now, steps: map[string][]Step{}} +} + +// stepPayloadJSON ist die Form des Schritts auf dem Topic. Pflichtfelder sind +// Zeiger, damit ein fehlendes Feld auffaellt. +type stepPayloadJSON struct { + At *float64 `json:"at"` + Err *float64 `json:"err"` + Net *float64 `json:"net"` + From *float64 `json:"from"` + To *float64 `json:"to"` + Why *string `json:"why"` +} + +// Add nimmt einen Schritt des Szenarios entgegen. Unlesbare Payloads, ein at +// mehr als 300 s in der Zukunft und Szenario-IDs ausserhalb von [a-z0-9_-]{1,64} +// werden abgelehnt. +func (l *StepLog) Add(scenario string, payload []byte) error { + if !stepScenarioRE.MatchString(scenario) { + return fmt.Errorf("szenario-id %q ungueltig", scenario) + } + var p stepPayloadJSON + if err := json.Unmarshal(payload, &p); err != nil { + return fmt.Errorf("schritt unlesbar: %w", err) + } + if p.At == nil || p.Err == nil || p.Net == nil || p.Why == nil { + return errors.New("schritt unvollstaendig") + } + why, ok := stepWhy(*p.Why) + if !ok { + return fmt.Errorf("unbekannter grund %q", *p.Why) + } + now := l.now() + if *p.At <= 0 || *p.At >= math.MaxUint32 || *p.At > float64(now.Add(stepFutureSlack).Unix()) { + return fmt.Errorf("zeitstempel %v ausserhalb des erlaubten bereichs", *p.At) + } + st := Step{At: int64(*p.At), Err: float32(*p.Err), Net: float32(*p.Net), Why: why} + if st.Err != st.Err || st.Net != st.Net || math.IsInf(float64(st.Err), 0) || math.IsInf(float64(st.Net), 0) { + return errors.New("fehler oder netz nicht endlich") + } + st.From = optFloat(p.From) + st.To = optFloat(p.To) + if !finitePtr(st.From) || !finitePtr(st.To) { + return errors.New("stellwert nicht endlich") + } + + l.mu.Lock() + defer l.mu.Unlock() + l.steps[scenario] = append(l.steps[scenario], st) + return nil +} + +// Steps liefert die Schritte des Szenarios mit einem Zeitpunkt von from bis to, +// beide Enden einschliesslich, in Ankunftsreihenfolge. +func (l *StepLog) Steps(scenario string, from, to time.Time) []Step { + l.mu.Lock() + defer l.mu.Unlock() + var out []Step + for _, st := range l.steps[scenario] { + if st.At >= from.Unix() && st.At <= to.Unix() { + out = append(out, st) + } + } + return out +} + +// Flush wirft die Schritte ab, die ausserhalb der Aufbewahrung liegen. Die +// Schreibstufe in die Datei am Ort kommt spaeter dazu. +func (l *StepLog) Flush(now time.Time) error { + cutoff := l.cutoff(now) + l.mu.Lock() + defer l.mu.Unlock() + for id, list := range l.steps { + keep := list[:0] + for _, st := range list { + if st.At >= cutoff { + keep = append(keep, st) + } + } + if len(keep) == 0 { + delete(l.steps, id) + } else { + l.steps[id] = keep + } + } + return nil +} + +// DayFigures rechnet die Tageskennzahlen je Szenario fuer den Tag day (JJJJ-MM-TT, +// Ortszeit) aus den Schritten im RAM. +func (l *StepLog) DayFigures(day string) map[string]*StepDay { + start, err := time.ParseInLocation(dayLayout, day, time.Local) + if err != nil { + return nil + } + end := start.Add(24 * time.Hour) + l.mu.Lock() + defer l.mu.Unlock() + out := map[string]*StepDay{} + for id, list := range l.steps { + var inDay []Step + for _, st := range list { + if st.At >= start.Unix() && st.At < end.Unix() { + inDay = append(inDay, st) + } + } + if len(inDay) == 0 { + continue + } + sort.SliceStable(inDay, func(i, j int) bool { return inDay[i].At < inDay[j].At }) + out[id] = stepFigures(inDay) + } + return out +} + +// cutoff ist der Anfang des ersten Tages, den der Ring behaelt. +func (l *StepLog) cutoff(now time.Time) int64 { + n := max(1, l.days()) + local := now.In(time.Local) + first := time.Date(local.Year(), local.Month(), local.Day()-(n-1), 0, 0, 0, 0, time.Local) + return first.Unix() +} + +// stepFigures rechnet die Kennzahlen eines Tages aus den nach Zeit sortierten Schritten. +func stepFigures(steps []Step) *StepDay { + fig := &StepDay{N: len(steps)} + var prevSign int + var impWh, expWh float64 + for i, st := range steps { + if st.From != nil && st.To != nil && *st.From != *st.To { + fig.Changes++ + } + if st.Err != 0 { + sign := 1 + if st.Err < 0 { + sign = -1 + } + if prevSign != 0 && sign != prevSign { + fig.SignFlips++ + } + prevSign = sign + } + if st.Why == StepDeadband || i+1 >= len(steps) { + continue + } + dt := float64(steps[i+1].At - st.At) + wh := math.Abs(float64(st.Err)) * dt / 3600 + switch { + case st.Net > 0: + impWh += wh + case st.Net < 0: + expWh += wh + } + } + fig.OutWhImport = float32(impWh) + fig.OutWhExport = float32(expWh) + return fig +} + +func stepWhy(s string) (uint8, bool) { + switch s { + case "sent": + return StepSent, true + case "deadband": + return StepDeadband, true + case "unchanged": + return StepUnchanged, true + case "limit": + return StepLimit, true + } + return 0, false +} + +func optFloat(p *float64) *float32 { + if p == nil { + return nil + } + v := float32(*p) + return &v +} + +func finitePtr(p *float32) bool { + return p == nil || (!math.IsNaN(float64(*p)) && !math.IsInf(float64(*p), 0)) +} + +// encodeStep schreibt einen Schritt als 24 Byte: Zeit als uint32, Fehler, +// Netz, Stellwert von und bis als float32 (NaN fehlt), Grund, drei Fuellbytes. +// Der Szenario-Schluessel gehoert nicht zum Satz. +func encodeStep(st Step) []byte { + buf := make([]byte, stepRecordSize) + binary.LittleEndian.PutUint32(buf[0:], uint32(st.At)) + binary.LittleEndian.PutUint32(buf[4:], math.Float32bits(st.Err)) + binary.LittleEndian.PutUint32(buf[8:], math.Float32bits(st.Net)) + binary.LittleEndian.PutUint32(buf[12:], math.Float32bits(ptrOrNaN(st.From))) + binary.LittleEndian.PutUint32(buf[16:], math.Float32bits(ptrOrNaN(st.To))) + buf[20] = st.Why + return buf +} + +// decodeStep liest einen Satz aus encodeStep. NaN wird wieder zu nil. +func decodeStep(buf []byte) Step { + st := Step{ + At: int64(binary.LittleEndian.Uint32(buf[0:])), + Err: math.Float32frombits(binary.LittleEndian.Uint32(buf[4:])), + Net: math.Float32frombits(binary.LittleEndian.Uint32(buf[8:])), + From: nanToNil(math.Float32frombits(binary.LittleEndian.Uint32(buf[12:]))), + To: nanToNil(math.Float32frombits(binary.LittleEndian.Uint32(buf[16:]))), + Why: buf[20], + } + return st +} + +func ptrOrNaN(p *float32) float32 { + if p == nil { + return float32(math.NaN()) + } + return *p +} + +func nanToNil(v float32) *float32 { + if math.IsNaN(float64(v)) { + return nil + } + return &v +} diff --git a/dashboard/internal/autolearn/steplog_test.go b/dashboard/internal/autolearn/steplog_test.go new file mode 100644 index 00000000..3948c599 --- /dev/null +++ b/dashboard/internal/autolearn/steplog_test.go @@ -0,0 +1,223 @@ +package autolearn + +import ( + "fmt" + "math" + "strings" + "testing" + "time" +) + +// stepPayload baut die JSON-Form eines Reglerschritts. +func stepPayload(at float64, err, net float64, from, to *float64, why string) []byte { + f := func(v *float64) string { + if v == nil { + return "null" + } + return fmt.Sprintf("%g", *v) + } + return []byte(fmt.Sprintf(`{"at":%.1f,"err":%g,"net":%g,"from":%s,"to":%s,"why":%q}`, + at, err, net, f(from), f(to), why)) +} + +func fptr(v float64) *float64 { return &v } + +// newTestStepLog legt einen StepLog mit fester Uhr an. +func newTestStepLog(days int, now time.Time) *StepLog { + l := NewStepLog(func() int { return days }, func() string { return "" }) + l.now = func() time.Time { return now } + return l +} + +func TestStepLogKeepsADayOfSteps(t *testing.T) { + loc := berlinLoc(t) + start := time.Date(2026, 11, 19, 0, 0, 0, 0, loc) + l := newTestStepLog(1, start.Add(24*time.Hour-time.Second)) + for i := 0; i < 8640; i++ { + at := float64(start.Add(time.Duration(i) * 10 * time.Second).Unix()) + if err := l.Add("heizung", stepPayload(at, -5, -5, fptr(1200), fptr(1200), "unchanged")); err != nil { + t.Fatalf("step %d: %v", i, err) + } + } + if got := len(l.Steps("heizung", start, start.Add(24*time.Hour))); got != 8640 { + t.Fatalf("steps = %d, want 8640", got) + } + // 10:00:00 bis 10:01:00 einschliesslich: 7 Schritte. + got := l.Steps("heizung", start.Add(10*time.Hour), start.Add(10*time.Hour+time.Minute)) + if len(got) != 7 { + t.Fatalf("range steps = %d, want 7", len(got)) + } + if got[0].At != start.Add(10*time.Hour).Unix() { + t.Errorf("first at = %d, want 10:00:00", got[0].At) + } +} + +func TestStepLogPrunesDaysOutsideTheRing(t *testing.T) { + loc := berlinLoc(t) + old := time.Date(2026, 11, 19, 12, 0, 0, 0, loc) + now := time.Date(2026, 11, 22, 12, 0, 0, 0, loc) + l := newTestStepLog(2, now) + if err := l.Add("heizung", stepPayload(float64(old.Unix()), 1, 1, nil, nil, "deadband")); err != nil { + t.Fatal(err) + } + if err := l.Flush(now); err != nil { + t.Fatal(err) + } + if got := l.Steps("heizung", old.Add(-time.Hour), now); len(got) != 0 { + t.Errorf("steps = %d, want the old day pruned", len(got)) + } +} + +func TestStepLogCountsChangesAndSignFlips(t *testing.T) { + loc := berlinLoc(t) + base := time.Date(2026, 11, 19, 10, 0, 0, 0, loc) + now := base.Add(time.Hour) + l := newTestStepLog(1, now) + steps := []struct { + err, net float64 + from, to *float64 + why string + }{ + {5, 5, fptr(1200), fptr(1180), "sent"}, + {-3, -3, fptr(1180), fptr(1180), "unchanged"}, + {-2, -2, fptr(1180), fptr(1180), "unchanged"}, + {0, 0, fptr(1180), fptr(1180), "deadband"}, + {4, 4, fptr(1180), fptr(1200), "sent"}, + } + for i, s := range steps { + at := float64(base.Add(time.Duration(i) * time.Minute).Unix()) + if err := l.Add("heizung", stepPayload(at, s.err, s.net, s.from, s.to, s.why)); err != nil { + t.Fatalf("step %d: %v", i, err) + } + } + fig := l.DayFigures("2026-11-19")["heizung"] + if fig == nil { + t.Fatal("no figures for heizung") + } + if fig.N != 5 { + t.Errorf("n = %d, want 5", fig.N) + } + if fig.Changes != 2 { + t.Errorf("changes = %d, want 2", fig.Changes) + } + // +5 gegen -3 und -2 gegen +4 wechseln das Vorzeichen, der Nullfehler zaehlt nicht. + if fig.SignFlips != 2 { + t.Errorf("flips = %d, want 2", fig.SignFlips) + } +} + +func TestStepLogOutOfDeadbandEnergySplitsBySign(t *testing.T) { + loc := berlinLoc(t) + base := time.Date(2026, 11, 19, 10, 0, 0, 0, loc) + l := newTestStepLog(1, base.Add(time.Hour)) + // Export 100 W ueber 60 s: 100 * 60 / 3600 Wh. Die Totzone-Zeile zaehlt nicht. + steps := [][]byte{ + stepPayload(float64(base.Unix()), -100, -100, fptr(1200), fptr(1200), "unchanged"), + stepPayload(float64(base.Unix()+60), -100, -100, fptr(1200), fptr(1200), "deadband"), + stepPayload(float64(base.Unix()+120), 50, 50, fptr(1200), fptr(1200), "unchanged"), + } + for _, p := range steps { + if err := l.Add("heizung", p); err != nil { + t.Fatal(err) + } + } + fig := l.DayFigures("2026-11-19")["heizung"] + if fig == nil { + t.Fatal("no figures") + } + wantExp := 100.0 * 60 / 3600 + if math.Abs(float64(fig.OutWhExport)-wantExp) > 1e-3 { + t.Errorf("out_exp = %v, want %v", fig.OutWhExport, wantExp) + } + if fig.OutWhImport != 0 { + t.Errorf("out_imp = %v, want 0 (the last step has no next step)", fig.OutWhImport) + } +} + +func TestStepLogRejectsBadPayloadsAndIDs(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 19, 10, 0, 0, 0, loc) + at := float64(now.Unix()) + l := newTestStepLog(1, now) + + bad := map[string][]byte{ + "not json": []byte(`{"at":`), + "number": []byte(`12`), + "no why": []byte(fmt.Sprintf(`{"at":%g,"err":1,"net":1,"from":null,"to":null}`, at)), + "unknown why": stepPayload(at, 1, 1, nil, nil, "bogus"), + "no err": []byte(fmt.Sprintf(`{"at":%g,"net":1,"why":"sent"}`, at)), + "future 301 s": stepPayload(at+301, 1, 1, nil, nil, "sent"), + "huge err": []byte(fmt.Sprintf(`{"at":%g,"err":1e300,"net":1,"why":"sent"}`, at)), + } + for name, p := range bad { + if err := l.Add("heizung", p); err == nil { + t.Errorf("%s: accepted, want rejected", name) + } + } + if err := l.Add("heizung", stepPayload(at+299, 1, 1, nil, nil, "sent")); err != nil { + t.Errorf("299 s in the future: %v, want accepted", err) + } + + for _, id := range []string{"", "Heizung", "a b", "a/b", "a.b", strings.Repeat("x", 65)} { + if err := l.Add(id, stepPayload(at, 1, 1, nil, nil, "sent")); err == nil { + t.Errorf("scenario %q accepted, want rejected", id) + } + } + for _, id := range []string{"a", "heizung-1", "a_b", strings.Repeat("x", 64)} { + if err := l.Add(id, stepPayload(at, 1, 1, nil, nil, "sent")); err != nil { + t.Errorf("scenario %q: %v, want accepted", id, err) + } + } +} + +func TestDayFileWithoutStepsLoads(t *testing.T) { + loc := berlinLoc(t) + dir := t.TempDir() + writeRawDay(t, dir, "2026-11-19", `{"v":1,"day":"2026-11-19","devices":{},"site":{},"events":[],"actions":[]}`) + base := time.Date(2026, 11, 19, 10, 0, 0, 0, loc) + s := OpenDayStore(dir, loc, keepAll, noLog) + days := mustDays(t, s, base, base) + if len(days) != 1 { + t.Fatalf("days = %d, want the old day", len(days)) + } + if days[0].Steps != nil { + t.Errorf("steps = %v, want nil", days[0].Steps) + } +} + +func TestDayFileStepsRoundTrip(t *testing.T) { + loc := berlinLoc(t) + dir := t.TempDir() + s := OpenDayStore(dir, loc, keepAll, noLog) + base := time.Date(2026, 11, 19, 10, 0, 0, 0, loc) + f := DayFile{V: dayFileVersion, Day: "2026-11-19", Devices: map[string]*DeviceDay{}, + Events: []EventRec{}, Actions: []ActionRec{}, + Steps: map[string]*StepDay{"heizung": {N: 3, Changes: 1, SignFlips: 2, OutWhImport: 1.5, OutWhExport: 0.5}}} + if err := s.writeFile("2026-11-19", f); err != nil { + t.Fatal(err) + } + days := mustDays(t, s, base, base) + if len(days) != 1 || days[0].Steps["heizung"] == nil { + t.Fatalf("days = %+v, want the steps back", days) + } + got := days[0].Steps["heizung"] + if got.N != 3 || got.Changes != 1 || got.SignFlips != 2 || got.OutWhImport != 1.5 || got.OutWhExport != 0.5 { + t.Errorf("steps = %+v, want the figures back", got) + } +} + +func TestStepRecordRoundTrip(t *testing.T) { + v := float32(1200) + in := Step{At: 1794000000, Err: -35, Net: -35, From: &v, To: nil, Why: StepLimit} + buf := encodeStep(in) + if len(buf) != 24 { + t.Fatalf("record = %d bytes, want 24", len(buf)) + } + out := decodeStep(buf) + if out.At != in.At || out.Err != in.Err || out.Net != in.Net || out.Why != in.Why { + t.Errorf("decoded = %+v, want %+v", out, in) + } + if out.From == nil || *out.From != 1200 || out.To != nil { + t.Errorf("from/to = %v/%v, want 1200/nil", out.From, out.To) + } +} From 8f2a75a3bd40cb06f4c632818e5228b4d511b4ca Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:06:53 +0100 Subject: [PATCH 08/21] fix(autolearn): write step files per scenario and day, drop deadband from figures Steps go to learnrec/minutes/YYYY-MM-DD..steps as 24-byte little endian records, appended once per step on each Flush. Steps older than the ring are read back from those files, and old day files are pruned. Day figures skip deadband steps and cap the gap to the next step at 300 s. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/autolearn/steplog.go | 228 ++++++++++++++++--- dashboard/internal/autolearn/steplog_test.go | 119 +++++++++- 2 files changed, 310 insertions(+), 37 deletions(-) diff --git a/dashboard/internal/autolearn/steplog.go b/dashboard/internal/autolearn/steplog.go index 49fb86cd..468ca83c 100644 --- a/dashboard/internal/autolearn/steplog.go +++ b/dashboard/internal/autolearn/steplog.go @@ -6,8 +6,11 @@ import ( "errors" "fmt" "math" + "os" + "path/filepath" "regexp" "sort" + "strings" "sync" "time" ) @@ -25,6 +28,10 @@ const ( // einer nachgehenden Uhr des Dienstes. const stepFutureSlack = 300 * time.Second +// stepGapCap begrenzt den Abstand zum naechsten Schritt bei der Energierechnung, +// damit eine Luecke im Schrittstrom nicht als Dauerbetrieb zaehlt. +const stepGapCap = 300 + // stepRecordSize ist die Laenge eines Satzes der Schrittdatei. const stepRecordSize = 24 @@ -39,9 +46,10 @@ type Step struct { Why uint8 } -// StepDay sind die Tageskennzahlen eines Szenarios. OutWhImport und OutWhExport -// sind die Energie ausserhalb der Totzone, Fehler mal Abstand zum naechsten -// Schritt. Netz ueber null zaehlt als Bezug, unter null als Einspeisung. +// StepDay sind die Tageskennzahlen eines Szenarios. Schritte mit dem Grund +// deadband zaehlen nicht. OutWhImport und OutWhExport sind die Energie +// ausserhalb der Totzone, Fehler mal Abstand zum naechsten Schritt, hoechstens +// 300 s. Netz ueber null zaehlt als Bezug, unter null als Einspeisung. type StepDay struct { N int `json:"n"` Changes int `json:"changes"` @@ -51,20 +59,25 @@ type StepDay struct { } // StepLog haelt die Reglerschritte je Szenario im RAM. Die Aufbewahrung folgt -// days, dir liefert das Basisverzeichnis der Schrittdateien. Leer heisst nur RAM. +// days. dir liefert das Basisverzeichnis: dort liegt je Szenario und Tag die +// Datei learnrec/minutes/JJJJ-MM-TT..steps. Leer heisst nur RAM. type StepLog struct { days func() int dir func() string now func() time.Time - mu sync.Mutex - steps map[string][]Step + flushMu sync.Mutex // serialisiert Flush, damit Schreiben und Zaehler zusammenpassen + + mu sync.Mutex // schuetzt die Felder darunter + steps map[string][]Step + written map[string]int // je Szenario: die ersten so vielen Schritte stehen in der Datei } // NewStepLog legt einen leeren Schrittspeicher an. days und dir werden bei // jedem Aufruf gelesen. func NewStepLog(days func() int, dir func() string) *StepLog { - return &StepLog{days: days, dir: dir, now: time.Now, steps: map[string][]Step{}} + return &StepLog{days: days, dir: dir, now: time.Now, + steps: map[string][]Step{}, written: map[string]int{}} } // stepPayloadJSON ist die Form des Schritts auf dem Topic. Pflichtfelder sind @@ -117,39 +130,91 @@ func (l *StepLog) Add(scenario string, payload []byte) error { } // Steps liefert die Schritte des Szenarios mit einem Zeitpunkt von from bis to, -// beide Enden einschliesslich, in Ankunftsreihenfolge. +// beide Enden einschliesslich. Aeltere Tage liest es aus den Dateien am Ort, +// die juengeren aus dem RAM. Ohne Ort zaehlt nur das RAM. func (l *StepLog) Steps(scenario string, from, to time.Time) []Step { + cutoff := l.cutoff(l.now()) + dir := l.dir() + var out []Step + if dir != "" && from.Unix() < cutoff { + out = l.readFiles(dir, scenario, from, to, cutoff) + } l.mu.Lock() defer l.mu.Unlock() - var out []Step for _, st := range l.steps[scenario] { - if st.At >= from.Unix() && st.At <= to.Unix() { - out = append(out, st) + if st.At < from.Unix() || st.At > to.Unix() { + continue } + if dir != "" && st.At < cutoff { + continue // steht in der Datei oder ist schon verfallen + } + out = append(out, st) } return out } -// Flush wirft die Schritte ab, die ausserhalb der Aufbewahrung liegen. Die -// Schreibstufe in die Datei am Ort kommt spaeter dazu. +// Flush haengt die neuen Schritte an die Dateien am Ort an und wirft die +// Schritte ab, die ausserhalb der Aufbewahrung liegen. Ein Schritt steht nach +// einem Flush genau einmal in der Datei, auch wenn Flush wiederholt laeuft. +// Ohne Ort passiert nur das Abwerfen im RAM. func (l *StepLog) Flush(now time.Time) error { + l.flushMu.Lock() + defer l.flushMu.Unlock() cutoff := l.cutoff(now) + dir := l.dir() + + type job struct { + id string + steps []Step + } + var jobs []job l.mu.Lock() - defer l.mu.Unlock() for id, list := range l.steps { + w := l.written[id] keep := list[:0] - for _, st := range list { - if st.At >= cutoff { - keep = append(keep, st) + dropped := 0 + for i, st := range list { + if st.At < cutoff { + if i < w { + dropped++ + } + continue } + keep = append(keep, st) } + w -= dropped if len(keep) == 0 { delete(l.steps, id) - } else { - l.steps[id] = keep + delete(l.written, id) + continue + } + l.steps[id] = keep + l.written[id] = w + if dir != "" && w < len(keep) { + jobs = append(jobs, job{id: id, steps: append([]Step(nil), keep[w:]...)}) } } - return nil + l.mu.Unlock() + + if dir == "" { + return nil + } + var errs []error + for _, j := range jobs { + n, err := appendSteps(dir, j.id, j.steps) + l.mu.Lock() + if _, ok := l.steps[j.id]; ok { + l.written[j.id] += n + } + l.mu.Unlock() + if err != nil { + errs = append(errs, err) + } + } + if err := pruneStepFiles(dir, time.Unix(cutoff, 0).In(time.Local).Format(dayLayout)); err != nil { + errs = append(errs, err) + } + return errors.Join(errs...) } // DayFigures rechnet die Tageskennzahlen je Szenario fuer den Tag day (JJJJ-MM-TT, @@ -170,11 +235,10 @@ func (l *StepLog) DayFigures(day string) map[string]*StepDay { inDay = append(inDay, st) } } - if len(inDay) == 0 { - continue - } sort.SliceStable(inDay, func(i, j int) bool { return inDay[i].At < inDay[j].At }) - out[id] = stepFigures(inDay) + if fig := stepFigures(inDay); fig.N > 0 { + out[id] = fig + } } return out } @@ -187,8 +251,107 @@ func (l *StepLog) cutoff(now time.Time) int64 { return first.Unix() } -// stepFigures rechnet die Kennzahlen eines Tages aus den nach Zeit sortierten Schritten. -func stepFigures(steps []Step) *StepDay { +// readFiles liest die Schritte des Szenarios aus den Tagesdateien vor dem +// Anfang des Rings, im Bereich von from bis to. +func (l *StepLog) readFiles(dir, scenario string, from, to time.Time, cutoff int64) []Step { + var out []Step + first := time.Unix(from.Unix(), 0).In(time.Local) + day := time.Date(first.Year(), first.Month(), first.Day(), 0, 0, 0, 0, time.Local) + last := time.Unix(min(to.Unix(), cutoff-1), 0).In(time.Local) + for ; !day.After(last); day = day.AddDate(0, 0, 1) { + raw, err := os.ReadFile(stepFileName(dir, day.Format(dayLayout), scenario)) + if err != nil { + continue + } + for off := 0; off+stepRecordSize <= len(raw); off += stepRecordSize { + st := decodeStep(raw[off : off+stepRecordSize]) + if st.At >= from.Unix() && st.At <= to.Unix() && st.At < cutoff { + out = append(out, st) + } + } + } + return out +} + +// appendSteps haengt die Schritte an ihre Tagesdateien an, Lauf fuer Lauf. Die +// Zahl der geschriebenen Schritte kommt zurueck, auch bei einem Fehler. +func appendSteps(dir, scenario string, steps []Step) (int, error) { + done := 0 + for start := 0; start < len(steps); { + day := time.Unix(steps[start].At, 0).In(time.Local).Format(dayLayout) + end := start + for end < len(steps) && time.Unix(steps[end].At, 0).In(time.Local).Format(dayLayout) == day { + end++ + } + if err := appendStepFile(stepFileName(dir, day, scenario), steps[start:end]); err != nil { + return done, err + } + done += end - start + start = end + } + return done, nil +} + +func appendStepFile(path string, steps []Step) error { + buf := make([]byte, 0, len(steps)*stepRecordSize) + for _, st := range steps { + buf = append(buf, encodeStep(st)...) + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + return err + } + if _, err := f.Write(buf); err != nil { + f.Close() + return err + } + return f.Close() +} + +// pruneStepFiles loescht die Schrittdateien, deren Tag vor cutoffDay liegt. +func pruneStepFiles(dir, cutoffDay string) error { + sub := filepath.Join(dir, "learnrec", "minutes") + entries, err := os.ReadDir(sub) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + var errs []error + for _, e := range entries { + name, ok := strings.CutSuffix(e.Name(), ".steps") + if !ok || e.IsDir() { + continue + } + day, _, ok := strings.Cut(name, ".") + if !ok || len(day) != len(dayLayout) || day >= cutoffDay { + continue + } + if err := os.Remove(filepath.Join(sub, e.Name())); err != nil && !errors.Is(err, os.ErrNotExist) { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +// stepFileName ist die Schrittdatei eines Szenarios an einem Tag. +func stepFileName(dir, day, scenario string) string { + return filepath.Join(dir, "learnrec", "minutes", day+"."+scenario+".steps") +} + +// stepFigures rechnet die Kennzahlen eines Tages aus den nach Zeit sortierten +// Schritten. Schritte mit dem Grund deadband fallen weg, bevor gezaehlt wird. +func stepFigures(all []Step) *StepDay { + var steps []Step + for _, st := range all { + if st.Why != StepDeadband { + steps = append(steps, st) + } + } fig := &StepDay{N: len(steps)} var prevSign int var impWh, expWh float64 @@ -206,10 +369,10 @@ func stepFigures(steps []Step) *StepDay { } prevSign = sign } - if st.Why == StepDeadband || i+1 >= len(steps) { + if i+1 >= len(steps) { continue } - dt := float64(steps[i+1].At - st.At) + dt := min(float64(steps[i+1].At-st.At), stepGapCap) wh := math.Abs(float64(st.Err)) * dt / 3600 switch { case st.Net > 0: @@ -249,9 +412,9 @@ func finitePtr(p *float32) bool { return p == nil || (!math.IsNaN(float64(*p)) && !math.IsInf(float64(*p), 0)) } -// encodeStep schreibt einen Schritt als 24 Byte: Zeit als uint32, Fehler, -// Netz, Stellwert von und bis als float32 (NaN fehlt), Grund, drei Fuellbytes. -// Der Szenario-Schluessel gehoert nicht zum Satz. +// encodeStep schreibt einen Schritt als 24 Byte little endian: Zeit als uint32, +// Fehler, Netz, Stellwert von und bis als float32 (NaN fehlt), Grund, drei +// Fuellbytes. Der Szenario-Schluessel steckt im Dateinamen. func encodeStep(st Step) []byte { buf := make([]byte, stepRecordSize) binary.LittleEndian.PutUint32(buf[0:], uint32(st.At)) @@ -265,7 +428,7 @@ func encodeStep(st Step) []byte { // decodeStep liest einen Satz aus encodeStep. NaN wird wieder zu nil. func decodeStep(buf []byte) Step { - st := Step{ + return Step{ At: int64(binary.LittleEndian.Uint32(buf[0:])), Err: math.Float32frombits(binary.LittleEndian.Uint32(buf[4:])), Net: math.Float32frombits(binary.LittleEndian.Uint32(buf[8:])), @@ -273,7 +436,6 @@ func decodeStep(buf []byte) Step { To: nanToNil(math.Float32frombits(binary.LittleEndian.Uint32(buf[16:]))), Why: buf[20], } - return st } func ptrOrNaN(p *float32) float32 { diff --git a/dashboard/internal/autolearn/steplog_test.go b/dashboard/internal/autolearn/steplog_test.go index 3948c599..ffa56114 100644 --- a/dashboard/internal/autolearn/steplog_test.go +++ b/dashboard/internal/autolearn/steplog_test.go @@ -3,6 +3,7 @@ package autolearn import ( "fmt" "math" + "os" "strings" "testing" "time" @@ -94,8 +95,8 @@ func TestStepLogCountsChangesAndSignFlips(t *testing.T) { if fig == nil { t.Fatal("no figures for heizung") } - if fig.N != 5 { - t.Errorf("n = %d, want 5", fig.N) + if fig.N != 4 { + t.Errorf("n = %d, want 4 (ohne Totzone)", fig.N) } if fig.Changes != 2 { t.Errorf("changes = %d, want 2", fig.Changes) @@ -110,7 +111,7 @@ func TestStepLogOutOfDeadbandEnergySplitsBySign(t *testing.T) { loc := berlinLoc(t) base := time.Date(2026, 11, 19, 10, 0, 0, 0, loc) l := newTestStepLog(1, base.Add(time.Hour)) - // Export 100 W ueber 60 s: 100 * 60 / 3600 Wh. Die Totzone-Zeile zaehlt nicht. + // Export 100 W, Abstand bis zum naechsten Schritt ohne Totzone 120 s: 100 * 120 / 3600 Wh. steps := [][]byte{ stepPayload(float64(base.Unix()), -100, -100, fptr(1200), fptr(1200), "unchanged"), stepPayload(float64(base.Unix()+60), -100, -100, fptr(1200), fptr(1200), "deadband"), @@ -125,7 +126,7 @@ func TestStepLogOutOfDeadbandEnergySplitsBySign(t *testing.T) { if fig == nil { t.Fatal("no figures") } - wantExp := 100.0 * 60 / 3600 + wantExp := 100.0 * 120 / 3600 if math.Abs(float64(fig.OutWhExport)-wantExp) > 1e-3 { t.Errorf("out_exp = %v, want %v", fig.OutWhExport, wantExp) } @@ -221,3 +222,113 @@ func TestStepRecordRoundTrip(t *testing.T) { t.Errorf("from/to = %v/%v, want 1200/nil", out.From, out.To) } } + +func TestStepLogGapIsCappedAt300Seconds(t *testing.T) { + loc := berlinLoc(t) + base := time.Date(2026, 11, 19, 10, 0, 0, 0, loc) + l := newTestStepLog(1, base.Add(2*time.Hour)) + // Zwei Schritte 1000 s auseinander: gezaehlt werden nur 300 s, 60 * 300 / 3600 Wh. + for _, at := range []int64{base.Unix(), base.Unix() + 1000} { + if err := l.Add("heizung", stepPayload(float64(at), -60, -60, fptr(1200), fptr(1200), "unchanged")); err != nil { + t.Fatal(err) + } + } + fig := l.DayFigures("2026-11-19")["heizung"] + if fig == nil { + t.Fatal("no figures") + } + if want := 60.0 * 300 / 3600; math.Abs(float64(fig.OutWhExport)-want) > 1e-3 { + t.Errorf("out_exp = %v, want %v", fig.OutWhExport, want) + } +} + +func TestStepLogFlushAppendsOncePerStepAndRoundTrips(t *testing.T) { + loc := berlinLoc(t) + dir := t.TempDir() + base := time.Date(2026, 11, 19, 10, 0, 0, 0, loc) + l := NewStepLog(func() int { return 2 }, func() string { return dir }) + l.now = func() time.Time { return base.Add(time.Hour) } + if err := l.Add("heizung", stepPayload(float64(base.Unix()), 5, 5, fptr(1200), nil, "sent")); err != nil { + t.Fatal(err) + } + if err := l.Add("heizung", stepPayload(float64(base.Unix()+10), -3, -3, nil, nil, "deadband")); err != nil { + t.Fatal(err) + } + if err := l.Add("lampe", stepPayload(float64(base.Unix()+20), 1, 1, nil, nil, "limit")); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if err := l.Flush(base.Add(time.Hour)); err != nil { + t.Fatalf("flush %d: %v", i, err) + } + } + file := stepFileName(dir, "2026-11-19", "heizung") + raw, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + if len(raw) != 2*stepRecordSize { + t.Fatalf("file = %d bytes, want 2 records after a repeated flush", len(raw)) + } + if _, err := os.Stat(stepFileName(dir, "2026-11-19", "lampe")); err != nil { + t.Errorf("lampe file: %v", err) + } + + // Ein neuer Speicher ohne RAM liest den Tag aus der Datei, auch nach dem Ring. + later := NewStepLog(func() int { return 1 }, func() string { return dir }) + later.now = func() time.Time { return base.Add(48 * time.Hour) } + got := later.Steps("heizung", base.Add(-time.Hour), base.Add(time.Hour)) + if len(got) != 2 { + t.Fatalf("read back %d steps, want 2", len(got)) + } + if got[0].At != base.Unix() || got[0].Err != 5 || got[0].Why != StepSent { + t.Errorf("first = %+v, want the sent step back", got[0]) + } + if got[0].From == nil || *got[0].From != 1200 || got[0].To != nil { + t.Errorf("from/to = %v/%v, want 1200/nil", got[0].From, got[0].To) + } + if got[1].Why != StepDeadband || got[1].From != nil { + t.Errorf("second = %+v, want the deadband step with from nil", got[1]) + } +} + +func TestStepLogFlushPrunesOldStepFiles(t *testing.T) { + loc := berlinLoc(t) + dir := t.TempDir() + old := time.Date(2026, 11, 10, 10, 0, 0, 0, loc) + now := time.Date(2026, 11, 22, 10, 0, 0, 0, loc) + l := NewStepLog(func() int { return 3 }, func() string { return dir }) + l.now = func() time.Time { return old } + if err := l.Add("heizung", stepPayload(float64(old.Unix()), 1, 1, nil, nil, "sent")); err != nil { + t.Fatal(err) + } + if err := l.Flush(old); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(stepFileName(dir, "2026-11-10", "heizung")); err != nil { + t.Fatalf("old file not written: %v", err) + } + l.now = func() time.Time { return now } + if err := l.Flush(now); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(stepFileName(dir, "2026-11-10", "heizung")); !os.IsNotExist(err) { + t.Errorf("old file still there, err = %v", err) + } +} + +func TestStepLogRAMOnlyWritesNoFiles(t *testing.T) { + loc := berlinLoc(t) + dir := t.TempDir() + base := time.Date(2026, 11, 19, 10, 0, 0, 0, loc) + l := newTestStepLog(1, base.Add(time.Hour)) + if err := l.Add("heizung", stepPayload(float64(base.Unix()), 1, 1, nil, nil, "sent")); err != nil { + t.Fatal(err) + } + if err := l.Flush(base.Add(time.Hour)); err != nil { + t.Fatal(err) + } + if entries, _ := os.ReadDir(dir); len(entries) != 0 { + t.Errorf("entries = %d, want none", len(entries)) + } +} From 885314a6bb744d6d50277738a6992cc2375154be Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:11:15 +0100 Subject: [PATCH 09/21] feat(dashboard): wire the minute recording and step log into the main program The MinuteStore and the StepLog start with the dashboard. Their settings and location come from a snapshot that the ten-second loop refreshes, so the minute path never reads a file under the hub mutex. Step topics of the automation service share one WatchTopics call with the node agent. Flush runs every five minutes and once more on shutdown. Reset clears minutes and steps, and chain suggestions take their switch before the replay. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_engine_test.go | 68 +++++++++ dashboard/cmd/dashboard/learn_minutes.go | 148 +++++++++++++++++++ dashboard/cmd/dashboard/main.go | 52 ++++++- dashboard/internal/autolearn/steplog.go | 46 ++++++ dashboard/internal/autolearn/steplog_test.go | 29 ++++ 5 files changed, 338 insertions(+), 5 deletions(-) create mode 100644 dashboard/cmd/dashboard/learn_minutes.go diff --git a/dashboard/cmd/dashboard/learn_engine_test.go b/dashboard/cmd/dashboard/learn_engine_test.go index c2c0801c..94e863f4 100644 --- a/dashboard/cmd/dashboard/learn_engine_test.go +++ b/dashboard/cmd/dashboard/learn_engine_test.go @@ -2,6 +2,7 @@ package main import ( "context" + "fmt" "os" "path/filepath" "testing" @@ -12,6 +13,7 @@ import ( "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" "github.com/Developer-Simon/energy-node-dashboard/internal/registry" "github.com/Developer-Simon/energy-node-dashboard/internal/settings" + "github.com/Developer-Simon/energy-node-dashboard/internal/storage" ) func TestEngineRunnerDropsTickWhenChannelIsFull(t *testing.T) { @@ -146,3 +148,69 @@ func TestPVKeepDaysFollowsTheSeasonSwitch(t *testing.T) { t.Fatalf("switch off without profile days = %d, want the default", got) } } + +func TestMinuteSnapshotWithoutDriveIsRAM(t *testing.T) { + snap := minuteSnapshotFor(settings.Default(), "", storage.Status{Mode: storage.ModeNone}, "/data", "/mnt/data", learnrec.Limits{}) + if snap.plan.Location != learnrec.LocRAM || !snap.plan.AutoLocation { + t.Fatalf("plan = %+v, want auto ram", snap.plan) + } + if snap.dirs.Drive != "" { + t.Fatalf("drive dir = %q without a drive", snap.dirs.Drive) + } + if dir := snap.stepDir(); dir != "" { + t.Fatalf("step dir = %q, want ram", dir) + } +} + +func TestMinuteSnapshotWithDriveFollowsStorageMode(t *testing.T) { + value := settings.Default() + up := minuteSnapshotFor(value, "uuid", storage.Status{Mode: storage.ModeDrive}, "/data", "/mnt/data", learnrec.Limits{}) + if up.plan.Location != learnrec.LocDrive || !up.driveUp { + t.Fatalf("plan = %+v driveUp = %v, want drive", up.plan, up.driveUp) + } + if up.dirs.Drive != "/mnt/data/runtime" || up.stepDir() != "/mnt/data/runtime" { + t.Fatalf("drive dir = %q, step dir = %q", up.dirs.Drive, up.stepDir()) + } + down := minuteSnapshotFor(value, "uuid", storage.Status{Mode: storage.ModeFallbackSystem}, "/data", "/mnt/data", learnrec.Limits{}) + if down.driveUp || down.dirs.Drive != "" || down.stepDir() != "" { + t.Fatalf("fallback keeps drive out: driveUp = %v drive = %q step = %q", down.driveUp, down.dirs.Drive, down.stepDir()) + } +} + +func TestMinuteSnapshotSystemLocationUsesDataDir(t *testing.T) { + value := settings.Default() + value.LearningMinutesLocation = "system" + snap := minuteSnapshotFor(value, "uuid", storage.Status{Mode: storage.ModeDrive}, "/data", "/mnt/data", learnrec.Limits{}) + if snap.plan.Location != learnrec.LocSystem || snap.stepDir() != "/data" { + t.Fatalf("location = %q step dir = %q, want system /data", snap.plan.Location, snap.stepDir()) + } +} + +func TestWatchHandlerRoutesStepsAndKeepsOtherTopics(t *testing.T) { + steps := autolearn.NewStepLog(func() int { return 3 }, func() string { return "" }) + var others []string + handler := watchHandler(automationServiceID, steps, func(topic string, _ []byte) { + others = append(others, topic) + }) + if got := stepTopic(automationServiceID); got != "outstation/automation/scenario/+/step" { + t.Fatalf("step topic = %q", got) + } + now := time.Now() + payload := []byte(fmt.Sprintf(`{"at":%d,"err":-5,"net":-5,"from":1200,"to":1200,"why":"unchanged"}`, now.Unix())) + handler("outstation/automation/scenario/heizung/step", payload) + if got := steps.Steps("heizung", now.Add(-time.Hour), now.Add(time.Hour)); len(got) != 1 { + t.Fatalf("steps routed to the log = %d, want 1", len(got)) + } + handler("outstation/automation/status/online", []byte("online")) + handler("outstation/energy_node/scenario/heizung/step", payload) + handler("outstation/automation/scenario/heizung/extra/step", payload) + want := []string{"outstation/automation/status/online", "outstation/energy_node/scenario/heizung/step", "outstation/automation/scenario/heizung/extra/step"} + if len(others) != len(want) { + t.Fatalf("other topics = %v, want %v", others, want) + } + for i := range want { + if others[i] != want[i] { + t.Fatalf("other topics = %v, want %v", others, want) + } + } +} diff --git a/dashboard/cmd/dashboard/learn_minutes.go b/dashboard/cmd/dashboard/learn_minutes.go new file mode 100644 index 00000000..7a5fdc76 --- /dev/null +++ b/dashboard/cmd/dashboard/learn_minutes.go @@ -0,0 +1,148 @@ +package main + +import ( + "errors" + "log" + "strings" + "sync/atomic" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" + "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" + "github.com/Developer-Simon/energy-node-dashboard/internal/settings" + "github.com/Developer-Simon/energy-node-dashboard/internal/storage" +) + +// automationServiceID ist der Dienst der Automationen. Seine Reglerschritte +// kommen auf outstation/automation/scenario//step. +const automationServiceID = "automation" + +// minuteSnapshot ist, was die Minutenaufzeichnung aus Einstellungen, Laufwerk +// und Lernstufe braucht. Der Minutenweg liest ihn atomar, ohne Datei und ohne Lock. +type minuteSnapshot struct { + plan learnrec.MinutePlan + dirs learnrec.MinuteDirs + driveUp bool + limits learnrec.Limits +} + +// minuteSnapshotFor baut den Schnappschuss. Das Laufwerksverzeichnis ist nur +// gesetzt, wenn der Speicher im Modus Laufwerk steht. Die Aufzeichnung legt +// learnrec/minutes selbst unter dem Basisverzeichnis an. +func minuteSnapshotFor(value settings.Settings, driveUUID string, status storage.Status, dataDir, mount string, limits learnrec.Limits) *minuteSnapshot { + plan := learnrec.ResolveMinutes(learnrec.MinuteSettings{ + Mode: value.LearningMinutesMode, + Location: value.LearningMinutesLocation, + Days: value.LearningMinutesDays, + }, driveUUID != "") + snap := &minuteSnapshot{plan: plan, dirs: learnrec.MinuteDirs{System: dataDir}, limits: limits} + if status.Mode == storage.ModeDrive { + snap.driveUp = true + snap.dirs.Drive = storage.DriveRuntimeDir(storage.Paths{Mount: mount}) + } + return snap +} + +// stepDir ist das Basisverzeichnis der Schrittdateien am Ort der Minuten. Leer +// heisst RAM, also am Laufwerk ohne Laufwerk. +func (s *minuteSnapshot) stepDir() string { + switch s.plan.Location { + case learnrec.LocDrive: + if s.driveUp { + return s.dirs.Drive + } + case learnrec.LocSystem: + return s.dirs.System + } + return "" +} + +// minuteSources sind die Quellen, aus denen Refresh den Schnappschuss baut. +type minuteSources struct { + settings func() (settings.Settings, error) + status func() storage.Status + limits func() learnrec.Limits + dataDir string + mount string +} + +// minuteRecording buendelt den MinuteStore und den StepLog. Beide lesen ihre +// Einstellungen aus dem Schnappschuss, den Refresh im Zehn-Sekunden-Takt erneuert. +type minuteRecording struct { + store *learnrec.MinuteStore + steps *autolearn.StepLog + src minuteSources + snap atomic.Pointer[minuteSnapshot] +} + +// newMinuteRecording legt die Aufzeichnung an und liest den ersten Schnappschuss. +func newMinuteRecording(src minuteSources) *minuteRecording { + r := &minuteRecording{src: src} + r.Refresh() + r.store = learnrec.NewMinuteStore(time.Local, r.plan, r.dirs, r.driveUp, r.limits, log.Printf) + r.steps = autolearn.NewStepLog(func() int { return r.snap.Load().plan.Days }, r.stepDir) + return r +} + +// Refresh liest Einstellungen, Laufwerk und Lernstufe und ersetzt den +// Schnappschuss. Ohne lesbare Einstellungen gelten die Standardwerte. +func (r *minuteRecording) Refresh() { + value, err := r.src.settings() + if err != nil { + value = settings.Default() + } + driveUUID := "" + if cfg, err := storage.LoadConfig(r.src.dataDir); err == nil { + driveUUID = cfg.UUID + } + r.snap.Store(minuteSnapshotFor(value, driveUUID, r.src.status(), r.src.dataDir, r.src.mount, r.src.limits())) +} + +func (r *minuteRecording) plan() learnrec.MinutePlan { return r.snap.Load().plan } +func (r *minuteRecording) dirs() learnrec.MinuteDirs { return r.snap.Load().dirs } +func (r *minuteRecording) driveUp() bool { return r.snap.Load().driveUp } +func (r *minuteRecording) limits() learnrec.Limits { return r.snap.Load().limits } +func (r *minuteRecording) stepDir() string { return r.snap.Load().stepDir() } + +// Flush schreibt Minuten und Schritte an den Ort. Beide laufen, auch wenn der +// eine einen Fehler meldet. +func (r *minuteRecording) Flush(now time.Time) error { + return errors.Join(r.store.Flush(now), r.steps.Flush(now)) +} + +// Reset loescht die Minuten und die Schritte am Ort, am Laufwerk und im System. +func (r *minuteRecording) Reset() error { + drive := storage.DriveRuntimeDir(storage.Paths{Mount: r.src.mount}) + return errors.Join(r.store.Reset(), r.steps.Reset(r.src.dataDir, drive)) +} + +// stepTopic ist das Topic der Reglerschritte aller Szenarien des Dienstes. +func stepTopic(serviceID string) string { + return "outstation/" + serviceID + "/scenario/+/step" +} + +// stepScenario liefert die Szenario-ID eines Schritt-Topics des Dienstes. ok ist +// false bei jedem anderen Topic. +func stepScenario(serviceID, topic string) (string, bool) { + id, ok := strings.CutPrefix(topic, "outstation/"+serviceID+"/scenario/") + if !ok { + return "", false + } + id, ok = strings.CutSuffix(id, "/step") + if !ok || strings.Contains(id, "/") { + return "", false + } + return id, true +} + +// watchHandler verteilt die Nachrichten von mqttclient.WatchTopics. Schritte gehen +// an den StepLog, alles andere an other. Ein unlesbarer Schritt faellt in Add weg. +func watchHandler(serviceID string, steps *autolearn.StepLog, other func(topic string, payload []byte)) func(topic string, payload []byte) { + return func(topic string, payload []byte) { + if id, ok := stepScenario(serviceID, topic); ok { + _ = steps.Add(id, payload) + return + } + other(topic, payload) + } +} diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index f8ca7525..9ea078b6 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -770,6 +770,17 @@ func main() { } return storageWatcher.Tick(ctx) } + // Minutenaufzeichnung: MinuteStore und StepLog. Der Zehn-Sekunden-Takt erneuert + // den Schnappschuss mit Einstellungen, Laufwerk und Lernstufe. + minutes := newMinuteRecording(minuteSources{ + settings: settingsStore.LoadSettings, + status: storageStatus, + limits: learnLimits, + dataDir: dataDir, + mount: storageMountPoint, + }) + learnHub.AddMinute("minutes", minutes.store) + var minuteReader learnrec.Reader = minutes.store go runStorageResume(ctx, storageService) // Die Belegung der Systemplatte: in der Demo feste Werte, sonst eine Messung // im Hintergrund, die alle zehn Minuten erneuert wird. @@ -905,7 +916,12 @@ func main() { log.Printf("energy-node-dashboard: manifests unreadable: %v", err) } nodeAgent.SetServiceCatalog(serviceIDs, cfg.Services) - client.WatchTopics(nodeAgent.WatchTopicsFor(), nodeAgent.ObserveLiveness) + // Ein einziger Aufruf, WatchTopics ersetzt die ganze Liste. Dazu kommen die + // Reglerschritte der Automationen fuer die Minutenaufzeichnung. + client.WatchTopics( + append(nodeAgent.WatchTopicsFor(), stepTopic(automationServiceID)), + watchHandler(automationServiceID, minutes.steps, nodeAgent.ObserveLiveness), + ) // Leistungsmessung: Messung alle 15 s, Fenster 6 h, Anlaufphase 5 min. // ENERGY_NODE_PERFORMANCE_FAKE=1 liefert erfundene Werte (Demo, Smoke). @@ -1342,7 +1358,7 @@ func main() { Rules: func() ([]byte, error) { return configManager.Read("automation_rules") }, Reset: func() error { resetLearned(learnedStore, client) - return errors.Join(dayStore.Reset(), reactions.Reset(), chainSuggest.ResetLearned(), chainMonitor.ResetLearned(), suggestions.Reset()) + return errors.Join(dayStore.Reset(), reactions.Reset(), chainSuggest.ResetLearned(), chainMonitor.ResetLearned(), suggestions.Reset(), minutes.Reset()) }, } handler := perfTiming.Middleware(basepath.Middleware(httpapi.NewAuthenticatedRouter(reg, configManager, settingsStore, tinytuya.NewClient( @@ -1468,13 +1484,38 @@ func main() { } // Nachlesen der Minuten nach dem Neustart, einmal und vor der ersten Live-Minute. - // Der MinuteStore als Reader kommt erst mit der Aufzeichnung (Task 7). Bis dahin - // ist minuteReader nil, und Replay passiert nichts. - var minuteReader learnrec.Reader + // Die Vorschlaege bekommen vorher ihren Schalter, sonst zaehlt ein abgeschalteter + // Speicher die nachgelesenen Minuten mit. if minuteReader != nil { + suggestionsOn := true + if value, err := settingsStore.LoadSettings(); err == nil { + suggestionsOn = !value.ChainSuggestionsDisabled + } + chainSuggest.SetEnabled(suggestionsOn) learnHub.Replay(minuteReader, time.Now()) } + // Minuten und Reglerschritte alle fuenf Minuten an den Ort schreiben, beim Beenden + // noch einmal. + go func() { + ticker := time.NewTicker(5 * time.Minute) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + if err := minutes.Flush(time.Now()); err != nil { + log.Printf("energy-node-dashboard: learning minutes not flushed on shutdown: %v", err) + } + return + case <-ticker.C: + start := time.Now() + if err := minutes.Flush(start); err != nil { + log.Printf("energy-node-dashboard: learning minutes not flushed: %v", err) + } + } + } + }() + go func() { // Eigene Monotonuhr: time.Since(monoStart) laeuft auch dann // gleichmaessig weiter, wenn NTP die Wanduhr stellt. Daran erkennt @@ -1493,6 +1534,7 @@ func main() { case <-ticker.C: start := time.Now() now := time.Now() + minutes.Refresh() snapshot := energy.Aggregate(reg.Snapshot(), energyResolver, now.UTC()).WithInterpretation(energyResolver.Interpretation()) energyRecorder.Observe(now, time.Since(monoStart), snapshot) // Ohne gestellte Uhr waere FirstSeen falsch. Der Modus off diff --git a/dashboard/internal/autolearn/steplog.go b/dashboard/internal/autolearn/steplog.go index 468ca83c..aa2726cb 100644 --- a/dashboard/internal/autolearn/steplog.go +++ b/dashboard/internal/autolearn/steplog.go @@ -311,6 +311,52 @@ func appendStepFile(path string, steps []Step) error { return f.Close() } +// Reset leert den Speicher und loescht die Schrittdateien am aktuellen Ort und +// in den extra Basisverzeichnissen, etwa dem Ort vor einem Wechsel. +func (l *StepLog) Reset(extra ...string) error { + l.flushMu.Lock() + defer l.flushMu.Unlock() + l.mu.Lock() + l.steps = map[string][]Step{} + l.written = map[string]int{} + l.mu.Unlock() + + var errs []error + seen := map[string]bool{} + for _, dir := range append([]string{l.dir()}, extra...) { + if dir == "" || seen[dir] { + continue + } + seen[dir] = true + if err := removeStepFiles(dir); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +// removeStepFiles loescht alle Schrittdateien unter dir. +func removeStepFiles(dir string) error { + sub := filepath.Join(dir, "learnrec", "minutes") + entries, err := os.ReadDir(sub) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + var errs []error + for _, e := range entries { + if _, ok := strings.CutSuffix(e.Name(), ".steps"); !ok || e.IsDir() { + continue + } + if err := os.Remove(filepath.Join(sub, e.Name())); err != nil && !errors.Is(err, os.ErrNotExist) { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + // pruneStepFiles loescht die Schrittdateien, deren Tag vor cutoffDay liegt. func pruneStepFiles(dir, cutoffDay string) error { sub := filepath.Join(dir, "learnrec", "minutes") diff --git a/dashboard/internal/autolearn/steplog_test.go b/dashboard/internal/autolearn/steplog_test.go index ffa56114..caf62d7b 100644 --- a/dashboard/internal/autolearn/steplog_test.go +++ b/dashboard/internal/autolearn/steplog_test.go @@ -4,6 +4,7 @@ import ( "fmt" "math" "os" + "path/filepath" "strings" "testing" "time" @@ -332,3 +333,31 @@ func TestStepLogRAMOnlyWritesNoFiles(t *testing.T) { t.Errorf("entries = %d, want none", len(entries)) } } + +func TestStepLogResetClearsRAMAndStepFiles(t *testing.T) { + dir := t.TempDir() + start := time.Date(2026, 11, 20, 10, 0, 0, 0, time.Local) + l := NewStepLog(func() int { return 3 }, func() string { return dir }) + l.now = func() time.Time { return start } + if err := l.Add("heizung", stepPayload(float64(start.Unix()), -5, -5, fptr(1200), fptr(1200), "unchanged")); err != nil { + t.Fatal(err) + } + if err := l.Flush(start); err != nil { + t.Fatal(err) + } + if err := l.Reset(); err != nil { + t.Fatal(err) + } + if got := l.Steps("heizung", start.Add(-time.Hour), start.Add(time.Hour)); len(got) != 0 { + t.Fatalf("steps survived reset: %d", len(got)) + } + entries, err := os.ReadDir(filepath.Join(dir, "learnrec", "minutes")) + if err != nil { + t.Fatal(err) + } + for _, e := range entries { + if strings.HasSuffix(e.Name(), ".steps") { + t.Fatalf("step file survived reset: %s", e.Name()) + } + } +} From 0046eee050201261ea2f68e1d6caf0f4687414c1 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:13:06 +0100 Subject: [PATCH 10/21] fix(dashboard): bound the step ring by the RAM days and log slow flushes The RAM ring of the step log follows the RAM day budget of the minute store, in every location. The step files keep the configured days. A step older than the ring that is not yet in its file stays in RAM until the next flush writes it. The flush logs its duration when it takes more than two seconds. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_minutes.go | 12 +++- dashboard/cmd/dashboard/main.go | 3 + dashboard/internal/autolearn/steplog.go | 66 ++++++++++++++------ dashboard/internal/autolearn/steplog_test.go | 31 +++++++++ 4 files changed, 93 insertions(+), 19 deletions(-) diff --git a/dashboard/cmd/dashboard/learn_minutes.go b/dashboard/cmd/dashboard/learn_minutes.go index 7a5fdc76..4c1c23c4 100644 --- a/dashboard/cmd/dashboard/learn_minutes.go +++ b/dashboard/cmd/dashboard/learn_minutes.go @@ -80,10 +80,20 @@ func newMinuteRecording(src minuteSources) *minuteRecording { r := &minuteRecording{src: src} r.Refresh() r.store = learnrec.NewMinuteStore(time.Local, r.plan, r.dirs, r.driveUp, r.limits, log.Printf) - r.steps = autolearn.NewStepLog(func() int { return r.snap.Load().plan.Days }, r.stepDir) + r.steps = autolearn.NewStepLog(func() int { return r.snap.Load().plan.Days }, r.stepDir).WithRingDays(r.stepRingDays) return r } +// stepRingDays ist die Zahl der Tage im RAM-Ring der Schritte. Sie folgt dem +// RAM-Budget wie die Minuten im RAM: die Bytes eines vollen Tages sind die +// Kanaele mal 1440 Minuten mal 4 Byte je Wert. Der Ort aendert den Ring nicht. +func (r *minuteRecording) stepRingDays() int { + const bytesPerValue = 4 + const minutesPerDay = 1440 + keys := r.store.Usage().Keys + return learnrec.RAMDays(r.limits(), int64(keys)*minutesPerDay*bytesPerValue) +} + // Refresh liest Einstellungen, Laufwerk und Lernstufe und ersetzt den // Schnappschuss. Ohne lesbare Einstellungen gelten die Standardwerte. func (r *minuteRecording) Refresh() { diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 9ea078b6..c4f8e3c3 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -1512,6 +1512,9 @@ func main() { if err := minutes.Flush(start); err != nil { log.Printf("energy-node-dashboard: learning minutes not flushed: %v", err) } + if took := time.Since(start); took > 2*time.Second { + log.Printf("energy-node-dashboard: learning minutes flush took %s", took.Round(time.Millisecond)) + } } } }() diff --git a/dashboard/internal/autolearn/steplog.go b/dashboard/internal/autolearn/steplog.go index aa2726cb..d5936e02 100644 --- a/dashboard/internal/autolearn/steplog.go +++ b/dashboard/internal/autolearn/steplog.go @@ -58,11 +58,13 @@ type StepDay struct { OutWhExport float32 `json:"out_exp"` } -// StepLog haelt die Reglerschritte je Szenario im RAM. Die Aufbewahrung folgt -// days. dir liefert das Basisverzeichnis: dort liegt je Szenario und Tag die -// Datei learnrec/minutes/JJJJ-MM-TT..steps. Leer heisst nur RAM. +// StepLog haelt die Reglerschritte je Szenario im RAM. Die Aufbewahrung der +// Dateien folgt days. Der RAM-Ring haelt ring Tage, standardmaessig days. dir +// liefert das Basisverzeichnis: dort liegt je Szenario und Tag die Datei +// learnrec/minutes/JJJJ-MM-TT..steps. Leer heisst nur RAM. type StepLog struct { days func() int + ring func() int dir func() string now func() time.Time @@ -129,24 +131,36 @@ func (l *StepLog) Add(scenario string, payload []byte) error { return nil } +// WithRingDays setzt die Zahl der Tage im RAM-Ring, getrennt von den Tagen der +// Dateien. Ohne diesen Aufruf zaehlt der Ring wie die Dateien. +func (l *StepLog) WithRingDays(ring func() int) *StepLog { + l.ring = ring + return l +} + // Steps liefert die Schritte des Szenarios mit einem Zeitpunkt von from bis to, -// beide Enden einschliesslich. Aeltere Tage liest es aus den Dateien am Ort, -// die juengeren aus dem RAM. Ohne Ort zaehlt nur das RAM. +// beide Enden einschliesslich. Vor dem Ring liest es aus den Dateien am Ort, im +// Ring aus dem RAM. Ein Schritt vor dem Ring steht im RAM, wenn er noch nicht +// in der Datei steht oder die Datei schon verfallen ist. Ohne Ort zaehlt nur das RAM. func (l *StepLog) Steps(scenario string, from, to time.Time) []Step { - cutoff := l.cutoff(l.now()) + now := l.now() + ringCut := l.ringCutoff(now) + fileCut := l.fileCutoff(now) dir := l.dir() var out []Step - if dir != "" && from.Unix() < cutoff { - out = l.readFiles(dir, scenario, from, to, cutoff) + if dir != "" && from.Unix() < ringCut { + out = l.readFiles(dir, scenario, from, to, ringCut) } l.mu.Lock() defer l.mu.Unlock() - for _, st := range l.steps[scenario] { + written := l.written[scenario] + for i, st := range l.steps[scenario] { if st.At < from.Unix() || st.At > to.Unix() { continue } - if dir != "" && st.At < cutoff { - continue // steht in der Datei oder ist schon verfallen + inFile := dir != "" && st.At < ringCut && i < written && st.At >= fileCut + if inFile { + continue // steht in der Datei, die readFiles liest } out = append(out, st) } @@ -160,7 +174,8 @@ func (l *StepLog) Steps(scenario string, from, to time.Time) []Step { func (l *StepLog) Flush(now time.Time) error { l.flushMu.Lock() defer l.flushMu.Unlock() - cutoff := l.cutoff(now) + ringCut := l.ringCutoff(now) + fileCut := l.fileCutoff(now) dir := l.dir() type job struct { @@ -174,7 +189,9 @@ func (l *StepLog) Flush(now time.Time) error { keep := list[:0] dropped := 0 for i, st := range list { - if st.At < cutoff { + // Ein Schritt vor dem Ring geht, sobald er in der Datei steht. Ohne Ort + // gibt es keine Datei, dort geht er gleich. + if st.At < ringCut && (dir == "" || i < w) { if i < w { dropped++ } @@ -211,7 +228,7 @@ func (l *StepLog) Flush(now time.Time) error { errs = append(errs, err) } } - if err := pruneStepFiles(dir, time.Unix(cutoff, 0).In(time.Local).Format(dayLayout)); err != nil { + if err := pruneStepFiles(dir, time.Unix(fileCut, 0).In(time.Local).Format(dayLayout)); err != nil { errs = append(errs, err) } return errors.Join(errs...) @@ -243,11 +260,24 @@ func (l *StepLog) DayFigures(day string) map[string]*StepDay { return out } -// cutoff ist der Anfang des ersten Tages, den der Ring behaelt. -func (l *StepLog) cutoff(now time.Time) int64 { - n := max(1, l.days()) +// ringCutoff ist der Anfang des ersten Tages, den der RAM-Ring behaelt. +func (l *StepLog) ringCutoff(now time.Time) int64 { + n := l.days() + if l.ring != nil { + n = l.ring() + } + return dayCutoff(now, n) +} + +// fileCutoff ist der Anfang des ersten Tages, dessen Datei am Ort bleibt. +func (l *StepLog) fileCutoff(now time.Time) int64 { + return dayCutoff(now, l.days()) +} + +// dayCutoff ist der Anfang des Tages, der n Tage bis einschliesslich heute zaehlt. +func dayCutoff(now time.Time, n int) int64 { local := now.In(time.Local) - first := time.Date(local.Year(), local.Month(), local.Day()-(n-1), 0, 0, 0, 0, time.Local) + first := time.Date(local.Year(), local.Month(), local.Day()-(max(1, n)-1), 0, 0, 0, 0, time.Local) return first.Unix() } diff --git a/dashboard/internal/autolearn/steplog_test.go b/dashboard/internal/autolearn/steplog_test.go index caf62d7b..cf2f8d93 100644 --- a/dashboard/internal/autolearn/steplog_test.go +++ b/dashboard/internal/autolearn/steplog_test.go @@ -361,3 +361,34 @@ func TestStepLogResetClearsRAMAndStepFiles(t *testing.T) { } } } + +func TestStepLogRingIsBoundedWhileFilesKeepTheirDays(t *testing.T) { + dir := t.TempDir() + now := time.Date(2026, 11, 20, 10, 0, 0, 0, time.Local) + l := NewStepLog(func() int { return 3 }, func() string { return dir }).WithRingDays(func() int { return 1 }) + l.now = func() time.Time { return now } + for _, back := range []int{2, 1, 0} { + at := now.AddDate(0, 0, -back) + if err := l.Add("heizung", stepPayload(float64(at.Unix()), -5, -5, fptr(1200), fptr(1200), "unchanged")); err != nil { + t.Fatal(err) + } + } + // The first flush writes the old days, the second one drops them from the ring. + for i := 0; i < 2; i++ { + if err := l.Flush(now); err != nil { + t.Fatal(err) + } + } + if got := len(l.steps["heizung"]); got != 1 { + t.Fatalf("ring holds %d steps, want only today", got) + } + for _, back := range []int{2, 1} { + day := now.AddDate(0, 0, -back).Format(dayLayout) + if _, err := os.Stat(stepFileName(dir, day, "heizung")); err != nil { + t.Fatalf("file of day -%d missing: %v", back, err) + } + } + if got := l.Steps("heizung", now.AddDate(0, 0, -3), now); len(got) != 3 { + t.Fatalf("Steps = %d, want 3 (two days from files, today from RAM)", len(got)) + } +} From 744091fb8ac201b2134cf361d2225e0357241ea3 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:15:01 +0100 Subject: [PATCH 11/21] feat(dashboard): report the minute recording in learning status The learning status gets a minutes object (resolved settings plus store usage) and a minutes_drive new-hint while an automatic location resolves to the drive and the hint is not acknowledged. The Reset path already clears minutes and steps from 7a. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/learn_minutes.go | 18 ++-- dashboard/cmd/dashboard/main.go | 2 + dashboard/internal/httpapi/learning_status.go | 56 ++++++++++- .../internal/httpapi/learning_status_test.go | 95 +++++++++++++++++++ 4 files changed, 163 insertions(+), 8 deletions(-) diff --git a/dashboard/cmd/dashboard/learn_minutes.go b/dashboard/cmd/dashboard/learn_minutes.go index 4c1c23c4..3a7df40a 100644 --- a/dashboard/cmd/dashboard/learn_minutes.go +++ b/dashboard/cmd/dashboard/learn_minutes.go @@ -20,10 +20,11 @@ const automationServiceID = "automation" // minuteSnapshot ist, was die Minutenaufzeichnung aus Einstellungen, Laufwerk // und Lernstufe braucht. Der Minutenweg liest ihn atomar, ohne Datei und ohne Lock. type minuteSnapshot struct { - plan learnrec.MinutePlan - dirs learnrec.MinuteDirs - driveUp bool - limits learnrec.Limits + plan learnrec.MinutePlan + dirs learnrec.MinuteDirs + driveUp bool + driveConfigured bool + limits learnrec.Limits } // minuteSnapshotFor baut den Schnappschuss. Das Laufwerksverzeichnis ist nur @@ -35,7 +36,7 @@ func minuteSnapshotFor(value settings.Settings, driveUUID string, status storage Location: value.LearningMinutesLocation, Days: value.LearningMinutesDays, }, driveUUID != "") - snap := &minuteSnapshot{plan: plan, dirs: learnrec.MinuteDirs{System: dataDir}, limits: limits} + snap := &minuteSnapshot{plan: plan, dirs: learnrec.MinuteDirs{System: dataDir}, driveConfigured: driveUUID != "", limits: limits} if status.Mode == storage.ModeDrive { snap.driveUp = true snap.dirs.Drive = storage.DriveRuntimeDir(storage.Paths{Mount: mount}) @@ -111,8 +112,11 @@ func (r *minuteRecording) Refresh() { func (r *minuteRecording) plan() learnrec.MinutePlan { return r.snap.Load().plan } func (r *minuteRecording) dirs() learnrec.MinuteDirs { return r.snap.Load().dirs } func (r *minuteRecording) driveUp() bool { return r.snap.Load().driveUp } -func (r *minuteRecording) limits() learnrec.Limits { return r.snap.Load().limits } -func (r *minuteRecording) stepDir() string { return r.snap.Load().stepDir() } + +// DriveConfigured meldet, ob ein Laufwerk eingerichtet ist, wie der Schnappschuss es sieht. +func (r *minuteRecording) DriveConfigured() bool { return r.snap.Load().driveConfigured } +func (r *minuteRecording) limits() learnrec.Limits { return r.snap.Load().limits } +func (r *minuteRecording) stepDir() string { return r.snap.Load().stepDir() } // Flush schreibt Minuten und Schritte an den Ort. Beide laufen, auch wenn der // eine einen Fehler meldet. diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index c4f8e3c3..7393bd28 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -1356,6 +1356,8 @@ func main() { ChainLearnInfo: chainMonitor.LearnedSpan, SetupDone: func() bool { return onboardingStore.Load().SetupDone }, Rules: func() ([]byte, error) { return configManager.Read("automation_rules") }, + Minutes: minutes.store.Usage, + DriveConfigured: minutes.DriveConfigured, Reset: func() error { resetLearned(learnedStore, client) return errors.Join(dayStore.Reset(), reactions.Reset(), chainSuggest.ResetLearned(), chainMonitor.ResetLearned(), suggestions.Reset(), minutes.Reset()) diff --git a/dashboard/internal/httpapi/learning_status.go b/dashboard/internal/httpapi/learning_status.go index d8d0533d..7d33cd76 100644 --- a/dashboard/internal/httpapi/learning_status.go +++ b/dashboard/internal/httpapi/learning_status.go @@ -25,9 +25,17 @@ type LearningDeps struct { // Rules reads the automation rule document. Its site location gives // location_set in the status. Nil or an unreadable document reads as no location. Rules func() ([]byte, error) - Reset func() error + // Minutes reads the minute recording store. Nil reads as nothing recorded. + Minutes func() learnrec.MinuteUsage + // DriveConfigured reports whether a storage drive is set up. It resolves + // the automatic location of the minute recording. Nil reads as no drive. + DriveConfigured func() bool + Reset func() error } +// minutesDriveKey is the new-hint of the minute recording that moved to the drive. +const minutesDriveKey = "minutes_drive" + // learningStatusBody is the answer of GET /api/v1/learning/status. type learningStatusBody struct { Fresh bool `json:"fresh"` @@ -39,6 +47,23 @@ type learningStatusBody struct { Acknowledged []string `json:"acknowledged"` New []string `json:"new"` LocationSet bool `json:"location_set"` + Minutes minutesBody `json:"minutes"` +} + +// minutesBody is the minute recording part of the status. Days and location are +// the resolved settings, the rest is the store's usage. +type minutesBody struct { + On bool `json:"on"` + Location string `json:"location"` + AutoLocation bool `json:"auto_location"` + DriveConfigured bool `json:"drive_configured"` + DriveDown bool `json:"drive_down"` + Days int `json:"days"` + RAMDays int `json:"ram_days"` + Bytes int64 `json:"bytes"` + WrittenPerDay int64 `json:"written_per_day"` + Since int64 `json:"since"` + Keys int `json:"keys"` } type learningFeaturesBody struct { @@ -107,12 +132,40 @@ func learningStatus(value settings.Settings, deps *LearningDeps, cores int) lear "chain_learning": chainLearn.On, "auto_patterns": patterns.On, } + driveConfigured := deps.DriveConfigured != nil && deps.DriveConfigured() + plan := learnrec.ResolveMinutes(learnrec.MinuteSettings{ + Mode: value.LearningMinutesMode, + Location: value.LearningMinutesLocation, + Days: value.LearningMinutesDays, + }, driveConfigured) + minutes := minutesBody{ + On: plan.On, + Location: string(plan.Location), + AutoLocation: plan.AutoLocation, + DriveConfigured: driveConfigured, + Days: plan.Days, + } + if deps.Minutes != nil { + store := deps.Minutes() + minutes.DriveDown = store.DriveDown + minutes.RAMDays = store.RAMDays + minutes.Bytes = store.Bytes + minutes.WrittenPerDay = store.WrittenPerDay + minutes.Since = store.Since + minutes.Keys = store.Keys + } + news := []string{} for _, key := range settings.LearningFeatures() { if features[key] && !learningAcknowledged(acknowledged, key) { news = append(news, key) } } + // The minute recording moved to the drive by itself (automatic location, not + // acknowledged yet). An explicit location never gives this hint. + if plan.On && plan.AutoLocation && plan.Location == learnrec.LocDrive && !learningAcknowledged(acknowledged, minutesDriveKey) { + news = append(news, minutesDriveKey) + } fresh := false var remembered learnrec.Level @@ -138,6 +191,7 @@ func learningStatus(value settings.Settings, deps *LearningDeps, cores int) lear Acknowledged: acknowledged, New: news, LocationSet: locationSet, + Minutes: minutes, } } diff --git a/dashboard/internal/httpapi/learning_status_test.go b/dashboard/internal/httpapi/learning_status_test.go index 0f80070e..bec2c802 100644 --- a/dashboard/internal/httpapi/learning_status_test.go +++ b/dashboard/internal/httpapi/learning_status_test.go @@ -7,6 +7,7 @@ import ( "net/http/httptest" "path/filepath" "reflect" + "slices" "strings" "testing" @@ -23,6 +24,8 @@ type fakeLearning struct { value settings.Settings state learnrec.State usage autolearn.Usage + minutes learnrec.MinuteUsage + driveOK bool chainS [2]int64 chainL [2]int64 setup bool @@ -39,6 +42,8 @@ func (f *fakeLearning) deps() *LearningDeps { ChainSuggestInfo: func() (int64, int) { return f.chainS[0], int(f.chainS[1]) }, ChainLearnInfo: func() (int64, int) { return f.chainL[0], int(f.chainL[1]) }, SetupDone: func() bool { return f.setup }, + Minutes: func() learnrec.MinuteUsage { return f.minutes }, + DriveConfigured: func() bool { return f.driveOK }, Reset: func() error { f.resets++ if f.resetErr != nil { @@ -309,3 +314,93 @@ func TestLearningWithoutDepsAnswers501(t *testing.T) { t.Fatalf("status without deps: %d, want 501", recorder.Code) } } + +func TestLearningStatusMinutesWithoutDriveIsRAM(t *testing.T) { + got := learningStatus(settings.Settings{}, &LearningDeps{}, 1) + if got.Minutes.Location != "ram" || !got.Minutes.AutoLocation || got.Minutes.DriveConfigured { + t.Fatalf("minutes without drive = %+v, want ram, auto_location, no drive", got.Minutes) + } + if !got.Minutes.On || got.Minutes.Days != learnrec.MinuteDaysDefault { + t.Fatalf("minutes on/days = %v/%d, want on and %d days", got.Minutes.On, got.Minutes.Days, learnrec.MinuteDaysDefault) + } + if slices.Contains(got.New, minutesDriveKey) { + t.Fatalf("new = %v, want no %s without drive", got.New, minutesDriveKey) + } +} + +func TestLearningStatusMinutesDriveAutoIsNewUntilAcknowledged(t *testing.T) { + deps := &LearningDeps{DriveConfigured: func() bool { return true }} + got := learningStatus(settings.Settings{}, deps, 1) + if got.Minutes.Location != "drive" || !got.Minutes.AutoLocation || !got.Minutes.DriveConfigured { + t.Fatalf("minutes with drive and auto = %+v, want drive, auto_location", got.Minutes) + } + if !slices.Contains(got.New, minutesDriveKey) { + t.Fatalf("new = %v, want %s", got.New, minutesDriveKey) + } + + acknowledged := settings.Settings{LearningAcknowledged: []string{minutesDriveKey}} + if got := learningStatus(acknowledged, deps, 1); slices.Contains(got.New, minutesDriveKey) { + t.Fatalf("acknowledged: new = %v, want no %s", got.New, minutesDriveKey) + } +} + +func TestLearningStatusMinutesExplicitLocationGivesNoHint(t *testing.T) { + deps := &LearningDeps{DriveConfigured: func() bool { return true }} + for _, location := range []string{"ram", "system", "drive"} { + got := learningStatus(settings.Settings{LearningMinutesLocation: location}, deps, 1) + if got.Minutes.AutoLocation { + t.Errorf("location %s: auto_location = true", location) + } + if slices.Contains(got.New, minutesDriveKey) { + t.Errorf("location %s: new = %v, want no %s", location, got.New, minutesDriveKey) + } + } +} + +func TestLearningStatusMinutesOffGivesNoHint(t *testing.T) { + deps := &LearningDeps{DriveConfigured: func() bool { return true }} + got := learningStatus(settings.Settings{LearningMinutesMode: "off"}, deps, 1) + if got.Minutes.On { + t.Fatal("mode off: on = true") + } + if slices.Contains(got.New, minutesDriveKey) { + t.Fatalf("mode off: new = %v, want no %s", got.New, minutesDriveKey) + } +} + +func TestLearningStatusMinutesUsageFields(t *testing.T) { + fake := &fakeLearning{ + driveOK: true, + minutes: learnrec.MinuteUsage{Bytes: 4096, WrittenPerDay: 512, Since: 1794000000, Keys: 7, RAMDays: 3, DriveDown: true}, + } + router, manager := learningTestRouter(t, fake.deps()) + cookie, _ := loginWithRoles(t, router, manager, "automata", []string{auth.RoleViewAutomations}) + + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, sessionRequest(t, "/api/v1/learning/status", cookie, true)) + if recorder.Code != http.StatusOK { + t.Fatalf("status: %d %s", recorder.Code, recorder.Body.String()) + } + var got struct { + Minutes map[string]any `json:"minutes"` + } + if err := json.NewDecoder(recorder.Body).Decode(&got); err != nil { + t.Fatal(err) + } + want := map[string]any{ + "on": true, "location": "drive", "auto_location": true, "drive_configured": true, + "drive_down": true, "days": float64(learnrec.MinuteDaysDefault), "ram_days": float64(3), + "bytes": float64(4096), "written_per_day": float64(512), "since": float64(1794000000), "keys": float64(7), + } + if !reflect.DeepEqual(got.Minutes, want) { + t.Fatalf("minutes = %v\nwant %v", got.Minutes, want) + } +} + +func TestLearningMinutesSettingsNeedEditSetup(t *testing.T) { + for _, key := range []string{"learning_minutes_mode", "learning_minutes_location", "learning_minutes_days"} { + if got := settingsFieldRoles[key]; got != auth.RoleEditSetup { + t.Errorf("%s: role %q, want %q", key, got, auth.RoleEditSetup) + } + } +} From 81d9b0957a3b0bdb7a6e380e063d8280680fcd91 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:15:37 +0100 Subject: [PATCH 12/21] feat(settings): add the texts for the minute recording card Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 19 +++++++++++++++++++ dashboard/internal/webui/catalogs/en.json | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index dbb3bbf9..51622798 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -4465,6 +4465,25 @@ "settings.learning.location.action": "Eintragen", "settings.learning.location.title": "Standort fehlt", "settings.learning.location.why": "Ohne Standort kennt das Lernen keine Sonnenzeiten, Schaltzeiten rechnen dann nach der Uhr.", + "settings.learning.minutes.days": "Minutenwerte aufbewahren", + "settings.learning.minutes.days_decrease": "Aufbewahrung der Minutenwerte verringern", + "settings.learning.minutes.days_increase": "Aufbewahrung der Minutenwerte erhöhen", + "settings.learning.minutes.drive_down": "Laufwerk nicht verfügbar, zeichnet im Arbeitsspeicher weiter", + "settings.learning.minutes.loc.drive": "Zusatzlaufwerk", + "settings.learning.minutes.loc.drive_none": "Noch kein Laufwerk eingerichtet", + "settings.learning.minutes.loc.drive_pill": "empfohlen", + "settings.learning.minutes.loc.drive_setup": "Einrichten ›", + "settings.learning.minutes.loc.drive_sub": "{free} frei", + "settings.learning.minutes.loc.ram": "Arbeitsspeicher", + "settings.learning.minutes.loc.ram_sub": "Hält {days} Tage, geht beim Neustart verloren", + "settings.learning.minutes.loc.system": "Systemlaufwerk", + "settings.learning.minutes.loc.system_sub": "Schreibt etwa {mb} MB am Tag auf die SD-Karte", + "settings.learning.minutes.new_drive": "Ein Zusatzlaufwerk ist eingerichtet. Minutenwerte werden jetzt dort aufbewahrt.", + "settings.learning.minutes.new_keep": "Behalten", + "settings.learning.minutes.toggle": "Minutenwerte aufzeichnen", + "settings.learning.minutes.toggle_note": "Die Node merkt sich Leistungen und Bilanz je Minute. So lernt sie genauer und holt nach einem Neustart verpasste Minuten nach.", + "settings.learning.minutes.usage": "Belegt {size}, schreibt {mb} MB am Tag", + "settings.learning.minutes.where": "Ort der Minutenwerte", "settings.learning.new.body_fresh": "Die Node lernt von Anfang an aus deinen Geräten.", "settings.learning.new.body_update": "Sie sind mit dem letzten Update dazugekommen.", "settings.learning.new.fresh_title.one": "Eine Lernfunktion ist aktiv", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index d29436ff..77225b18 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -4465,6 +4465,25 @@ "settings.learning.location.action": "Add", "settings.learning.location.title": "Location missing", "settings.learning.location.why": "Without a location, learning has no sun times and switching times follow the clock.", + "settings.learning.minutes.days": "Keep minute values", + "settings.learning.minutes.days_decrease": "Decrease retention of minute values", + "settings.learning.minutes.days_increase": "Increase retention of minute values", + "settings.learning.minutes.drive_down": "Drive unavailable, recording continues in memory", + "settings.learning.minutes.loc.drive": "Extra drive", + "settings.learning.minutes.loc.drive_none": "No drive set up yet", + "settings.learning.minutes.loc.drive_pill": "recommended", + "settings.learning.minutes.loc.drive_setup": "Set up ›", + "settings.learning.minutes.loc.drive_sub": "{free} free", + "settings.learning.minutes.loc.ram": "Memory", + "settings.learning.minutes.loc.ram_sub": "Holds {days} days, lost on restart", + "settings.learning.minutes.loc.system": "System drive", + "settings.learning.minutes.loc.system_sub": "Writes about {mb} MB a day to the SD card", + "settings.learning.minutes.new_drive": "An extra drive is set up. Minute values are now kept there.", + "settings.learning.minutes.new_keep": "Keep", + "settings.learning.minutes.toggle": "Record minute values", + "settings.learning.minutes.toggle_note": "The node remembers power and balance for every minute. This lets it learn more precisely and catch up on missed minutes after a restart.", + "settings.learning.minutes.usage": "Uses {size}, writes {mb} MB a day", + "settings.learning.minutes.where": "Where minute values are kept", "settings.learning.new.body_fresh": "The node learns from your devices from the start.", "settings.learning.new.body_update": "You got them with the latest update.", "settings.learning.new.fresh_title.one": "One learning feature is on", From d6e14c7a862987cb544f5dc93e173cdaa0a96e6a Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:19:14 +0100 Subject: [PATCH 13/21] feat(settings): choose where minute values are kept The learning record card gets the minute recording block above the profile days: a switch for the recording, three location rows (RAM, drive, system) with their sub lines, a stepper for the days on drive and system, the usage line and the hint when the minutes moved to a newly set up drive. Choosing a row writes the location explicitly. Everything is disabled without edit_setup. Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/css/learning-settings.css | 18 ++++ .../webui/static/js/learning-settings.js | 91 ++++++++++++++++++- .../internal/webui/static/js/settings.page.js | 14 ++- .../internal/webui/templates/settings.html | 48 ++++++++++ dashboard/test/learning-settings.test.mjs | 79 ++++++++++++++++ 5 files changed, 247 insertions(+), 3 deletions(-) diff --git a/dashboard/internal/webui/static/css/learning-settings.css b/dashboard/internal/webui/static/css/learning-settings.css index 58f676ba..ba9a3025 100644 --- a/dashboard/internal/webui/static/css/learning-settings.css +++ b/dashboard/internal/webui/static/css/learning-settings.css @@ -96,3 +96,21 @@ @media (max-width: 30rem) { .learn-hint .learn-pick-action { display: none; } } + +/* Ort der Minutenwerte: Radiozeilen auf der Karte Aufzeichnung. Das Radio + sitzt unsichtbar im Label, die Zeile zeigt den Punkt und den Rahmen. */ +.learn-radio-group { display: grid; gap: 0; } +.learn-radio-row { flex-wrap: wrap; } +.learn-radio-row.is-checked { border-color: var(--accent-line); } +.learn-radio-row:focus-within { outline: 2px solid var(--accent); outline-offset: 2px; } +.learn-radio-label { box-sizing: border-box; flex: 1 1 12rem; display: flex; align-items: center; gap: .6rem; min-width: 0; cursor: pointer; } +.learn-radio-label:has(input:disabled) { cursor: not-allowed; } +.learn-radio-dot { flex: none; width: .95rem; height: .95rem; border: 2px solid var(--border); border-radius: 50%; box-sizing: border-box; } +.learn-radio-row.is-checked .learn-radio-dot { border-color: var(--accent-line); + background: radial-gradient(circle, var(--accent-line) 0 40%, transparent 46%); } +.learn-radio-row.is-unavailable { opacity: .55; } +.learn-radio-row .learn-link { flex: none; margin: 0; } +.learn-minutes-hint { margin: .2rem 0 .7rem; } +@media (prefers-reduced-motion: reduce) { + .learn-radio-dot { transition: none; } +} diff --git a/dashboard/internal/webui/static/js/learning-settings.js b/dashboard/internal/webui/static/js/learning-settings.js index 918f4352..ee7d5528 100644 --- a/dashboard/internal/webui/static/js/learning-settings.js +++ b/dashboard/internal/webui/static/js/learning-settings.js @@ -49,7 +49,43 @@ return fresh.filter(key => Boolean(features[key] && features[key].on)); } - window.LearningSettings = {usageText, sinceText, newFeatures}; + // Minutenwerte (status.minutes). Schluessel und Schreibmenge wie in learnrec: + // 1440 Minuten am Tag, 4 Bytes je Wert. + const MINUTES_PER_DAY = 1440; + const BYTES_PER_VALUE = 4; + const MINUTES_DRIVE_KEY = 'minutes_drive'; + const MINUTE_LOCATIONS = ['ram', 'drive', 'system']; + + // Ort der Aufzeichnung: eine gewaehlte Zeile gilt, bei "auto" der aufgeloeste Ort aus dem Status. + function minutesLocation(choice, status) { + if (MINUTE_LOCATIONS.includes(choice)) return choice; + const resolved = status && status.minutes && status.minutes.location; + return MINUTE_LOCATIONS.includes(resolved) ? resolved : 'ram'; + } + + // Freier Platz des Zusatzlaufwerks aus GET /api/v1/storage/status (drive.size, drive.used). + function driveFreeBytes(storageStatus) { + const drive = storageStatus && storageStatus.drive; + const size = Number(drive && drive.size) || 0; + if (size <= 0) return 0; + return Math.max(0, size - (Number(drive.used) || 0)); + } + + // Schreibmenge am Tag fuer die Zeile Systemlaufwerk: Schluessel mal Minuten + // mal Bytes, mindestens die gemessene Rate. + function systemBytesPerDay(minutes) { + const keys = Math.max(0, Number(minutes && minutes.keys) || 0); + const measured = Math.max(0, Number(minutes && minutes.written_per_day) || 0); + return Math.max(keys * MINUTES_PER_DAY * BYTES_PER_VALUE, measured); + } + + // Nur die Zahl in MB, die Einheit steht im Satz. Unter 10 MB mit einer Nachkommastelle. + function mbNumber(bytes) { + const mb = Math.max(0, Number(bytes) || 0) / MB; + return numberText(mb, mb < 10 ? 1 : 0); + } + + window.LearningSettings = {usageText, sinceText, newFeatures, minutesLocation, driveFreeBytes, systemBytesPerDay, mbNumber}; // Gleiche Anfrage wie in settings.page.js: Basispfad vor die URL, JSON zurueck. const requestJSON = async (url, options) => { @@ -107,6 +143,8 @@ // Standort ist in den Automationen eingetragen (status.location_set). Solange // der Stand nicht geladen ist, bleibt der Hinweis verborgen. location_set: true, + // Freier Platz des Zusatzlaufwerks (GET /api/v1/storage/status), null solange nicht geladen. + storageStatus: null, // Die Auswahl gehoert der Seite (settings.page.js, speichert sie). Diese // Seite bekommt den Stand beim Laden und meldet jede Aenderung zurueck. @@ -175,13 +213,15 @@ this.loading = true; this.error = ''; try { - const [status, session, settings, devices] = await Promise.all([ + const [status, session, settings, devices, storageStatus] = await Promise.all([ requestJSON('/api/v1/learning/status'), requestJSON('/api/v1/auth/session').catch(() => null), requestJSON('/api/v1/settings').catch(() => null), requestJSON('/api/v1/devices').catch(() => null), + requestJSON('/api/v1/storage/status').catch(() => null), ]); this.status = status; + this.storageStatus = storageStatus; this.csrfToken = (session && session.csrf_token) || ''; this.learnCanEdit = session ? session.edit_setup === true : true; this.automation_outdoor_entity = settings && typeof settings.automation_outdoor_entity === 'string' ? settings.automation_outdoor_entity : ''; @@ -212,6 +252,53 @@ return usageText(this.status && this.status.usage, t); }, + // Aufzeichnung der Minutenwerte. Die Auswahl (Modus, Ort, Tage) steht in den + // Einstellungen der Seite; hier kommen nur der Status und die Texte dazu. + minutesLocationOf(choice) { + return minutesLocation(choice, this.status); + }, + + get minutesMeta() { + return (this.status && this.status.minutes) || {}; + }, + + get minutesDriveConfigured() { + return Boolean(this.minutesMeta.drive_configured); + }, + + get minutesDriveDown() { + return Boolean(this.minutesMeta.drive_down); + }, + + // Der Hinweis "neu aktiv" zum Laufwerk. Er steht nicht in newKeys, weil er + // keine Lernfunktion mit Schalter ist. + get minutesDriveNew() { + return Array.isArray(this.status && this.status.new) && this.status.new.includes(MINUTES_DRIVE_KEY); + }, + + get minutesUsage() { + const minutes = this.minutesMeta; + return t('settings.learning.minutes.usage', {size: sizeText(minutes.bytes || 0, t), mb: mbNumber(minutes.written_per_day)}); + }, + + get minutesUsageVisible() { + return Number(this.minutesMeta.bytes) > 0; + }, + + minutesDriveSub() { + return t('settings.learning.minutes.loc.drive_sub', {free: sizeText(driveFreeBytes(this.storageStatus), t)}); + }, + + // Die Tage im RAM kommen aus dem Status, ohne Status die Tage der Einstellung. + minutesRamSub(days) { + const ram = Number(this.minutesMeta.ram_days) || Number(days) || 0; + return t('settings.learning.minutes.loc.ram_sub', {days: numberText(ram, 0)}); + }, + + minutesSystemSub() { + return t('settings.learning.minutes.loc.system_sub', {mb: mbNumber(systemBytesPerDay(this.minutesMeta))}); + }, + get newKeys() { return newFeatures(this.status); }, diff --git a/dashboard/internal/webui/static/js/settings.page.js b/dashboard/internal/webui/static/js/settings.page.js index 77ac22ef..3e522dfd 100644 --- a/dashboard/internal/webui/static/js/settings.page.js +++ b/dashboard/internal/webui/static/js/settings.page.js @@ -44,6 +44,7 @@ historyRetentionHours: {min: 1, max: 8760, step: 1}, historyBudgetMb: {min: 16, max: 8192, step: 16}, learningProfileDays: {min: 14, max: 365, step: 7}, + learningMinutesDays: {min: 1, max: 365, step: 1}, }; const settingsPanel = () => ({ @@ -92,6 +93,10 @@ learningSeasonYearDisabled: false, learningExcludedDevices: [], learningProfileDays: 56, + // Aufzeichnung der Minutenwerte: Modus auto/always/off, Ort auto/ram/drive/system, Tage 1 bis 365. + learningMinutesMode: 'auto', + learningMinutesLocation: 'auto', + learningMinutesDays: 60, learningAcknowledged: [], learningLevel: '', energyStatsRecording: 'always', @@ -229,6 +234,9 @@ this.learningSeasonYearDisabled = Boolean(value.learning_season_year_disabled); this.learningExcludedDevices = Array.isArray(value.learning_excluded_devices) ? [...value.learning_excluded_devices] : []; this.learningProfileDays = Number(value.learning_profile_days) || 56; + this.learningMinutesMode = ['auto', 'always', 'off'].includes(value.learning_minutes_mode) ? value.learning_minutes_mode : 'auto'; + this.learningMinutesLocation = ['auto', 'ram', 'drive', 'system'].includes(value.learning_minutes_location) ? value.learning_minutes_location : 'auto'; + this.learningMinutesDays = Number(value.learning_minutes_days) || 60; this.learningAcknowledged = Array.isArray(value.learning_acknowledged) ? [...value.learning_acknowledged] : []; this.learningLevel = typeof value.learning_level === 'string' ? value.learning_level : ''; window.dispatchEvent(new CustomEvent('settings-learning-loaded', {detail: {ids: [...this.learningExcludedDevices]}})); @@ -652,7 +660,8 @@ this.liveUpdateIntervalSeconds >= 1 && this.liveUpdateIntervalSeconds <= 60 && this.historySampleIntervalSeconds >= 5 && this.historySampleIntervalSeconds <= 3600 && this.historyRetentionHours >= 1 && this.historyBudgetMb >= 16 && - this.learningProfileDays >= 14 && this.learningProfileDays <= 365; + this.learningProfileDays >= 14 && this.learningProfileDays <= 365 && + this.learningMinutesDays >= 1 && this.learningMinutesDays <= 365; }, payload() { @@ -684,6 +693,9 @@ learning_season_year_disabled: Boolean(this.learningSeasonYearDisabled), learning_excluded_devices: [...this.learningExcludedDevices], learning_profile_days: Number(this.learningProfileDays), + learning_minutes_mode: this.learningMinutesMode, + learning_minutes_location: this.learningMinutesLocation, + learning_minutes_days: Number(this.learningMinutesDays), learning_acknowledged: [...this.learningAcknowledged], learning_level: this.learningLevel, history_views: [...this.historyViews], diff --git a/dashboard/internal/webui/templates/settings.html b/dashboard/internal/webui/templates/settings.html index bd77ce26..8bba1cb3 100644 --- a/dashboard/internal/webui/templates/settings.html +++ b/dashboard/internal/webui/templates/settings.html @@ -250,6 +250,54 @@

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

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

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

+
+ +
{{t "settings.learning.minutes.new_drive"}}
+ +
+ +

{{t "settings.learning.minutes.toggle_note"}}

+ {{t "settings.learning.minutes.where"}} +
+
+ +
+
+ + +
+
+ +
+
+
+ {{t "settings.learning.minutes.days"}} {{t "settings.unit.days"}} + + + + + +
+

+

{{t "settings.learning.minutes.drive_down"}}

{{t "settings.learning.record.days"}} {{t "settings.unit.days"}} diff --git a/dashboard/test/learning-settings.test.mjs b/dashboard/test/learning-settings.test.mjs index 68000cdd..a6636eed 100644 --- a/dashboard/test/learning-settings.test.mjs +++ b/dashboard/test/learning-settings.test.mjs @@ -336,3 +336,82 @@ test('the location action opens the automations panel', () => { assert.equal(seen.length, 1); assert.equal(seen[0].panel, 'automations-panel'); }); + +// Aufzeichnung der Minutenwerte: Ort, Stepper, Verbrauch und der Hinweis zum Laufwerk. +const minutesStatus = (minutes, extra = {}) => ({ + ...statusBody, + minutes: { on: true, location: 'ram', auto_location: false, drive_configured: false, drive_down: false, days: 60, ram_days: 14, bytes: 412000, written_per_day: 0, since: 0, keys: 20, ...minutes }, + ...extra, +}); +const minutesRoutes = (status, storage = null) => ({ + '/api/v1/learning/status': status, + '/api/v1/auth/session': { csrf_token: 'tok', roles: [] }, + '/api/v1/storage/status': storage || { drive: { size: 0, used: 0 } }, + '/api/v1/settings': { learning_acknowledged: [] }, +}); + +test('the RAM choice ignores the stepper and "auto" follows the resolved location', async () => { + const { page } = createPage({ routes: minutesRoutes(minutesStatus({ location: 'ram' })) }); + await page.load(); + assert.equal(page.minutesLocationOf('auto'), 'ram'); + assert.equal(page.minutesLocationOf('drive'), 'drive'); + assert.equal(page.minutesLocationOf('system'), 'system'); + assert.equal(page.minutesLocationOf('bogus'), 'ram'); +}); + +test('without a drive the drive row is unavailable and the setup text names the next step', async () => { + const { page } = createPage({ routes: minutesRoutes(minutesStatus({ drive_configured: false })) }); + await page.load(); + assert.equal(page.minutesDriveConfigured, false); + assert.equal(page.minutesRamSub(60), 'Hält 14 Tage, geht beim Neustart verloren'); +}); + +test('with a drive the drive sub line shows the free space', async () => { + const storage = { drive: { size: 800_000_000, used: 200_000_000 } }; + const { page } = createPage({ routes: minutesRoutes(minutesStatus({ drive_configured: true, location: 'drive' }), storage) }); + await page.load(); + assert.equal(page.minutesDriveConfigured, true); + assert.equal(page.minutesDriveSub(), '600,0 MB frei'); +}); + +test('the system estimate uses the keys and 1440 minutes at 4 bytes each', () => { + const window = load(new JSDOM('', { runScripts: 'outside-only' })); + const { systemBytesPerDay, mbNumber } = window.LearningSettings; + // 20 Schluessel, 1440 Minuten, 4 Bytes: 115200 Bytes am Tag. + assert.equal(systemBytesPerDay({ keys: 20, written_per_day: 0 }), 115200); + assert.equal(systemBytesPerDay({ keys: 20, written_per_day: 500000 }), 500000); + assert.equal(mbNumber(115200), '0,1'); + assert.equal(mbNumber(12_000_000), '12'); +}); + +test('the minute usage line states the size and the daily write', async () => { + const { page } = createPage({ routes: minutesRoutes(minutesStatus({ bytes: 412000, written_per_day: 96000 })) }); + await page.load(); + assert.equal(page.minutesUsage, 'Belegt 0,4 MB, schreibt 0,1 MB am Tag'); +}); + +test('the minutes_drive hint is not a feature pill and stays out of the generic hint', async () => { + const status = minutesStatus({ location: 'drive', auto_location: true, drive_configured: true }, { new: ['minutes_drive'], setup_done: true }); + const { page } = createPage({ routes: minutesRoutes(status) }); + await page.load(); + assert.equal(page.minutesDriveNew, true); + assert.deepEqual([...page.newKeys], []); + assert.equal(page.newHintVisible, false); +}); + +test('"Behalten" acknowledges minutes_drive with the CSRF header and reloads', async () => { + const status = minutesStatus({ location: 'drive', auto_location: true, drive_configured: true }, { new: ['minutes_drive'], setup_done: true, acknowledged: [] }); + const { page, calls } = createPage({ + routes: { + ...minutesRoutes(status), + 'PUT /api/v1/settings': { ok: true }, + }, + }); + await page.load(); + calls.length = 0; + await page.acknowledge(['minutes_drive']); + const save = calls.find(call => call.method !== 'GET'); + assert.ok(save, 'a settings write happened'); + assert.equal(save.headers['X-CSRF-Token'], 'tok'); + assert.ok(save.body.includes('minutes_drive'), save.body); +}); From 2c55808f7ea762f6df34191167f548d82d48f92d Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:20:13 +0100 Subject: [PATCH 14/21] fix(settings): format the drive free space in GB The drive row of the minute recording showed the free space in MB ("6000,0 MB frei"). It now uses GB and TB with one decimal from 1000 MB upward, the same 1000 steps as the storage page. Co-Authored-By: Claude Sonnet 5.5 --- .../internal/webui/static/js/learning-settings.js | 15 +++++++++++++-- dashboard/test/learning-settings.test.mjs | 15 +++++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/dashboard/internal/webui/static/js/learning-settings.js b/dashboard/internal/webui/static/js/learning-settings.js index ee7d5528..13a44218 100644 --- a/dashboard/internal/webui/static/js/learning-settings.js +++ b/dashboard/internal/webui/static/js/learning-settings.js @@ -79,13 +79,24 @@ return Math.max(keys * MINUTES_PER_DAY * BYTES_PER_VALUE, measured); } + // Groesse fuer die Zeile Zusatzlaufwerk: Einheiten ab 1000, GB und TB mit einer + // Nachkommastelle, wie formatStorageBytes auf der Speicherseite (dort eine + // Methode, deshalb hier eigene Kopie der Regel). + function driveSizeText(bytes) { + const units = ['B', 'KB', 'MB', 'GB', 'TB']; + let amount = Math.max(0, Number(bytes) || 0); + let unit = 0; + while (amount >= 1000 && unit < units.length - 1) { amount /= 1000; unit += 1; } + return `${numberText(amount, unit >= 3 ? 1 : 0)} ${units[unit]}`; + } + // Nur die Zahl in MB, die Einheit steht im Satz. Unter 10 MB mit einer Nachkommastelle. function mbNumber(bytes) { const mb = Math.max(0, Number(bytes) || 0) / MB; return numberText(mb, mb < 10 ? 1 : 0); } - window.LearningSettings = {usageText, sinceText, newFeatures, minutesLocation, driveFreeBytes, systemBytesPerDay, mbNumber}; + window.LearningSettings = {usageText, sinceText, newFeatures, minutesLocation, driveFreeBytes, driveSizeText, systemBytesPerDay, mbNumber}; // Gleiche Anfrage wie in settings.page.js: Basispfad vor die URL, JSON zurueck. const requestJSON = async (url, options) => { @@ -286,7 +297,7 @@ }, minutesDriveSub() { - return t('settings.learning.minutes.loc.drive_sub', {free: sizeText(driveFreeBytes(this.storageStatus), t)}); + return t('settings.learning.minutes.loc.drive_sub', {free: driveSizeText(driveFreeBytes(this.storageStatus))}); }, // Die Tage im RAM kommen aus dem Status, ohne Status die Tage der Einstellung. diff --git a/dashboard/test/learning-settings.test.mjs b/dashboard/test/learning-settings.test.mjs index a6636eed..bad60190 100644 --- a/dashboard/test/learning-settings.test.mjs +++ b/dashboard/test/learning-settings.test.mjs @@ -367,11 +367,11 @@ test('without a drive the drive row is unavailable and the setup text names the }); test('with a drive the drive sub line shows the free space', async () => { - const storage = { drive: { size: 800_000_000, used: 200_000_000 } }; + const storage = { drive: { size: 8_000_000_000, used: 2_000_000_000 } }; const { page } = createPage({ routes: minutesRoutes(minutesStatus({ drive_configured: true, location: 'drive' }), storage) }); await page.load(); assert.equal(page.minutesDriveConfigured, true); - assert.equal(page.minutesDriveSub(), '600,0 MB frei'); + assert.equal(page.minutesDriveSub(), '6,0 GB frei'); }); test('the system estimate uses the keys and 1440 minutes at 4 bytes each', () => { @@ -415,3 +415,14 @@ test('"Behalten" acknowledges minutes_drive with the CSRF header and reloads', a assert.equal(save.headers['X-CSRF-Token'], 'tok'); assert.ok(save.body.includes('minutes_drive'), save.body); }); + +test('driveSizeText uses 1000 steps, GB and TB with one decimal and MB without', () => { + const window = load(new JSDOM('', { runScripts: 'outside-only' })); + const { driveSizeText } = window.LearningSettings; + assert.equal(driveSizeText(600_000_000), '600 MB'); + assert.equal(driveSizeText(999_000_000), '999 MB'); + assert.equal(driveSizeText(1_000_000_000), '1,0 GB'); + assert.equal(driveSizeText(6_500_000_000), '6,5 GB'); + assert.equal(driveSizeText(2_000_000_000_000), '2,0 TB'); + assert.equal(driveSizeText(0), '0 B'); +}); From 956b55969e8f85ecd5336464361c6118fe0d7116 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:22:58 +0100 Subject: [PATCH 15/21] feat(autolearn): seed minute values and regulator steps in the demo The demo writes three days of minute values (device power, balance and outdoor temperature) into learnrec/minutes under the data directory, and the regulator steps of the nulleinspeisung scenario for the last day. Existing files are kept, so a second seed writes the same bytes. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 5 + dashboard/internal/autolearn/demo.go | 165 ++++++++++++++++++++++ dashboard/internal/autolearn/demo_test.go | 63 +++++++++ 3 files changed, 233 insertions(+) diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 7393bd28..6481f343 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -507,6 +507,11 @@ func main() { log.Printf("autolearn: demo profiles written to %s", demoDir) } } + // Die Minutenaufzeichnung liegt im Datenordner, dort liest der MinuteStore sie + // am Ort System. Die Demo schreibt sie bei jedem Start, vorhandene Dateien bleiben. + if err := autolearn.SeedDemoMinutes(dataDir, time.Now(), time.Local); err != nil { + log.Printf("autolearn: demo minutes: %v", err) + } } // PV-Himmelsraster: nur ungedrosselte PV-Minuten zaehlen. Standort und Regler // kommen aus dem Regelwerk, das pvSite.refresh nur beim Speichern liest. diff --git a/dashboard/internal/autolearn/demo.go b/dashboard/internal/autolearn/demo.go index 422e4505..d41859b1 100644 --- a/dashboard/internal/autolearn/demo.go +++ b/dashboard/internal/autolearn/demo.go @@ -1,13 +1,16 @@ package autolearn import ( + "bytes" "fmt" "math" "math/rand" "os" + "path/filepath" "sort" "time" + "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" "github.com/Developer-Simon/energy-node-dashboard/internal/sun" ) @@ -746,3 +749,165 @@ func WithDemoHouseState(vals []Value) []Value { out = append(out, vals...) return append(out, Value{Key: "site/house_state", Kind: ValueState, Group: "habit", Text: "quiet", N: demoHouseStateDays}) } + +// Die Minutenaufzeichnung der Demo: die letzten drei Tage vor dem heutigen Tag +// mit Leistung je Gerät, Bilanz und Außentemperatur, dazu am letzten Tag die +// Reglerschritte des Szenarios der Demo. Die Dateien tragen keine Kennzeichnung, +// sie liegen im Datenordner der Demo und verschwinden mit dessen Zurücksetzen. +const ( + demoMinuteDays = 3 + // demoStepScenario ist das Szenario der Demo, das den Regler fährt (Nulleinspeisung). + demoStepScenario = "nulleinspeisung" + // demoStepEveryMin ist der Abstand der Reglerschritte in Minuten, von 06:00 bis 20:00. + demoStepEveryMin = 2 + // demoStepTargetW ist der Zielwert der Nulleinspeisung, und demoStepDeadbandW + // die Totzone um ihn, wie in der Regel der Demo. + demoStepTargetW = -30.0 + demoStepDeadbandW = 20.0 + // demoStepLimitMin und demoStepLimitMax sind die Grenzen des Stellwerts in W. + demoStepLimitMin = 50.0 + demoStepLimitMax = 800.0 + // demoStepGain ist der Verstärkungsfaktor des Reglers der Demo. + demoStepGain = 0.8 +) + +// SeedDemoMinutes schreibt die Minutenaufzeichnung der Demo nach dataDir, in +// /learnrec/minutes: je Tag eine Datei mit den Minuten, am letzten Tag +// zusätzlich die Reglerschritte des Szenarios. Vorhandene Dateien bleiben +// unberührt, derselbe Aufruf schreibt dieselben Bytes. +func SeedDemoMinutes(dataDir string, now time.Time, loc *time.Location) error { + if loc == nil { + loc = time.Local + } + days := demoDays(now.In(loc), loc) + rng := rand.New(rand.NewSource(demoSeed + 4)) + for i := demoSeedDays - demoMinuteDays; i < demoSeedDays; i++ { + f := days[i] + path := minuteFileName(dataDir, f.Day) + if err := seedMinuteDay(path, f); err != nil { + return fmt.Errorf("autolearn: demo minutes: %w", err) + } + if i == demoSeedDays-1 { + if err := seedDemoSteps(dataDir, f, loc, rng); err != nil { + return fmt.Errorf("autolearn: demo steps: %w", err) + } + } + } + return nil +} + +// minuteFileName ist die Minutendatei eines Tages am Basisverzeichnis dir. +func minuteFileName(dir, day string) string { + return filepath.Join(dir, "learnrec", "minutes", day+".enm") +} + +// seedMinuteDay schreibt die Minuten eines Demo-Tages in path, wenn die Datei fehlt. +// Je Viertelstunde gilt ein Wert, für die Minuten einer Viertelstunde. +func seedMinuteDay(path string, f DayFile) error { + if demoFileExists(path) { + return nil + } + var keys []string + var values [][]float32 + add := func(key string, quarter func(q int) float32) { + row := make([]float32, minutesPerDayDemo) + for m := range row { + row[m] = quarter(m / 15) + } + keys = append(keys, key) + values = append(values, row) + } + ids := make([]string, 0, len(demoEntities)) + for id := range demoEntities { + ids = append(ids, id) + } + sort.Strings(ids) + for _, id := range ids { + dd := f.Devices[id] + add("e:"+demoEntities[id], func(q int) float32 { return dd.AvgW[q] }) + } + add("b:load_total", func(q int) float32 { return f.Site.LoadTotal[q] }) + add("b:grid_import", func(q int) float32 { return f.Site.GridImport[q] }) + add("b:pv", func(q int) float32 { return f.Site.PV[q] }) + add("t:outdoor", func(q int) float32 { + if p := f.Site.TempC[q]; p != nil { + return *p + } + return float32(math.NaN()) + }) + + var buf bytes.Buffer + if _, err := learnrec.AppendBlock(&buf, f.Day, learnrec.MinuteBlock{Keys: keys, Values: values}, map[string]int{}); err != nil { + return err + } + return writeNewFile(path, buf.Bytes()) +} + +// minutesPerDayDemo ist die Zahl der Minuten eines Tages. +const minutesPerDayDemo = 1440 + +// seedDemoSteps schreibt die Reglerschritte des Szenarios am Tag f, wenn die +// Datei fehlt. Der Regler zieht den Netzbezug auf den Zielwert: Netz ist PV minus +// Last, der Stellwert folgt dem Fehler mit dem Verstärkungsfaktor und bleibt in +// seinen Grenzen. Gesendet wird jeder Schritt, auch ohne Stellwertänderung. +func seedDemoSteps(dataDir string, f DayFile, loc *time.Location, rng *rand.Rand) error { + path := stepFileName(dataDir, f.Day, demoStepScenario) + if demoFileExists(path) { + return nil + } + day, err := time.ParseInLocation(dayLayout, f.Day, loc) + if err != nil { + return err + } + var steps []Step + prev := demoStepLimitMax + for m := 6 * 60; m < 20*60; m += demoStepEveryMin { + q := m / 15 + net := float64(f.Site.PV[q]-f.Site.LoadTotal[q]) + 5*rng.NormFloat64() + errW := net - demoStepTargetW + to, why := prev, StepUnchanged + switch { + case math.Abs(errW) <= demoStepDeadbandW: + why = StepDeadband + default: + raw := float64(prev) - demoStepGain*errW + switch { + case raw > demoStepLimitMax || raw < demoStepLimitMin: + to = math.Max(demoStepLimitMin, math.Min(demoStepLimitMax, math.Round(raw/10)*10)) + why = StepLimit + default: + to = math.Round(raw/10) * 10 + if to != prev { + why = StepSent + } + } + } + from32, to32 := float32(prev), float32(to) + at := time.Date(day.Year(), day.Month(), day.Day(), m/60, m%60, 0, 0, loc) + steps = append(steps, Step{At: at.Unix(), Err: float32(errW), Net: float32(net), + From: &from32, To: &to32, Why: why}) + prev = to + } + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + var buf []byte + for _, st := range steps { + buf = append(buf, encodeStep(st)...) + } + return writeNewFile(path, buf) +} + +// demoFileExists meldet, ob path existiert. +func demoFileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} + +// writeNewFile schreibt data nach path, nur wenn path noch nicht existiert. +func writeNewFile(path string, data []byte) error { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + return os.WriteFile(path, data, 0o644) +} diff --git a/dashboard/internal/autolearn/demo_test.go b/dashboard/internal/autolearn/demo_test.go index 943a35ff..32e15dc9 100644 --- a/dashboard/internal/autolearn/demo_test.go +++ b/dashboard/internal/autolearn/demo_test.go @@ -766,3 +766,66 @@ func TestDemoPVYearRestsTheFeedInRule(t *testing.T) { t.Fatalf("week = %v, want a spring week", got.Summary.Params["week"]) } } + +// TestSeedDemoMinutesAndSteps checks that the demo writes three days of minute +// values and the regulator steps of the last day, and that both read back. +func TestSeedDemoMinutesAndSteps(t *testing.T) { + loc := berlinLoc(t) + now := time.Date(2026, 11, 22, 12, 0, 0, 0, loc) + dir := t.TempDir() + if err := SeedDemoMinutes(dir, now, loc); err != nil { + t.Fatalf("SeedDemoMinutes: %v", err) + } + for i := 1; i <= demoMinuteDays; i++ { + day := now.AddDate(0, 0, -i).Format(dayLayout) + f, err := os.Open(filepath.Join(dir, "learnrec", "minutes", day+".enm")) + if err != nil { + t.Fatalf("minute file of %s: %v", day, err) + } + keys, values, err := learnrec.ReadDay(f) + f.Close() + if err != nil { + t.Fatalf("ReadDay %s: %v", day, err) + } + for _, key := range []string{"e:plug_balkon_steckdose", "b:load_total", "b:pv", "t:outdoor"} { + if _, ok := values[key]; !ok { + t.Errorf("%s: key %s missing, keys %v", day, key, keys) + } + } + if v := values["b:load_total"]; v == nil || math.IsNaN(float64(v[12*60])) { + t.Errorf("%s: no load_total value at 12:00", day) + } + } + + yesterday := now.AddDate(0, 0, -1) + from := time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, loc) + to := from.Add(24*time.Hour - time.Second) + // Ring of one day: yesterday is read from the step file, not from RAM. + steps := NewStepLog(func() int { return 60 }, func() string { return dir }).WithRingDays(func() int { return 1 }) + got := steps.Steps(demoStepScenario, from, to) + if len(got) < 100 { + t.Fatalf("steps of %s on the last day = %d, want at least 100", demoStepScenario, len(got)) + } + for _, st := range got { + if st.At < from.Unix() || st.At > to.Unix() { + t.Fatalf("step at %d outside the last day", st.At) + } + } + + // A second seed keeps the existing files unchanged. + name := filepath.Join(dir, "learnrec", "minutes", from.Format(dayLayout)+".enm") + before, err := os.ReadFile(name) + if err != nil { + t.Fatal(err) + } + if err := SeedDemoMinutes(dir, now, loc); err != nil { + t.Fatalf("second SeedDemoMinutes: %v", err) + } + after, err := os.ReadFile(name) + if err != nil { + t.Fatal(err) + } + if string(before) != string(after) { + t.Fatal("second seed changed an existing minute file") + } +} From 4c6823b13d8e13578bbd495fa3718b50c76cbcbb Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:23:22 +0100 Subject: [PATCH 16/21] chore(demo): keep the minute recording on the system drive Co-Authored-By: Claude Sonnet 5.5 --- demo/fixtures/seed/demo/settings.json | 1 + 1 file changed, 1 insertion(+) diff --git a/demo/fixtures/seed/demo/settings.json b/demo/fixtures/seed/demo/settings.json index 3b8353bd..807a18ec 100644 --- a/demo/fixtures/seed/demo/settings.json +++ b/demo/fixtures/seed/demo/settings.json @@ -2,6 +2,7 @@ "theme": "mint", "automation_outdoor_entity": "aussentemperatur", "learning_level": "eco", + "learning_minutes_location": "system", "show_runtime_status": true, "device_view_mode": "analysis", "show_config_entities_on_tile": true, From e3c771184eceb89c6c1e951768e68b5d87cf36dc Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:25:55 +0100 Subject: [PATCH 17/21] docs(automations): describe the minute recording Co-Authored-By: Claude Sonnet 5.5 --- docs/dashboard/automations-scenarios.md | 16 +++++++++++ docs/dashboard/settings.md | 35 +++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/docs/dashboard/automations-scenarios.md b/docs/dashboard/automations-scenarios.md index 058128de..cbd8bdbe 100644 --- a/docs/dashboard/automations-scenarios.md +++ b/docs/dashboard/automations-scenarios.md @@ -113,3 +113,19 @@ regulator without an output, an output that another scenario already uses, a minimum above the maximum, a gain outside 0.1 to 1, an inverter without a fallback value, or a repeat that is shorter than the minimum interval for commands. + +### Regulator steps + +A regulating scenario publishes every step it calculates, whether or not the +output changes. The node keeps the steps of each scenario, in memory and on the +same place and for the same days as the +[minute values](settings.md#learning-features). Each step has one of four +reasons: + +- **sent**: the new output went to the device. +- **deadband**: the error lies inside the tolerance band, so nothing was sent. +- **unchanged**: the output would be the same as before, so nothing was sent. +- **limit**: the output was held at its minimum or maximum. + +A step whose command was blocked counts as sent with the output unchanged, +because nothing reached the device. diff --git a/docs/dashboard/settings.md b/docs/dashboard/settings.md index e78337ce..03a487e0 100644 --- a/docs/dashboard/settings.md +++ b/docs/dashboard/settings.md @@ -77,10 +77,41 @@ from which calendar week a PV threshold is reached again. When it is off, the sun course stays as long as the profiles. In the first year, while the summer sun is still missing, a PV threshold is never reported as **Never triggers**. +**Record minute values** is on by default. The node keeps the power of each +device and the grid balance for every minute. The chain suggestions use this +record. After a restart they catch up on the minutes they missed, if the record +is kept on the drive or the system drive. Switch it off and the node stops +recording minutes. + +**Where minute values are kept** chooses the place: + +- **Memory** keeps the minutes in RAM, for up to 3 days on the economical level + and up to 14 days on the full level. They are lost on restart, so the node + cannot catch up from memory. +- **Extra drive** keeps the minutes on the drive. It is the recommended place + once a drive is set up. The row shows the free space of the drive. +- **System drive** keeps the minutes on the SD card of the node. It writes + about the amount shown on the row each day, so it is never the default. + +Without an extra drive the node records in memory. With a drive, the node +records on the drive. When you set up a drive while the place is on automatic, +the recording moves there by itself, and the page shows the note **An extra +drive is set up. Minute values are now kept there.** with the button **Keep**. +A place you chose yourself is never changed. + +If the drive fails, the recording goes on in memory and the row says **Drive +not available, still recording in memory**. When the drive comes back, the +missing minutes are added, so the day has no gap and no minute twice. + +**Keep minute values** sets how many days stay on the drive or the system drive, +from 1 to 365 days. The default is 60 days. Minute values are large and the node +can learn them again, so they are not part of a backup. **Delete learned data** +removes them too. + **Delete learned data** asks for confirmation first. It deletes the day profiles, the reaction times, the sums of the chain suggestions and the learned -loss values of the chains. Dismissed suggestions, ignored hints and the counters -of the rule check stay. +loss values of the chains. It also deletes the minute values. Dismissed +suggestions, ignored hints and the counters of the rule check stay. ### New features From 604eb49cd1ed0490d09de448fb78d2b43febb90e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:26:23 +0100 Subject: [PATCH 18/21] chore(dashboard): bump the cache-bust marks for the minute recording Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/cache-bust-history.csv | 2 ++ dashboard/internal/webui/templates/base.html | 2 +- dashboard/internal/webui/webui_test.go | 6 +++--- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index 21e16e60..5d2413af 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,10 +1,12 @@ version,date,asset,v,note v0.11.22-pre.31,2026-11-22,css/automations.css,23, +v0.11.22-pre.31,2026-11-22,css/learning-settings.css,3, v0.11.22-pre.31,2026-11-22,js/automation-evidence.js,5, v0.11.22-pre.31,2026-11-22,js/automation-learned.js,4, v0.11.22-pre.31,2026-11-22,js/automation-suggestions.js,4, v0.11.22-pre.31,2026-11-22,js/automation-templates.js,10, v0.11.22-pre.31,2026-11-22,js/automations.page.js,30, +v0.11.22-pre.31,2026-11-22,js/learning-settings.js,3, v0.11.22-pre.31,2026-11-22,js/monitoring-model.js,2, v0.11.22-pre.31,2026-11-22,js/monitoring.page.js,2, v0.11.22-pre.31,2026-11-22,js/settings.page.js,42, diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index f8ce9322..6c231e9d 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -243,7 +243,7 @@

{{t "no_access.title"}}

{{if index .Can "view_config"}}

{{t "panel.config_loading"}}

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

{{t "panel.energy_loading"}}

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

{{t "panel.devicemap_loading"}}

{{end}} -

{{t "panel.settings_loading"}}

+

{{t "panel.settings_loading"}}

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

{{t "panel.automations_loading"}}

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

{{t "panel.diagnostics_loading"}}

{{end}} diff --git a/dashboard/internal/webui/webui_test.go b/dashboard/internal/webui/webui_test.go index 8e046f15..325e56c6 100644 --- a/dashboard/internal/webui/webui_test.go +++ b/dashboard/internal/webui/webui_test.go @@ -159,7 +159,7 @@ func TestOverviewDoesNotLoadManagerAssetsInitially(t *testing.T) { } for path, script := range map[string]string{ "history-panel": "/static/js-deps/apexcharts.min.js,/static/js-deps/flatpickr.min.js?v=1,/static/js-deps/flatpickr-l10n-de.js?v=1,/static/js/history-export.js?v=2,/static/js/energy-model.js?v=5,/static/js/history-chart.js?v=5,/static/js/history.js?v=21", - "settings-panel": "/static/js-deps/choices.min.js,/static/js/revisions.js?v=4,/static/js/schema-form.js?v=2,/static/js/settings-masonry.js?v=2,/static/js/device-picker.js?v=2,/static/js/learning-settings.js?v=2,/static/js/settings-field.js?v=1,/static/js/settings.page.js?v=42", + "settings-panel": "/static/js-deps/choices.min.js,/static/js/revisions.js?v=4,/static/js/schema-form.js?v=2,/static/js/settings-masonry.js?v=2,/static/js/device-picker.js?v=2,/static/js/learning-settings.js?v=3,/static/js/settings-field.js?v=1,/static/js/settings.page.js?v=42", } { if !strings.Contains(body, `id="`+path+`"`) { t.Fatalf("page is missing %s", path) @@ -168,7 +168,7 @@ func TestOverviewDoesNotLoadManagerAssetsInitially(t *testing.T) { t.Fatalf("%s does not declare lazy script %q", path, script) } } - if !strings.Contains(body, `data-panel-css="/static/css/choices.min.css,/static/css/choices.css?v=2,/static/css/manager.css?v=53,/static/css/settings-controls.css?v=20,/static/css/learning-settings.css?v=2"`) { + if !strings.Contains(body, `data-panel-css="/static/css/choices.min.css,/static/css/choices.css?v=2,/static/css/manager.css?v=53,/static/css/settings-controls.css?v=20,/static/css/learning-settings.css?v=3"`) { t.Fatal("settings-panel does not declare lazy choices.css + manager.css + settings-controls.css") } if strings.Contains(body, ` Date: Sun, 22 Nov 2026 19:05:56 +0100 Subject: [PATCH 19/21] chore(dashboard): bump the cache-bust mark of the settings page Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/cache-bust-history.csv | 5 +++-- dashboard/internal/webui/templates/base.html | 2 +- dashboard/internal/webui/webui_test.go | 6 +++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/dashboard/internal/webui/cache-bust-history.csv b/dashboard/internal/webui/cache-bust-history.csv index 5d2413af..0851b028 100644 --- a/dashboard/internal/webui/cache-bust-history.csv +++ b/dashboard/internal/webui/cache-bust-history.csv @@ -1,12 +1,13 @@ version,date,asset,v,note +v0.11.22-pre.32,2026-11-22,css/learning-settings.css,3, +v0.11.22-pre.32,2026-11-22,js/learning-settings.js,3, +v0.11.22-pre.32,2026-11-22,js/settings.page.js,43, v0.11.22-pre.31,2026-11-22,css/automations.css,23, -v0.11.22-pre.31,2026-11-22,css/learning-settings.css,3, v0.11.22-pre.31,2026-11-22,js/automation-evidence.js,5, v0.11.22-pre.31,2026-11-22,js/automation-learned.js,4, v0.11.22-pre.31,2026-11-22,js/automation-suggestions.js,4, v0.11.22-pre.31,2026-11-22,js/automation-templates.js,10, v0.11.22-pre.31,2026-11-22,js/automations.page.js,30, -v0.11.22-pre.31,2026-11-22,js/learning-settings.js,3, v0.11.22-pre.31,2026-11-22,js/monitoring-model.js,2, v0.11.22-pre.31,2026-11-22,js/monitoring.page.js,2, v0.11.22-pre.31,2026-11-22,js/settings.page.js,42, diff --git a/dashboard/internal/webui/templates/base.html b/dashboard/internal/webui/templates/base.html index 6c231e9d..1405450a 100644 --- a/dashboard/internal/webui/templates/base.html +++ b/dashboard/internal/webui/templates/base.html @@ -243,7 +243,7 @@

{{t "no_access.title"}}

{{if index .Can "view_config"}}

{{t "panel.config_loading"}}

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

{{t "panel.energy_loading"}}

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

{{t "panel.devicemap_loading"}}

{{end}} -

{{t "panel.settings_loading"}}

+

{{t "panel.settings_loading"}}

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

{{t "panel.automations_loading"}}

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

{{t "panel.diagnostics_loading"}}

{{end}} diff --git a/dashboard/internal/webui/webui_test.go b/dashboard/internal/webui/webui_test.go index 325e56c6..6e55fdf3 100644 --- a/dashboard/internal/webui/webui_test.go +++ b/dashboard/internal/webui/webui_test.go @@ -159,7 +159,7 @@ func TestOverviewDoesNotLoadManagerAssetsInitially(t *testing.T) { } for path, script := range map[string]string{ "history-panel": "/static/js-deps/apexcharts.min.js,/static/js-deps/flatpickr.min.js?v=1,/static/js-deps/flatpickr-l10n-de.js?v=1,/static/js/history-export.js?v=2,/static/js/energy-model.js?v=5,/static/js/history-chart.js?v=5,/static/js/history.js?v=21", - "settings-panel": "/static/js-deps/choices.min.js,/static/js/revisions.js?v=4,/static/js/schema-form.js?v=2,/static/js/settings-masonry.js?v=2,/static/js/device-picker.js?v=2,/static/js/learning-settings.js?v=3,/static/js/settings-field.js?v=1,/static/js/settings.page.js?v=42", + "settings-panel": "/static/js-deps/choices.min.js,/static/js/revisions.js?v=4,/static/js/schema-form.js?v=2,/static/js/settings-masonry.js?v=2,/static/js/device-picker.js?v=2,/static/js/learning-settings.js?v=3,/static/js/settings-field.js?v=1,/static/js/settings.page.js?v=43", } { if !strings.Contains(body, `id="`+path+`"`) { t.Fatalf("page is missing %s", path) @@ -4657,8 +4657,8 @@ func TestBackupAssetsAreRegisteredOnTheShell(t *testing.T) { if !strings.Contains(renderPanel(t, "settings"), `data-subpage-css="/static/css/backup.css?v=2"`) { t.Fatal("backup.css ist nicht als Stylesheet der Unterseite Backup eingetragen") } - if !strings.Contains(page, "static/js/settings.page.js?v=42") { - t.Fatal("settings.page.js ist nicht auf v=40 hochgezaehlt") + if !strings.Contains(page, "static/js/settings.page.js?v=43") { + t.Fatal("settings.page.js ist nicht auf v=43 hochgezaehlt") } } From 2135428b523170a810115acbe637ea7d6845b724 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 22 Nov 2026 18:06:36 +0000 Subject: [PATCH 20/21] chore(release): bump component versions --- dashboard/VERSION | 2 +- services/automation/manifest.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dashboard/VERSION b/dashboard/VERSION index 66d3b7c5..68462daf 100644 --- a/dashboard/VERSION +++ b/dashboard/VERSION @@ -1 +1 @@ -v0.11.22-pre.31 +v0.11.22-pre.32 diff --git a/services/automation/manifest.json b/services/automation/manifest.json index 7a12a96e..88a27456 100644 --- a/services/automation/manifest.json +++ b/services/automation/manifest.json @@ -1,6 +1,6 @@ { "service_id": "automation", - "version": "0.7.3-pre.4", + "version": "0.7.3-pre.5", "unit": "automation.service", "bootstrap_step": "88", "schema": "config.schema.json", From eca18eed5a2396bec6304777f770c93e2a482f32 Mon Sep 17 00:00:00 2001 From: energy-node-bot Date: Sun, 22 Nov 2026 18:07:25 +0000 Subject: [PATCH 21/21] docs(changelog): update changelogs --- changelog/highlights/293.json | 8 ++++++++ dashboard/CHANGELOG.md | 24 ++++++++++++++++++++---- services/automation/CHANGELOG.md | 4 +++- 3 files changed, 31 insertions(+), 5 deletions(-) create mode 100644 changelog/highlights/293.json diff --git a/changelog/highlights/293.json b/changelog/highlights/293.json new file mode 100644 index 00000000..78421cd0 --- /dev/null +++ b/changelog/highlights/293.json @@ -0,0 +1,8 @@ +{ + "de": { + "*": "Die Node zeichnet Minutenwerte auf und behält jeden Reglerschritt als Grundlage zum Lernen" + }, + "en": { + "*": "The node records minute values and keeps every regulator step as a base for learning" + } +} diff --git a/dashboard/CHANGELOG.md b/dashboard/CHANGELOG.md index 3c987b36..b9c827e9 100644 --- a/dashboard/CHANGELOG.md +++ b/dashboard/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.11.22-pre.31 (2026-11-06) +## v0.11.22-pre.32 (2026-11-06) ### Features @@ -31,6 +31,19 @@ - **automations:** Learning knows the seasons, the sun and the outdoor temperature (#287) (8812dc2) - **automations:** Learning knows device cycles, the PV reserve and the remaining surplus of the day (#289) (5d86b6b) - **monitoring:** A Monitoring tab with notices, acknowledgement and all learned values (#291) (7ae50a9) +- **autolearn:** The rule check finds feedback, competition for the surplus, a rising base load and battery problems (#292) (142387b) +- **learnrec:** resolve where the minute recording lives (972c4aa) +- **learnrec:** add the binary day format of the minute recording (f0e0eec) +- **learnrec:** keep minute values in RAM and append them to the chosen drive (64aff34) +- **learnrec:** read ranges from the minute recording and replay them to one consumer (cfb599f) +- **learnrec:** let chain suggestions catch up from the recording (9ca1843) +- **autolearn:** keep the regulator steps of each scenario (cb5a507) +- **dashboard:** wire the minute recording and step log into the main program (885314a) +- **dashboard:** report the minute recording in learning status (744091f) +- **settings:** add the texts for the minute recording card (81d9b09) +- **settings:** choose where minute values are kept (d6e14c7) +- **autolearn:** seed minute values and regulator steps in the demo (956b559) +- **autolearn:** The node records minute values and keeps every regulator step as a base for learning (#293) - **autolearn:** let a fix change several rules and estimate signal noise (80c444e) - **autolearn:** flag rules whose own load flips their condition (67cbc32) - **autolearn:** name feedback as the cause of flapping rules (f6ea384) @@ -54,7 +67,6 @@ - **automations:** draw Ist and Soll curves in one chart (5f880ad) - **monitoring:** open the suggestion from its notice (9eaa37c) - **monitoring:** collect the suggestions under their own filter (add1bab) -- **autolearn:** The rule check finds feedback, competition for the surplus, a rising base load and battery problems (#292) - **i18n:** add the view_monitoring texts (0385648) - **auth:** add the view_monitoring right (44c40f9) - **monitoring:** collect notices from energy, chains and learning (e85d98c) @@ -287,10 +299,13 @@ - **storage:** offer sticks with several partitions as a group and format single partitions (#243) (c4e6d33) - **storage:** wipe old file system signatures before formatting a stick (#245) (aeafa63) - **storage:** set up, back up and replug the additional drive reliably (#247) (b668394) +- **autolearn:** write step files per scenario and day, drop deadband from figures (8f2a75a) +- **dashboard:** bound the step ring by the RAM days and log slow flushes (0046eee) +- **settings:** format the drive free space in GB (2c55808) +- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **autolearn:** drop findings whose fix is saved and show an early full battery in Monitoring (cb2d65b) - **automations:** keep learned findings while a fix sits in the draft (715cbfd) - **automations:** preselect the switch of night off and quiet off suggestions (e3a0952) -- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437) - **webui:** translate the time value of the monitoring model (d55ca28) - **webui:** add labels and load error to the monitoring panel (79ad0f3) - **energy:** keep monitoring jumps and refresh the summary line (9ad7b8a) @@ -423,8 +438,9 @@ ### Chores +- **dashboard:** bump the cache-bust marks for the minute recording (604eb49) +- **dashboard:** bump the cache-bust mark of the settings page (84aa771) - **dashboard:** bump the cache-bust marks for energy findings (85a44b4) -- **dashboard:** bump the cache-bust mark of the settings page (a590474) - **dashboard:** bump the cache-bust marks for the curve chart and suggestion notices (e4c86cb) - **webui:** bump the lazy asset marks of the monitoring page (79de377) - **dashboard:** bump the cache-bust marks for energy learning (8bd6f10) diff --git a/services/automation/CHANGELOG.md b/services/automation/CHANGELOG.md index a669758f..fdd67bd3 100644 --- a/services/automation/CHANGELOG.md +++ b/services/automation/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## v0.7.3-pre.4 (2026-11-21) +## v0.7.3-pre.5 (2026-11-22) ### Features @@ -8,6 +8,8 @@ - **storage:** Add an additional drive for running data and backups (#233) (015cc2c) - **automations:** flag rules that do not work and offer a fix (#278) (d369133) - **automations:** Rules can follow learned values with bounds and react to a quiet or active house (#284) (8aae55b) +- **automation:** publish every regulator step of a scenario (b82ff94) +- **autolearn:** The node records minute values and keeps every regulator step as a base for learning (#293) - **automation:** resolve learned values with bounds and a fallback (1049a08) - **automation:** compare against learned values and the learned house state (e27f41c) - **automations:** accept learned values in the rule schema (a8c404d)