refac(cmd): mergeing, ordering and outsourcing cmd subcommands

This commit is contained in:
Markus Pesch 2020-01-13 22:26:41 +01:00
parent 0261203395
commit 0765bd29d1
Signed by: volker.raschek
GPG Key ID: 852BCC170D81A982
34 changed files with 1209 additions and 1302 deletions

View File

@ -1,20 +0,0 @@
package completion
import (
"os"
"github.com/spf13/cobra"
)
var bashCompletionCmd = &cobra.Command{
Use: "bash",
Short: "Generates a bash completion file",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
rootCmd.GenBashCompletion(os.Stdout)
},
}
func init() {
completionCmd.AddCommand(bashCompletionCmd)
}

View File

@ -1,22 +1,42 @@
package completion
import (
"os"
"github.com/spf13/cobra"
)
var (
rootCmd *cobra.Command
)
// InitCmd initialize all completion subcommands
func InitCmd(cmd *cobra.Command) error {
var completionCmd = &cobra.Command{
Use: "completion",
Short: "Generates a shell completion file",
}
completionCmd := &cobra.Command{
Use: "completion",
Short: "Generates a shell completion file",
}
// InitCmd initialize the subcommand
func InitCmd(cmd *cobra.Command) {
bashCompletionCmd := &cobra.Command{
Use: "bash",
Short: "Generates a bash completion file",
Args: cobra.NoArgs,
Example: "flucky completion bash",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.GenBashCompletion(os.Stdout)
},
}
zshCompletionCmd := &cobra.Command{
Use: "zsh",
Short: "Generate a zsh completion file",
Args: cobra.NoArgs,
Example: "flucky completion zsh",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.GenZshCompletion(os.Stdout)
},
}
completionCmd.AddCommand(bashCompletionCmd)
completionCmd.AddCommand(zshCompletionCmd)
cmd.AddCommand(completionCmd)
rootCmd = cmd
return nil
}

View File

@ -1,20 +0,0 @@
package completion
import (
"os"
"github.com/spf13/cobra"
)
var zshCompletionCmd = &cobra.Command{
Use: "zsh",
Short: "Generate a zsh completion file",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
rootCmd.GenZshCompletion(os.Stdout)
},
}
func init() {
completionCmd.AddCommand(zshCompletionCmd)
}

View File

