fix: get temperatures

This commit is contained in:
Markus Pesch 2018-11-29 20:03:42 +01:00
parent e9630f5a19
commit cc16bb9555
Signed by: volker.raschek
GPG Key ID: 852BCC170D81A982
7 changed files with 124 additions and 113 deletions

View File

@ -8,7 +8,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var follow, writeLogfiles, push bool var follow, push bool
var getTemperatureCmd = &cobra.Command{ var getTemperatureCmd = &cobra.Command{
Use: "get", Use: "get",
@ -16,11 +16,11 @@ var getTemperatureCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if follow { if follow {
if err := temperature.GetFollow(args, writeLogfiles, push, configDir, os.Stdout); err != nil { if err := temperature.Follow(args, push, configDir, os.Stdout); err != nil {
log.Fatal(err) log.Fatal(err)
} }
} else { } else {
if err := temperature.Get(args, writeLogfiles, push, configDir, os.Stdout); err != nil { if err := temperature.Get(args, push, configDir, os.Stdout); err != nil {
log.Fatal(err) log.Fatal(err)
} }
} }
@ -31,5 +31,4 @@ func init() {
temperatureCmd.AddCommand(getTemperatureCmd) temperatureCmd.AddCommand(getTemperatureCmd)
getTemperatureCmd.Flags().BoolVarP(&follow, "follow", "f", false, "Follow output") getTemperatureCmd.Flags().BoolVarP(&follow, "follow", "f", false, "Follow output")
getTemperatureCmd.Flags().BoolVarP(&push, "push", "p", false, "Push to remote server") getTemperatureCmd.Flags().BoolVarP(&push, "push", "p", false, "Push to remote server")
getTemperatureCmd.Flags().BoolVarP(&writeLogfiles, "log", "l", true, "Write to logfiles")
} }

View File

@ -10,10 +10,9 @@ import (
var pushTemperatureCmd = &cobra.Command{ var pushTemperatureCmd = &cobra.Command{
Use: "push", Use: "push",
Short: "push temperature from sensor to remote servers", Short: "push temperature from sensor to remote servers",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if err := temperature.Push(args[0], configDir); err != nil { if err := temperature.Push(configDir); err != nil {
log.Fatal(err) log.Fatal(err)
} }
}, },

View File

@ -56,8 +56,6 @@ func SyncDevice(configDir string, force bool) error {
} }
defer resp.Body.Close() defer resp.Body.Close()
log.Println(resp.StatusCode)
// if resource does not exxists, create a new one // if resource does not exxists, create a new one
if resp.StatusCode == 404 { if resp.StatusCode == 404 {
log.Println("test") log.Println("test")

View File

@ -7,7 +7,6 @@ import (
"io/ioutil" "io/ioutil"
"net/http" "net/http"
stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
"git.cryptic.systems/fh-trier/go-flucky/pkg/config" "git.cryptic.systems/fh-trier/go-flucky/pkg/config"
) )
@ -59,49 +58,3 @@ func SyncSensors(configDir string, force bool) error {
return nil 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
}

View File

@ -2,6 +2,7 @@ package httpcall
import ( import (
"bytes" "bytes"
"encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@ -11,22 +12,24 @@ import (
stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types" stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
) )
// SendTemperature remote servers // SendTemperatures remote servers
func SendTemperatures(temperatures []*stypes.Temperature, configDir string) error { func SendTemperatures(temperatures []*stypes.Temperature, configDir string) error {
con, err := config.Read(configDir) cnf, err := config.Read(configDir)
if err != nil { if err != nil {
return err return err
} }
var buffer bytes.Buffer temperaturesAsBytes, err := json.Marshal(temperatures)
for _, temperature := range temperatures { if err != nil {
temperature.EncodeToJSON(&buffer) return fmt.Errorf("Can not marshal temperatures to JSON: %v", err)
} }
for _, remote := range con.Remotes { temperaturesAsReader := bytes.NewReader(temperaturesAsBytes)
for _, remote := range cnf.Remotes {
requestURL := fmt.Sprintf("%s%s", remote.Address, "/temperatures") requestURL := fmt.Sprintf("%s%s", remote.Address, "/temperatures")
req, err := http.NewRequest("POST", requestURL, &buffer) req, err := http.NewRequest("POST", requestURL, temperaturesAsReader)
if err != nil { if err != nil {
return err return err
} }

View File

@ -1,8 +1,9 @@
package logs package logs
import ( import (
"bufio" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -10,34 +11,79 @@ import (
"git.cryptic.systems/fh-trier/go-flucky/pkg/types" "git.cryptic.systems/fh-trier/go-flucky/pkg/types"
) )
// Temperature write a given array of temperatures to a logfile // AppendTemperature write a given array of temperatures to a logfile
func Temperature(temperatures []*stypes.Temperature, config *types.Config) error { func AppendTemperature(temperatures []*stypes.Temperature, cnf *types.Config) error {
logPath := filepath.Dir(config.TemperatureLogfile) tLog, err := ReadTemperatures(cnf.TemperatureLogfile)
// create log dir if not exist
if _, err := os.Stat(logPath); os.IsNotExist(err) {
err := os.MkdirAll(logPath, os.ModePerm)
if err != nil {
return fmt.Errorf("Can not create directory: %v", err)
}
}
f, err := os.OpenFile(config.TemperatureLogfile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil { if err != nil {
return err return err
} }
defer f.Close()
w := bufio.NewWriter(f) tLog = append(tLog, temperatures...)
for _, temperature := range temperatures { err = WriteTemperatures(tLog, cnf.TemperatureLogfile)
fmt.Fprintf(w, "%v\t%v\t%v\t%v\n", temperature.TemperatureID, temperature.TemperatureValue, temperature.TemperatureDate, temperature.SensorID)
}
err = w.Flush()
if err != nil { if err != nil {
return fmt.Errorf("Can not flush writer: %v", err) return err
}
return nil
}
// FlushTemperatures ...
func FlushTemperatures(logFile string) error {
if err := ioutil.WriteFile(logFile, []byte(""), 0644); err != nil {
return err
}
return nil
}
// ReadTemperatures ...
func ReadTemperatures(logFile string) ([]*stypes.Temperature, error) {
logPath := filepath.Dir(logFile)
// create log dir if not exist
if _, err := os.Stat(logFile); os.IsNotExist(err) {
if _, err := os.Stat(logPath); os.IsNotExist(err) {
err := os.MkdirAll(logPath, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("Can not create directory: %v", err)
}
}
if err := FlushTemperatures(logFile); err != nil {
return nil, err
}
}
// open config file
jsonFile, err := os.Open(logFile)
if err != nil {
return nil, fmt.Errorf("Can not open file %v: %v", logFile, err)
}
defer jsonFile.Close()
bytes, err := ioutil.ReadAll(jsonFile)
if err != nil {
return nil, fmt.Errorf("Can not read jsonfile %v: %v", logFile, err)
}
temperatures := []*stypes.Temperature{}
json.Unmarshal(bytes, &temperatures)
return temperatures, nil
}
// WriteTemperatures ...
func WriteTemperatures(temperatures []*stypes.Temperature, logFile string) error {
bytes, err := json.Marshal(temperatures)
if err != nil {
return err
}
if err := ioutil.WriteFile(logFile, bytes, 0644); err != nil {
return err
} }
return nil return nil

View File

@ -10,6 +10,7 @@ import (
"time" "time"
stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types" stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
"git.cryptic.systems/fh-trier/go-flucky/pkg/httpcall"
"git.cryptic.systems/fh-trier/go-flucky/pkg/logs" "git.cryptic.systems/fh-trier/go-flucky/pkg/logs"
"git.cryptic.systems/fh-trier/go-flucky/pkg/config" "git.cryptic.systems/fh-trier/go-flucky/pkg/config"
@ -21,7 +22,7 @@ import (
var temperatureLog = "temperature.log" var temperatureLog = "temperature.log"
// Get ... // Get ...
func Get(sensorNames []string, writeLogfiles, push bool, configDir string, w io.Writer) error { func Get(sensorNames []string, push bool, configDir string, w io.Writer) error {
// get cnf // get cnf
cnf, err := config.Read(configDir) cnf, err := config.Read(configDir)
@ -37,7 +38,8 @@ func Get(sensorNames []string, writeLogfiles, push bool, configDir string, w io.
for _, sensorName := range sensorNames { for _, sensorName := range sensorNames {
for _, sensor := range cnf.Sensors { for _, sensor := range cnf.Sensors {
if sensorName == *sensor.SensorName || if sensorName == *sensor.SensorName ||
sensorName == sensor.SensorID { sensorName == sensor.SensorID ||
sensorName == *sensor.WireID {
sensors = append(sensors, sensor) sensors = append(sensors, sensor)
} }
} }
@ -85,23 +87,22 @@ func Get(sensorNames []string, writeLogfiles, push bool, configDir string, w io.
tw.Flush() tw.Flush()
// if writeLogfiles { // write logfiles or push
// if err := logs.Temperature(temperatures, cnf); err != nil { if !push {
// return err if err := logs.AppendTemperature(temperatures, cnf); err != nil {
// } return err
// } }
} else {
// if push { if err := httpcall.SendTemperatures(temperatures, configDir); err != nil {
// if err := httpcall.SendTemperatures(temperatures, configDir); err != nil { return err
// return err }
// } }
// }
return nil return nil
} }
func GetFollow(sensorNames []string, writeLogfiles, push bool, configDir string, w io.Writer) error { func Follow(sensorNames []string, push bool, configDir string, w io.Writer) error {
// get cnf // get cnf
cnf, err := config.Read(configDir) cnf, err := config.Read(configDir)
@ -153,7 +154,7 @@ func GetFollow(sensorNames []string, writeLogfiles, push bool, configDir string,
// get temperatures from sensors and write them into writer // get temperatures from sensors and write them into writer
temperatures, err = getTemperatures(sensors) temperatures, err = getTemperatures(sensors)
for _, temperature := range temperatures { for _, temperature := range temperatures {
fmt.Fprintf(tw, "%v\t", temperature.TemperatureValue) fmt.Fprintf(tw, "%3.3f\t", temperature.TemperatureValue)
} }
fmt.Fprint(tw, "\n") fmt.Fprint(tw, "\n")
@ -172,9 +173,13 @@ func GetFollow(sensorNames []string, writeLogfiles, push bool, configDir string,
fmt.Printf("Got signal %s, initiating shutdown\n", sig) fmt.Printf("Got signal %s, initiating shutdown\n", sig)
ticker.Stop() ticker.Stop()
// write logfiles // write logfiles or push
if writeLogfiles { if !push {
if err := logs.Temperature(temperatures, cnf); err != nil { if err := logs.AppendTemperature(temperatures, cnf); err != nil {
return err
}
} else {
if err := httpcall.SendTemperatures(temperatures, configDir); err != nil {
return err return err
} }
} }
@ -182,20 +187,27 @@ func GetFollow(sensorNames []string, writeLogfiles, push bool, configDir string,
return nil return nil
} }
func Push(sensorName, configDir string) error { // Push ...
func Push(configDir string) error {
// var temperatures []*stypes.Temperature // get cnf
cnf, err := config.Read(configDir)
if err != nil {
return err
}
// temperature, err := getTemperature(sensorName, configDir) temperatures, err := logs.ReadTemperatures(cnf.TemperatureLogfile)
// if err != nil { if err != nil {
// return err return err
// } }
// temperatures = append(temperatures, &temperature) if err := httpcall.SendTemperatures(temperatures, configDir); err != nil {
return err
}
// if err := httpcall.SendTemperatures(temperatures, configDir); err != nil { if err := logs.FlushTemperatures(cnf.TemperatureLogfile); err != nil {
// return err return err
// } }
return nil return nil
@ -214,8 +226,9 @@ func getTemperatures(sensors []*stypes.Sensor) ([]*stypes.Temperature, error) {
temperature := &stypes.Temperature{ temperature := &stypes.Temperature{
TemperatureID: uuid.NewV4().String(), TemperatureID: uuid.NewV4().String(),
TemperatureValue: t, TemperatureValue: t,
SensorID: sensor.SensorID,
TemperatureDate: time.Now(), TemperatureDate: time.Now(),
SensorID: sensor.SensorID,
CreationDate: time.Now(),
} }
temperatures = append(temperatures, temperature) temperatures = append(temperatures, temperature)