diff --git a/cmd/energyd/energyd.go b/cmd/energyd/energyd.go index 9df6e94..94edbc1 100644 --- a/cmd/energyd/energyd.go +++ b/cmd/energyd/energyd.go @@ -1,9 +1,11 @@ package main import ( + "context" "flag" "log" "os" + "os/signal" "runtime/pprof" "github.com/amigan/energyd/internal/config" @@ -27,5 +29,11 @@ func main() { ic := isoclient.New(cfg) - energy.Compute(ic) + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + + ener := energy.New(ic) + go ener.Go(ctx) + <-ctx.Done() + log.Printf("shutting down\n") } diff --git a/internal/config/config.go b/internal/config/config.go index 42d3293..9662e35 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -20,8 +20,8 @@ func Config() *Conf { } return &Conf{ - ISOUser: viper.Get("isouser").(string), - ISOPassword: viper.Get("isopassword").(string), + ISOUser: viper.Get("iso.user").(string), + ISOPassword: viper.Get("iso.password").(string), } } diff --git a/pkg/energy/energy.go b/pkg/energy/energy.go index 1dfc541..26e581f 100644 --- a/pkg/energy/energy.go +++ b/pkg/energy/energy.go @@ -1,6 +1,7 @@ package energy import ( + "context" "fmt" "math" "time" @@ -8,6 +9,10 @@ import ( "github.com/amigan/energyd/pkg/isoclient" ) +type Energy struct { + iso isoclient.Client +} + type LoadProfile struct { Current int Peak int @@ -19,7 +24,9 @@ type LoadProfile struct { HoursAway int } -func Compute(ic isoclient.Client) { +func (e *Energy) Compute() { + ic := e.iso + load, err := ic.GetCurrentLoad() if err != nil { panic(err) @@ -53,5 +60,23 @@ func Compute(ic isoclient.Client) { lp.PctPeak = int(float32(load.LoadMW / float32(lp.Peak)) * 100) lp.HoursAway = int(math.Abs(float64(hour) - float64(lp.PeakHr))) fmt.Printf("lp %#v\n", lp) - +} + +func (e *Energy) Go(ctx context.Context) { + tick := time.NewTicker(time.Minute*15) + e.Compute() + for { + select { + case <-tick.C: + e.Compute() + case <-ctx.Done(): + return + } + } +} + +func New(ic isoclient.Client) *Energy { + return &Energy{ + iso: ic, + } }