PKGBUILD/cli/temperature/temperature.go

132 lines
2.6 KiB
Go
Raw Normal View History

package temperature
import (
"context"
"fmt"
"net/url"
"os"
"git.cryptic.systems/volker.raschek/flucky/pkg/cli"
"git.cryptic.systems/volker.raschek/flucky/pkg/config"
"git.cryptic.systems/volker.raschek/flucky/pkg/repository"
"git.cryptic.systems/volker.raschek/flucky/pkg/sensor"
"git.cryptic.systems/volker.raschek/flucky/pkg/types"
"git.cryptic.systems/volker.raschek/go-logger"
"github.com/spf13/cobra"
)
func InitCmd(cmd *cobra.Command) error {
temperatureCmd := &cobra.Command{
Use: "temperature",
Short: "Read and list temperature values",
}
readTemperatureCmd := &cobra.Command{
Use: "read",
Short: "Read temperature values from sensors",
RunE: readTemperature,
}
readTemperatureCmd.Flags().Bool("persist", true, "Persist measured values to the repository")
temperatureCmd.AddCommand(readTemperatureCmd)
cmd.AddCommand(temperatureCmd)
return nil
}
func readTemperature(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
persist, err := cmd.Flags().GetBool("persist")
if err != nil {
return fmt.Errorf("Flag persist not defined: %v", err)
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
dsnURL, err := url.Parse(cnf.DSN)
if err != nil {
return err
}
logLevelString, err := cmd.Flags().GetString("loglevel")
if err != nil {
return err
}
logLevel, err := logger.ParseLogLevel(logLevelString)
if err != nil {
return err
}
flogger := logger.NewLogger(logLevel)
repo, err := repository.New(dsnURL, flogger)
if err != nil {
return err
}
ctx := context.Background()
sensorTypes, err := repo.GetSensors(ctx)
if err != nil {
return err
}
sensorTypes, err = types.FilterSensorByMeasuredValueTypes(sensorTypes, types.Temperature)
if err != nil {
return err
}
sensors := make([]sensor.Sensor, 0)
for i := range sensorTypes {
s, err := sensor.New(sensorTypes[i])
if err != nil {
return err
}
sensors = append(sensors, s)
}
measuredValueChannel, errorChannel := sensor.ReadPipeline(context.TODO(), sensors...)
go func() {
for {
2021-05-16 21:02:46 +00:00
err, open := <-errorChannel
if !open {
return
}
2021-05-16 21:02:46 +00:00
flogger.Error("%v", err)
}
}()
measuredValues := make([]*types.MeasuredValue, 0)
LOOP:
for {
2021-05-16 21:02:46 +00:00
measuredValue, open := <-measuredValueChannel
if !open {
break LOOP
}
2021-05-16 21:02:46 +00:00
measuredValues = append(measuredValues, measuredValue)
}
err = cli.PrintMeasuredValues(measuredValues, os.Stdout)
if err != nil {
return err
}
if persist {
err = repo.AddMeasuredValues(ctx, measuredValues...)
if err != nil {
return err
}
}
return nil
}