fix: configuration pkg

This commit is contained in:
Markus Pesch 2019-02-17 18:23:59 +01:00
parent 60fa83244e
commit c437127531
Signed by: volker.raschek
GPG Key ID: 852BCC170D81A982
18 changed files with 596 additions and 420 deletions

View File

@ -1,15 +1,11 @@
package cmd package cmd
import ( import (
"git.cryptic.systems/fh-trier/go-flucky/cmd/config"
"git.cryptic.systems/fh-trier/go-flucky/cmd/humidity"
"git.cryptic.systems/fh-trier/go-flucky/cmd/remote" "git.cryptic.systems/fh-trier/go-flucky/cmd/remote"
"git.cryptic.systems/fh-trier/go-flucky/cmd/sensor"
"git.cryptic.systems/fh-trier/go-flucky/cmd/temperature"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var configDir string var cfg string
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
Use: "flucky", Use: "flucky",
@ -20,13 +16,12 @@ var rootCmd = &cobra.Command{
func Execute(version string) { func Execute(version string) {
rootCmd.Version = version rootCmd.Version = version
rootCmd.PersistentFlags().StringVarP(&configDir, "config", "c", "/etc/flucky", "The base directory for all configuration files.") rootCmd.PersistentFlags().StringVar(&cfg, "config", "/etc/flucky/config.json", "Config file")
config.InitCmd(rootCmd, configDir) // humidity.InitCmd(rootCmd, configDir)
humidity.InitCmd(rootCmd, configDir) remote.InitCmd(rootCmd, cfg)
remote.InitCmd(rootCmd, configDir) // sensor.InitCmd(rootCmd, configDir)
sensor.InitCmd(rootCmd, configDir) // temperature.InitCmd(rootCmd, configDir)
temperature.InitCmd(rootCmd, configDir)
rootCmd.Execute() rootCmd.Execute()
} }

View File

@ -1,28 +0,0 @@
package config
import (
"git.cryptic.systems/fh-trier/go-flucky/pkg/config"
"github.com/spf13/cobra"
)
var configDir string
var configCmd = &cobra.Command{
Use: "config",
Short: "Manage Configuration",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
if args[0] == "device.name" {
config.DeviceName(args[1], configDir)
} else if args[0] == "device.location" {
config.DeviceLocation(args[1], configDir)
}
},
}
func InitCmd(cmd *cobra.Command, c string) {
configDir = c
cmd.AddCommand(configCmd)
}

View File

@ -1,28 +0,0 @@
package config
import (
"log"
"git.cryptic.systems/fh-trier/go-flucky/pkg/config"
"github.com/spf13/cobra"
)
var force bool
var logDir string
var createConfigCmd = &cobra.Command{
Use: "create",
Short: "create",
Run: func(cmd *cobra.Command, args []string) {
if err := config.Create(configDir, logDir, force); err != nil {
log.Fatal(err)
}
},
}
func init() {
configCmd.AddCommand(createConfigCmd)
createConfigCmd.Flags().BoolVarP(&force, "force", "f", false, "Force the creation of a new configuration")
createConfigCmd.Flags().StringVarP(&logDir, "log-dir", "l", "/var/log/flucky", "Directory for logfiles")
}

View File

@ -3,8 +3,7 @@ package remote
import ( import (
"log" "log"
"git.cryptic.systems/fh-trier/go-flucky/pkg/remote" "git.cryptic.systems/fh-trier/go-flucky/pkg/config"
"git.cryptic.systems/fh-trier/go-flucky/pkg/types"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -16,19 +15,35 @@ var addRemoteCmd = &cobra.Command{
Args: cobra.ExactArgs(2), Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
remoteObject := types.Remote{ // read configuration
fc, err := config.Read(cfg)
if err != nil {
log.Fatalln(err)
}
// create new remote struct
remote := config.Remote{
Name: args[0], Name: args[0],
Address: args[1], Address: args[1],
Enabled: enabled, Enabled: enabled,
} }
if err := remote.Add(&remoteObject, configDir); err != nil { // // add remote entry to list
log.Fatal(err) err = fc.AddRemote(&remote)
if err != nil {
log.Fatalln(err)
} }
// save new configuration
err = config.Write(fc, cfg)
if err != nil {
log.Fatalln(err)
}
}, },
} }
func init() { func init() {
remoteCmd.AddCommand(addRemoteCmd) remoteCmd.AddCommand(addRemoteCmd)
addRemoteCmd.Flags().BoolVarP(&enabled, "enabled", "e", true, "Enable Remote Link") addRemoteCmd.Flags().BoolVarP(&enabled, "enable", "e", true, "Enable")
} }

View File

@ -3,7 +3,7 @@ package remote
import ( import (
"log" "log"
"git.cryptic.systems/fh-trier/go-flucky/pkg/remote" "git.cryptic.systems/fh-trier/go-flucky/pkg/config"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -13,9 +13,24 @@ var disableRemoteCmd = &cobra.Command{
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if err := remote.Disable(args[0], configDir); err != nil { // read configuration
log.Fatal(err) fc, err := config.Read(cfg)
if err != nil {
log.Fatalln(err)
} }
// disnable remote address
err = fc.DisableRemote(args[0])
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(fc, cfg)
if err != nil {
log.Fatalln(err)
}
}, },
} }

