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") }