PKGBUILD/pkg/daemon/daemon.go

106 lines
2.6 KiB
Go
Raw Normal View History

package daemon
import (
"context"
"os"
"os/signal"
"syscall"
"time"
2019-06-15 13:58:41 +00:00
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/logfile"
"github.com/go-flucky/flucky/pkg/logger"
"github.com/go-flucky/flucky/pkg/rgbled"
2019-06-15 13:58:41 +00:00
"github.com/go-flucky/flucky/pkg/sensor"
"github.com/go-flucky/flucky/pkg/types"
)
// Start the daemon
func Start(cnf *config.Configuration, cleanCacheInterval time.Duration, compression bool, round float64, logger logger.Logger) {
// Info
logger.Info("Use clean-cache-interval: %v", cleanCacheInterval.String())
logger.Info("Use compression: %v", compression)
2019-06-30 13:22:02 +00:00
logger.Info("Round: %v", round)
ticker := time.Tick(cleanCacheInterval)
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)
errorChannel := make(chan error, 0)
measuredValuesChannel := make(chan []*types.MeasuredValue, 0)
ctx := context.Background()
childContext, cancel := context.WithCancel(ctx)
measuredValuesLogfile := logfile.New(cnf.Device.Logfile)
measuredValuesCache := make([]*types.MeasuredValue, 0)
go sensor.ReadContinuously(childContext, cnf.GetSensors(config.ENABLED), measuredValuesChannel, errorChannel)
rgbLEDs := cnf.GetRGBLEDs(config.ENABLED)
for {
err := rgbled.Run(rgbLEDs)
if err != nil {
logger.Error("Can not turn on green info light: %v", err)
}
select {
case err, _ := <-errorChannel:
logger.Error("%v", err)
err = rgbled.Error(rgbLEDs)
if err != nil {
logger.Error("Can not turn on red info light: %v", err)
}
time.Sleep(time.Second * 2)
case <-ticker:
err := rgbled.Logfile(rgbLEDs)
if err != nil {
logger.Error("Can not turn on blue info light: %v", err)
}
err = logfile.Append(measuredValuesLogfile, compression, round, measuredValuesCache)
if err != nil {
err = rgbled.Error(rgbLEDs)
if err != nil {
logger.Error("Can not turn on red info light: %v", err)
}
cancel()
logger.Fatal("Can not save temperatures: %v", err)
}
measuredValuesCache = make([]*types.MeasuredValue, 0)
case measuredValues, _ := <-measuredValuesChannel:
measuredValuesCache = append(measuredValuesCache, measuredValues...)
case killSignal := <-interrupt:
logger.Warn("Daemon was interruped by system signal %v\n", killSignal)
cancel()
err := rgbled.Error(rgbLEDs)
if err != nil {
logger.Error("Can not turn on red info light: %v", err)
}
logger.Warn("Save remaining data from the cache")
err = logfile.Append(measuredValuesLogfile, compression, round, measuredValuesCache)
if err != nil {
logger.Fatal("%v", err)
}
return
}
}
}