fix: temperature, sensor

changes:
- sensor temperature add
- sensor temperature list
- sensor temperature rm
- temperature get
- temperature log
- temperature push
This commit is contained in:
2018-11-20 22:55:06 +01:00
parent dd7ea3156e
commit 6d9368e86c
25 changed files with 850 additions and 48 deletions

View File

@ -22,7 +22,6 @@ func Create(configDir string, force bool) error {
}
// If no config file exists, create a new one on the location
if !force {
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
return fmt.Errorf("%v already exists. Use -f to overwrite", configPath)
@ -54,7 +53,7 @@ func Read(configDir string) (*types.Config, error) {
var config types.Config
// If no config file exists, create a new one on the location
// 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)
}
@ -78,7 +77,7 @@ func Write(config *types.Config, configDir string) error {
configPath := filepath.Join(configDir, configFilename)
// If no config file exists, create a new one on the location
// 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)
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"text/tabwriter"
@ -44,10 +45,10 @@ func List(w io.Writer, configDir string) error {
tw := tabwriter.NewWriter(w, 0, 0, 5, ' ', 0)
fmt.Fprint(tw, "name\taddress\n")
fmt.Fprint(tw, "name\taddress\tregistered\n")
for _, remote := range configuration.Remotes {
fmt.Fprintf(tw, "%v\t%v\n", remote.Name, remote.Address)
fmt.Fprintf(tw, "%v\t%v\t%v\n", remote.Name, remote.Address, remote.Registered)
}
tw.Flush()
@ -123,7 +124,11 @@ func SendTemperature(temperature *stypes.Temperature, configDir string) error {
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d", resp.StatusCode)
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))
}
}
@ -131,8 +136,8 @@ func SendTemperature(temperature *stypes.Temperature, configDir string) error {
}
// SendDevice ..
func SendDevice(configDir string) error {
// RegisterDevice ..
func RegisterDevice(configDir string, force bool) error {
con, err := config.Read(configDir)
if err != nil {
return err
@ -145,23 +150,39 @@ func SendDevice(configDir string) error {
device.EncodeToJSON(&buffer)
for _, remote := range con.Remotes {
requestURL := fmt.Sprintf("%s%s", remote.Address, "/devices")
req, err := http.NewRequest("POST", requestURL, &buffer)
if err != nil {
return err
}
if !remote.Registered || force {
requestURL := fmt.Sprintf("%s%s", remote.Address, "/devices")
req, err := http.NewRequest("POST", requestURL, &buffer)
if err != nil {
return err
}
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d", resp.StatusCode)
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))
}
remote.Registered = true
}
}
if err := config.Write(con, configDir); err != nil {
return err
}
return nil
}
func UnregisterDevice(configDir string) error {
return nil
}

14
pkg/sensor/sensor.go Normal file
View File

@ -0,0 +1,14 @@
package sensor
import (
"os"
"path/filepath"
)
func sensorExists(wirePath, sensorID string) bool {
sensorPath := filepath.Join(wirePath, sensorID)
if _, err := os.Stat(sensorPath); os.IsNotExist(err) {
return false
}
return true
}

99
pkg/sensor/temperature.go Normal file
View File

@ -0,0 +1,99 @@
package sensor
import (
"fmt"
"io"
"path/filepath"
"text/tabwriter"
"git.cryptic.systems/fh-trier/go-flucky/pkg/config"
"git.cryptic.systems/fh-trier/go-flucky/pkg/types"
)
func AddTemperature(sensorID, sensorName, configDir, wirePath string) error {
// read cnf file
cnf, err := config.Read(configDir)
if err != nil {
return err
}
// check if sensor exists
if !sensorExists(wirePath, sensorID) {
return fmt.Errorf("Can not find sensor: %v", filepath.Join(wirePath, sensorID))
}
temperatureSensor := &types.WireSensor{
ID: sensorID,
Name: sensorName,
WirePath: wirePath,
}
// append sensor to list
cnf.TemperatureSensors = append(cnf.TemperatureSensors, temperatureSensor)
// write cnf file
if err := config.Write(cnf, configDir); err != nil {
return err
}
return nil
}
func PrintTemperature(w io.Writer, configDir string, quiet bool) error {
// read cnf file
cnf, err := config.Read(configDir)
if err != nil {
return err
}
// declar tabwriter
tw := tabwriter.NewWriter(w, 0, 0, 5, ' ', 0)
// headline
if !quiet {
fmt.Fprint(tw, "id\tname\tpath\n")
}
for _, sensor := range cnf.TemperatureSensors {
if quiet {
fmt.Fprintf(tw, "%v\n", sensor.ID)
} else {
fmt.Fprintf(tw, "%v\t%v\t%v\n", sensor.ID, sensor.Name, sensor.WirePath)
}
}
tw.Flush()
return nil
}
func RemoveTemperature(sensorID, configDir string) error {
// read cnf file
cnf, err := config.Read(configDir)
if err != nil {
return err
}
// remove matching sensor ids
var j int
for _, sensor := range cnf.TemperatureSensors {
if sensor.ID == sensorID {
cnf.TemperatureSensors = append(cnf.TemperatureSensors[:j], cnf.TemperatureSensors[j+1:]...)
if j > 0 {
j = j - 1
}
continue
}
j++
}
// write cnf file
if err := config.Write(cnf, configDir); err != nil {
return err
}
return nil
}

