2019-06-13 19:25:32 +00:00
|
|
|
package daemon
|
|
|
|
|
|
|
|
import (
|
2019-06-15 13:45:35 +00:00
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"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/sensor"
|
|
|
|
"github.com/go-flucky/flucky/pkg/types"
|
2019-06-13 19:25:32 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Start the daemon
|
2019-06-14 19:35:13 +00:00
|
|
|
func Start(cnf *config.Configuration) error {
|
2019-06-13 19:25:32 +00:00
|
|
|
|
2019-06-15 13:45:35 +00:00
|
|
|
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)
|
|
|
|
|
|
|
|
// go sensor.ReadHumiditiesContinuously(cnf.GetHumiditySensors(config.ENABLED), humidityChannel, errorChannel)
|
|
|
|
go sensor.ReadTemperaturesContinuously(cnf.GetTemperatureSensors(config.ENABLED), temperatureChannel, errorChannel)
|
|
|
|
|
|
|
|
temperatures := make([]*types.Temperature, 0)
|
|
|
|
|
|
|
|
ticker := time.Tick(time.Second * 60)
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker:
|
|
|
|
log.Printf("Write measured values into logfile")
|
2019-06-13 19:25:32 +00:00
|
|
|
|
2019-06-15 13:45:35 +00:00
|
|
|
log.Printf("%v new measured temperature values", len(temperatures))
|
|
|
|
err := logfile.WriteTemperatures(temperatures, cnf.Device.TemperatureLogfile, true)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Can not save temperatures: %v", err)
|
|
|
|
}
|
|
|
|
temperatures = make([]*types.Temperature, 0)
|
2019-06-13 19:25:32 +00:00
|
|
|
|
2019-06-15 13:45:35 +00:00
|
|
|
case temperature, more := <-temperatureChannel:
|
|
|
|
if more {
|
|
|
|
temperatures = append(temperatures, temperature)
|
|
|
|
} else {
|
|
|
|
log.Printf("Temperature Channel closed. Write remaining values into the logfile")
|
|
|
|
err := logfile.WriteTemperatures(temperatures, cnf.Device.TemperatureLogfile, true)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("Can not save temperatures: %v", err)
|
|
|
|
}
|
|
|
|
}
|
2019-06-13 19:25:32 +00:00
|
|
|
|
2019-06-15 13:45:35 +00:00
|
|
|
case killSignal := <-interrupt:
|
|
|
|
//close(humidityChannel)
|
|
|
|
close(temperatureChannel)
|
|
|
|
return fmt.Errorf("Daemon was interruped by system signal %v", killSignal)
|
|
|
|
}
|
|
|
|
}
|
2019-06-13 19:25:32 +00:00
|
|
|
}
|