fix: add, rename and remove sensor

changes:
- Implement function to add, rename and remove sensors
This commit is contained in:
Markus Pesch 2020-05-17 13:00:51 +02:00
parent fb8d4dd5eb
commit fb916c94ae
Signed by: volker.raschek
GPG Key ID: 852BCC170D81A982
12 changed files with 757 additions and 85 deletions

48
cli/daemon/daemon.go Normal file
View File

@ -0,0 +1,48 @@
package daemon
import (
"fmt"
"github.com/spf13/cobra"
"github.com/volker-raschek/flucky/pkg/config"
"github.com/volker-raschek/flucky/pkg/daemon"
"github.com/volker-raschek/go-logger/pkg/logger"
)
// 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,
}
daemonCmd.Flags().Bool("compression", true, "Compress measured values")
daemonCmd.Flags().Uint("cached-values", 500, "Number of cached values before saveing into the storage endpoint")
daemonCmd.Flags().Float64("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)
}
// logLevel, err := cmd.Flags().GetString("loglevel")
// if err != nil {
// return fmt.Errorf("No loglevel defined: %v", err)
// }
flogger := logger.NewDefaultLogger(logger.LogLevelDebug)
cnf, err := config.Read(configFile)
if err != nil {
return err
}
return daemon.Start(cnf, flogger)
}

112
cli/root.go Normal file
View File

@ -0,0 +1,112 @@
package cli
import (
"fmt"
"math"
"os"
"os/user"
"path/filepath"
"time"
"github.com/Masterminds/semver"
"github.com/volker-raschek/flucky/cli/daemon"
"github.com/volker-raschek/flucky/cli/sensor"
"github.com/volker-raschek/flucky/pkg/config"
"github.com/volker-raschek/flucky/pkg/types"
uuid "github.com/satori/go.uuid"
"github.com/spf13/cobra"
)
// Execute a
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(),
}
defaultConfigFile, err := getDefaultConfigFile()
if err != nil {
return err
}
rootCmd.PersistentFlags().String("config", defaultConfigFile, "Config file")
rootCmd.PersistentFlags().String("loglevel", "info", "Set the Loglevel. Possible values: debug, info, warn, error, fatal")
subCommands := []func(cmd *cobra.Command) error{
daemon.InitCmd,
sensor.InitCmd,
}
for _, subCommand := range subCommands {
if err := subCommand(rootCmd); err != nil {
return err
}
}
err = rootCmd.Execute()
if err != nil {
return err
}
return nil
}
func preRunError(cmd *cobra.Command, args []string) error {
configFile := cmd.Flag("config").Value.String()
// check if config file exists
if _, err := os.Stat(configFile); os.IsNotExist(err) {
hostname, err := os.Hostname()
if err != nil {
return fmt.Errorf("Failed to determine 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.Config{
Device: &types.Device{
ID: uuid.NewV4().String(),
Name: hostname,
CreationDate: postgresTimeStamp,
},
StorageEndpoint: "file:/var/log/flucky/sqlite.db?cache=shared&mode=memory",
}
err = config.Write(&cnf, configFile)
if err != nil {
return err
}
}
return nil
}
// GetDefaultConfigPath returns the default path to the configuration of
// rpm-distributor
func getDefaultConfigFile() (string, error) {
u, err := user.Current()
if err != nil {
return "", fmt.Errorf("Can not read current user: %v", err)
}
switch u.Uid {
case "0":
return "/etc/flucky/config.json", nil
default:
return filepath.Join(u.HomeDir, ".config/flucky/config.json"), nil
}
}

307
cli/sensor/sensor.go Normal file
View File

@ -0,0 +1,307 @@
package sensor
import (
"fmt"
"os"
uuid "github.com/satori/go.uuid"
"github.com/spf13/cobra"
"github.com/volker-raschek/flucky/pkg/cli"
"github.com/volker-raschek/flucky/pkg/config"
"github.com/volker-raschek/flucky/pkg/types"
)
// InitCmd initialize all sensor subcommands
func InitCmd(cmd *cobra.Command) error {
sensorCmd := &cobra.Command{
Use: "sensor",
Short: "Manage Sensors",
}
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().Bool("enabled", true, "Enable new sensor")
addSensorCmd.Flags().String("gpio", "", "Defines the GPIO port")
addSensorCmd.Flags().Uint8("i2c-address", 0, "Defines the I2C address on the I2C bus")
addSensorCmd.Flags().Int("i2c-bus", 0, "Defines the I2C bus")
addSensorCmd.Flags().String("location", "", "Location of the sensor")
addSensorCmd.Flags().String("tick-duration", "1m", "Specifies how often measured values should be read from the sensor")
addSensorCmd.Flags().String("wire-id", "", "Defines the Wire-ID")
disableSensorCmd := &cobra.Command{
Use: "disable",
Short: "Disable Sensor",
Args: cobra.ExactArgs(1),
Example: "flucky sensor disable outdoor",
RunE: disableSensor,
}
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: removeSensor,
}
removeSensorCmd.Flags().Bool("definitive", true, "Remove the sensor definitive from the backend")
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,
}
for _, subCommand := range []*cobra.Command{
addSensorCmd,
disableSensorCmd,
enableSensorCmd,
listSensorCmd,
removeSensorCmd,
renameSensorCmd,
} {
sensorCmd.AddCommand(subCommand)
}
cmd.AddCommand(sensorCmd)
return nil
}
func addSensor(cmd *cobra.Command, args []string) error {
sensor := &types.Sensor{
ID: uuid.NewV4().String(),
Name: args[0],
Model: args[1],
}
sensorLocation, err := cmd.Flags().GetString("location")
if err != nil {
return err
}
sensor.Location = sensorLocation
sensorEnabled, err := cmd.Flags().GetBool("enabled")
if err != nil {
return err
}
sensor.Enabled = sensorEnabled
sensorGPIO, err := cmd.Flags().GetString("gpio")
if err != nil {
return err
}
if len(sensorGPIO) > 0 {
sensor.GPIONumber = sensorGPIO
}
sensorI2CAddress, err := cmd.Flags().GetUint8("i2c-address")
if err != nil {
return err
}
if sensorI2CAddress > 0 {
sensor.I2CAddress = &sensorI2CAddress
}
sensorI2CBus, err := cmd.Flags().GetInt("i2c-bus")
if err != nil {
return err
}
if sensorI2CBus > 0 {
sensor.I2CBus = &sensorI2CBus
}
sensorTickDuration, err := cmd.Flags().GetString("tick-duration")
if err != nil {
return err
}
sensor.TickDuration = sensorTickDuration
sensorWireID, err := cmd.Flags().GetString("wire-id")
if err != nil {
return err
}
if len(sensorWireID) > 0 {
sensor.WireID = &sensorWireID
}
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
}
// 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 disableSensor(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")
}
definitive, err := cmd.Flags().GetBool("definitive")
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], definitive)
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
}

