PKGBUILD/cmd/temperature/read.go

78 lines
2.0 KiB
Go

package temperature
import (
"context"
"fmt"
"log"
"os"
"github.com/go-flucky/flucky/pkg/types/typeswitch"
"github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/logfile"
"github.com/go-flucky/flucky/pkg/sensor"
"github.com/spf13/cobra"
)
var logs bool
var temperatureUnit string
var readTemperatureCmd = &cobra.Command{
Use: "read",
Short: "read temperature from sensor",
Example: fmt.Sprintf("flucky temperature read\nflucky temperature read outdoor"),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(configFile)
if err != nil {
log.Fatalln(err)
}
rgbLEDs := cnf.GetRGBLEDs(config.ENABLED)
rgbled.Run(rgbLEDs)
// fetch all temperature sensors or sensors by args
sensors := make([]sensor.Sensor, 0)
if len(args) == 0 {
sensors = cnf.GetTemperatureSensors(config.ENABLED)
} else {
sensors = cnf.GetTemperatureSensorsByName(args)
}
ctx := context.Background()
measuredValues, err := sensor.Read(ctx, sensors)
if err != nil {
rgbled.Error(rgbLEDs)
log.Fatalln(err)
}
temperatures := typeswitch.TemperatureValues(measuredValues)
// print temperatures on stdout
cli.PrintMeasuredValues(temperatures, cnf, os.Stdout)
if logs {
logfile := logfile.New(cnf.Device.Logfile)
err := logfile.Append(compression, measuredValues)
if err != nil {
rgbled.Error(rgbLEDs)
log.Fatalln(err)
}
}
rgbled.Off(rgbLEDs)
},
}
func init() {
temperatureCmd.AddCommand(readTemperatureCmd)
readTemperatureCmd.Flags().BoolVar(&logs, "logs", true, "Log temperature")
readTemperatureCmd.Flags().BoolVar(&compression, "compression", true, "Compress measured with logged temperatures")
readTemperatureCmd.Flags().Float64VarP(&round, "round", "r", 0.25, "Round values. The value 0 deactivates the function")
readTemperatureCmd.Flags().StringVar(&temperatureUnit, "temperature-unit", "celsius", "Temperature unit")
}