View File

@ -1,10 +1,146 @@
package temperature
import (
"fmt"
"io"
"log"
"os"
"os/signal"
"syscall"
"text/tabwriter"
"time"
stypes "git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
"git.cryptic.systems/fh-trier/go-flucky/pkg/remote"
"git.cryptic.systems/fh-trier/go-flucky/pkg/types"
"git.cryptic.systems/fh-trier/go-flucky/pkg/config"
uuid "github.com/satori/go.uuid"
"github.com/yryz/ds18b20"
)
func Get(w io.Writer) error {
// Get ...
func Get(w io.Writer, sensorName string, configDir string) error {
temperature, err := getTemperature(sensorName, configDir)
if err != nil {
return err
}
fmt.Fprintf(w, "%3.3f\n", temperature.TemperatureValue)
return nil
}
// Logs ...
func Logs(w io.Writer, configDir string) error {
// get cnf
cnf, err := config.Read(configDir)
if err != nil {
return err
}
// declar tabwriter
tw := tabwriter.NewWriter(w, 0, 0, 5, ' ', 0)
// headlines
for _, sensor := range cnf.TemperatureSensors {
if sensor.Name != "" {
fmt.Fprintf(tw, "%v\t", sensor.Name)
} else {
fmt.Fprintf(tw, "%v\t", sensor.ID)
}
}
fmt.Fprint(tw, "\n")
// body
ticker := time.NewTicker(1 * time.Second)
go func() {
for {
select {
case _, more := <-ticker.C:
if !more {
return
}
for _, sensor := range cnf.TemperatureSensors {
temperature, err := ds18b20.Temperature(sensor.ID)
if err != nil {
return
}
fmt.Fprintf(tw, "%3.3f°\t", temperature)
}
fmt.Fprint(tw, "\n")
tw.Flush()
}
}
}()
signalChannel := make(chan os.Signal)
signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)
sig := <-signalChannel
log.Printf("Got signal %s, initiating shutdown\n", sig)
ticker.Stop()
return nil
}
// Push ...
func Push(sensorName, configDir string) error {
temperature, err := getTemperature(sensorName, configDir)
if err != nil {
return err
}
if err := remote.SendTemperature(&temperature, configDir); err != nil {
return err
}
return nil
}
func getTemperature(sensorName, configDir string) (stypes.Temperature, error) {
cnf, err := config.Read(configDir)
if err != nil {
return stypes.Temperature{}, err
}
var foundSensor types.WireSensor
var sensorFound bool
for _, sensor := range cnf.TemperatureSensors {
if sensor.ID == sensorName || sensor.Name == sensorName {
foundSensor = *sensor
sensorFound = true
break
}
}
if !sensorFound {
return stypes.Temperature{}, fmt.Errorf("Sensor not found sensor %v in config", sensorName)
}
t, err := ds18b20.Temperature(foundSensor.ID)
if err != nil {
return stypes.Temperature{}, fmt.Errorf("Can not read temperature from sensor %v: %v", foundSensor.ID, err)
}
temperature := stypes.Temperature{
TemperatureID: uuid.NewV4().String(),
TemperatureValue: t,
SensorID: foundSensor.ID,
TemperatureDate: time.Now(),
DeviceID: cnf.DeviceID,
}
return temperature, nil
}

View File

@ -8,8 +8,9 @@ import (
)
type Config struct {
DeviceID string `json:"device_id"`
Remotes []*Remote `json:"remotes"`
DeviceID string `json:"device_id"`
Remotes []*Remote `json:"remotes"`
TemperatureSensors []*WireSensor `json:"temperature_sensors"`
}
func (c *Config) ToJSON() (string, error) {
@ -43,6 +44,13 @@ func (c *Config) JSONDecoder(r io.Reader) error {
}
type Remote struct {
Name string `json:"remote_name"`
Address string `json:"remote_address"`
Name string `json:"remote_name"`
Address string `json:"remote_address"`
Registered bool `json:"remote_registered"`
}
type WireSensor struct {
ID string `json:"sensor_id"`
Name string `json:"sensor_name"`
WirePath string `json:"wire_path"`
}