View File

@ -3,7 +3,7 @@ package remote
import ( import (
"log" "log"
"git.cryptic.systems/fh-trier/go-flucky/pkg/remote" "git.cryptic.systems/fh-trier/go-flucky/pkg/config"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -13,8 +13,22 @@ var enableRemoteCmd = &cobra.Command{
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if err := remote.Enable(args[0], configDir); err != nil { // read configuration
log.Fatal(err) fc, err := config.Read(cfg)
if err != nil {
log.Fatalln(err)
}
// enable remote address
err = fc.EnableRemote(args[0])
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(fc, cfg)
if err != nil {
log.Fatalln(err)
} }
}, },
} }

View File

@ -4,7 +4,7 @@ import (
"log" "log"
"os" "os"
"git.cryptic.systems/fh-trier/go-flucky/pkg/remote" "git.cryptic.systems/fh-trier/go-flucky/pkg/config"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -16,14 +16,26 @@ var listRemoteCmd = &cobra.Command{
Aliases: []string{"ls"}, Aliases: []string{"ls"},
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if err := remote.Print(os.Stdout, configDir, quiet); err != nil { // read configuration
log.Fatal(err) fc, err := config.Read(cfg)
if err != nil {
log.Fatalln(err)
}
// print all configured remote addresses on stdout
err = fc.PrintRemotes(os.Stdout)
if err != nil {
log.Fatalln(err)
}
// save new configuration
err = config.Write(fc, cfg)
if err != nil {
log.Fatalln(err)
} }
}, },
} }
func init() { func init() {
remoteCmd.AddCommand(listRemoteCmd) remoteCmd.AddCommand(listRemoteCmd)
listRemoteCmd.Flags().BoolVarP(&quiet, "quiet", "q", false, "List only sensor id's")
} }

View File

@ -4,15 +4,15 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var configDir string var cfg string
var remoteCmd = &cobra.Command{ var remoteCmd = &cobra.Command{
Use: "remote", Use: "remote",
Short: "Manage Remote Server", Short: "Manage Remote Server",
} }
func InitCmd(cmd *cobra.Command, cnf string) { func InitCmd(cmd *cobra.Command, config string) {
configDir = cnf cfg = config
cmd.AddCommand(remoteCmd) cmd.AddCommand(remoteCmd)
} }

View File

