ecodash/cache.go

73 lines
1.9 KiB
Go
Raw Normal View History

2022-10-15 17:58:44 +00:00
package main
import (
"encoding/json"
"fmt"
"os"
"time"
)
type CacheEntry struct {
Date string `json:"date""`
GreenEnergyPercentage float32 `json:"green_energy_percentage"`
PolledSmartEnergySummation float32 `json:"polled_smart_energy_summation"`
}
type CacheFile []CacheEntry
func (config Config) updateCache() {
// in order to avoid querying and storing each day's data from 0001-01-01 in future versions
if config.HomeAssistant.InstallationDate.IsZero() {
return
}
2022-10-15 17:58:44 +00:00
now := time.Now()
h, m, s := now.Clock()
start := now.AddDate(0, 0, -7).Add(-(time.Duration(h)*time.Hour + time.Duration(m)*time.Minute + time.Duration(s)*time.Second))
greenEnergyPercentage, err := config.historyAverageAndConvertToGreen(config.Sensors.FossilPercentage, start, now)
if err != nil {
fmt.Println("Error updating cached data for FossilPercentage -" + err.Error())
return
}
historyPolledSmartEnergySummation, err := config.historyDelta(config.Sensors.PolledSmartEnergySummation, start, now)
if err != nil {
fmt.Println("Error updating cached data for PolledSmartEnergySummation -" + err.Error())
return
}
var cacheEntries []CacheEntry
for key, day := range greenEnergyPercentage {
cacheEntries = append(cacheEntries, CacheEntry{
Date: day.DayTime.Format("02/01"),
GreenEnergyPercentage: greenEnergyPercentage[key].Value,
PolledSmartEnergySummation: historyPolledSmartEnergySummation[key].Value,
})
}
out, _ := json.Marshal(cacheEntries)
err = os.WriteFile("cache.json", out, 0666)
if err != nil {
fmt.Println("Error saving cached data to file -" + err.Error())
}
}
func readCache() (CacheFile, error) {
data, err := os.ReadFile("cache.json")
if err != nil {
return CacheFile{}, err
}
var cache CacheFile
err = json.Unmarshal(data, &cache)
if err != nil {
return CacheFile{}, err
}
return cache, nil
}