@ -1,8 +1,6 @@
package compression
import (
"log"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/storage/logfile"
@ -10,40 +8,43 @@ import (
)
var (
configFile *string
round float64
round float64
)
var compressionCmd = &cobra.Command{
Use: "compression",
Short: "Compress a logfile",
Args: cobra.ExactArgs(1),
Example: "flucky compression /var/log/flucky/logfile.csv",
Run: func(cmd *cobra.Command, args []string) {
// InitCmd initialize all compression subcommands
func InitCmd(cmd *cobra.Command) error {
logfileInput := logfile.New(args[0])
measuredValues, err := logfileInput.Read()
if err != nil {
log.Fatalln(err)
}
compressionCmd := &cobra.Command{
Use: "compression",
Short: "Compress a logfile",
Args: cobra.ExactArgs(1),
Example: "flucky compression /var/log/flucky/logfile.csv",
RunE: run,
}
if round != 0 {
storage.Round(measuredValues, round)
}
storage.Compression(measuredValues)
err = logfileInput.Write(measuredValues)
if err != nil {
log.Fatalln(err)
}
},
}
func InitCmd(cmd *cobra.Command, cnfFile *string) {
configFile = cnfFile
cmd.AddCommand(compressionCmd)
compressionCmd.Flags().Float64Var(&round, "round", 0, "Round values. The value 0 deactivates the function")
cmd.AddCommand(compressionCmd)
return nil
}
func run(cmd *cobra.Command, args []string) error {
logfileInput := logfile.New(args[0])
measuredValues, err := logfileInput.Read()
if err != nil {
return err
}
if round != 0 {
storage.Round(measuredValues, round)
}
storage.Compression(measuredValues)
err = logfileInput.Write(measuredValues)
if err != nil {
return err
}
return nil
}

View File

@ -1,8 +1,6 @@
package convert
import (
"log"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/storage/logfile"
@ -11,45 +9,47 @@ import (
var (
compression bool
configFile *string
round float64
)
var convertCmd = &cobra.Command{
Use: "convert",
Short: "Convert logfiles into other markup language",
Args: cobra.ExactArgs(2),
Example: "flucky convert /var/log/flucky/logfile.json /var/log/flucky/logfile.csv",
Run: func(cmd *cobra.Command, args []string) {
// InitCmd initialize all convert subcommands
func InitCmd(cmd *cobra.Command) error {
logfileInput := logfile.New(args[0])
measuredValues, err := logfileInput.Read()
if err != nil {
log.Fatalln(err)
}
convertCmd := &cobra.Command{
Use: "convert",
Short: "Convert logfiles into other markup language",
Args: cobra.ExactArgs(2),
Example: "flucky convert /var/log/flucky/logfile.json /var/log/flucky/logfile.csv",
RunE: run,
}
if round != 0 {
storage.Round(measuredValues, round)
}
if compression {
measuredValues = storage.Compression(measuredValues)
}
logfileOutput := logfile.New(args[1])
err = logfileOutput.Write(measuredValues)
if err != nil {
log.Fatalln(err)
}
},
}
// InitCmd ...
func InitCmd(cmd *cobra.Command, cnfFile *string) {
configFile = cnfFile
cmd.AddCommand(convertCmd)
convertCmd.Flags().BoolVar(&compression, "compression", false, "Compress measured values")
convertCmd.Flags().Float64Var(&round, "round", 0, "Round values. The value 0 deactivates the function")
cmd.AddCommand(convertCmd)
return nil
}
func run(cmd *cobra.Command, args []string) error {
logfileInput := logfile.New(args[0])
measuredValues, err := logfileInput.Read()
if err != nil {
return err
}
if round != 0 {
storage.Round(measuredValues, round)
}
if compression {
measuredValues = storage.Compression(measuredValues)
}
logfileOutput := logfile.New(args[1])
err = logfileOutput.Write(measuredValues)
if err != nil {
return err
}
return nil
}

View File

@ -1,6 +1,7 @@
package daemon
import (
"fmt"
"log"
"github.com/go-flucky/flucky/pkg/config"
@ -12,33 +13,64 @@ import (
var (
cachedMeasuredValues uint
compression bool
configFile *string
round float64
temperatureUnit string
)
var daemonCmd = &cobra.Command{
Use: "daemon",
Short: "Read continuously data from all enabled sensors",
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// InitCmd initialize all daemon subcommands
func InitCmd(cmd *cobra.Command) error {
daemonCmd := &cobra.Command{
Use: "daemon",
Short: "Read continuously data from all enabled sensors",
Example: "flucky daemon",
RunE: run,
}
logger := logger.NewDefaultLogger(logger.LogLevelDebug)
daemon.SetLogger(logger)
daemon.Start(cnf, cachedMeasuredValues, compression, round)
},
}
func InitCmd(cmd *cobra.Command, cnfFile *string) {
configFile = cnfFile
cmd.AddCommand(daemonCmd)
daemonCmd.Flags().BoolVar(&compression, "compression", true, "Compress measured values")
daemonCmd.Flags().UintVar(&cachedMeasuredValues, "cached-values", 500, "Number of cached values before saveing into the storage endpoint")
daemonCmd.Flags().Float64Var(&round, "round", 0.5, "Round values. The value 0 deactivates the function")
cmd.AddCommand(daemonCmd)
return nil
}
func run(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined: %v", err)
}
// WARNING: Must set logger for daemon package
// logLevel, err := cmd.Flags().GetString("loglevel")
// if err != nil {
// return fmt.Errorf("No loglevel defined: %v", err)
// }
//flogger := initializeLogger(logLevel)
// daemon.SetLogLevel(flogger)
cnf, err := config.Read(configFile)
if err != nil {
return err
}
return daemon.Start(cnf, cachedMeasuredValues, compression, round)
}
func initializeLogger(logLevel string) logger.Logger {
log.Println(logLevel)
switch logLevel {
case "debug", "DEBUG":
return logger.NewDefaultLogger(logger.LogLevelDebug)
case "info", "INFO":
return logger.NewDefaultLogger(logger.LogLevelInfo)
case "warn", "WARN":
return logger.NewDefaultLogger(logger.LogLevelWarn)
case "error", "ERROR":
return logger.NewDefaultLogger(logger.LogLevelError)
case "fatal", "FATAL":
return logger.NewDefaultLogger(logger.LogLevelFatal)
default:
return nil
}
}

View File

@ -1,24 +1,133 @@
package humidity
import (
"context"
"fmt"
"os"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/sensor"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var (
compression bool
configFile *string
configFile string
save bool
round float64
)
var humidityCmd = &cobra.Command{
Use: "humidity",
Short: "Operates with humidity values",
}
// InitCmd initialize all humidity subcommands
func InitCmd(cmd *cobra.Command) error {
humidityCmd := &cobra.Command{
Use: "humidity",
Short: "Operates with humidity values",
}
// Execute a
func InitCmd(cmd *cobra.Command, cnfFile *string) {
configFile = cnfFile
listHumiditiesCmd := &cobra.Command{
Use: "list",
Short: "List humidity values from specified or all sensors",
Example: fmt.Sprintf("flucky humidity list"),
RunE: listHumidities,
}
readHumiditiesCmd := &cobra.Command{
Use: "read",
Short: "Read humidity values from specified or all sensors",
Example: fmt.Sprintf("flucky humidity read"),
RunE: readHumidities,
}
readHumiditiesCmd.Flags().BoolVar(&save, "save", true, "Save humidities")
readHumiditiesCmd.Flags().BoolVar(&compression, "compression", true, "Compress measured with logged temperatures")
readHumiditiesCmd.Flags().Float64VarP(&round, "round", "r", 0.25, "Round values. The value 0 deactivates the function")
humidityCmd.AddCommand(listHumiditiesCmd)
humidityCmd.AddCommand(readHumiditiesCmd)
cmd.AddCommand(humidityCmd)
return nil
}
func listHumidities(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
// read configuration
cnf, err := config.Read(configFile)
if err != nil {
return err
}
ctx := context.Background()
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
return err
}
measuredValues, err := storage.Read(ctx, storageEndpoint)
if err != nil {
return err
}
measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeHumidity, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
return nil
}
func readHumidities(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
// fetch all temperature sensors or sensors by args
sensors := make([]sensor.Sensor, 0)
if len(args) == 0 {
sensors = cnf.GetHumiditySensors(config.ENABLED)
} else {
sensors = cnf.GetHumiditySensorsByName(args)
}
if len(sensors) == 0 {
return fmt.Errorf("No sensors matched")
}
measuredValues, err := sensor.Read(sensors, types.MeasuredValueTypeHumidity)
if err != nil {
return err
}
measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeHumidity, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
if save {
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
return err
}
ctx := context.Background()
err = storage.Write(ctx, measuredValues, storageEndpoint)
if err != nil {
return err
}
}
return nil
}

View File

@ -1,49 +0,0 @@
package humidity
import (
"context"
"fmt"
"log"
"os"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/types"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var listTemperatureCmd = &cobra.Command{
Use: "list",
Short: "List humidity values from different or specified sensors by arguments",
Example: fmt.Sprintf("flucky humidity logs"),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
ctx := context.Background()
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
log.Fatalln(err)
}
measuredValues, err := storage.Read(ctx, storageEndpoint)
if err != nil {
log.Fatalln(err)
}
measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeHumidity, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
},
}
func init() {
humidityCmd.AddCommand(listTemperatureCmd)
}

View File

@ -1,79 +0,0 @@
package humidity
import (
"context"
"log"
"os"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/sensor"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var logs bool
var readHumidityCmd = &cobra.Command{
Use: "read",
Short: "Reading air pressure values from different or specified sensors by arguments",
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// fetch all temperature sensors or sensors by args
sensors := make([]sensor.Sensor, 0)
if len(args) == 0 {
sensors = cnf.GetHumiditySensors(config.ENABLED)
} else {
sensors = cnf.GetHumiditySensorsByName(args)
}
if len(sensors) == 0 {
return
}
rgbLEDs := cnf.GetRGBLEDs(config.ENABLED)
if err := rgbled.Run(rgbLEDs); err != nil {
log.Fatalln(err)
}
measuredValues, err := sensor.Read(sensors, types.MeasuredValueTypeTemperature)
if err := rgbled.Run(rgbLEDs); err != nil {
log.Fatalln(err)
}
measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeHumidity, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
if logs {
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
log.Fatalln(err)
}
ctx := context.Background()
err = storage.Write(ctx, measuredValues, storageEndpoint)
if err != nil {
log.Fatalln(err)
}
}
rgbled.Off(rgbLEDs)
},
}
func init() {
humidityCmd.AddCommand(readHumidityCmd)
readHumidityCmd.Flags().BoolVar(&logs, "logs", true, "Log temperature")
readHumidityCmd.Flags().BoolVar(&compression, "compression", true, "Compress measured with logged temperatures")
readHumidityCmd.Flags().Float64VarP(&round, "round", "r", 0.25, "Round values. The value 0 deactivates the function")
}

View File

@ -1,48 +0,0 @@
package pressure
import (
"context"
"fmt"
"log"
"os"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var listTemperatureCmd = &cobra.Command{
Use: "list",
Short: "Reading temperature values from different or specified sensors by arguments",
Example: fmt.Sprintf("flucky pressure logs"),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
ctx := context.Background()
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
log.Fatalln(err)
}
measuredValues, err := storage.Read(ctx, storageEndpoint)
if err != nil {
log.Fatalln(err)
}
measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypePressure, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
},
}
func init() {
pressureCmd.AddCommand(listTemperatureCmd)
}

View File

@ -1,27 +1,133 @@
package pressure
import (
"github.com/Masterminds/semver"
"context"
"fmt"
"os"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/sensor"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var (
compression bool
configFile *string
configFile string
save bool
round float64
version *semver.Version
)
var pressureCmd = &cobra.Command{
Use: "pressure",
Short: "List air pressure values from different or specified sensors by arguments",
}
// InitCmd initialize all pressure subcommands
func InitCmd(cmd *cobra.Command) error {
// Execute a
func InitCmd(cmd *cobra.Command, cnfFile *string) {
configFile = cnfFile
pressureCmd := &cobra.Command{
Use: "pressure",
Short: "Operates with pressure values",
}
listPressuresCmd := &cobra.Command{
Use: "list",
Short: "List pressure values from specified or all sensors",
Example: fmt.Sprintf("flucky pressure list"),
RunE: listHumidities,
}
readPressuresCmd := &cobra.Command{
Use: "read",
Short: "Read pressure values from specified or all sensors",
Example: fmt.Sprintf("flucky pressure read"),
RunE: readPressure,
}
readPressuresCmd.Flags().BoolVar(&save, "save", true, "Save humidities")
readPressuresCmd.Flags().BoolVar(&compression, "compression", true, "Compress measured with logged temperatures")
readPressuresCmd.Flags().Float64VarP(&round, "round", "r", 0.25, "Round values. The value 0 deactivates the function")
pressureCmd.AddCommand(listPressuresCmd)
pressureCmd.AddCommand(readPressuresCmd)
cmd.AddCommand(pressureCmd)
return nil
}
func listHumidities(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
ctx := context.Background()
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
return err
}
measuredValues, err := storage.Read(ctx, storageEndpoint)
if err != nil {
return err
}
measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypePressure, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
return nil
}
func readPressure(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
// fetch all temperature sensors or sensors by args
sensors := make([]sensor.Sensor, 0)
if len(args) == 0 {
sensors = cnf.GetPressureSensors(config.ENABLED)
} else {
sensors = cnf.GetPressureSensorsByName(args)
}
if len(sensors) == 0 {
return fmt.Errorf("No sensors matched")
}
measuredValues, err := sensor.Read(sensors, types.MeasuredValueTypePressure)
if err != nil {
return err
}
measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypePressure, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
if save {
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
return err
}
ctx := context.Background()
err = storage.Write(ctx, measuredValues, storageEndpoint)
if err != nil {
return err
}
}
return nil
}

