ecodash/cache.go

75 lines
2.1 KiB
Go
Raw Normal View History

2022-10-15 17:58:44 +00:00
package main
import (
"fmt"
"time"
)
type CacheEntry struct {
Date int64
GreenEnergyPercentage float32
PolledSmartEnergySummation float32
2022-10-15 17:58:44 +00:00
}
type CacheData []CacheEntry
2022-10-15 17:58:44 +00:00
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
}
_, err = config.db.Exec("DELETE FROM cache")
if err != nil {
fmt.Println("Error deleting previous records to cache: -", err.Error())
return
2022-10-15 17:58:44 +00:00
}
for key, day := range greenEnergyPercentage {
_, err := config.db.Exec("INSERT INTO cache(time,green_energy_percentage,energy_consumption) VALUES (?,?,?);", day.DayTime.Unix(), greenEnergyPercentage[key].Value, historyPolledSmartEnergySummation[key].Value)
if err != nil {
fmt.Println("Error adding record to cache: -", err.Error())
return
}
2022-10-15 17:58:44 +00:00
}
}
func (config Config) readCache() (CacheData, error) {
2022-10-15 17:58:44 +00:00
rows, err := config.db.Query("SELECT time, green_energy_percentage, energy_consumption FROM cache")
2022-10-15 17:58:44 +00:00
if err != nil {
return CacheData{}, err
2022-10-15 17:58:44 +00:00
}
defer rows.Close()
var ret CacheData
2022-10-15 17:58:44 +00:00
for rows.Next() {
var (
date int64
greenEnergyPercentage float32
polledSmartEnergyConsumption float32
)
err = rows.Scan(&date, &greenEnergyPercentage, &polledSmartEnergyConsumption)
ret = append(ret, CacheEntry{date, greenEnergyPercentage, polledSmartEnergyConsumption})
2022-10-15 17:58:44 +00:00
}
return ret, nil
2022-10-15 17:58:44 +00:00
}