Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
594282c
fix(learning): reset every learned state through one registry
Developer-Simon Nov 23, 2026
102cad0
fix(autolearn): survive a detector panic and keep results of finished…
Developer-Simon Nov 23, 2026
bde4c6a
fix(autolearn): keep harm first, cap open suggestions and give every …
Developer-Simon Nov 23, 2026
420f092
fix(autolearn): drop suggestions an existing rule covers and energy s…
Developer-Simon Nov 23, 2026
2f2cd59
fix(autolearn): match rule actions by direction and use one minimum r…
Developer-Simon Nov 23, 2026
2764157
fix(autolearn): skip unreachable and away days and keep switch time I…
Developer-Simon Nov 23, 2026
c3a946e
fix(autolearn): detect downward shifts in the change point test
Developer-Simon Nov 23, 2026
081de7b
fix(autolearn): replay learned values over their history and fix seas…
Developer-Simon Nov 23, 2026
0a38900
fix(autolearn): fix threshold plateau, replay base once and count PV …
Developer-Simon Nov 23, 2026
6edba7c
fix(autolearn): use the PV day count in production wiring
Developer-Simon Nov 23, 2026
edc5b1d
fix(learnrec): keep recording what Home Assistant cannot deliver and …
Developer-Simon Nov 23, 2026
c70503a
fix(learnrec): reset zeroed minute file headers on append
Developer-Simon Nov 23, 2026
15cd9c7
fix(automations): reject learned bounds on save that the service woul…
Developer-Simon Nov 23, 2026
ba98fb8
fix(dashboard): check field roles on settings restore and CSRF on mon…
Developer-Simon Nov 23, 2026
cf08e7f
fix(webui): gate finding actions, close the popover on scroll and kee…
Developer-Simon Nov 23, 2026
2405fe4
fix(automations): read the resolve section of the learned vectors in …
Developer-Simon Nov 23, 2026
ae782ae
fix(webui): animate the band card and soften the popover close
Developer-Simon Nov 23, 2026
6c82592
chore(webui): bump the cache-bust marks for the learning review fixes
Developer-Simon Nov 23, 2026
bf1dd6d
chore(release): bump component versions
Nov 23, 2026
9839733
docs(changelog): update changelogs
Nov 23, 2026
2e4acd0
fix(autolearn): list findings without a fix only in Monitoring
Developer-Simon Nov 23, 2026
a15aa96
docs(changelog): update changelogs
Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions changelog/highlights/296.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"de": {
"*": "Das Lernen der Automationen ist nach einer Gesamtprüfung zuverlässiger, Löschen räumt alles auf"
},
"en": {
"*": "Correct the learning feature after the full review"
}
}
24 changes: 22 additions & 2 deletions dashboard/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Changelog

## v0.11.22-pre.34 (2026-11-06)
## v0.11.22-pre.35 (2026-11-06)

### Features