@ -3,32 +3,37 @@ package remote
import ( import (
"log" "log"
"git.cryptic.systems/fh-trier/go-flucky/pkg/remote" "git.cryptic.systems/fh-trier/go-flucky/pkg/config"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var all bool
var rmRemoteCmd = &cobra.Command{ var rmRemoteCmd = &cobra.Command{
Use: "rm", Use: "rm",
Short: "Remove Remote Server", Short: "Remove Remote Server",
Aliases: []string{"remove"}, Aliases: []string{"remove"},
Args: cobra.RangeArgs(0, 1), Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if all { // read configuration
if err := remote.RemoveAll(configDir); err != nil { fc, err := config.Read(cfg)
log.Fatal(err) if err != nil {
log.Fatalln(err)
} }
} else {
if err := remote.Remove(args[0], configDir); err != nil { // add remote entry to list
log.Fatal(err) err = fc.RemoveRemote(args[0])
if err != nil {
log.Fatalln(err)
} }
// save new configuration
err = config.Write(fc, cfg)
if err != nil {
log.Fatalln(err)
} }
}, },
} }
func init() { func init() {
remoteCmd.AddCommand(rmRemoteCmd) remoteCmd.AddCommand(rmRemoteCmd)
rmRemoteCmd.Flags().BoolVarP(&all, "all", "a", false, "Select all remote connections")
} }

View File

@ -1,27 +0,0 @@
package remote
import (
"log"
"git.cryptic.systems/fh-trier/go-flucky/pkg/httpcall"
"github.com/spf13/cobra"
)
var force bool
var syncRemoteCmd = &cobra.Command{
Use: "sync",
Aliases: []string{"synchronize"},
Short: "Synchronise Device Values with Remote Servers",
Run: func(cmd *cobra.Command, args []string) {
if err := httpcall.SyncDevice(configDir, force); err != nil {
log.Fatal(err)
}
},
}
func init() {
remoteCmd.AddCommand(syncRemoteCmd)
syncRemoteCmd.Flags().BoolVarP(&force, "force", "f", false, "Include disabled remote links")
}

View File

@ -1,9 +1,6 @@
package sensor package sensor
import ( import (
"log"
"git.cryptic.systems/fh-trier/go-flucky/pkg/sensor"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -15,9 +12,7 @@ var addSensorCmd = &cobra.Command{
Short: "Add Sensor", Short: "Add Sensor",
Args: cobra.ExactArgs(3), Args: cobra.ExactArgs(3),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if err := sensor.Add(&args[0], &sensorLocation, &args[1], &wireID, &args[2], wirePath, configDir, &enabled); err != nil {
log.Fatal(err)
}
}, },
} }

View File