9
go.mod
View File

@ -3,13 +3,14 @@ module github.com/volker-raschek/flucky
go 1.12
require (
github.com/Masterminds/semver v1.5.0
github.com/d2r2/go-bsbmp v0.0.0-20190515110334-3b4b3aea8375
github.com/d2r2/go-i2c v0.0.0-20181113114621-14f8dd4e89ce
github.com/d2r2/go-i2c v0.0.0-20191123181816-73a8a799d6bc
github.com/d2r2/go-logger v0.0.0-20181221090742-9998a510495e
github.com/go-flucky/flucky v0.0.0-20190714170626-0dd156f480be
github.com/go-flucky/go-dht v0.1.1
github.com/lib/pq v1.4.0
github.com/satori/go.uuid v1.2.0
github.com/stretchr/testify v1.4.0
github.com/volker-raschek/go-logger v0.0.0-20190924132822-0c50a64d7f26
github.com/spf13/cobra v1.0.0
github.com/stretchr/testify v1.5.1
github.com/volker-raschek/go-logger v0.1.0
)

128
go.sum
View File

@ -1,17 +1,67 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=
github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/d2r2/go-bsbmp v0.0.0-20190515110334-3b4b3aea8375 h1:vdUOwcZdV+bBfGUUh5oPPWSzw9p+lBnNSuGgQwGpCH4=
github.com/d2r2/go-bsbmp v0.0.0-20190515110334-3b4b3aea8375/go.mod h1:3iz1WHlYJU9b4NJei+Q8G7DN3K05arcCMlOQ+qNCDjo=
github.com/d2r2/go-i2c v0.0.0-20181113114621-14f8dd4e89ce h1:Dog7PLNz1fPaXqHPOHonpERqsF57Oh4X76pM80T1GDY=
github.com/d2r2/go-i2c v0.0.0-20181113114621-14f8dd4e89ce/go.mod h1:AwxDPnsgIpy47jbGXZHA9Rv7pDkOJvQbezPuK1Y+nNk=
github.com/d2r2/go-i2c v0.0.0-20191123181816-73a8a799d6bc h1:HLRSIWzUGMLCq4ldt0W1GLs3nnAxa5EGoP+9qHgh6j0=
github.com/d2r2/go-i2c v0.0.0-20191123181816-73a8a799d6bc/go.mod h1:AwxDPnsgIpy47jbGXZHA9Rv7pDkOJvQbezPuK1Y+nNk=
github.com/d2r2/go-logger v0.0.0-20181221090742-9998a510495e h1:ZG3JBA6rPRl0xxQ+nNSfO7tor8w+CNCTs05DNJQYbLM=
github.com/d2r2/go-logger v0.0.0-20181221090742-9998a510495e/go.mod h1:oA+9PUt8F1aKJ6o4YU1T120i7sgo1T6/1LWEEBy0BSs=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-flucky/flucky v0.0.0-20190714170626-0dd156f480be h1:jCs/SAXdXUA0aqvEVH0wyeGpJzYOZ1XC9Kpm5anSY5E=
github.com/go-flucky/flucky v0.0.0-20190714170626-0dd156f480be/go.mod h1:WNT729lCsTFhT6Vyvg6cG8aHV1t6p+DsA8l4omOuaos=
github.com/go-flucky/go-dht v0.1.1 h1:dPz9F5D7oUaTd0GUGTvT4lBH2R043h1bkmhTlpQax1Y=
github.com/go-flucky/go-dht v0.1.1/go.mod h1:Yk/cct+/u+eCS7pB/kc0tc7MrVXdFI4W15MJCj5FRUc=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
@ -19,26 +69,100 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.4.0 h1:TmtCFbH+Aw0AixwyttznSMQDgbR5Yed/Gg6S8Funrhc=
github.com/lib/pq v1.4.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8=
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/cobra v1.0.0 h1:6m/oheQuQ13N9ks4hubMG6BnvwOeaJrqSPLahSnczz8=
github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
github.com/stianeikeland/go-rpio v4.2.0+incompatible h1:CUOlIxdJdT+H1obJPsmg8byu7jMSECLfAN9zynm5QGo=
github.com/stianeikeland/go-rpio v4.2.0+incompatible/go.mod h1:Sh81rdJwD96E2wja2Gd7rrKM+XZ9LrwvN2w4IXrqLR8=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/volker-raschek/go-logger v0.0.0-20190924132822-0c50a64d7f26 h1:7xmCI9JL1pIsiv3ACpadGxpHZd96TP7pcT7iWK2IF+g=
github.com/volker-raschek/go-logger v0.0.0-20190924132822-0c50a64d7f26/go.mod h1:V4TEAy1Kx45GPlB2VvS5mVpNfSksNDDuEgk7wm7cd0k=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
github.com/volker-raschek/go-logger v0.1.0 h1:BJPK4wCfcWlQYnOQC7ORU4LlMSgEYcwvpXQFs2rdPhE=
github.com/volker-raschek/go-logger v0.1.0/go.mod h1:V4TEAy1Kx45GPlB2VvS5mVpNfSksNDDuEgk7wm7cd0k=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
periph.io/x/periph v3.4.0+incompatible h1:5gzxE4ryPq52cdqSw0mErR6pyJK8cBF2qdUAcOWh0bo=
periph.io/x/periph v3.4.0+incompatible/go.mod h1:EWr+FCIU2dBWz5/wSWeiIUJTriYv9v2j2ENBmgYyy7Y=

