PKGBUILD/cmd/sensor/add.go

105 lines
2.5 KiB
Go
Raw Normal View History

2018-11-28 17:07:20 +00:00
package sensor
import (
2019-02-24 21:46:36 +00:00
"log"
2019-02-22 12:08:58 +00:00
2019-06-15 13:58:41 +00:00
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/types"
2018-11-28 17:07:20 +00:00
"github.com/spf13/cobra"
)
var (
enabled bool
gpioIn string
i2cAddress uint8
i2cBus int
location string
tickDuration string
wireID string
)
2018-11-28 17:07:20 +00:00
var addSensorCmd = &cobra.Command{
2019-02-22 12:08:58 +00:00
Use: "add",
Short: "Add Sensor",
2019-02-24 21:46:36 +00:00
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`,
2019-02-24 21:46:36 +00:00
Run: func(cmd *cobra.Command, args []string) {
// read configuration
cnf, err := config.Read(*configFile)
2019-02-24 21:46:36 +00:00
if err != nil {
log.Fatalln(err)
}
2019-02-28 18:48:25 +00:00
// determine sensor model
sensorModel, err := types.SelectSensorModel(args[1])
if err != nil {
log.Fatalln(err)
}
2019-02-24 21:46:36 +00:00
// create new sensor struct
sensor := &types.Sensor{
Name: args[0],
Model: sensorModel,
Location: location,
Enabled: enabled,
TickDuration: tickDuration,
2019-02-24 21:46:36 +00:00
}
// 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)
2019-02-24 21:46:36 +00:00
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(cnf, *configFile)
2019-02-24 21:46:36 +00:00
if err != nil {
log.Fatalln(err)
}
},
2018-11-28 17:07:20 +00:00
}
func init() {
sensorCmd.AddCommand(addSensorCmd)
2019-02-24 21:46:36 +00:00
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")
2018-11-28 17:07:20 +00:00
}