View File

@ -1,78 +0,0 @@
package pressure
import (
"context"
"log"
"os"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/types"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/sensor"
"github.com/spf13/cobra"
)
var logs bool
var readPressureCmd = &cobra.Command{
Use: "read",
Short: "Operates with air pressure values",
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// fetch all temperature sensors or sensors by args
sensors := make([]sensor.Sensor, 0)
if len(args) == 0 {
sensors = cnf.GetPressureSensors(config.ENABLED)
} else {
sensors = cnf.GetPressureSensorsByName(args)
}
if len(sensors) == 0 {
return
}
rgbLEDs := cnf.GetRGBLEDs(config.ENABLED)
if err := rgbled.Run(rgbLEDs); err != nil {
log.Fatalln(err)
}
measuredValues, err := sensor.Read(sensors, types.MeasuredValueTypePressure)
if err := rgbled.Run(rgbLEDs); err != nil {
log.Fatalln(err)
}
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
if logs {
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
log.Fatalln(err)
}
ctx := context.Background()
err = storage.Write(ctx, measuredValues, storageEndpoint)
if err != nil {
log.Fatalln(err)
}
}
rgbled.Off(rgbLEDs)
},
}
func init() {
pressureCmd.AddCommand(readPressureCmd)
readPressureCmd.Flags().BoolVar(&logs, "logs", true, "Log temperature")
readPressureCmd.Flags().BoolVar(&compression, "compression", true, "Compress measured with logged temperatures")
readPressureCmd.Flags().Float64VarP(&round, "round", "r", 0.25, "Round values. The value 0 deactivates the function")
}

View File

