PKGBUILD/pkg/temperature/temperature.go

151 lines
2.9 KiB
Go

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/httpcall"
"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"
)
// 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 {
var temperatures []*stypes.Temperature
temperature, err := getTemperature(sensorName, configDir)
if err != nil {
return err
}
temperatures = append(temperatures, &temperature)
if err := httpcall.SendTemperatures(temperatures, 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
}