Expand Down Expand Up @@ -34,11 +34,11 @@
- **autolearn:** The rule check finds feedback, competition for the surplus, a rising base load and battery problems (#292) (142387b)
- **autolearn:** The node records minute values and keeps every regulator step as a base for learning (#293) (19e65e7)
- **autolearn:** Automation suggestions for surplus and load shifts are checked against your data (#295) (6c255ad)
- **autolearn:** Learning functions can take minute values from Home Assistant (#294) (7aa657e)
- **learnrec:** fetch minute values from Home Assistant through the companion (97e2665)
- **learnrec:** pause the own recording while Home Assistant delivers minutes (4086c45)
- **learnrec:** read own minutes first, then Home Assistant, and fetch gaps before the heavy run (44ee05d)
- **settings:** let Home Assistant fill the minute recording (3d7d231)
- **autolearn:** Learning functions can take minute values from Home Assistant (#294)
- **autolearn:** parse the learned_value condition (da541e8)
- **automations:** edit the learned_value condition (672ca29)
- **automations:** edit the learned_value fields in the rule card (ae0c8e1)
Expand Down Expand Up @@ -334,6 +334,25 @@
- **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)
- **learning:** reset every learned state through one registry (594282c)
- **autolearn:** survive a detector panic and keep results of finished devices (102cad0)
- **autolearn:** keep harm first, cap open suggestions and give every value a spread (bde4c6a)
- **autolearn:** drop suggestions an existing rule covers and energy suggestions without replay (420f092)
- **autolearn:** match rule actions by direction and use one minimum run table (2f2cd59)
- **autolearn:** skip unreachable and away days and keep switch time IDs stable (2764157)
- **autolearn:** detect downward shifts in the change point test (c3a946e)
- **autolearn:** replay learned values over their history and fix season edge cases (081de7b)
- **autolearn:** fix threshold plateau, replay base once and count PV days (0a38900)
- **autolearn:** use the PV day count in production wiring (6edba7c)
- **learnrec:** keep recording what Home Assistant cannot deliver and clean every location (edc5b1d)
- **learnrec:** reset zeroed minute file headers on append (c70503a)
- **automations:** reject learned bounds on save that the service would reject (15cd9c7)
- **dashboard:** check field roles on settings restore and CSRF on monitoring ack (ba98fb8)
- **webui:** gate finding actions, close the popover on scroll and keep every undo (cf08e7f)
- **automations:** read the resolve section of the learned vectors in the JS test (2405fe4)
- **webui:** animate the band card and soften the popover close (ae782ae)
- **autolearn:** list findings without a fix only in Monitoring (2e4acd0)
- **automations:** correct the learning feature after the full review (#296)
- **backup:** A restore stays in place even when the battery state cannot be written (#288) (e5c5437)
- **autolearn:** harden the replay against unsupported fields and absent keys (f762aae)
- **automations:** prefill the surplus templates from a suggestion (d977098)
Expand Down Expand Up @@ -493,6 +512,7 @@

### Chores

- **webui:** bump the cache-bust marks for the learning review fixes (6c82592)
- **dashboard:** bump the cache-bust marks for the Home Assistant source (8b3bb59)
- **dashboard:** refresh the cache-bust history after the rebase (33c7bcb)
- **dashboard:** bump the cache-bust marks for energy suggestions (5e08c00)
Expand Down
2 changes: 1 addition & 1 deletion dashboard/VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v0.11.22-pre.34
v0.11.22-pre.35
18 changes: 15 additions & 3 deletions dashboard/cmd/dashboard/learn_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,10 @@ func anyGroupOn(groups map[string]bool) bool {

// registerEnergyDetectors meldet die Erkenner der Gruppe Energie bei der Engine.
// Sie laufen nur, wenn der Schalter Energie an ist. reserve liefert die PV-Reserve
// der letzten Minute, check ist die Selbstpruefung der Prognose des Rest-Ueberschusses.
func registerEnergyDetectors(e *autolearn.Engine, reserve func() (float64, bool, bool), check *autolearn.ForecastCheck) {
// der letzten Minute, days zaehlt die Tage der PV-Daten fuer das Tor, check ist die Selbstpruefung der Prognose des Rest-Ueberschusses.
func registerEnergyDetectors(e *autolearn.Engine, reserve func() (float64, bool, bool), days func() int, check *autolearn.ForecastCheck) {
e.Register(autolearn.TemperatureDetector)
e.Register(autolearn.PVReserveDetector(reserve))
e.Register(autolearn.PVReserveDetectorWithDays(reserve, days))
e.Register(autolearn.LearnCyclesDetector)
e.Register(autolearn.NewLearnSurplusDetector(check))
e.Register(autolearn.SurplusDetector)
Expand Down Expand Up @@ -522,3 +522,15 @@ func loadPVRaster(path string, limits learnrec.Limits, logf func(string, ...any)
}
return autolearn.LoadRaster(data, limits.PVCellAzDeg, limits.PVCellElDeg)
}

// Reset setzt den Zustand der Zyklen auf leer und loescht cycles.json. Ein
// erneutes Save schreibt den leeren Stand.
func (c *cycleRunner) Reset() error {
c.mu.Lock()
c.tracker = autolearn.NewCycleTracker(nil)
c.mu.Unlock()
if err := os.Remove(c.path); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("cycle state reset: %w", err)
}
return nil
}
3 changes: 2 additions & 1 deletion dashboard/cmd/dashboard/learn_ha_prepare.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const haPrefetchTimeout = 90 * time.Second

// haFetcher ist der Teil des Abgleichs, den der Vorlauf braucht.
type haFetcher interface {
Offered() bool
Prefetch(keys []string, days []string, deadline time.Time)
WaitIdle(ctx context.Context) bool
Drop()
Expand Down Expand Up @@ -61,7 +62,7 @@ func (p *haPreparer) Prepare(now time.Time) {
days = append(days, start.Format("2006-01-02"))
}
}
if len(days) == 0 {
if len(days) == 0 || !p.ha.Offered() {
return
}
keys := make([]string, 0, len(keySet))
Expand Down
14 changes: 14 additions & 0 deletions dashboard/cmd/dashboard/learn_ha_prepare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,11 @@ type fakeHA struct {
days []string
deadline time.Time
drops int
noOffer bool
}

func (f *fakeHA) Offered() bool { return !f.noOffer }

func (f *fakeHA) Prefetch(keys []string, days []string, deadline time.Time) {
f.prefetches++
f.keys, f.days, f.deadline = keys, days, deadline
Expand All @@ -37,6 +40,17 @@ func (f *fakeHA) WaitIdle(ctx context.Context) bool { return true }

func (f *fakeHA) Drop() { f.drops++ }

func TestHAPreparerSkipsPrefetchWithoutOffer(t *testing.T) {
now := time.Date(2026, 11, 20, 3, 30, 0, 0, time.UTC)
ha := &fakeHA{noOffer: true}
own := &fakeOwn{keys: []string{"e:uid1"}}
p := &haPreparer{own: own, ha: ha, active: func() bool { return true }, loc: time.UTC}
p.Prepare(now)
if ha.prefetches != 0 {
t.Fatalf("Prefetch ohne Angebot des Companion aufgerufen: %d", ha.prefetches)
}
}

func TestHAPreparerDoesNothingWhenReconcileIsOff(t *testing.T) {
ha := &fakeHA{}
p := &haPreparer{own: &fakeOwn{}, ha: ha, active: func() bool { return false }, loc: time.UTC}
Expand Down
27 changes: 27 additions & 0 deletions dashboard/cmd/dashboard/learn_reset_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import (
"os"
"path/filepath"
"testing"
)

func TestCycleRunnerResetClearsStateAndFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "cycles.json")
c := newCycleRunner(path, nil, nil, func(string, ...any) {})
if err := c.Save(); err != nil {
t.Fatal(err)
}
if err := c.Reset(); err != nil {
t.Fatalf("Reset = %v", err)
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("cycles.json still exists after Reset (err %v)", err)
}
if err := c.Save(); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(path); err != nil {
t.Fatalf("Save after Reset writes no file: %v", err)
}
}
11 changes: 10 additions & 1 deletion dashboard/cmd/dashboard/learn_suggestions.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ func gateSuggestions(book *suggestionBook, source suggestionCandidates, readDoc
if (g != "habit" && g != "energy") || !groups[g] {
continue
}
// A finding without a fix is a notice for Monitoring, not a suggestion.
if len(c.Finding.Apply) == 0 {
continue
}
if c.Finding.Device != "" && exists != nil && !exists(c.Finding.Device) {
continue
}
Expand All @@ -133,7 +137,12 @@ func gateSuggestions(book *suggestionBook, source suggestionCandidates, readDoc
}
}
before := shownIDs(book.state.Shown())
out, shown := autolearn.Gate(cands, doc, book.state.Shown())
// The switch entities of a rule come from its entity_id actions. The command
// topic table is not needed for that, so no payload check runs here.
out, shown := autolearn.Gate(cands, doc, book.state.Shown(), autolearn.GateOptions{
Hidden: book.state.Hidden,
Targets: autolearn.RuleTargets(doc, nil),
})
for i := range out {
f := &out[i]
// The temperature limit is the cure for warm weather, so it is never rested.
Expand Down
2 changes: 1 addition & 1 deletion dashboard/cmd/dashboard/learn_suggestions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ var (
// habitCandidate is a candidate that passes every gate of the habit group.
func habitCandidate(id, device string, kwh float64) autolearn.Candidate {
return autolearn.Candidate{
Finding: autolearn.Finding{ID: id, Kind: "switchtime", Group: "habit", Device: device, Severity: "info", Confidence: "high"},
Finding: autolearn.Finding{ID: id, Kind: "switchtime", Group: "habit", Device: device, Severity: "info", Confidence: "high", Apply: []autolearn.Fix{{Code: "time_point", Template: "time_point"}}},
Detector: "switchtime",
NEff: 10,
MinNEff: 5,
Expand Down
20 changes: 18 additions & 2 deletions dashboard/cmd/dashboard/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,7 @@ func main() {
// Abgleich mit dem Companion: holt fehlende Minuten- und 5-Minuten-Werte
// fuer die Lernfunktionen, nur im RAM.
learnHA := learnrec.NewHASync(time.Now, learnLimits, time.Local)
learnHub.AddResetter("hasync", learnHA)
learnHub.SetOutdoor(func() string {
if value, err := settingsStore.LoadSettings(); err == nil {
return value.AutomationOutdoorEntity
Expand All @@ -481,7 +482,9 @@ func main() {
automationChecker.ObserveTick(at, automationState(), balanceRuleValues(snap.Balance), automationEntityValue)
}))
learnHub.AddSaver("chainwatch", chainMonitor)
learnHub.AddResetter("chainwatch", learnrec.ResetterFunc(chainMonitor.ResetLearned))
learnHub.AddSaver("chainsuggest", chainSuggest)
learnHub.AddResetter("chainsuggest", learnrec.ResetterFunc(chainSuggest.ResetLearned))
learnHub.AddSaver("autolearn", automationObserver)
// Herkunft der Schaltvorgaenge: Regel, Hand oder Aussen. Die Reaktionszeiten
// liegen in autolearn/reaction.json und werden vom Hub mitgesichert.
Expand All @@ -491,6 +494,7 @@ func main() {
originTracker := autolearn.NewTracker(reactions)
learnHub.AddMinute("origin", originTracker)
learnHub.AddSaver("reactions", reactions)
learnHub.AddResetter("reactions", reactions)
// Demo: mit ENERGY_NODE_AUTOLEARN_FAST=1 bekommt ein leeres Tagesverzeichnis
// die Demo-Profile, dazu Himmelsraster und Dachmodell. Der Block steht vor
// den Trackern, die die Dateien beim Start laden. Vorhandene Dateien bleiben unberührt.
Expand Down Expand Up @@ -538,10 +542,12 @@ func main() {
pvSite.refresh()
return pvTracker.Save()
}))
learnHub.AddResetter("pvtracker", pvTracker)
// Geometriemodell der Dachflaechen: nachts aus dem Himmelsraster neu gefittet,
// nur bei Aenderung gespeichert.
pvModelStore := autolearn.NewPVModelStore(filepath.Join(autolearnDir, "pvmodel.json"))
learnHub.AddSaver("pvmodel", pvModelStore)
learnHub.AddResetter("pvmodel", pvModelStore)
// Wetterfaktor und PV-Reserve: laeuft nach dem Tracker, damit dieselbe Minute
// schon im Raster steht. Die Reserve geht ueber den Minutenrahmen in den
// Tagesspeicher (Schluessel k).
Expand All @@ -550,6 +556,7 @@ func main() {
autolearn.LoadPVWeather(pvWeatherPath, log.Printf), pvWeatherPath)
learnHub.AddMinute("pvreserve", pvReserve)
learnHub.AddSaver("pvweather", pvReserve)
learnHub.AddResetter("pvweather", pvReserve)
// Tagesdateien: je Minute der Rahmen, je Minute die Ereignisse des Trackers.
// Die Aufbewahrung kommt aus den Einstellungen, 0 heisst 56 Tage.
dayStore := autolearn.OpenDayStore(filepath.Join(autolearnDir, "days"), time.Local, func() int {
Expand All @@ -560,10 +567,12 @@ func main() {
}, log.Printf)
learnHub.AddMinute("daystore", dayStore)
learnHub.AddSaver("daystore", dayStore)
learnHub.AddResetter("daystore", dayStore)
// Zyklen der Geraete: ohne Herkunftsabfrage enden alle Zyklen als self.
cycles := newCycleRunner(filepath.Join(autolearnDir, "cycles.json"), dayStore, nil, log.Printf)
learnHub.AddMinute("cycles", cycles)
learnHub.AddSaver("cycles", cycles)
learnHub.AddResetter("cycles", cycles)
// Automationen-Engine: die Erkenner laufen in eigener Goroutine, nie im
// MQTT-Pfad. Die Gruppen folgen dem Schalter Muster lernen und den beiden
// Gruppenschaltern darunter. Ohne lesbare Einstellungen bleibt alles an.
Expand All @@ -588,7 +597,8 @@ func main() {
// Prognose-Selbstpruefung des Rest-Ueberschusses, gespeichert mit dem Hub.
forecastCheck := autolearn.LoadForecastCheck(filepath.Join(autolearnDir, "forecast.json"), log.Printf)
learnHub.AddSaver("forecast", forecastCheck)
registerEnergyDetectors(automationEngine, pvReserve.Current, forecastCheck)
learnHub.AddResetter("forecast", forecastCheck)
registerEnergyDetectors(automationEngine, pvReserve.Current, pvReserve.DayCount, forecastCheck)
automationEngine.Register(autolearn.BaseLoadDetector)
automationEngine.Register(autolearn.BatteryDetector)
automationEngine.Register(autolearn.NewPVModelDetector(pvTracker.Snapshot, pvModelStore))
Expand Down Expand Up @@ -647,6 +657,8 @@ func main() {
}
engineLoop := newEngineRunner(automationEngine, engineGroups, engineDowngrade)
learnHub.AddMinute("autolearn-engine", engineLoop)
// Die Engine hat keinen Speicher, ihr Reset verwirft nur die letzte Runde.
learnHub.AddResetter("autolearn-engine", automationEngine)
// Tagesanteil der Lernlast, stuendlich in den Lernstand.
learnHub.AddSaver("daily-share", dailyShareSaver(automationEngine, engineGroups, &learnStateMu, &learnState, learnStatePath, time.Now))
// Vorschlaege der Gewohnheiten: nach jeder Runde durch die Gates, gespeichert
Expand Down Expand Up @@ -794,6 +806,7 @@ func main() {
mount: storageMountPoint,
})
learnHub.AddMinute("minutes", minutes.store)
learnHub.AddResetter("minutes", minutes)
var minuteReader learnrec.Reader = minutes.store
// Der schwere Lauf liest eigene Minuten zuerst, dann Home Assistant. Vor dem Lauf
// holt der Vorlauf fehlende Tage beim Companion und verwirft sie danach.
Expand All @@ -808,6 +821,8 @@ func main() {
})
// Die Reglerschritte fuer die Regelguete der Nulleinspeisung.
automationEngine.SetSteps(minutes.steps.Steps)
// Die gezeigten Vorschläge, damit eine Schaltzeit ihre ID behält.
automationEngine.SetShown(func() map[string]bool { return shownIDs(suggestionState.Shown()) })
go runStorageResume(ctx, storageService)
// Die Belegung der Systemplatte: in der Demo feste Werte, sonst eine Messung
// im Hintergrund, die alle zehn Minuten erneuert wird.
Expand Down Expand Up @@ -1223,6 +1238,7 @@ func main() {
} else if len(bridgeCfg.Connections) > 0 {
client.SetBridgeWatch(bridgeCfg.Connections[0].RemoteClientID)
}
configManager.SetSaveCheck(autolearn.CheckLearnedBoundsOnSave)
configManager.SetReloadFunc(func(name string, _ []byte) error {
if serviceID, ok := config.ServiceIDForConfig(name); ok {
return client.ReloadService(serviceID)
Expand Down Expand Up @@ -1390,7 +1406,7 @@ func main() {
HAMinuteDays: learnHA.Days,
Reset: func() error {
resetLearned(learnedStore, client)
return errors.Join(dayStore.Reset(), reactions.Reset(), chainSuggest.ResetLearned(), chainMonitor.ResetLearned(), suggestions.Reset(), minutes.Reset())
return errors.Join(learnHub.Reset(), suggestions.Reset())
},
}
handler := perfTiming.Middleware(basepath.Middleware(httpapi.NewAuthenticatedRouter(reg, configManager, settingsStore, tinytuya.NewClient(
Expand Down
13 changes: 12 additions & 1 deletion dashboard/internal/autolearn/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ func (c *Checker) reliabilityLocked() []Finding {
var out []Finding
for _, cand := range c.engineCandidates() {
f := cand.Finding
if f.Group != "check" || cand.NEff < cand.MinNEff || !rulesCurrent(f.RuleIDs, current) || fixSaved(f, c.doc) {
if !notRule(f) || cand.NEff < cand.MinNEff || !rulesCurrent(f.RuleIDs, current) || fixSaved(f, c.doc) {
continue
}
out = append(out, f)
Expand Down Expand Up @@ -466,3 +466,14 @@ func triggerCounts(payload string) map[string]int {
}
return counts
}

// notRule reports whether a finding belongs to the rule check and to Monitoring
// instead of the suggestion band. That holds for the check group and for every
// finding that has no rule to offer and no rule it belongs to: without an Apply
// fix it is a notice, never a suggestion. A candidate without an ID only carries learned values.
func notRule(f Finding) bool {
if f.ID == "" {
return false
}
return f.Group == "check" || (len(f.Apply) == 0 && len(f.RuleIDs) == 0)
}
20 changes: 20 additions & 0 deletions dashboard/internal/autolearn/checker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,3 +450,23 @@ func TestCheckerReplayInputNotBuiltWithoutEnabledRule(t *testing.T) {
t.Fatalf("source calls without rules = %d, want 0", calls)
}
}

func TestNotRuleSendsFindingsWithoutFixToMonitoring(t *testing.T) {
fix := []Fix{{Code: "night_off", Template: "night_off"}}
cases := []struct {
name string
f Finding
want bool
}{
{"check group", Finding{ID: "a", Group: "check"}, true},
{"energy without fix", Finding{ID: "b", Group: "energy"}, true},
{"energy with fix", Finding{ID: "c", Group: "energy", Apply: fix}, false},
{"habit of a rule", Finding{ID: "d", Group: "habit", RuleIDs: []string{"r1"}}, false},
{"values only", Finding{Group: "energy"}, false},
}
for _, c := range cases {
if got := notRule(c.f); got != c.want {
t.Errorf("%s: notRule = %v, want %v", c.name, got, c.want)
}
}
}
16 changes: 2 additions & 14 deletions dashboard/internal/autolearn/daystore.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"sync"
"time"

"github.com/Developer-Simon/energy-node-dashboard/internal/energystats"
"github.com/Developer-Simon/energy-node-dashboard/internal/learnrec"
)

Expand Down Expand Up @@ -857,20 +858,7 @@ func (s *DayStore) writeFile(day string, f DayFile) error {
if err := zw.Close(); err != nil {
return fmt.Errorf("autolearn: compress %s: %w", day, err)
}
tmp, err := os.CreateTemp(s.dir, ".day-*.tmp")
if err != nil {
return fmt.Errorf("autolearn: save %s: %w", day, err)
}
tmpName := tmp.Name()
_, err = tmp.Write(buf.Bytes())
if cerr := tmp.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Rename(tmpName, s.path(day))
}
if err != nil {
_ = os.Remove(tmpName)
if err := energystats.WriteFileAtomic(s.dir, s.path(day), buf.Bytes()); err != nil {
return fmt.Errorf("autolearn: save %s: %w", day, err)
}
if s.written == nil {
Expand Down
Loading
Loading