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, degree types.TemperatureUnit, 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) logger.Info("Temperature unit: %v", degree) 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), degree, 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: err = rgbled.Red(rgbLEDs) if err != nil { logger.Error("Can not turn on red info light: %v", err) } logger.Error("%v", err) time.Sleep(time.Second * 2) case <-ticker: err := rgbled.Blue(rgbLEDs) if err != nil { logger.Error("Can not turn on blue info light: %v", err) } err = logfile.AppendTemperatures(temperatureLogfile, compression, temperatureCache) if err != nil { err = rgbled.Red(rgbLEDs) if err != nil { logger.Error("Can not turn on red info light: %v", err) } 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 } } }