@ -1,136 +1,68 @@
package config package config
import ( import (
"encoding/json"
"fmt" "fmt"
"io"
"os" "os"
"path/filepath" "regexp"
"git.cryptic.systems/fh-trier/go-flucky/pkg/types" "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
"github.com/satori/go.uuid"
) )
var configFilename = "config.json" var validUUID = regexp.MustCompile("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
var humiditiesLogfileName = "humidities.log"
var temperatureLogfileName = "temperature.log"
func Create(configDir, logDir string, force bool) error { type Config interface {
AddSensor(sensor *types.Sensor) error
AddRemote(remote *Remote) error
DisableRemote(nameOrUUID string) error
DisableSensor(nameOrUUID string) error
EnableRemote(nameOrUUID string) error
EnableSensor(nameOrUUID string) error
GetDevice() *Device
GetRemotes() []*Remote
GetSensors() []*types.Sensor
JSONDecoder(r io.Reader) error
JSONWriter(w io.Writer) error
RemoveSensor(nameOrUUID string) error
RemoveRemote(nameOrUUID string) error
SetDevice(device *Device)
ToJSON() (string, error)
}
configPath := filepath.Join(configDir, configFilename) // Read the configuration file
humiditiesLogfile := filepath.Join(logDir, humiditiesLogfileName) func Read(configFile string) (*FluckyConfig, error) {
temperaturLogfile := filepath.Join(logDir, temperatureLogfileName)
config := &types.Config{ fc := &FluckyConfig{}
DeviceID: uuid.NewV4().String(),
HumidityLogfile: humiditiesLogfile,
TemperatureLogfile: temperaturLogfile,
}
// If no config file exists, create a new one on the location f, err := os.Open(configFile)
if !force {
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
return fmt.Errorf("%v already exists. Use -f to overwrite", configPath)
}
}
if _, err := os.Stat(configPath); os.IsNotExist(err) {
err := os.MkdirAll(configDir, os.ModePerm)
if err != nil { if err != nil {
return fmt.Errorf("Can not create directory: %v", err) return nil, fmt.Errorf("Can not open file %v: %v", configFile, err)
}
}
f, err := os.Create(configPath)
if err != nil {
return fmt.Errorf("Can not create config: %v", err)
} }
defer f.Close() defer f.Close()
config.JSONWriter(f) err = fc.JSONDecoder(f)
if err != nil {
return nil, fmt.Errorf("Can not decode json file %v: %v", configFile, err)
}
return nil return fc, nil
} }
func DeviceName(deviceName, configDir string) error { // Write the configuration into a file, specified by the configuration filepath
cnf, err := Read(configDir) func Write(cfg Config, configFile string) error {
f, err := os.Create(configFile)
if err != nil { if err != nil {
return err return err
} }
defer f.Close()
cnf.DeviceName = deviceName err = cfg.JSONWriter(f)
err = Write(cnf, configDir)
if err != nil {
return err
}
return nil
}
func DeviceLocation(deviceLocation, configDir string) error {
cnf, err := Read(configDir)
if err != nil {
return err
}
cnf.DeviceLocation = deviceLocation
err = Write(cnf, configDir)
if err != nil {
return err
}
return nil
}
func Read(configDir string) (*types.Config, error) {
configPath := filepath.Join(configDir, configFilename)
var config types.Config
// If no config file exists, return an error
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return nil, fmt.Errorf("Can not find config %v: %v", configPath, err)
}
// open config file
jsonFile, err := os.Open(configPath)
if err != nil {
return nil, fmt.Errorf("Can not open file %v: %v", configPath, err)
}
defer jsonFile.Close()
jsonParser := json.NewDecoder(jsonFile)
if err := jsonParser.Decode(&config); err != nil {
return nil, err
}
return &config, nil
}
func Write(config *types.Config, configDir string) error {
configPath := filepath.Join(configDir, configFilename)
// If no config file exists, return an error
if _, err := os.Stat(configPath); os.IsNotExist(err) {
return fmt.Errorf("Can not find config %v: %v", configPath, err)
}
// open config file
jsonFile, err := os.Create(configPath)
if err != nil {
return fmt.Errorf("Can not open file %v: %v", configPath, err)
}
defer jsonFile.Close()
err = config.JSONWriter(jsonFile)
if err != nil { if err != nil {
return err return err
} }
return nil return nil
} }

7
pkg/config/device.go Normal file
View File

@ -0,0 +1,7 @@
package config
type Device struct {
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
DeviceLocation string `json:"device_location"`
}

312
pkg/config/fluckyconfig.go Normal file
View File

