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, round float64, logger logger.Logger) { // Info logger.Info("Use clean-cache-interval: %v", cleanCacheInterval.String()) logger.Info("Use compression: %v", compression) logger.Info("Round values: %v", round) temperatureLogfile := logfile.New(cnf.Device.TemperatureLogfile) ticker := time.Tick(cleanCacheInterval) interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM) errorChannel := make(chan error, 0) //humidityChannel := make(chan *types.Humidity, 0) temperatureChannel := make(chan *types.Temperature, 0) ctx := context.Background() childContext, cancel := context.WithCancel(ctx) // go sensor.ReadHumiditiesContinuously(cnf.GetHumiditySensors(config.ENABLED), humidityChannel, errorChannel) go sensor.ReadTemperaturesContinuously(childContext, cnf.GetTemperatureSensors(config.ENABLED), round, temperatureChannel, errorChannel) temperatureCache := make([]*types.Temperature, 0) rgbLEDs := cnf.GetRGBLEDs(config.ENABLED) err := rgbled.Green(rgbLEDs) if err != nil { logger.Error("Can not turn on green info light: %v", err) } for { select { case err, _ := <-errorChannel: logger.Error("%v", err) case <-ticker: err := rgbled.Blue(rgbLEDs) if err != nil { logger.Error("Can not turn on blue info light: %v", err) } //temperaturesLogfile,_ := temperatureLogfile.ReadTemperatures() err = logfile.AppendTemperatures(temperatureLogfile, compression, temperatureCache) if err != nil { cancel() logger.Fatal("Can not save temperatures: %v", err) } temperatureCache = make([]*types.Temperature, 0) err = rgbled.Green(rgbLEDs) if err != nil { logger.Error("Can not turn on green info light: %v", err) } case temperature, _ := <-temperatureChannel: temperatureCache = append(temperatureCache, temperature) case killSignal := <-interrupt: logger.Warn("Daemon was interruped by system signal %v\n", killSignal) cancel() err := rgbled.Red(rgbLEDs) if err != nil { logger.Error("Can not turn on red info light: %v", err) } logger.Warn("Save remaining temperature data from the cache") err = logfile.AppendTemperatures(temperatureLogfile, compression, temperatureCache) if err != nil { logger.Fatal("%v", err) } return } } }