@ -1,77 +0,0 @@
package rgbled
import (
"fmt"
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var enabled bool
var location string
var addRgbLedCmd = &cobra.Command{
Use: "add",
Short: "Add a RGB-LED",
Aliases: []string{"append"},
Args: cobra.ExactArgs(4),
Example: fmt.Sprintf(`flucky rgb-led add <name> <gpio-for-blue> <gpio-for-green> <gpio-for-red>
flucky rgb-led add my-led GPIO13 GPIO17 GPIO26`),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// determine gpio port
gpioBlue, err := types.StringToGPIO(args[1])
if err != nil {
log.Fatalln(err)
}
gpioGreen, err := types.StringToGPIO(args[2])
if err != nil {
log.Fatalln(err)
}
gpioRed, err := types.StringToGPIO(args[3])
if err != nil {
log.Fatalln(err)
}
// create new sensor struct
rgbLED := &types.RGBLED{
RGBLEDName: args[0],
RGBLEDLocation: location,
RGBLEDEnabled: enabled,
ActionMapping: types.DefaultActionMapping,
BaseColorsToGPIO: map[types.BaseColor]*types.GPIO{
types.BaseColorBlue: &gpioBlue,
types.BaseColorGreen: &gpioGreen,
types.BaseColorRed: &gpioRed,
},
}
// // add sensor entry to list
err = cnf.AddRGBLED(rgbLED)
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
rgbLedCmd.AddCommand(addRgbLedCmd)
addRgbLedCmd.Flags().BoolVarP(&enabled, "enabled", "e", true, "Enable Sensor")
addRgbLedCmd.Flags().StringVarP(&location, "location", "l", "", "Sensor location")
}

View File

@ -1,42 +0,0 @@
package rgbled
import (
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var disableRgbLedCmd = &cobra.Command{
Use: "disable",
Short: "Disable a RGB-LED",
Args: cobra.ExactArgs(1),
Example: `flucky rgb-led disable <name/uuid>
flucky rgb-led disable my-led
flucky rgb-led disable 9f8abfc5-91f3-480c-a42d-b990b6f89e5d`,
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// disable sensor entry to list
err = cnf.DisableRGBLED(args[0])
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
rgbLedCmd.AddCommand(disableRgbLedCmd)
}

View File

@ -1,41 +0,0 @@
package rgbled
import (
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var enableRgbLedCmd = &cobra.Command{
Use: "enable",
Short: "Enable a RGB-LED",
Example: `flucky rgb-led enable <name/uuid>
flucky rgb-led enable my-led
flucky rgb-led enable 9f8abfc5-91f3-480c-a42d-b990b6f89e5d`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// disable sensor entry to list
err = cnf.EnableRGBLED(args[0])
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
rgbLedCmd.AddCommand(enableRgbLedCmd)
}

View File

@ -1,30 +0,0 @@
package rgbled
import (
"log"
"os"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var listRgbLedCmd = &cobra.Command{
Use: "list",
Short: "List RGB-LEDs",
Aliases: []string{"ls"},
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// print sensors on stdout
cli.PrintRGBLEDs(cnf, os.Stdout)
},
}
func init() {
rgbLedCmd.AddCommand(listRgbLedCmd)
}

View File

@ -1,41 +0,0 @@
package rgbled
import (
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/rgbled"
"github.com/spf13/cobra"
)
var offRgbLedCmd = &cobra.Command{
Use: "off",
Short: "Turn a RGB-LED color off",
Example: `flucky rgb-led off <name/uuid> <blue>
flucky rgb-led off my-led`,
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
rgbLEDs := make([]rgbled.RGBLED, 0)
if len(args) != 0 {
rgbLEDs = cnf.GetRGBLEDsByName(args)
} else {
rgbLEDs = cnf.GetRGBLEDs(config.ENABLED)
}
err = rgbled.Off(rgbLEDs)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
rgbLedCmd.AddCommand(offRgbLedCmd)
}

View File

@ -1,50 +0,0 @@
package rgbled
import (
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var onRgbLedCmd = &cobra.Command{
Use: "on",
Short: "Turn a RGB-LED color on",
Example: `flucky rgb-led on <names/uuids> <blue/green/purple/red/turquoise/white/yellow>
flucky rgb-led on my-led blue
flucky rgb-led on my-led my-sweet-led white
flucky rgb-led on 1c5b9424-f6e9-4a37-be5c-77e531e94aab red`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
rgbLEDs := make([]rgbled.RGBLED, 0)
if len(args) > 1 {
rgbLEDs = cnf.GetRGBLEDsByName(args[0 : len(args)-1])
} else {
rgbLEDs = cnf.GetRGBLEDs(config.ENABLED)
}
color, err := types.StringToLEDColor(args[len(args)-1])
if err != nil {
log.Fatalln(err)
}
err = rgbled.CustomColor(rgbLEDs, color)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
rgbLedCmd.AddCommand(onRgbLedCmd)
}

View File

@ -1,41 +0,0 @@
package rgbled
import (
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var removeRgbLedCmd = &cobra.Command{
Use: "remove",
Short: "Remove a RGB-LED",
Example: `flucky rgb-led remove <name/uuid>
flucky rgb-led remove my-led
flucky rgb-led remove 9f8abfc5-91f3-480c-a42d-b990b6f89e5d`,
Aliases: []string{"rm"},
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// // add remote entry to list
err = cnf.RemoveRGBLED(args[0])
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
rgbLedCmd.AddCommand(removeRgbLedCmd)
}

View File

@ -1,40 +0,0 @@
package rgbled
import (
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var renameRgbLedCmd = &cobra.Command{
Use: "rename",
Short: "Rename a RGB-LED",
Args: cobra.ExactArgs(2),
Example: `flucky rgb-led disable <name/uuid> <new-name>
flucky rgb-led disable my-led my-sweet-led
flucky rgb-led disable 9f8abfc5-91f3-480c-a42d-b990b6f89e5d my-sweet-led`,
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// rename sensor
err = cnf.RenameRGBLED(args[0], args[1])
if err != nil {
log.Println(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
rgbLedCmd.AddCommand(renameRgbLedCmd)
}

View File

@ -1,25 +1,347 @@
package rgbled
import (
"fmt"
"os"
"github.com/Masterminds/semver"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var (
configFile *string
version *semver.Version
enabled bool
location string
version *semver.Version
)
var rgbLedCmd = &cobra.Command{
Use: "rgb-led",
Short: "Manage RGB-LEDs",
}
// InitCmd initialize all rgb-led subcommands
func InitCmd(cmd *cobra.Command) error {
// InitCmd da
func InitCmd(cmd *cobra.Command, cnfFile *string) {
configFile = cnfFile
rgbLedCmd := &cobra.Command{
Use: "rgb-led",
Short: "Manage RGB-LEDs",
}
addRGBLEDCmd := &cobra.Command{
Use: "add",
Short: "Add a RGB-LED",
Aliases: []string{"append"},
Args: cobra.ExactArgs(4),
Example: fmt.Sprintf(`flucky rgb-led add <name> <gpio-for-blue> <gpio-for-green> <gpio-for-red>
flucky rgb-led add my-led GPIO13 GPIO17 GPIO26`),
RunE: addRGBLED,
}
addRGBLEDCmd.Flags().BoolVarP(&enabled, "enabled", "e", true, "Enable Sensor")
addRGBLEDCmd.Flags().StringVarP(&location, "location", "l", "", "Sensor location")
disableRGBLEDCmd := &cobra.Command{
Use: "disable",
Short: "Disable a RGB-LED",
Args: cobra.ExactArgs(1),
Example: `flucky rgb-led disable <name/uuid>
flucky rgb-led disable my-led
flucky rgb-led disable 9f8abfc5-91f3-480c-a42d-b990b6f89e5d`,
RunE: disableRGBLED,
}
enableRGBLEDCmd := &cobra.Command{
Use: "enable",
Short: "Enable a RGB-LED",
Args: cobra.ExactArgs(1),
Example: `flucky rgb-led enable <name/uuid>
flucky rgb-led enable my-led
flucky rgb-led enable 9f8abfc5-91f3-480c-a42d-b990b6f89e5d`,
RunE: enableRGBLED,
}
listRGBLEDCmd := &cobra.Command{
Use: "list",
Short: "List RGB-LEDs",
Aliases: []string{"ls"},
RunE: listRGBLED,
}
turnOffRGBLEDCmd := &cobra.Command{
Use: "off",
Short: "Turn a RGB-LED color off",
Example: `flucky rgb-led off <name/uuid> <blue>
flucky rgb-led off my-led`,
RunE: turnOffRGBLED,
}
turnOnRGBLEDCmd := &cobra.Command{
Use: "on",
Short: "Turn a RGB-LED color on",
Example: `flucky rgb-led on <names/uuids> <blue/green/purple/red/turquoise/white/yellow>
flucky rgb-led on my-led blue
flucky rgb-led on my-led my-sweet-led white
flucky rgb-led on 1c5b9424-f6e9-4a37-be5c-77e531e94aab red`,
Args: cobra.MinimumNArgs(1),
RunE: turnOnRGBLED,
}
removeRGBLEDCmd := &cobra.Command{
Use: "remove",
Short: "Remove a RGB-LED",
Example: `flucky rgb-led remove <name/uuid>
flucky rgb-led remove my-led
flucky rgb-led remove 9f8abfc5-91f3-480c-a42d-b990b6f89e5d`,
Aliases: []string{"rm"},
Args: cobra.ExactArgs(1),
RunE: removeRGBLED,
}
renameRGBLEDCmd := &cobra.Command{
Use: "rename",
Short: "Rename a RGB-LED",
Args: cobra.ExactArgs(2),
Example: `flucky rgb-led disable <name/uuid> <new-name>
flucky rgb-led disable my-led my-sweet-led
flucky rgb-led disable 9f8abfc5-91f3-480c-a42d-b990b6f89e5d my-sweet-led`,
RunE: renameRGBLED,
}
rgbLedCmd.AddCommand(addRGBLEDCmd)
rgbLedCmd.AddCommand(disableRGBLEDCmd)
rgbLedCmd.AddCommand(enableRGBLEDCmd)
rgbLedCmd.AddCommand(listRGBLEDCmd)
rgbLedCmd.AddCommand(turnOffRGBLEDCmd)
rgbLedCmd.AddCommand(turnOnRGBLEDCmd)
rgbLedCmd.AddCommand(removeRGBLEDCmd)
rgbLedCmd.AddCommand(renameRGBLEDCmd)
cmd.AddCommand(rgbLedCmd)
return nil
}
func addRGBLED(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
gpioBlue, err := types.StringToGPIO(args[1])
if err != nil {
return err
}
gpioGreen, err := types.StringToGPIO(args[2])
if err != nil {
return err
}
gpioRed, err := types.StringToGPIO(args[3])
if err != nil {
return err
}
rgbLED := &types.RGBLED{
RGBLEDName: args[0],
RGBLEDLocation: location,
RGBLEDEnabled: enabled,
ActionMapping: types.DefaultActionMapping,
BaseColorsToGPIO: map[types.BaseColor]*types.GPIO{
types.BaseColorBlue: &gpioBlue,
types.BaseColorGreen: &gpioGreen,
types.BaseColorRed: &gpioRed,
},
}
err = cnf.AddRGBLED(rgbLED)
if err != nil {
return err
}
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}
func disableRGBLED(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
err = cnf.DisableRGBLED(args[0])
if err != nil {
return err
}
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}
func enableRGBLED(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
err = cnf.EnableRGBLED(args[0])
if err != nil {
return err
}
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}
func listRGBLED(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
// print sensors on stdout
cli.PrintRGBLEDs(cnf, os.Stdout)
return nil
}
func turnOffRGBLED(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
rgbLEDs := make([]rgbled.RGBLED, 0)
if len(args) != 0 {
rgbLEDs = cnf.GetRGBLEDsByName(args)
} else {
rgbLEDs = cnf.GetRGBLEDs(config.ENABLED)
}
err = rgbled.Off(rgbLEDs)
if err != nil {
return err
}
return nil
}
func turnOnRGBLED(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
rgbLEDs := make([]rgbled.RGBLED, 0)
if len(args) > 1 {
rgbLEDs = cnf.GetRGBLEDsByName(args[0 : len(args)-1])
} else {
rgbLEDs = cnf.GetRGBLEDs(config.ENABLED)
}
color, err := types.StringToLEDColor(args[len(args)-1])
if err != nil {
return err
}
err = rgbled.CustomColor(rgbLEDs, color)
if err != nil {
return err
}
return nil
}
func removeRGBLED(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
err = cnf.RemoveRGBLED(args[0])
if err != nil {
return err
}
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}
func renameRGBLED(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
err = cnf.RenameRGBLED(args[0], args[1])
if err != nil {
return err
}
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}

View File

@ -2,6 +2,7 @@ package cmd
import (
"fmt"
"log"
"math"
"os"
"time"
@ -17,66 +18,107 @@ import (
"github.com/go-flucky/flucky/cmd/sensor"
"github.com/go-flucky/flucky/cmd/temperature"
"github.com/go-flucky/flucky/pkg/types"
"github.com/volker-raschek/go-logger/pkg/logger"
"github.com/go-flucky/flucky/pkg/config"
uuid "github.com/satori/go.uuid"
"github.com/spf13/cobra"
)
var configFile string
var rootCmd = &cobra.Command{
Use: "flucky",
Short: "flucky - operate with differen sensors, his values and remote servers to synchronize measured values",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
// check if config file exists
if _, err := os.Stat(configFile); os.IsNotExist(err) {
hostname, err := os.Hostname()
if err != nil {
return fmt.Errorf("Can not locate the hostname: %v", err)
}
// Time must be truncted for postgres. Postgres currently does not support
// nanoseconds which is automatically include into the go time object
t := time.Now()
l, _ := time.LoadLocation("Europe/Berlin")
t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), int(math.Round(float64(t.Nanosecond())/1000000)*1000000), l)
// Default configuration
cnf := config.Configuration{
Device: &types.Device{
ID: uuid.NewV4().String(),
Name: hostname,
CreationDate: t,
},
StorageEndpoint: "file:///var/log/flucky/logfile.csv",
}
err = config.Write(&cnf, configFile)
if err != nil {
return err
}
}
return nil
},
}
var (
configFile string
)
// Execute a
func Execute(version *semver.Version) {
rootCmd.Version = version.String()
func Execute(version *semver.Version) error {
rootCmd := &cobra.Command{
Use: "flucky",
Short: "flucky - operate with differen sensors, his values and remote servers to synchronize measured values",
PersistentPreRunE: preRunError,
Version: version.String(),
}
logLevel := ""
rootCmd.PersistentFlags().StringVar(&configFile, "config", "/etc/flucky/config.json", "Config file")
rootCmd.PersistentFlags().StringVar(&logLevel, "loglevel", "info", "Set the Loglevel. Possible values: debug, info, warn, error, fatal")
completion.InitCmd(rootCmd)
compression.InitCmd(rootCmd, &configFile)
convert.InitCmd(rootCmd, &configFile)
daemon.InitCmd(rootCmd, &configFile)
humidity.InitCmd(rootCmd, &configFile)
pressure.InitCmd(rootCmd, &configFile)
rgbled.InitCmd(rootCmd, &configFile)
sensor.InitCmd(rootCmd, &configFile)
temperature.InitCmd(rootCmd, &configFile)
rootCmd.Execute()
subCommands := []func(cmd *cobra.Command) error{
completion.InitCmd,
compression.InitCmd,
convert.InitCmd,
daemon.InitCmd,
humidity.InitCmd,
pressure.InitCmd,
rgbled.InitCmd,
sensor.InitCmd,
temperature.InitCmd,
}
for _, subCommand := range subCommands {
if err := subCommand(rootCmd); err != nil {
return err
}
}
err := rootCmd.Execute()
if err != nil {
return err
}
return nil
}
func parseLogger(logLevel string) logger.Logger {
log.Println(logLevel)
switch logLevel {
case "debug", "DEBUG":
return logger.NewDefaultLogger(logger.LogLevelDebug)
case "info", "INFO":
return logger.NewDefaultLogger(logger.LogLevelInfo)
case "warn", "WARN":
return logger.NewDefaultLogger(logger.LogLevelWarn)
case "error", "ERROR":
return logger.NewDefaultLogger(logger.LogLevelError)
case "fatal", "FATAL":
return logger.NewDefaultLogger(logger.LogLevelFatal)
default:
return logger.NewDefaultLogger(logger.LogLevelInfo)
}
}
func preRunError(cmd *cobra.Command, args []string) error {
// check if config file exists
if _, err := os.Stat(configFile); os.IsNotExist(err) {
hostname, err := os.Hostname()
if err != nil {
return fmt.Errorf("Can not locate the hostname: %v", err)
}
// Time must be truncted for postgres. Postgres currently does not support
// nanoseconds which is automatically include into the go time object
postgresTimeStamp := time.Now()
location, err := time.LoadLocation("Europe/Berlin")
if err != nil {
return err
}
postgresTimeStamp = time.Date(postgresTimeStamp.Year(), postgresTimeStamp.Month(), postgresTimeStamp.Day(), postgresTimeStamp.Hour(), postgresTimeStamp.Minute(), postgresTimeStamp.Second(), int(math.Round(float64(postgresTimeStamp.Nanosecond())/1000000)*1000000), location)
// Default configuration
cnf := config.Configuration{
Device: &types.Device{
ID: uuid.NewV4().String(),
Name: hostname,
CreationDate: postgresTimeStamp,
},
StorageEndpoint: "file:///var/log/flucky/logfile.csv",
}
err = config.Write(&cnf, configFile)
if err != nil {
return err
}
}
return nil
}

View File

@ -1,104 +0,0 @@
package sensor
import (
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var (
enabled bool
gpioIn string
i2cAddress uint8
i2cBus int
location string
tickDuration string
wireID string
)
var addSensorCmd = &cobra.Command{
Use: "add",
Short: "Add Sensor",
Aliases: []string{"append"},
Args: cobra.ExactArgs(2),
Example: `flucky sensor add --gpio GPIO14 indoor DHT11
flucky sensor add --wire-id 28-011432f0bb3d outdoor DS18B20
flucky sensor add --i2c-bus 1 --i2c-address 0x76 wetter-station BME280`,
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// determine sensor model
sensorModel, err := types.SelectSensorModel(args[1])
if err != nil {
log.Fatalln(err)
}
// create new sensor struct
sensor := &types.Sensor{
Name: args[0],
Model: sensorModel,
Location: location,
Enabled: enabled,
TickDuration: tickDuration,
}
// determine gpio port if set
if gpioIn != "" &&
i2cAddress == 0 &&
i2cBus == 0 &&
wireID == "" {
gpio, err := types.StringToGPIO(gpioIn)
if err != nil {
log.Fatalln(err)
}
sensor.GPIONumber = &gpio
}
// set i2c connection settings
if gpioIn == "" &&
i2cAddress != 0 &&
i2cBus != 0 &&
wireID == "" {
sensor.I2CAddress = &i2cAddress
sensor.I2CBus = &i2cBus
}
// set wire connection settings
if gpioIn == "" &&
i2cAddress == 0 &&
i2cBus == 0 &&
wireID != "" {
sensor.WireID = &wireID
}
// add sensor entry to list
err = cnf.AddSensor(sensor)
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
sensorCmd.AddCommand(addSensorCmd)
addSensorCmd.Flags().BoolVar(&enabled, "enabled", true, "Enable new sensor")
addSensorCmd.Flags().StringVar(&gpioIn, "gpio", "", "Defines the GPIO port")
addSensorCmd.Flags().Uint8Var(&i2cAddress, "i2c-address", 0, "Defines the I2C address on the I2C bus")
addSensorCmd.Flags().IntVar(&i2cBus, "i2c-bus", 0, "Defines the I2C bus")
addSensorCmd.Flags().StringVar(&location, "location", "", "Location of the sensor")
addSensorCmd.Flags().StringVar(&tickDuration, "tick-duration", "1m", "Controls how often values should be read from the sensor when running flucky in daemon mode")
addSensorCmd.Flags().StringVar(&wireID, "wire-id", "", "Defines the Wire-ID")
}

View File

@ -1,40 +0,0 @@
package sensor
import (
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var disableSensorCmd = &cobra.Command{
Use: "disable",
Short: "Disable Sensor",
Args: cobra.ExactArgs(1),
Example: "flucky sensor disable outdoor",
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// disable sensor entry to list
err = cnf.DisableSensor(args[0])
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
sensorCmd.AddCommand(disableSensorCmd)
}

View File

@ -1,39 +0,0 @@
package sensor
import (
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var enableSensorCmd = &cobra.Command{
Use: "enable",
Short: "Enable Sensor",
Example: "flucky sensor enable outdoor",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// disable sensor entry to list
err = cnf.EnableSensor(args[0])
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
sensorCmd.AddCommand(enableSensorCmd)
}

View File

@ -1,39 +0,0 @@
package sensor
import (
"log"
"os"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var listSensorCmd = &cobra.Command{
Use: "list",
Short: "List Sensors",
Aliases: []string{"ls"},
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// print sensors on stdout
err = cli.PrintSensors(cnf, os.Stdout)
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
sensorCmd.AddCommand(listSensorCmd)
}

View File

@ -1,39 +0,0 @@
package sensor
import (
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var rmSensorCmd = &cobra.Command{
Use: "remove",
Short: "Remove Sensor",
Example: "flucky sensor rm outdoor",
Aliases: []string{"rm"},
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// // add remote entry to list
err = cnf.RemoveSensor(args[0])
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
sensorCmd.AddCommand(rmSensorCmd)
}

View File

@ -1,39 +0,0 @@
package sensor
import (
"fmt"
"log"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var renameSensorCmd = &cobra.Command{
Use: "rename",
Short: "Rename Sensor",
Args: cobra.ExactArgs(2),
Example: fmt.Sprintf("flucky sensor rename indoor outdoor\nflucky sensor rename f98b00ea-a9b2-4e00-924f-113859d0af2d outdoor"),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
// rename sensor
err = cnf.RenameSensor(args[0], args[1])
if err != nil {
log.Println(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
if err != nil {
log.Fatalln(err)
}
},
}
func init() {
sensorCmd.AddCommand(renameSensorCmd)
}

View File

@ -1,25 +1,291 @@
package sensor
import (
"github.com/Masterminds/semver"
"fmt"
"os"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var (
configFile *string
version *semver.Version
enabled bool
gpioIn string
i2cAddress uint8
i2cBus int
location string
tickDuration string
wireID string
)
var sensorCmd = &cobra.Command{
Use: "sensor",
Short: "Manage Sensors",
}
// InitCmd initialize all sensor subcommands
func InitCmd(cmd *cobra.Command) error {
sensorCmd := &cobra.Command{
Use: "sensor",
Short: "Manage Sensors",
}
// InitCmd da
func InitCmd(cmd *cobra.Command, cnfFile *string) {
configFile = cnfFile
addSensorCmd := &cobra.Command{
Use: "add",
Short: "Add Sensor",
Aliases: []string{"append"},
Args: cobra.ExactArgs(2),
Example: `flucky sensor add --gpio GPIO14 indoor DHT11
flucky sensor add --wire-id 28-011432f0bb3d outdoor DS18B20
flucky sensor add --i2c-bus 1 --i2c-address 0x76 wetter-station BME280`,
RunE: addSensor,
}
addSensorCmd.Flags().BoolVar(&enabled, "enabled", true, "Enable new sensor")
addSensorCmd.Flags().StringVar(&gpioIn, "gpio", "", "Defines the GPIO port")
addSensorCmd.Flags().Uint8Var(&i2cAddress, "i2c-address", 0, "Defines the I2C address on the I2C bus")
addSensorCmd.Flags().IntVar(&i2cBus, "i2c-bus", 0, "Defines the I2C bus")
addSensorCmd.Flags().StringVar(&location, "location", "", "Location of the sensor")
addSensorCmd.Flags().StringVar(&tickDuration, "tick-duration", "1m", "Controls how often values should be read from the sensor when running flucky in daemon mode")
addSensorCmd.Flags().StringVar(&wireID, "wire-id", "", "Defines the Wire-ID")
disableSensorCmd := &cobra.Command{
Use: "disable",
Short: "Disable Sensor",
Args: cobra.ExactArgs(1),
Example: "flucky sensor disable outdoor",
RunE: deleteSensor,
}
enableSensorCmd := &cobra.Command{
Use: "enable",
Short: "Enable Sensor",
Example: "flucky sensor enable outdoor",
Args: cobra.ExactArgs(1),
RunE: enableSensor,
}
listSensorCmd := &cobra.Command{
Use: "list",
Short: "List Sensors",
Aliases: []string{"ls"},
RunE: listSensors,
}
removeSensorCmd := &cobra.Command{
Use: "remove",
Short: "Remove Sensor",
Aliases: []string{"rm"},
Example: "flucky sensor remove outdoor",
Args: cobra.ExactArgs(1),
RunE: enableSensor,
}
renameSensorCmd := &cobra.Command{
Use: "rename",
Short: "Rename Sensor",
Args: cobra.ExactArgs(2),
Example: `flucky sensor rename indoor outdoor
flucky sensor rename f98b00ea-a9b2-4e00-924f-113859d0af2d outdoor`,
RunE: renameSensor,
}
sensorCmd.AddCommand(addSensorCmd)
sensorCmd.AddCommand(disableSensorCmd)
sensorCmd.AddCommand(enableSensorCmd)
sensorCmd.AddCommand(listSensorCmd)
sensorCmd.AddCommand(removeSensorCmd)
sensorCmd.AddCommand(renameSensorCmd)
cmd.AddCommand(sensorCmd)
return nil
}
func addSensor(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
sensorModel, err := types.SelectSensorModel(args[1])
if err != nil {
return err
}
sensor := &types.Sensor{
Name: args[0],
Model: sensorModel,
Location: location,
Enabled: enabled,
TickDuration: tickDuration,
}
// determine gpio port if set
if gpioIn != "" &&
i2cAddress == 0 &&
i2cBus == 0 &&
wireID == "" {
gpio, err := types.StringToGPIO(gpioIn)
if err != nil {
return err
}
sensor.GPIONumber = &gpio
}
// set i2c connection settings
if gpioIn == "" &&
i2cAddress != 0 &&
i2cBus != 0 &&
wireID == "" {
sensor.I2CAddress = &i2cAddress
sensor.I2CBus = &i2cBus
}
// set wire connection settings
if gpioIn == "" &&
i2cAddress == 0 &&
i2cBus == 0 &&
wireID != "" {
sensor.WireID = &wireID
}
// add sensor entry to list
err = cnf.AddSensor(sensor)
if err != nil {
return err
}
// save new configuration
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}
func deleteSensor(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
err = cnf.DisableSensor(args[0])
if err != nil {
return err
}
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}
func enableSensor(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
err = cnf.EnableSensor(args[0])
if err != nil {
return err
}
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}
func listSensors(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
err = cli.PrintSensors(cnf, os.Stdout)
if err != nil {
return err
}
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}
func removeSensor(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
err = cnf.RemoveSensor(args[0])
if err != nil {
return err
}
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}
func renameSensor(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
err = cnf.RenameSensor(args[0], args[1])
if err != nil {
return err
}
err = config.Write(cnf, configFile)
if err != nil {
return err
}
return nil
}

View File

@ -1,49 +0,0 @@
package temperature
import (
"context"
"fmt"
"log"
"os"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/types"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/spf13/cobra"
)
var listTemperatureCmd = &cobra.Command{
Use: "list",
Short: "List temperature values from different or specified sensors by arguments",
Example: fmt.Sprintf("flucky temperature logs"),
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
if err != nil {
log.Fatalln(err)
}
ctx := context.Background()
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
log.Fatalln(err)
}
measuredValues, err := storage.Read(ctx, storageEndpoint)
if err != nil {
log.Fatalln(err)
}
measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeTemperature, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
},
}
func init() {
temperatureCmd.AddCommand(listTemperatureCmd)
}

View File

@ -1,77 +0,0 @@
package temperature
import (
"context"
"fmt"
"log"
"os"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/sensor"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var readTemperatureCmd = &cobra.Command{
Use: "read",
Short: "Reading temperature values from different or specified sensors by arguments",
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)
}
// 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)
}
if len(sensors) == 0 {
log.Fatalln("No sensors found, specified or configured")
}
rgbLEDs := cnf.GetRGBLEDs(config.ENABLED)
if err := rgbled.Run(rgbLEDs); err != nil {
log.Fatalln(err)
}
measuredValues, err := sensor.Read(sensors, types.MeasuredValueTypeTemperature)
if err := rgbled.Run(rgbLEDs); err != nil {
log.Fatalln(err)
}
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
if logs {
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
log.Fatalln(err)
}
ctx := context.Background()
err = storage.Write(ctx, measuredValues, storageEndpoint)
if err != nil {
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")
}

View File

@ -1,31 +1,131 @@
package temperature
import (
"context"
"fmt"
"os"
"github.com/Masterminds/semver"
"github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/sensor"
"github.com/go-flucky/flucky/pkg/storage"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var (
compression bool
configFile *string
logs bool
save bool
round float64
version *semver.Version
)
var temperatureCmd = &cobra.Command{
Use: "temperature",
Short: "Operates with temperature values",
Example: fmt.Sprintf("flucky temperature read\nflucky temperature read outdoor"),
}
// InitCmd initialize all temperature subcommands
func InitCmd(cmd *cobra.Command) error {
// InitCmd initialize the subcommand
func InitCmd(cmd *cobra.Command, cnfFile *string) {
configFile = cnfFile
temperatureCmd := &cobra.Command{
Use: "temperature",
Short: "Operates with temperature values",
}
listTemperaturesCmd := &cobra.Command{
Use: "list",
Short: "List temperature values from specified or all sensors",
Example: fmt.Sprintf("flucky temperature list"),
RunE: listTemperatures,
}
readTemperatures := &cobra.Command{
Use: "read",
Short: "Read temperature values from specified or all sensors",
Example: fmt.Sprintf("flucky temperature read"),
RunE: readTemperature,
}
readTemperatures.Flags().BoolVar(&save, "save", true, "Save humidities")
readTemperatures.Flags().BoolVar(&compression, "compression", true, "Compress measured with logged temperatures")
readTemperatures.Flags().Float64VarP(&round, "round", "r", 0.25, "Round values. The value 0 deactivates the function")
temperatureCmd.AddCommand(listTemperaturesCmd)
temperatureCmd.AddCommand(readTemperatures)
cmd.AddCommand(temperatureCmd)
return nil
}
func listTemperatures(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
ctx := context.Background()
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
return err
}
measuredValues, err := storage.Read(ctx, storageEndpoint)
if err != nil {
return err
}
measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeTemperature, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
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")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
sensors := make([]sensor.Sensor, 0)
if len(args) == 0 {
sensors = cnf.GetTemperatureSensors(config.ENABLED)
} else {
sensors = cnf.GetTemperatureSensorsByName(args)
}
if len(sensors) == 0 {
return fmt.Errorf("No sensors matched")
}
measuredValues, err := sensor.Read(sensors, types.MeasuredValueTypeTemperature)
if err != nil {
return err
}
measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeTemperature, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)
if save {
storageEndpoint, err := cnf.GetStorageEndpointURL()
if err != nil {
return err
}
ctx := context.Background()
err = storage.Write(ctx, measuredValues, storageEndpoint)
if err != nil {
return err
}
}
return nil
}

View File

@ -19,5 +19,8 @@ func main() {
os.Exit(1)
}
cmd.Execute(sversion)
err = cmd.Execute(sversion)
if err != nil {
log.Fatal(err)
}
}

View File

@ -15,19 +15,9 @@ import (
)
var (
postgresHost = "markus-pc.trier.cryptic.systems"
postgresPort = "5432"
postgresDatabase = "postgres"
postgresUser = "postgres"
postgresPassword = "postgres"
flogger = logger.NewSilentLogger()
flogger = logger.NewDefaultLogger(logger.LogLevelDebug)
)
func SetLogger(logger logger.Logger) {
flogger = logger
}
// Start the daemon
func Start(cnf *config.Configuration, cacheSize uint, compression bool, round float64) error {
@ -59,8 +49,8 @@ func Start(cnf *config.Configuration, cacheSize uint, compression bool, round fl
measuredValueChannel := make(chan *types.MeasuredValue, 0)
// Info
flogger.Info("Use compression: %v", compression)
flogger.Info("Round: %v", round)
flogger.Debug("Use compression: %v", compression)
flogger.Debug("Round values to: %v", round)
// Init semaphoreChannel
semaphoreChannels := make(map[string]chan struct{})
@ -77,7 +67,6 @@ func Start(cnf *config.Configuration, cacheSize uint, compression bool, round fl
for {
select {
case <-ctx.Done():
errorChannel <- fmt.Errorf("Closed context: %v", ctx.Err().Error())
return
case <-semaphoreChannels[sensor.GetID()]:
measuredValues, err := sensor.Read()
@ -97,7 +86,6 @@ func Start(cnf *config.Configuration, cacheSize uint, compression bool, round fl
for {
select {
case <-ctx.Done():
errorChannel <- fmt.Errorf("Closed context: %v", ctx.Err().Error())
return
case <-sensor.GetTicker().C:
semaphoreChannels[sensor.GetID()] <- struct{}{}
@ -114,7 +102,7 @@ func Start(cnf *config.Configuration, cacheSize uint, compression bool, round fl
return
case measuredValue := <-measuredValueChannel:
cache.Add(measuredValue)
debugChannel <- fmt.Sprintf("CacheStore ID %v: %v - %v - %v", cache.Size(), measuredValue.SensorID, measuredValue.ValueType, measuredValue.Value)
debugChannel <- fmt.Sprintf("CacheStore ID: %v, Sensor ID: %v, Type: %v, Value: %v", cache.Size(), measuredValue.SensorID, measuredValue.ValueType, measuredValue.Value)
if cache.Size() >= int(cacheSize) {
debugChannel <- fmt.Sprint("Write cache into storage endpoint")
err := cache.WriteToEndpoint()