@ -0,0 +1,312 @@
package config
import (
"bytes"
"encoding/json"
"fmt"
"io"
"text/tabwriter"
"github.com/satori/go.uuid"
"git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
)
// FluckyConfig dasd
type FluckyConfig struct {
Device *Device `json:"device"`
Sensors []*types.Sensor `json:"sensors"`
Remotes []*Remote `json:"remotes"`
}
// AddSensor add a new sensor
func (fc *FluckyConfig) AddSensor(sensor *types.Sensor) error {
// check if sensorID is a valid UUID string
if !validUUID.MatchString(sensor.SensorID) {
sensor.SensorID = uuid.NewV4().String()
}
// check if sensor name and sensor uuid already exists
for _, s := range fc.Sensors {
if s.SensorName == sensor.SensorName {
return fmt.Errorf("Sensor %v already exists", s.SensorName)
}
if s.SensorID == sensor.SensorID {
return fmt.Errorf("Remote %v with UUID %v already exists", s.SensorName, s.SensorID)
}
}
fc.Sensors = append(fc.Sensors, sensor)
return nil
}
// AddRemote add a new remote address
func (fc *FluckyConfig) AddRemote(remote *Remote) error {
// check if remoteID is a valid UUID string
if !validUUID.MatchString(remote.RemoteID) {
remote.RemoteID = uuid.NewV4().String()
}
// check if remote name or remiteid already exists
for _, r := range fc.Remotes {
if r.Name == remote.Name {
return fmt.Errorf("Remote %v -> %v already exists", r.Name, r.Address)
}
if r.RemoteID == remote.RemoteID {
return fmt.Errorf("Remote %v with UUID %v already exists", r.Name, r.RemoteID)
}
}
fc.Remotes = append(fc.Remotes, remote)
return nil
}
// DisableRemote disables a remote address by its name or its unique UUID
func (fc *FluckyConfig) DisableRemote(nameOrUUID string) error {
found := false
for _, remote := range fc.Remotes {
// disable sensor matched after name
if !validUUID.MatchString(nameOrUUID) &&
remote.Name == nameOrUUID {
remote.Enabled = false
found = true
break
}
// remove machted uuid
if validUUID.MatchString(nameOrUUID) &&
remote.RemoteID == nameOrUUID {
remote.Enabled = false
found = true
break
}
}
if !found {
return fmt.Errorf("Can not found sensor %v", nameOrUUID)
}
return nil
}
// DisableSensor disables a sensor by its name or its unique UUID
func (fc *FluckyConfig) DisableSensor(nameOrUUID string) error {
found := false
for _, sensor := range fc.Sensors {
// disable sensor matched after name
if !validUUID.MatchString(nameOrUUID) &&
*sensor.SensorName == nameOrUUID {
*sensor.SensorEnabled = false
found = true
break
}
// remove machted uuid
if validUUID.MatchString(nameOrUUID) &&
sensor.SensorID == nameOrUUID {
*sensor.SensorEnabled = false
found = true
break
}
}
if !found {
return fmt.Errorf("Can not found sensor %v", nameOrUUID)
}
return nil
}
// EnableRemote enable a remote address by its name or its unique UUID
func (fc *FluckyConfig) EnableRemote(nameOrUUID string) error {
found := false
for _, remote := range fc.Remotes {
// disable sensor matched after name
if !validUUID.MatchString(nameOrUUID) &&
remote.Name == nameOrUUID {
remote.Enabled = true
found = true
break
}
// remove machted uuid
if validUUID.MatchString(nameOrUUID) &&
remote.RemoteID == nameOrUUID {
remote.Enabled = true
found = true
break
}
}
if !found {
return fmt.Errorf("Can not found sensor %v", nameOrUUID)
}
return nil
}
// EnableSensor enables a sensor by its name or its unique UUID
func (fc *FluckyConfig) EnableSensor(nameOrUUID string) error {
found := false
for _, sensor := range fc.Sensors {
// disable sensor matched after name
if !validUUID.MatchString(nameOrUUID) &&
*sensor.SensorName == nameOrUUID {
*sensor.SensorEnabled = true
found = true
break
}
// remove machted uuid
if validUUID.MatchString(nameOrUUID) &&
sensor.SensorID == nameOrUUID {
*sensor.SensorEnabled = true
found = true
break
}
}
if !found {
return fmt.Errorf("Can not found sensor %v", nameOrUUID)
}
return nil
}
// GetDevice returns device informations
func (fc *FluckyConfig) GetDevice() *Device {
return fc.Device
}
// GetRemotes returns an array if remote struct poniter
func (fc *FluckyConfig) GetRemotes() []*Remote {
return fc.Remotes
}
// GetSensors returns an array if remote struct poniter
func (fc *FluckyConfig) GetSensors() []*types.Sensor {
return fc.Sensors
}
// JSONDecoder decode a JSON string from a reader into a struct
func (fc *FluckyConfig) JSONDecoder(r io.Reader) error {
jsonDecoder := json.NewDecoder(r)
if err := jsonDecoder.Decode(&fc); err != nil {
return fmt.Errorf("Can not unmarshal JSON: %v", err)
}
return nil
}
// JSONWriter needs a writer to write the struct into JSON string
func (fc *FluckyConfig) JSONWriter(w io.Writer) error {
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
err := encoder.Encode(&fc)
if err != nil {
return fmt.Errorf("Error in encoding struct to json: %v", err)
}
return nil
}
func (fc *FluckyConfig) PrintRemotes(w io.Writer) error {
tw := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0)
fmt.Fprint(tw, "name\taddress\tenabled\tregistered\n")
for _, remote := range fc.Remotes {
fmt.Fprintf(tw, "%v\t%v\t%v\t%v\n", remote.Name, remote.Address, remote.Enabled, remote.Registered)
}
tw.Flush()
return nil
}
// RemoveSensor deletes a sensor by its name or its unique UUID
func (fc *FluckyConfig) RemoveSensor(nameOrUUID string) error {
found := false
for i, sensor := range fc.Sensors {
// remove machted name
if !validUUID.MatchString(nameOrUUID) &&
*sensor.SensorName == nameOrUUID {
fc.Sensors = append(fc.Sensors[:i], fc.Sensors[i+1:]...)
found = true
break
}
// remove machted uuid
if validUUID.MatchString(nameOrUUID) &&
sensor.SensorID == nameOrUUID {
fc.Sensors = append(fc.Sensors[:i], fc.Sensors[i+1:]...)
found = true
break
}
}
if !found {
return fmt.Errorf("Can not find remote %v", nameOrUUID)
}
return nil
}
// RemoveRemote deletes a remote address by its name or its unique UUID
func (fc *FluckyConfig) RemoveRemote(nameOrUUID string) error {
found := false
for i, remote := range fc.Remotes {
// remove machted name
if !validUUID.MatchString(nameOrUUID) &&
remote.Name == nameOrUUID {
fc.Remotes = append(fc.Remotes[:i], fc.Remotes[i+1:]...)
found = true
}
// remove machted uuid
if validUUID.MatchString(nameOrUUID) &&
remote.RemoteID == nameOrUUID {
fc.Remotes = append(fc.Remotes[:i], fc.Remotes[i+1:]...)
found = true
}
}
if !found {
return fmt.Errorf("Can not find remote %v", nameOrUUID)
}
return nil
}
// SetDevice informations, like device name or device location
func (fc *FluckyConfig) SetDevice(device *Device) {
fc.Device = device
}
// ToJSON returns the struct as JSON string
func (fc *FluckyConfig) ToJSON() (string, error) {
var b bytes.Buffer
err := fc.JSONWriter(&b)
if err != nil {
return "", err
}
return b.String(), nil
}

