forked from massivebox/ecodash
68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
|
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() {
|
||
|
|
||
|
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
|
||
|
|
||
|
}
|