105 lines
2.5 KiB
Go
105 lines
2.5 KiB
Go
package daemon
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"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"
|
|
"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, logger logger.Logger) {
|
|
|
|
// Info
|
|
logger.Info("Use clean-cache-interval: %v", cleanCacheInterval.String())
|
|
logger.Info("Use compression: %v", compression)
|
|
|
|
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)
|
|
|
|
logfile := logfile.New(cnf.Device.Logfile)
|
|
|
|
measuredValuesCache := make([]types.MeasuredValue, 0)
|
|
|
|
go sensor.ReadContinuously(childContext, cnf.GetTemperatureSensors(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(compression, 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: %v", len(measuredValuesCache))
|
|
err = logfile.Append(compression, measuredValuesCache)
|
|
if err != nil {
|
|
logger.Fatal("%v", err)
|
|
}
|
|
|
|
return
|
|
}
|
|
}
|
|
}
|