10
pkg/config/remote.go Normal file
View File

@ -0,0 +1,10 @@
package config
// Remote ...
type Remote struct {
RemoteID string `json:"remote_id"`
Name string `json:"remote_name"`
Address string `json:"remote_address"`
Registered bool `json:"remote_registered"`
Enabled bool `json:"remote_enabled"`
}

View File

@ -22,6 +22,8 @@ func SyncDevice(configDir string, force bool) error {
return err return err
} }
jsonBuffer := bytes.Buffer{}
// define array of devices // define array of devices
device := types.Device{ device := types.Device{
DeviceID: cnf.DeviceID, DeviceID: cnf.DeviceID,
@ -32,19 +34,23 @@ func SyncDevice(configDir string, force bool) error {
} }
// encode to json // encode to json
deviceAsBytes, err := json.Marshal(device) encoder := json.NewEncoder(&jsonBuffer)
if err != nil { if err != nil {
return err return err
} }
deviceAsReader := bytes.NewReader(deviceAsBytes) if err = encoder.Encode(device); err != nil {
return fmt.Errorf("Can not encode device to json: %v", err)
}
log.Println(jsonBuffer.String())
// send array of devices to remote links // send array of devices to remote links
for _, remote := range cnf.Remotes { for _, remote := range cnf.Remotes {
if !remote.Registered || force { if !remote.Registered || force {
requestURL := fmt.Sprintf("%v/devices/%v", remote.Address, cnf.DeviceID) requestURL := fmt.Sprintf("%v/devices/%v", remote.Address, cnf.DeviceID)
req, err := http.NewRequest("PUT", requestURL, deviceAsReader) req, err := http.NewRequest("PUT", requestURL, &jsonBuffer)
if err != nil { if err != nil {
return err return err
} }
@ -60,7 +66,7 @@ func SyncDevice(configDir string, force bool) error {
if resp.StatusCode == 404 { if resp.StatusCode == 404 {
log.Println("test") log.Println("test")
requestURL := fmt.Sprintf("%v/devices", remote.Address) requestURL := fmt.Sprintf("%v/devices", remote.Address)
req, err := http.NewRequest("POST", requestURL, deviceAsReader) req, err := http.NewRequest("POST", requestURL, &jsonBuffer)
if err != nil { if err != nil {
return err return err
} }

View File

@ -1,158 +1,157 @@
package remote package remote
import ( // import (
"fmt" // "fmt"
"io" // "io"
"text/tabwriter" // "text/tabwriter"
"git.cryptic.systems/fh-trier/go-flucky/pkg/config" // "git.cryptic.systems/fh-trier/go-flucky/pkg/config"
"git.cryptic.systems/fh-trier/go-flucky/pkg/types" // )
)
func Add(remote *types.Remote, configDir string) error { // func Add(remote *types.Remote, configDir string) error {
configuration, err := config.Read(configDir) // configuration, err := config.Read(configDir)
if err != nil { // if err != nil {
return err // return err
} // }
// search after duplicate remote_names // // search after duplicate remote_names
for _, r := range configuration.Remotes { // for _, r := range configuration.Remotes {
if r.Name == remote.Name { // if r.Name == remote.Name {
return fmt.Errorf("Remote-Name %v already exists", remote.Name) // return fmt.Errorf("Remote-Name %v already exists", remote.Name)
} // }
} // }
configuration.Remotes = append(configuration.Remotes, remote) // configuration.Remotes = append(configuration.Remotes, remote)
if err := config.Write(configuration, configDir); err != nil { // if err := config.Write(configuration, configDir); err != nil {
return err // return err
} // }
return nil // return nil
} // }
// Enable a remote link // // Enable a remote link
func Enable(remoteName string, configDir string) error { // func Enable(remoteName string, configDir string) error {
cnf, err := config.Read(configDir) // cnf, err := config.Read(configDir)
if err != nil { // if err != nil {
return err // return err
} // }
// search after duplicate remote_names // // search after duplicate remote_names
var found bool // var found bool
for _, r := range cnf.Remotes { // for _, r := range cnf.Remotes {
if r.Name == remoteName { // if r.Name == remoteName {
r.Enabled = true // r.Enabled = true
found = true // found = true
} // }
} // }
if !found { // if !found {
return fmt.Errorf("Can not find remote %v", remoteName) // return fmt.Errorf("Can not find remote %v", remoteName)
} // }
if err := config.Write(cnf, configDir); err != nil { // if err := config.Write(cnf, configDir); err != nil {
return err // return err
} // }
return nil // return nil
} // }
// Disable a remote link // // Disable a remote link
func Disable(remoteName string, configDir string) error { // func Disable(remoteName string, configDir string) error {
cnf, err := config.Read(configDir) // cnf, err := config.Read(configDir)
if err != nil { // if err != nil {
return err // return err
} // }
// search after duplicate remote_names // // search after duplicate remote_names
var found bool // var found bool
for _, r := range cnf.Remotes { // for _, r := range cnf.Remotes {
if r.Name == remoteName { // if r.Name == remoteName {
r.Enabled = false // r.Enabled = false
found = true // found = true
} // }
} // }
if !found { // if !found {
return fmt.Errorf("Can not find remote %v", remoteName) // return fmt.Errorf("Can not find remote %v", remoteName)
} // }
if err := config.Write(cnf, configDir); err != nil { // if err := config.Write(cnf, configDir); err != nil {
return err // return err
} // }
return nil // return nil
} // }
func Print(w io.Writer, configDir string, quiet bool) error { // func Print(w io.Writer, configDir string, quiet bool) error {
configuration, err := config.Read(configDir) // configuration, err := config.Read(configDir)
if err != nil { // if err != nil {
return err // return err
} // }
tw := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0) // tw := tabwriter.NewWriter(w, 0, 0, 3, ' ', 0)
if !quiet { // if !quiet {
fmt.Fprint(tw, "name\taddress\tenabled\tregistered\n") // fmt.Fprint(tw, "name\taddress\tenabled\tregistered\n")
} // }
for _, remote := range configuration.Remotes { // for _, remote := range configuration.Remotes {
if quiet { // if quiet {
fmt.Fprintf(tw, "%v\n", remote.Name) // fmt.Fprintf(tw, "%v\n", remote.Name)
} else { // } else {
fmt.Fprintf(tw, "%v\t%v\t%v\t%v\n", remote.Name, remote.Address, remote.Enabled, remote.Registered) // fmt.Fprintf(tw, "%v\t%v\t%v\t%v\n", remote.Name, remote.Address, remote.Enabled, remote.Registered)
} // }
} // }
tw.Flush() // tw.Flush()
return nil // return nil
} // }
func Remove(name string, configDir string) error { // func Remove(name string, configDir string) error {
con, err := config.Read(configDir) // con, err := config.Read(configDir)
if err != nil { // if err != nil {
return err // return err
} // }
var j int // var j int
for _, remote := range con.Remotes { // for _, remote := range con.Remotes {
if remote.Name == name { // if remote.Name == name {
con.Remotes = append(con.Remotes[:j], con.Remotes[j+1:]...) // con.Remotes = append(con.Remotes[:j], con.Remotes[j+1:]...)
if j > 0 { // if j > 0 {
j = j - 1 // j = j - 1
} // }
continue // continue
} // }
j++ // j++
} // }
if err := config.Write(con, configDir); err != nil { // if err := config.Write(con, configDir); err != nil {
return err // return err
} // }
return nil // return nil
} // }
func RemoveAll(configDir string) error { // func RemoveAll(configDir string) error {
con, err := config.Read(configDir) // con, err := config.Read(configDir)
if err != nil { // if err != nil {
return err // return err
} // }
con.Remotes = nil // con.Remotes = nil
if err := config.Write(con, configDir); err != nil { // if err := config.Write(con, configDir); err != nil {
return err // return err
} // }
return nil // return nil
} // }

View File

@ -1,58 +0,0 @@
package types
import (
"bytes"
"encoding/json"
"fmt"
"io"
stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
)
type Config struct {
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
DeviceLocation string `json:"device_location"`
TemperatureLogfile string `json:"temperature_logfile"`
HumidityLogfile string `json:"humiditiy_logfile"`
Remotes []*Remote `json:"remotes"`
Sensors []*stypes.Sensor `json:"sensors"`
}
func (c *Config) ToJSON() (string, error) {
var b bytes.Buffer
err := c.JSONWriter(&b)
if err != nil {
return "", err
}
return b.String(), nil
}
// JSONWriter needs a writer to write the struct into json string
func (c *Config) JSONWriter(w io.Writer) error {
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
err := encoder.Encode(&c)
if err != nil {
return fmt.Errorf("Error in encoding struct to json: %v", err)
}
return nil
}
// JSONDecoder decode a json string from a reader into a struct
func (c *Config) JSONDecoder(r io.Reader) error {
jsonDecoder := json.NewDecoder(r)
if err := jsonDecoder.Decode(&c); err != nil {
return fmt.Errorf("Can not unmarshal JSON: %v", err)
}
return nil
}
// Remote ...
type Remote struct {
Name string `json:"remote_name"`
Address string `json:"remote_address"`
Registered bool `json:"remote_registered"`
Enabled bool `json:"remote_enabled"`
}