83
main.go
View File

@ -2,11 +2,10 @@ package main
import (
"log"
"strings"
"os"
"github.com/volker-raschek/flucky/pkg/config"
"github.com/volker-raschek/flucky/pkg/daemon"
"github.com/volker-raschek/go-logger/pkg/logger"
"github.com/Masterminds/semver"
"github.com/volker-raschek/flucky/cli"
)
var (
@ -14,79 +13,11 @@ var (
)
func main() {
// sversion, err := semver.NewVersion(version)
// if err != nil {
// log.Printf("The sematic versioning is invalid: %v", version)
// os.Exit(1)
// }
cnfString := `{
"device": {
"id": "d0c600bc-6eab-4b9b-b93f-dc0477b4658f",
"name": "poseidon",
"location": null,
"last_contact": null,
"creation_date": "2020-04-23T22:09:20.932+02:00"
},
"storage_endpoint": "postgres://postgres:postgres@markus-pc.trier.cryptic.systems:5432/postgres?sslmode=disable",
"sensors": [
{
"id": "1c180121-9e98-4053-a6f6-4ed7fad3935b",
"name": "bme280",
"location": "",
"wire_id": null,
"i2c_bus": 1,
"i2c_address": 118,
"gpio_number": null,
"model": "BME280",
"enabled": true,
"last_contact": null,
"tick_duration": "5s",
"device_id": "d0c600bc-6eab-4b9b-b93f-dc0477b4658f",
"creation_date": "2020-04-23T22:09:20.934+02:00"
},
{
"id": "5cebd127-8976-4b66-b1bb-e551f26c4af4",
"name": "ds18b20_2",
"location": "",
"wire_id": "28-02131dbffeaa",
"i2c_bus": null,
"i2c_address": null,
"gpio_number": null,
"model": "DS18B20",
"enabled": true,
"last_contact": null,
"tick_duration": "1m",
"device_id": "d0c600bc-6eab-4b9b-b93f-dc0477b4658f",
"creation_date": "2020-04-23T22:09:27.901+02:00"
},
{
"id": "579628cc-b667-4b56-b305-73256c0c9dce",
"name": "ds18b20",
"location": "",
"wire_id": "28-01131646f11d",
"i2c_bus": null,
"i2c_address": null,
"gpio_number": null,
"model": "DS18B20",
"enabled": true,
"last_contact": null,
"tick_duration": "1m",
"device_id": "d0c600bc-6eab-4b9b-b93f-dc0477b4658f",
"creation_date": "2020-04-23T22:09:56.468+02:00"
}
]
}`
cnf, err := config.Decode(strings.NewReader(cnfString))
sversion, err := semver.NewVersion(version)
if err != nil {
log.Fatal(err)
log.Printf("The sematic versioning is invalid: %v", version)
os.Exit(1)
}
flogger := logger.NewDefaultLogger(logger.LogLevelDebug)
err = daemon.Start(cnf, flogger)
if err != nil {
log.Fatal(err)
}
cli.Execute(sversion)
}

48
pkg/cli/cli.go Normal file
View File

@ -0,0 +1,48 @@
package cli
import (
"fmt"
"io"
"text/tabwriter"
"github.com/volker-raschek/flucky/pkg/config"
)
// PrintSensors displays a list with all configured sensors
func PrintSensors(cnf *config.Config, w io.Writer) error {
// declar tabwriter
tw := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0)
fmt.Fprint(tw, "name\tlocation\ttype\twire-id\ti2c-bus\ti2c-address\tgpio\ttick-duration\tenabled\n")
for _, sensor := range cnf.Sensors {
fmt.Fprintf(tw, "%v\t%v\t%v\t", sensor.Name, sensor.Location, sensor.Model)
if sensor.WireID != nil {
fmt.Fprintf(tw, "%v\t", *sensor.WireID)
} else {
fmt.Fprintf(tw, "\t")
}
if sensor.I2CBus != nil {
fmt.Fprintf(tw, "%v\t", *sensor.I2CBus)
} else {
fmt.Fprintf(tw, "\t")
}
if sensor.I2CAddress != nil {
fmt.Fprintf(tw, "%#v\t", *sensor.I2CAddress)
} else {
fmt.Fprintf(tw, "\t")
}
fmt.Fprintf(tw, "%v\t", sensor.GPIONumber)
fmt.Fprintf(tw, "%v\t%v\n", sensor.TickDuration, sensor.Enabled)
}
tw.Flush()
return nil
}

