PKGBUILD/pkg/httpcall/sensor.go
Markus Pesch f8e829d3d2
fix: sync and fetch temperatures
changes:
- add sync command to synchronize device sensor information with remote
  servers
- fix fetch functions to get temperatures
2018-11-29 16:06:39 +01:00

108 lines
2.4 KiB
Go

package httpcall
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
"git.cryptic.systems/fh-trier/go-flucky/pkg/config"
)
// SyncSensors ..
func SyncSensors(configDir string, force bool) error {
// read config
cnf, err := config.Read(configDir)
if err != nil {
return err
}
// send array of sensors to remote links
for _, remote := range cnf.Remotes {
if remote.Enabled || force {
// encode to json
sensorsAsBytes, err := json.Marshal(cnf.Sensors)
if err != nil {
return err
}
sensorsAsReader := bytes.NewReader(sensorsAsBytes)
requestURL := fmt.Sprintf("%v/sensors", remote.Address)
req, err := http.NewRequest("PUT", requestURL, sensorsAsReader)
if err != nil {
return err
}
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d - can not read response body: %v", resp.StatusCode, err)
}
return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d: %v", resp.StatusCode, string(b))
}
}
}
return nil
}
// PostSensors ...
func PostSensors(sensors []*stypes.Sensor, configDir string, force bool) error {
// read config
cnf, err := config.Read(configDir)
if err != nil {
return err
}
// send array of sensors to remote links
for _, remote := range cnf.Remotes {
if remote.Enabled || force {
// encode to json
sensorsAsBytes, err := json.Marshal(sensors)
if err != nil {
return err
}
sensorsAsReader := bytes.NewReader(sensorsAsBytes)
requestURL := fmt.Sprintf("%v/sensors", remote.Address)
req, err := http.NewRequest("PUT", requestURL, sensorsAsReader)
if err != nil {
return err
}
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d - can not read response body: %v", resp.StatusCode, err)
}
return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d: %v", resp.StatusCode, string(b))
}
}
}
return nil
}