forked from massivebox/ecodash
e9125b783c
This is the first, most basic implementation of a SQLite database for caching. Future commits will make it much more optimized and able to efficiently store data for periods longer than 8 days.
75 lines
2.1 KiB
Go
75 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
type CacheEntry struct {
|
|
Date int64
|
|
GreenEnergyPercentage float32
|
|
PolledSmartEnergySummation float32
|
|
}
|
|
type CacheData []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
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
func (config Config) readCache() (CacheData, error) {
|
|
|
|
rows, err := config.db.Query("SELECT time, green_energy_percentage, energy_consumption FROM cache")
|
|
if err != nil {
|
|
return CacheData{}, err
|
|
}
|
|
defer rows.Close()
|
|
var ret CacheData
|
|
|
|
for rows.Next() {
|
|
var (
|
|
date int64
|
|
greenEnergyPercentage float32
|
|
polledSmartEnergyConsumption float32
|
|
)
|
|
err = rows.Scan(&date, &greenEnergyPercentage, &polledSmartEnergyConsumption)
|
|
ret = append(ret, CacheEntry{date, greenEnergyPercentage, polledSmartEnergyConsumption})
|
|
}
|
|
|
|
return ret, nil
|
|
|
|
}
|