View File

@ -1,6 +1,7 @@
package config
import (
"context"
"fmt"
"os"
"path/filepath"
@ -9,6 +10,7 @@ import (
"time"
"github.com/volker-raschek/flucky/pkg/internal/format"
"github.com/volker-raschek/flucky/pkg/storage"
uuid "github.com/satori/go.uuid"
"github.com/volker-raschek/flucky/pkg/types"
@ -154,21 +156,56 @@ func (cnf *Config) GetSensorByID(id string) *types.Sensor {
return nil
}
// RemoveSensor deletes a sensor by its name or its unique UUID
func (cnf *Config) RemoveSensor(name string) error {
// RemoveSensor deletes a sensor by its name or its unique UUID, If definitive
// is set to true, the sensor will not only be removed in the configuration file
// but also in the backend.
func (cnf *Config) RemoveSensor(name string, definitive bool) error {
backend, err := storage.New(cnf.StorageEndpoint, nil)
if err != nil {
return err
}
for i, sensor := range cnf.Sensors {
// remove machted name
if !validUUID.MatchString(name) &&
sensor.Name == name {
cnf.Sensors = append(cnf.Sensors[:i], cnf.Sensors[i+1:]...)
if definitive {
err = backend.RemoveSensorByName(context.Background(), name)
if err != nil {
return err
}
}
return nil
}
// remove machted uuid
if validUUID.MatchString(name) &&
sensor.ID == name {
cnf.Sensors = append(cnf.Sensors[:i], cnf.Sensors[i+1:]...)
if definitive {
err = backend.RemoveSensorByID(context.Background(), name)
if err != nil {
return err
}
}
return nil
}
}
return fmt.Errorf("Can not find sensor %v", name)
}
// RenameSensor renamed a sensor
func (cnf *Config) RenameSensor(oldName string, newName string) error {
for _, cnfSensor := range cnf.Sensors {
if cnfSensor.Name == oldName {
cnfSensor.Name = newName
return nil
}
}
return fmt.Errorf("No sensor %v found", oldName)
}

View File

@ -45,7 +45,7 @@ func Read(configFile string) (*Config, error) {
func Write(cnf *Config, configFile string) error {
if _, err := os.Stat(configFile); os.IsNotExist(err) {
configDir := filepath.Dir(configFile)
err := os.MkdirAll(configDir, os.ModeDir)
err := os.MkdirAll(configDir, 0775)
if err != nil {
return fmt.Errorf("Failed to create config directory %v: %v", configDir, err)
}

View File

@ -0,0 +1,2 @@
DELETE FROM sensors
WHERE sensor_id = $1;

View File

@ -0,0 +1,2 @@
DELETE FROM sensors
WHERE sensor_name = $1;

View File

@ -17,6 +17,8 @@ type Storage interface {
InsertDevice(ctx context.Context, device *types.Device) error
InsertMeasuredValues(ctx context.Context, measuredValues []*types.MeasuredValue) error
InsertSensor(ctx context.Context, sensor *types.Sensor) error
RemoveSensorByID(ctx context.Context, sensorID string) error
RemoveSensorByName(ctx context.Context, sensorName string) error
SelectDevice(ctx context.Context, id string) (*types.Device, error)
SelectSensor(ctx context.Context, id string) (*types.Sensor, error)
}
@ -154,6 +156,64 @@ func (postgres *Postgres) InsertSensor(ctx context.Context, sensor *types.Sensor
return tx.Commit()
}
// RemoveSensorByID from the database
func (postgres *Postgres) RemoveSensorByID(ctx context.Context, sensorID string) error {
asset := filepath.Join(postgresAssetPath, "removeSensorByID.sql")
queryBytes, err := Asset(asset)
if err != nil {
return fmt.Errorf("Failed to load asset %v: %v", asset, err)
}
query := string(queryBytes)
tx, err := postgres.dbo.BeginTx(ctx, &sql.TxOptions{ReadOnly: false})
if err != nil {
return fmt.Errorf("Failed to begin new transaction: %v", err)
}
stmt, err := tx.Prepare(query)
if err != nil {
return fmt.Errorf("Failed to prepare statement: %v", err)
}
defer stmt.Close()
_, err = stmt.Exec(sensorID)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
// RemoveSensorByName from the database
func (postgres *Postgres) RemoveSensorByName(ctx context.Context, sensorID string) error {
asset := filepath.Join(postgresAssetPath, "removeSensorByName.sql")
queryBytes, err := Asset(asset)
if err != nil {
return fmt.Errorf("Failed to load asset %v: %v", asset, err)
}
query := string(queryBytes)
tx, err := postgres.dbo.BeginTx(ctx, &sql.TxOptions{ReadOnly: false})
if err != nil {
return fmt.Errorf("Failed to begin new transaction: %v", err)
}
stmt, err := tx.Prepare(query)
if err != nil {
return fmt.Errorf("Failed to prepare statement: %v", err)
}
defer stmt.Close()
_, err = stmt.Exec(sensorID)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
// SelectDevice from database
func (postgres *Postgres) SelectDevice(ctx context.Context, id string) (*types.Device, error) {
asset := filepath.Join(postgresAssetPath, "selectDeviceByID.sql")