fix(pkg/types): use measured values as struct instead interface

This commit is contained in:
Markus Pesch 2019-07-02 22:33:01 +02:00
parent d703d33e08
commit 825511c3b5
Signed by: volker.raschek
GPG Key ID: 852BCC170D81A982
23 changed files with 218 additions and 659 deletions

View File

@ -5,11 +5,12 @@ import (
"log" "log"
"os" "os"
"github.com/go-flucky/flucky/pkg/types"
"github.com/go-flucky/flucky/pkg/cli" "github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config" "github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/logfile" "github.com/go-flucky/flucky/pkg/logfile"
"github.com/go-flucky/flucky/pkg/rgbled" "github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/types/typeswitch"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -41,7 +42,7 @@ var listTemperatureCmd = &cobra.Command{
log.Fatalln(err) log.Fatalln(err)
} }
measuredValues = typeswitch.HumidityValues(measuredValues) measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeHumidity, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout) cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)

View File

@ -5,12 +5,12 @@ import (
"log" "log"
"os" "os"
"github.com/go-flucky/flucky/pkg/logfile" "github.com/go-flucky/flucky/pkg/types"
"github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/types/typeswitch"
"github.com/go-flucky/flucky/pkg/cli" "github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config" "github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/logfile"
"github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/sensor" "github.com/go-flucky/flucky/pkg/sensor"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -51,7 +51,7 @@ var readHumidityCmd = &cobra.Command{
log.Fatalln(err) log.Fatalln(err)
} }
measuredValues = typeswitch.HumidityValues(measuredValues) measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeHumidity, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout) cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)

View File

@ -5,11 +5,12 @@ import (
"log" "log"
"os" "os"
"github.com/go-flucky/flucky/pkg/types"
"github.com/go-flucky/flucky/pkg/cli" "github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config" "github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/logfile" "github.com/go-flucky/flucky/pkg/logfile"
"github.com/go-flucky/flucky/pkg/rgbled" "github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/types/typeswitch"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -41,7 +42,7 @@ var listTemperatureCmd = &cobra.Command{
log.Fatalln(err) log.Fatalln(err)
} }
measuredValues = typeswitch.TemperatureValues(measuredValues) measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeTemperature, measuredValues)
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout) cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)

View File

@ -6,9 +6,8 @@ import (
"log" "log"
"os" "os"
"github.com/go-flucky/flucky/pkg/types/typeswitch"
"github.com/go-flucky/flucky/pkg/rgbled" "github.com/go-flucky/flucky/pkg/rgbled"
"github.com/go-flucky/flucky/pkg/types"
"github.com/go-flucky/flucky/pkg/cli" "github.com/go-flucky/flucky/pkg/cli"
"github.com/go-flucky/flucky/pkg/config" "github.com/go-flucky/flucky/pkg/config"
@ -55,7 +54,7 @@ var readTemperatureCmd = &cobra.Command{
log.Fatalln(err) log.Fatalln(err)
} }
measuredValues = typeswitch.TemperatureValues(measuredValues) measuredValues = types.SelectMeasuredValues(types.MeasuredValueTypeTemperature, measuredValues)
// print temperatures on stdout // print temperatures on stdout
cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout) cli.PrintMeasuredValues(measuredValues, cnf, os.Stdout)

View File

@ -10,13 +10,13 @@ import (
) )
// GetSensorsByMeasuredValues returns commulated list of sensors by measured values // GetSensorsByMeasuredValues returns commulated list of sensors by measured values
func GetSensorsByMeasuredValues(measuredValues []types.MeasuredValue, cnf *config.Configuration) []*types.Sensor { func GetSensorsByMeasuredValues(measuredValues []*types.MeasuredValue, cnf *config.Configuration) []*types.Sensor {
sensors := []*types.Sensor{} sensors := []*types.Sensor{}
for _, measuredValue := range measuredValues { for _, measuredValue := range measuredValues {
duplicated := false duplicated := false
foundSensor := &types.Sensor{} foundSensor := &types.Sensor{}
for _, cnfSensor := range cnf.Sensors { for _, cnfSensor := range cnf.Sensors {
if measuredValue.GetSensorID() == cnfSensor.SensorID { if measuredValue.SensorID == cnfSensor.SensorID {
foundSensor = cnfSensor foundSensor = cnfSensor
// compare if id has already been added to list // compare if id has already been added to list
@ -35,7 +35,7 @@ func GetSensorsByMeasuredValues(measuredValues []types.MeasuredValue, cnf *confi
sensors = append(sensors, foundSensor) sensors = append(sensors, foundSensor)
continue continue
} else { } else {
sensors = append(sensors, &types.Sensor{SensorID: measuredValue.GetSensorID()}) sensors = append(sensors, &types.Sensor{SensorID: measuredValue.SensorID})
} }
} }
return sensors return sensors
@ -81,14 +81,14 @@ func PrintSensors(cnf *config.Configuration, w io.Writer) error {
} }
// PrintMeasuredValues displays a list of measured values // PrintMeasuredValues displays a list of measured values
func PrintMeasuredValues(measuredValues []types.MeasuredValue, cnf *config.Configuration, w io.Writer) { func PrintMeasuredValues(measuredValues []*types.MeasuredValue, cnf *config.Configuration, w io.Writer) {
sensors := GetSensorsByMeasuredValues(measuredValues, cnf) sensors := GetSensorsByMeasuredValues(measuredValues, cnf)
// sort measured values for every sensor // sort measured values for every sensor
orderedMeasuredValues := make(map[string][]types.MeasuredValue) orderedMeasuredValues := make(map[string][]*types.MeasuredValue)
for _, measuredValue := range measuredValues { for _, measuredValue := range measuredValues {
orderedMeasuredValues[measuredValue.GetSensorID()] = append(orderedMeasuredValues[measuredValue.GetSensorID()], measuredValue) orderedMeasuredValues[measuredValue.SensorID] = append(orderedMeasuredValues[measuredValue.SensorID], measuredValue)
} }
// declare tabwriter // declare tabwriter
@ -114,7 +114,7 @@ func PrintMeasuredValues(measuredValues []types.MeasuredValue, cnf *config.Confi
for i := 0; i < maxLength; i++ { for i := 0; i < maxLength; i++ {
for _, sensor := range sensors { for _, sensor := range sensors {
if len(orderedMeasuredValues[sensor.SensorID]) > i { if len(orderedMeasuredValues[sensor.SensorID]) > i {
fmt.Fprintf(tw, "%3.3f\t", orderedMeasuredValues[sensor.SensorID][i].GetValue()) fmt.Fprintf(tw, "%3.3f\t", orderedMeasuredValues[sensor.SensorID][i].Value)
} else { } else {
fmt.Fprint(tw, "\t") fmt.Fprint(tw, "\t")
} }

View File

@ -29,14 +29,14 @@ func Start(cnf *config.Configuration, cleanCacheInterval time.Duration, compress
signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM) signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)
errorChannel := make(chan error, 0) errorChannel := make(chan error, 0)
measuredValuesChannel := make(chan []types.MeasuredValue, 0) measuredValuesChannel := make(chan []*types.MeasuredValue, 0)
ctx := context.Background() ctx := context.Background()
childContext, cancel := context.WithCancel(ctx) childContext, cancel := context.WithCancel(ctx)
measuredValuesLogfile := logfile.New(cnf.Device.Logfile) measuredValuesLogfile := logfile.New(cnf.Device.Logfile)
measuredValuesCache := make([]types.MeasuredValue, 0) measuredValuesCache := make([]*types.MeasuredValue, 0)
go sensor.ReadContinuously(childContext, cnf.GetSensors(config.ENABLED), measuredValuesChannel, errorChannel) go sensor.ReadContinuously(childContext, cnf.GetSensors(config.ENABLED), measuredValuesChannel, errorChannel)
@ -78,7 +78,7 @@ func Start(cnf *config.Configuration, cleanCacheInterval time.Duration, compress
cancel() cancel()
logger.Fatal("Can not save temperatures: %v", err) logger.Fatal("Can not save temperatures: %v", err)
} }
measuredValuesCache = make([]types.MeasuredValue, 0) measuredValuesCache = make([]*types.MeasuredValue, 0)
case measuredValues, _ := <-measuredValuesChannel: case measuredValues, _ := <-measuredValuesChannel:
measuredValuesCache = append(measuredValuesCache, measuredValues...) measuredValuesCache = append(measuredValuesCache, measuredValues...)

View File

@ -4,8 +4,8 @@ import (
"github.com/go-flucky/flucky/pkg/types" "github.com/go-flucky/flucky/pkg/types"
) )
func MeasuredValues(measuredValuesChannel <-chan []types.MeasuredValue) []types.MeasuredValue { func MeasuredValues(measuredValuesChannel <-chan []*types.MeasuredValue) []*types.MeasuredValue {
cachedMeasuredValues := make([]types.MeasuredValue, 0) cachedMeasuredValues := make([]*types.MeasuredValue, 0)
for { for {
select { select {
case measuredValues, more := <-measuredValuesChannel: case measuredValues, more := <-measuredValuesChannel:

View File

@ -14,7 +14,7 @@ type csvLogfile struct {
logfile string logfile string
} }
func (cl *csvLogfile) Read() ([]types.MeasuredValue, error) { func (cl *csvLogfile) Read() ([]*types.MeasuredValue, error) {
if _, err := os.Stat(cl.logfile); os.IsNotExist(err) { if _, err := os.Stat(cl.logfile); os.IsNotExist(err) {
return nil, fmt.Errorf("%v: %v", errorLogfileNotFound, cl.logfile) return nil, fmt.Errorf("%v: %v", errorLogfileNotFound, cl.logfile)
} }
@ -31,10 +31,16 @@ func (cl *csvLogfile) Read() ([]types.MeasuredValue, error) {
return nil, fmt.Errorf("%v %v: %v", errorLogfileDecode, cl.logfile, err) return nil, fmt.Errorf("%v %v: %v", errorLogfileDecode, cl.logfile, err)
} }
measuredValues := make([]types.MeasuredValue, 0) measuredValues := make([]*types.MeasuredValue, 0)
for _, record := range records { for _, record := range records {
// ValueType
valueType, err := types.SelectMeasuredValueType(record[1])
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseFloat, record[1], err)
}
// Value // Value
value, err := strconv.ParseFloat(record[2], 64) value, err := strconv.ParseFloat(record[2], 64)
if err != nil { if err != nil {
@ -51,25 +57,22 @@ func (cl *csvLogfile) Read() ([]types.MeasuredValue, error) {
times = append(times, time) times = append(times, time)
} }
switch record[1] { measuredValue := &types.MeasuredValue{
case fmt.Sprint(types.MeasuredValueTypeHumidity): ID: record[0],
measuredValue := &types.Humidity{ ValueType: *valueType,
HumidityID: record[0], // 0 Value: value,
// 1 - MeasuredValue FromDate: times[0],
HumidityValue: value, // 2 TillDate: times[1],
HumidityFromDate: times[0], // 3 SensorID: record[5],
HumidityTillDate: times[1], // 4
SensorID: record[5], // 5
} }
// CreationDate // Creation date
creationDate, err := time.Parse(timeFormat, record[6]) creationDate, err := time.Parse(timeFormat, record[6])
if err != nil { if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseTime, record[6], err) return nil, fmt.Errorf("%v %v: %v", errorParseTime, record[6], err)
} }
measuredValue.CreationDate = &creationDate measuredValue.CreationDate = &creationDate
// UpdateDate
if record[7] != "null" { if record[7] != "null" {
updateDate, err := time.Parse(timeFormat, record[7]) updateDate, err := time.Parse(timeFormat, record[7])
if err != nil { if err != nil {
@ -80,72 +83,13 @@ func (cl *csvLogfile) Read() ([]types.MeasuredValue, error) {
measuredValues = append(measuredValues, measuredValue) measuredValues = append(measuredValues, measuredValue)
case fmt.Sprint(types.MeasuredValueTypePressure):
measuredValue := &types.Pressure{
PressureID: record[0], // 0
// 1 - MeasuredValue
PressureValue: value, // 2
PressureFromDate: times[0], // 3
PressureTillDate: times[1], // 4
SensorID: record[5], // 5
}
// CreationDate
creationDate, err := time.Parse(timeFormat, record[6])
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseTime, record[6], err)
}
measuredValue.CreationDate = &creationDate
// UpdateDate
if record[7] != "null" {
updateDate, err := time.Parse(timeFormat, record[7])
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseTime, record[7], err)
}
measuredValue.UpdateDate = &updateDate
}
measuredValues = append(measuredValues, measuredValue)
case fmt.Sprint(types.MeasuredValueTypeTemperature):
measuredValue := &types.Temperature{
TemperatureID: record[0], // 0
// 1 - MeasuredValue
TemperatureValue: value, // 2
TemperatureFromDate: times[0], // 3
TemperatureTillDate: times[1], // 4
SensorID: record[5], // 5
}
// CreationDate
creationDate, err := time.Parse(timeFormat, record[6])
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseTime, record[6], err)
}
measuredValue.CreationDate = &creationDate
// UpdateDate
if record[7] != "null" {
updateDate, err := time.Parse(timeFormat, record[7])
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorParseTime, record[7], err)
}
measuredValue.UpdateDate = &updateDate
}
measuredValues = append(measuredValues, measuredValue)
default:
continue
}
} }
return measuredValues, nil return measuredValues, nil
} }
func (cl *csvLogfile) Write(measuredValues []types.MeasuredValue) error { func (cl *csvLogfile) Write(measuredValues []*types.MeasuredValue) error {
f, err := os.Create(cl.logfile) f, err := os.Create(cl.logfile)
if err != nil { if err != nil {
return fmt.Errorf("%v: %v", errorLogfileCreate, cl.logfile) return fmt.Errorf("%v: %v", errorLogfileCreate, cl.logfile)
@ -159,22 +103,22 @@ func (cl *csvLogfile) Write(measuredValues []types.MeasuredValue) error {
for _, measuredValue := range measuredValues { for _, measuredValue := range measuredValues {
record := []string{ record := []string{
measuredValue.GetID(), measuredValue.ID,
fmt.Sprintf("%v", measuredValue.GetMeasuredValueType()), fmt.Sprintf("%v", measuredValue.ValueType),
fmt.Sprintf("%v", measuredValue.GetValue()), fmt.Sprintf("%v", measuredValue.Value),
measuredValue.GetFromDate().Format(timeFormat), measuredValue.FromDate.Format(timeFormat),
measuredValue.GetTillDate().Format(timeFormat), measuredValue.TillDate.Format(timeFormat),
measuredValue.GetSensorID(), measuredValue.SensorID,
} }
if measuredValue.GetCreationDate() != nil { if measuredValue.CreationDate != nil {
record = append(record, measuredValue.GetCreationDate().Format(timeFormat)) record = append(record, measuredValue.CreationDate.Format(timeFormat))
} else { } else {
record = append(record, "null") record = append(record, "null")
} }
if measuredValue.GetUpdateDate() != nil { if measuredValue.UpdateDate != nil {
record = append(record, measuredValue.GetUpdateDate().Format(timeFormat)) record = append(record, measuredValue.UpdateDate.Format(timeFormat))
} else { } else {
record = append(record, "null") record = append(record, "null")
} }

View File

@ -5,6 +5,6 @@ import (
) )
type Logfile interface { type Logfile interface {
Read() ([]types.MeasuredValue, error) Read() ([]*types.MeasuredValue, error)
Write(measuredValues []types.MeasuredValue) error Write(measuredValues []*types.MeasuredValue) error
} }

View File

@ -3,12 +3,8 @@ package logfile
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"log"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"time"
"github.com/go-flucky/flucky/pkg/types" "github.com/go-flucky/flucky/pkg/types"
) )
@ -17,209 +13,27 @@ type jsonLogfile struct {
logfile string logfile string
} }
func (jl *jsonLogfile) Read() ([]types.MeasuredValue, error) { func (jl *jsonLogfile) Read() ([]*types.MeasuredValue, error) {
if _, err := os.Stat(jl.logfile); os.IsNotExist(err) { if _, err := os.Stat(jl.logfile); os.IsNotExist(err) {
return nil, fmt.Errorf("%v: %v", errorLogfileNotFound, jl.logfile) return nil, fmt.Errorf("%v: %v", errorLogfileNotFound, jl.logfile)
} }
unmarshaledMeasuredValues := make([]interface{}, 0) f, err := os.Open(jl.logfile)
bytes, err := ioutil.ReadFile(jl.logfile)
if err != nil { if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorLogfileRead, jl.logfile, err) return nil, fmt.Errorf("%v %v: %v", errorLogfileOpen, jl.logfile, err)
} }
err = json.Unmarshal(bytes, &unmarshaledMeasuredValues) measuredValues := make([]*types.MeasuredValue, 0)
if err != nil {
return nil, fmt.Errorf("%v %v: %v", errorLogfileUnmarshal, jl.logfile, err)
}
measuredValues := make([]types.MeasuredValue, 0)
for _, unmarshaledMeasuredValue := range unmarshaledMeasuredValues {
if unmarshaledMeasuredValue == nil {
continue
}
mappedMeasuredValue, ok := unmarshaledMeasuredValue.(map[string]interface{})
if !ok {
log.Println("Can not parse into map")
continue
}
if _, ok := mappedMeasuredValue["temperature_id"]; ok {
temperature, err := jl.transformTemperature(mappedMeasuredValue)
if err != nil {
log.Printf("Can not unmarshal temperature from map: %v", err)
continue
}
measuredValues = append(measuredValues, temperature)
}
if _, ok := mappedMeasuredValue["pressure_id"]; ok {
pressure, err := jl.transformPressure(mappedMeasuredValue)
if err != nil {
log.Printf("Can not unmarshal pressure from map: %v", err)
continue
}
measuredValues = append(measuredValues, pressure)
}
if _, ok := mappedMeasuredValue["humidity_id"]; ok {
humidity, err := jl.transformHumidity(mappedMeasuredValue)
if err != nil {
log.Printf("Can not unmarshal humidity from map: %v", err)
continue
}
measuredValues = append(measuredValues, humidity)
}
if err := json.NewDecoder(f).Decode(measuredValues); err != nil {
return nil, fmt.Errorf("%v %v: %v", errorLogfileDecode, jl.logfile, err)
} }
return measuredValues, nil return measuredValues, nil
} }
func (jl *jsonLogfile) transformHumidity(mappedMeasuredValue map[string]interface{}) (types.MeasuredValue, error) { func (jl *jsonLogfile) Write(measuredValues []*types.MeasuredValue) error {
humidity := &types.Humidity{
HumidityID: mappedMeasuredValue["humidity_id"].(string),
SensorID: mappedMeasuredValue["sensor_id"].(string),
CreationDate: nil,
UpdateDate: nil,
}
humidityValue, err := strconv.ParseFloat(mappedMeasuredValue["humidity_value"].(string), 64)
if err != nil {
return nil, fmt.Errorf("%v for humidity value. HumidityID %v: %v", errorParseFloat, mappedMeasuredValue["humidity_id"].(string), err)
}
humidity.HumidityValue = humidityValue
humidityFromDate, err := time.Parse(timeFormat, mappedMeasuredValue["humidity_from_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for humidity from date. HumidityID %v: %v", errorParseTime, mappedMeasuredValue["humidity_id"].(string), err)
}
humidity.HumidityFromDate = humidityFromDate
humidityTillDate, err := time.Parse(timeFormat, mappedMeasuredValue["humidity_till_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for humidity till date. HumidityID %v: %v", errorParseTime, mappedMeasuredValue["humidity_id"].(string), err)
}
humidity.HumidityTillDate = humidityTillDate
if mappedMeasuredValue["creation_date"] != nil {
creationDate, err := time.Parse(timeFormat, mappedMeasuredValue["creation_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for creation date. HumidityID %v: %v", errorParseTime, mappedMeasuredValue["humidity_id"].(string), err)
}
humidity.CreationDate = &creationDate
}
if mappedMeasuredValue["update_date"] != nil {
updateDate, err := time.Parse(timeFormat, mappedMeasuredValue["update_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for update date. HumidityID %v: %v", errorParseTime, mappedMeasuredValue["humidity_id"].(string), err)
}
humidity.UpdateDate = &updateDate
}
return humidity, nil
}
func (jl *jsonLogfile) transformPressure(mappedMeasuredValue map[string]interface{}) (types.MeasuredValue, error) {
pressure := &types.Pressure{
PressureID: mappedMeasuredValue["pressure_id"].(string),
SensorID: mappedMeasuredValue["sensor_id"].(string),
CreationDate: nil,
UpdateDate: nil,
}
pressureValue, err := strconv.ParseFloat(mappedMeasuredValue["pressure_value"].(string), 64)
if err != nil {
return nil, fmt.Errorf("%v for pressure value. PressureID %v: %v", errorParseFloat, mappedMeasuredValue["pressure_id"].(string), err)
}
pressure.PressureValue = pressureValue
pressureFromDate, err := time.Parse(timeFormat, mappedMeasuredValue["pressure_from_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for pressure from date. PressureID %v: %v", errorParseTime, mappedMeasuredValue["pressure_id"].(string), err)
}
pressure.PressureFromDate = pressureFromDate
pressureTillDate, err := time.Parse(timeFormat, mappedMeasuredValue["pressure_till_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for pressure till date. PressureID %v: %v", errorParseTime, mappedMeasuredValue["pressure_id"].(string), err)
}
pressure.PressureTillDate = pressureTillDate
if mappedMeasuredValue["creation_date"] != nil {
creationDate, err := time.Parse(timeFormat, mappedMeasuredValue["creation_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for creation date. PressureID %v: %v", errorParseTime, mappedMeasuredValue["pressure_id"].(string), err)
}
pressure.CreationDate = &creationDate
}
if mappedMeasuredValue["update_date"] != nil {
updateDate, err := time.Parse(timeFormat, mappedMeasuredValue["update_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for update date. PressureID %v: %v", errorParseTime, mappedMeasuredValue["pressure_id"].(string), err)
}
pressure.UpdateDate = &updateDate
}
return pressure, nil
}
func (jl *jsonLogfile) transformTemperature(mappedMeasuredValue map[string]interface{}) (types.MeasuredValue, error) {
temperature := &types.Temperature{
TemperatureID: mappedMeasuredValue["temperature_id"].(string),
SensorID: mappedMeasuredValue["sensor_id"].(string),
CreationDate: nil,
UpdateDate: nil,
}
temperatureValue, err := strconv.ParseFloat(mappedMeasuredValue["temperature_value"].(string), 64)
if err != nil {
return nil, fmt.Errorf("%v for temperature value. TemperatureID %v: %v", errorParseFloat, mappedMeasuredValue["temperature_id"].(string), err)
}
temperature.TemperatureValue = temperatureValue
temperatureFromDate, err := time.Parse(timeFormat, mappedMeasuredValue["temperature_from_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for temperature from date. TemperatureID %v: %v", errorParseTime, mappedMeasuredValue["temperature_id"].(string), err)
}
temperature.TemperatureFromDate = temperatureFromDate
temperatureTillDate, err := time.Parse(timeFormat, mappedMeasuredValue["temperature_till_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for temperature till date. TemperatureID %v: %v", errorParseTime, mappedMeasuredValue["temperature_id"].(string), err)
}
temperature.TemperatureTillDate = temperatureTillDate
if mappedMeasuredValue["creation_date"] != nil {
creationDate, err := time.Parse(timeFormat, mappedMeasuredValue["creation_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for creation date. TemperatureID %v: %v", errorParseTime, mappedMeasuredValue["temperature_id"].(string), err)
}
temperature.CreationDate = &creationDate
}
if mappedMeasuredValue["update_date"] != nil {
updateDate, err := time.Parse(timeFormat, mappedMeasuredValue["update_date"].(string))
if err != nil {
return nil, fmt.Errorf("%v for update date. TemperatureID %v: %v", errorParseTime, mappedMeasuredValue["temperature_id"].(string), err)
}
temperature.UpdateDate = &updateDate
}
return temperature, nil
}
func (jl *jsonLogfile) Write(measuredValues []types.MeasuredValue) error {
if _, err := os.Stat(filepath.Dir(jl.logfile)); os.IsNotExist(err) { if _, err := os.Stat(filepath.Dir(jl.logfile)); os.IsNotExist(err) {
if err := os.MkdirAll(filepath.Dir(jl.logfile), 755); err != nil { if err := os.MkdirAll(filepath.Dir(jl.logfile), 755); err != nil {

View File

@ -12,11 +12,11 @@ import (
// var validUUID = regexp.MustCompile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$") // var validUUID = regexp.MustCompile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$")
var timeFormat = "2006-01-02T15:04:05.999999Z07:00" var timeFormat = "2006-01-02T15:04:05.999999Z07:00"
func Append(logfile Logfile, compression bool, round float64, measuredValues []types.MeasuredValue) error { func Append(logfile Logfile, compression bool, round float64, measuredValues []*types.MeasuredValue) error {
if round != 0 { if round != 0 {
for _, measuredValue := range measuredValues { for _, measuredValue := range measuredValues {
measuredValue.SetValue(math.Round(measuredValue.GetValue()/round) * round) measuredValue.Value = math.Round(measuredValue.Value/round) * round
} }
} }
@ -45,35 +45,35 @@ func Append(logfile Logfile, compression bool, round float64, measuredValues []t
// the current value is discarded and the validity date of the previous value is // the current value is discarded and the validity date of the previous value is
// set to that of the current value. This means that no information is lost. // set to that of the current value. This means that no information is lost.
// Only the validity period of the measured value is increased. // Only the validity period of the measured value is increased.
func Compression(measuredValues []types.MeasuredValue) []types.MeasuredValue { func Compression(measuredValues []*types.MeasuredValue) []*types.MeasuredValue {
compressedMeasuredValues := make([]types.MeasuredValue, 0) compressedMeasuredValues := make([]*types.MeasuredValue, 0)
lastMeasuredValuesBySensors := make(map[string]map[types.MeasuredValueType]types.MeasuredValue, 0) lastMeasuredValuesBySensors := make(map[string]map[types.MeasuredValueType]*types.MeasuredValue, 0)
// Sort all measured values according to the start time of the validity date // Sort all measured values according to the start time of the validity date
// in order to successfully implement the subsequent compression. // in order to successfully implement the subsequent compression.
sort.SliceStable(measuredValues, func(i int, j int) bool { sort.SliceStable(measuredValues, func(i int, j int) bool {
return measuredValues[i].GetFromDate().Before(measuredValues[j].GetFromDate()) return measuredValues[i].FromDate.Before(measuredValues[j].TillDate)
}) })
now := time.Now() now := time.Now()
for _, measuredValue := range measuredValues { for _, measuredValue := range measuredValues {
if _, ok := lastMeasuredValuesBySensors[measuredValue.GetSensorID()]; !ok { if _, ok := lastMeasuredValuesBySensors[measuredValue.SensorID]; !ok {
lastMeasuredValuesBySensors[measuredValue.GetSensorID()] = make(map[types.MeasuredValueType]types.MeasuredValue, 0) lastMeasuredValuesBySensors[measuredValue.SensorID] = make(map[types.MeasuredValueType]*types.MeasuredValue, 0)
} }
if _, ok := lastMeasuredValuesBySensors[measuredValue.GetSensorID()][measuredValue.GetMeasuredValueType()]; !ok { if _, ok := lastMeasuredValuesBySensors[measuredValue.SensorID][measuredValue.ValueType]; !ok {
lastMeasuredValuesBySensors[measuredValue.GetSensorID()][measuredValue.GetMeasuredValueType()] = measuredValue lastMeasuredValuesBySensors[measuredValue.SensorID][measuredValue.ValueType] = measuredValue
continue continue
} }
if lastMeasuredValuesBySensors[measuredValue.GetSensorID()][measuredValue.GetMeasuredValueType()].GetValue() == measuredValue.GetValue() { if lastMeasuredValuesBySensors[measuredValue.SensorID][measuredValue.ValueType].Value == measuredValue.Value {
lastMeasuredValuesBySensors[measuredValue.GetSensorID()][measuredValue.GetMeasuredValueType()].SetTillDate(measuredValue.GetTillDate()) lastMeasuredValuesBySensors[measuredValue.SensorID][measuredValue.ValueType].TillDate = measuredValue.TillDate
lastMeasuredValuesBySensors[measuredValue.GetSensorID()][measuredValue.GetMeasuredValueType()].SetUpdateDate(&now) lastMeasuredValuesBySensors[measuredValue.SensorID][measuredValue.ValueType].UpdateDate = &now
} else if lastMeasuredValuesBySensors[measuredValue.GetSensorID()][measuredValue.GetMeasuredValueType()].GetValue() != measuredValue.GetValue() { } else if lastMeasuredValuesBySensors[measuredValue.SensorID][measuredValue.ValueType].Value != measuredValue.Value {
compressedMeasuredValues = append(compressedMeasuredValues, lastMeasuredValuesBySensors[measuredValue.GetSensorID()][measuredValue.GetMeasuredValueType()]) compressedMeasuredValues = append(compressedMeasuredValues, lastMeasuredValuesBySensors[measuredValue.SensorID][measuredValue.ValueType])
delete(lastMeasuredValuesBySensors[measuredValue.GetSensorID()], measuredValue.GetMeasuredValueType()) delete(lastMeasuredValuesBySensors[measuredValue.SensorID], measuredValue.ValueType)
lastMeasuredValuesBySensors[measuredValue.GetSensorID()][measuredValue.GetMeasuredValueType()] = measuredValue lastMeasuredValuesBySensors[measuredValue.SensorID][measuredValue.ValueType] = measuredValue
} }
} }
@ -89,7 +89,7 @@ func Compression(measuredValues []types.MeasuredValue) []types.MeasuredValue {
// Sort all measured values again to include the measured values from the // Sort all measured values again to include the measured values from the
// cache. // cache.
sort.SliceStable(compressedMeasuredValues, func(i int, j int) bool { sort.SliceStable(compressedMeasuredValues, func(i int, j int) bool {
return compressedMeasuredValues[i].GetFromDate().Before(compressedMeasuredValues[j].GetFromDate()) return compressedMeasuredValues[i].FromDate.Before(compressedMeasuredValues[j].FromDate)
}) })
return compressedMeasuredValues return compressedMeasuredValues
@ -123,11 +123,11 @@ func New(logfile string) Logfile {
} }
func writeCreationDate(measuredValues []types.MeasuredValue) { func writeCreationDate(measuredValues []*types.MeasuredValue) {
now := time.Now() now := time.Now()
for _, measuredValue := range measuredValues { for _, measuredValue := range measuredValues {
if measuredValue.GetCreationDate() == nil { if measuredValue.CreationDate == nil {
measuredValue.SetCreationDate(&now) measuredValue.CreationDate = &now
} }
} }
} }

View File

@ -1,17 +1,11 @@
package logfile package logfile
import ( // type Temperatures struct {
"encoding/xml" // XMLName xml.Name `xml:"temperatures"`
// Temperatures []*Temperature `xml:"temperature"`
// }
"github.com/go-flucky/flucky/pkg/types" // type Temperature struct {
) // XMLName xml.Name `xml:"temperature"`
// *types.Temperature
type Temperatures struct { // }
XMLName xml.Name `xml:"temperatures"`
Temperatures []*Temperature `xml:"temperature"`
}
type Temperature struct {
XMLName xml.Name `xml:"temperature"`
*types.Temperature
}

View File

@ -25,7 +25,7 @@ func (s *BME280) GetSensorModel() types.SensorModel {
} }
// Read measured values // Read measured values
func (s *BME280) Read() ([]types.MeasuredValue, error) { func (s *BME280) Read() ([]*types.MeasuredValue, error) {
// Create new connection to i2c-bus on 1 line with address 0x76. // Create new connection to i2c-bus on 1 line with address 0x76.
// Use i2cdetect utility to find device address over the i2c-bus // Use i2cdetect utility to find device address over the i2c-bus
@ -62,26 +62,29 @@ func (s *BME280) Read() ([]types.MeasuredValue, error) {
log.Fatal(err) log.Fatal(err)
} }
measuredValues := []types.MeasuredValue{ measuredValues := []*types.MeasuredValue{
&types.Humidity{ &types.MeasuredValue{
HumidityID: uuid.NewV4().String(), ID: uuid.NewV4().String(),
HumidityValue: float64(humidityValue), Value: float64(humidityValue),
HumidityFromDate: time.Now(), ValueType: types.MeasuredValueTypeHumidity,
HumidityTillDate: time.Now(), FromDate: time.Now(),
TillDate: time.Now(),
SensorID: s.SensorID, SensorID: s.SensorID,
}, },
&types.Pressure{ &types.MeasuredValue{
PressureID: uuid.NewV4().String(), ID: uuid.NewV4().String(),
PressureValue: float64(pressureValue), Value: float64(pressureValue),
PressureFromDate: time.Now(), ValueType: types.MeasuredValueTypePressure,
PressureTillDate: time.Now(), FromDate: time.Now(),
TillDate: time.Now(),
SensorID: s.SensorID, SensorID: s.SensorID,
}, },
&types.Temperature{ &types.MeasuredValue{
TemperatureID: uuid.NewV4().String(), ID: uuid.NewV4().String(),
TemperatureValue: float64(temperatureValue), Value: float64(temperatureValue),
TemperatureFromDate: time.Now(), ValueType: types.MeasuredValueTypeTemperature,
TemperatureTillDate: time.Now(), FromDate: time.Now(),
TillDate: time.Now(),
SensorID: s.SensorID, SensorID: s.SensorID,
}, },
} }
@ -91,7 +94,7 @@ func (s *BME280) Read() ([]types.MeasuredValue, error) {
// ReadChannel reads the measured values from the sensor and writes them to a // ReadChannel reads the measured values from the sensor and writes them to a
// channel. // channel.
func (s *BME280) ReadChannel(measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) { func (s *BME280) ReadChannel(measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) {
if wg != nil { if wg != nil {
defer wg.Done() defer wg.Done()
} }
@ -108,7 +111,7 @@ func (s *BME280) ReadChannel(measuredValuesChannel chan<- []types.MeasuredValue,
// ReadContinously reads the measured values continously from the sensor and // ReadContinously reads the measured values continously from the sensor and
// writes them to a channel. // writes them to a channel.
func (s *BME280) ReadContinously(ctx context.Context, measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error) { func (s *BME280) ReadContinously(ctx context.Context, measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error) {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():

View File

@ -22,7 +22,7 @@ func (s *DHT11) GetSensorModel() types.SensorModel {
} }
// Read measured values // Read measured values
func (s *DHT11) Read() ([]types.MeasuredValue, error) { func (s *DHT11) Read() ([]*types.MeasuredValue, error) {
err := dht.HostInit() err := dht.HostInit()
if err != nil { if err != nil {
@ -44,19 +44,21 @@ func (s *DHT11) Read() ([]types.MeasuredValue, error) {
return nil, fmt.Errorf("Read error: %v", err) return nil, fmt.Errorf("Read error: %v", err)
} }
measuredValues := []types.MeasuredValue{ measuredValues := []*types.MeasuredValue{
&types.Humidity{ &types.MeasuredValue{
HumidityID: uuid.NewV4().String(), ID: uuid.NewV4().String(),
HumidityValue: humidityValue, Value: float64(humidityValue),
HumidityFromDate: time.Now(), ValueType: types.MeasuredValueTypeHumidity,
HumidityTillDate: time.Now(), FromDate: time.Now(),
TillDate: time.Now(),
SensorID: s.SensorID, SensorID: s.SensorID,
}, },
&types.Temperature{ &types.MeasuredValue{
TemperatureID: uuid.NewV4().String(), ID: uuid.NewV4().String(),
TemperatureValue: temperatureValue, Value: float64(temperatureValue),
TemperatureFromDate: time.Now(), ValueType: types.MeasuredValueTypeTemperature,
TemperatureTillDate: time.Now(), FromDate: time.Now(),
TillDate: time.Now(),
SensorID: s.SensorID, SensorID: s.SensorID,
}, },
} }
@ -66,7 +68,7 @@ func (s *DHT11) Read() ([]types.MeasuredValue, error) {
// ReadChannel reads the measured values from the sensor and writes them to a // ReadChannel reads the measured values from the sensor and writes them to a
// channel. // channel.
func (s *DHT11) ReadChannel(measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) { func (s *DHT11) ReadChannel(measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) {
if wg != nil { if wg != nil {
defer wg.Done() defer wg.Done()
} }
@ -83,7 +85,7 @@ func (s *DHT11) ReadChannel(measuredValuesChannel chan<- []types.MeasuredValue,
// ReadContinously reads the measured values continously from the sensor and // ReadContinously reads the measured values continously from the sensor and
// writes them to a channel. // writes them to a channel.
func (s *DHT11) ReadContinously(ctx context.Context, measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error) { func (s *DHT11) ReadContinously(ctx context.Context, measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error) {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():

View File

@ -22,7 +22,7 @@ func (s *DHT22) GetSensorModel() types.SensorModel {
} }
// Read measured values // Read measured values
func (s *DHT22) Read() ([]types.MeasuredValue, error) { func (s *DHT22) Read() ([]*types.MeasuredValue, error) {
err := dht.HostInit() err := dht.HostInit()
if err != nil { if err != nil {
@ -44,19 +44,21 @@ func (s *DHT22) Read() ([]types.MeasuredValue, error) {
return nil, fmt.Errorf("Read error: %v", err) return nil, fmt.Errorf("Read error: %v", err)
} }
measuredValues := []types.MeasuredValue{ measuredValues := []*types.MeasuredValue{
&types.Humidity{ &types.MeasuredValue{
HumidityID: uuid.NewV4().String(), ID: uuid.NewV4().String(),
HumidityValue: humidityValue, Value: float64(humidityValue),
HumidityFromDate: time.Now(), ValueType: types.MeasuredValueTypeHumidity,
HumidityTillDate: time.Now(), FromDate: time.Now(),
TillDate: time.Now(),
SensorID: s.SensorID, SensorID: s.SensorID,
}, },
&types.Temperature{ &types.MeasuredValue{
TemperatureID: uuid.NewV4().String(), ID: uuid.NewV4().String(),
TemperatureValue: temperatureValue, Value: float64(temperatureValue),
TemperatureFromDate: time.Now(), ValueType: types.MeasuredValueTypeTemperature,
TemperatureTillDate: time.Now(), FromDate: time.Now(),
TillDate: time.Now(),
SensorID: s.SensorID, SensorID: s.SensorID,
}, },
} }
@ -66,7 +68,7 @@ func (s *DHT22) Read() ([]types.MeasuredValue, error) {
// ReadChannel reads the measured values from the sensor and writes them to a // ReadChannel reads the measured values from the sensor and writes them to a
// channel. // channel.
func (s *DHT22) ReadChannel(measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) { func (s *DHT22) ReadChannel(measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) {
if wg != nil { if wg != nil {
defer wg.Done() defer wg.Done()
} }
@ -83,7 +85,7 @@ func (s *DHT22) ReadChannel(measuredValuesChannel chan<- []types.MeasuredValue,
// ReadContinously reads the measured values continously from the sensor and // ReadContinously reads the measured values continously from the sensor and
// writes them to a channel. // writes them to a channel.
func (s *DHT22) ReadContinously(ctx context.Context, measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error) { func (s *DHT22) ReadContinously(ctx context.Context, measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error) {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():

View File

@ -25,7 +25,7 @@ func (s *DS18B20) GetSensorModel() types.SensorModel {
} }
// Read measured values // Read measured values
func (s *DS18B20) Read() ([]types.MeasuredValue, error) { func (s *DS18B20) Read() ([]*types.MeasuredValue, error) {
if s.WireID == nil { if s.WireID == nil {
return nil, fmt.Errorf("WireID is not specified for sensor %v", s.Name()) return nil, fmt.Errorf("WireID is not specified for sensor %v", s.Name())
@ -50,12 +50,13 @@ func (s *DS18B20) Read() ([]types.MeasuredValue, error) {
temperatureValue := c / 1000 temperatureValue := c / 1000
measuredValues := []types.MeasuredValue{ measuredValues := []*types.MeasuredValue{
&types.Temperature{ &types.MeasuredValue{
TemperatureID: uuid.NewV4().String(), ID: uuid.NewV4().String(),
TemperatureValue: temperatureValue, Value: float64(temperatureValue),
TemperatureFromDate: time.Now(), ValueType: types.MeasuredValueTypeTemperature,
TemperatureTillDate: time.Now(), FromDate: time.Now(),
TillDate: time.Now(),
SensorID: s.SensorID, SensorID: s.SensorID,
}, },
} }
@ -66,7 +67,7 @@ func (s *DS18B20) Read() ([]types.MeasuredValue, error) {
// ReadChannel reads the measured values from the sensor and writes them to a // ReadChannel reads the measured values from the sensor and writes them to a
// channel. // channel.
func (s *DS18B20) ReadChannel(measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) { func (s *DS18B20) ReadChannel(measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) {
if wg != nil { if wg != nil {
defer wg.Done() defer wg.Done()
} }
@ -83,7 +84,7 @@ func (s *DS18B20) ReadChannel(measuredValuesChannel chan<- []types.MeasuredValue
// ReadContinously reads the measured values continously from the sensor and // ReadContinously reads the measured values continously from the sensor and
// writes them to a channel. // writes them to a channel.
func (s *DS18B20) ReadContinously(ctx context.Context, measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error) { func (s *DS18B20) ReadContinously(ctx context.Context, measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error) {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():

View File

@ -9,7 +9,7 @@ import (
type Sensor interface { type Sensor interface {
GetSensorModel() types.SensorModel GetSensorModel() types.SensorModel
Read() ([]types.MeasuredValue, error) Read() ([]*types.MeasuredValue, error)
ReadChannel(measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) ReadChannel(measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup)
ReadContinously(ctx context.Context, measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error) ReadContinously(ctx context.Context, measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error)
} }

View File

@ -12,9 +12,9 @@ import (
) )
// Read measured values from sensors // Read measured values from sensors
func Read(ctx context.Context, sensors []Sensor) ([]types.MeasuredValue, error) { func Read(ctx context.Context, sensors []Sensor) ([]*types.MeasuredValue, error) {
measuredValuesChannel := make(chan []types.MeasuredValue, len(sensors)) measuredValuesChannel := make(chan []*types.MeasuredValue, len(sensors))
errorChannel := make(chan error, len(sensors)) errorChannel := make(chan error, len(sensors))
ReadChannel(ctx, sensors, measuredValuesChannel, errorChannel) ReadChannel(ctx, sensors, measuredValuesChannel, errorChannel)
@ -31,7 +31,7 @@ func Read(ctx context.Context, sensors []Sensor) ([]types.MeasuredValue, error)
// ReadChannel reads the measured values from sensors and writes them to a // ReadChannel reads the measured values from sensors and writes them to a
// channel. // channel.
func ReadChannel(ctx context.Context, sensors []Sensor, measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error) { func ReadChannel(ctx context.Context, sensors []Sensor, measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error) {
wg := new(sync.WaitGroup) wg := new(sync.WaitGroup)
wg.Add(len(sensors)) wg.Add(len(sensors))
@ -45,7 +45,7 @@ func ReadChannel(ctx context.Context, sensors []Sensor, measuredValuesChannel ch
// ReadContinuously reads the measured values continously from sensors and writes // ReadContinuously reads the measured values continously from sensors and writes
// them to a channel. // them to a channel.
func ReadContinuously(ctx context.Context, sensors []Sensor, measuredValuesChannel chan<- []types.MeasuredValue, errorChannel chan<- error) { func ReadContinuously(ctx context.Context, sensors []Sensor, measuredValuesChannel chan<- []*types.MeasuredValue, errorChannel chan<- error) {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():

View File

@ -1,62 +0,0 @@
package types
import "time"
// Humidity ...
type Humidity struct {
HumidityID string `json:"humidity_id" xml:"humidity_id"`
HumidityValue float64 `json:"humidity_value,string" xml:"humidity_value"`
HumidityFromDate time.Time `json:"humidity_from_date" xml:"humidity_from_date"`
HumidityTillDate time.Time `json:"humidity_till_date" xml:"humidity_till_date"`
SensorID string `json:"sensor_id" xml:"sensor_id"`
CreationDate *time.Time `json:"creation_date" xml:"creation_date"`
UpdateDate *time.Time `json:"update_date" xml:"update_date"`
}
func (h *Humidity) GetID() string {
return h.HumidityID
}
func (h *Humidity) GetValue() float64 {
return h.HumidityValue
}
func (h *Humidity) GetFromDate() time.Time {
return h.HumidityFromDate
}
func (h *Humidity) GetTillDate() time.Time {
return h.HumidityTillDate
}
func (h *Humidity) GetSensorID() string {
return h.SensorID
}
func (h *Humidity) GetCreationDate() *time.Time {
return h.CreationDate
}
func (h *Humidity) GetUpdateDate() *time.Time {
return h.UpdateDate
}
func (h *Humidity) GetMeasuredValueType() MeasuredValueType {
return MeasuredValueTypeHumidity
}
func (h *Humidity) SetValue(value float64) {
h.HumidityValue = value
}
func (h *Humidity) SetTillDate(date time.Time) {
h.HumidityTillDate = date
}
func (h *Humidity) SetCreationDate(date *time.Time) {
h.CreationDate = date
}
func (h *Humidity) SetUpdateDate(date *time.Time) {
h.UpdateDate = date
}

View File

@ -1,21 +1,19 @@
package types package types
import "time" import (
"fmt"
"time"
)
type MeasuredValue interface { type MeasuredValue struct {
GetID() string ID string `json:"id" xml:"id"`
GetMeasuredValueType() MeasuredValueType Value float64 `json:"value,string" xml:"value,string"`
GetValue() float64 ValueType MeasuredValueType `json:"value_type" xml:"value_type"`
GetFromDate() time.Time FromDate time.Time `json:"from_date" xml:"from_date"`
GetTillDate() time.Time TillDate time.Time `json:"till_date" xml:"till_date"`
GetSensorID() string SensorID string `json:"sensor_id" xml:"sensor_id"`
GetCreationDate() *time.Time CreationDate *time.Time `json:"creation_date" xml:"creation_date"`
GetUpdateDate() *time.Time UpdateDate *time.Time `json:"update_date" xml:"update_date"`
SetValue(value float64)
SetTillDate(date time.Time)
SetCreationDate(date *time.Time)
SetUpdateDate(date *time.Time)
} }
type MeasuredValueType string type MeasuredValueType string
@ -31,3 +29,24 @@ var MeasuredValueTypes = []MeasuredValueType{
MeasuredValueTypePressure, MeasuredValueTypePressure,
MeasuredValueTypeTemperature, MeasuredValueTypeTemperature,
} }
func SelectMeasuredValues(measuredValueType MeasuredValueType, measuredValues []*MeasuredValue) []*MeasuredValue {
cachedMeasuredValues := make([]*MeasuredValue, 0)
for _, measuredValue := range measuredValues {
if measuredValue.ValueType == measuredValueType {
cachedMeasuredValues = append(cachedMeasuredValues, measuredValue)
}
}
return cachedMeasuredValues
}
func SelectMeasuredValueType(valueType string) (*MeasuredValueType, error) {
for _, measuredValueType := range MeasuredValueTypes {
if fmt.Sprint(measuredValueType) == valueType {
return &measuredValueType, nil
}
}
return nil, fmt.Errorf("Can not determine value type: %v", valueType)
}

View File

@ -1,64 +0,0 @@
package types
import (
"time"
)
// Pressure ...
type Pressure struct {
PressureID string `json:"pressure_id" xml:"pressure_id"`
PressureValue float64 `json:"pressure_value,string" xml:"pressure_value,string"`
PressureFromDate time.Time `json:"pressure_from_date" xml:"pressure_from_date"`
PressureTillDate time.Time `json:"pressure_till_date" xml:"pressure_till_date"`
SensorID string `json:"sensor_id" xml:"sensor_id"`
CreationDate *time.Time `json:"creation_date" xml:"creation_date"`
UpdateDate *time.Time `json:"update_date" xml:"update_date"`
}
func (t *Pressure) GetID() string {
return t.PressureID
}
func (t *Pressure) GetValue() float64 {
return t.PressureValue
}
func (t *Pressure) GetFromDate() time.Time {
return t.PressureFromDate
}
func (t *Pressure) GetTillDate() time.Time {
return t.PressureTillDate
}
func (t *Pressure) GetSensorID() string {
return t.SensorID
}
func (t *Pressure) GetCreationDate() *time.Time {
return t.CreationDate
}
func (t *Pressure) GetUpdateDate() *time.Time {
return t.UpdateDate
}
func (t *Pressure) GetMeasuredValueType() MeasuredValueType {
return MeasuredValueTypePressure
}
func (t *Pressure) SetValue(value float64) {
t.PressureValue = value
}
func (t *Pressure) SetTillDate(date time.Time) {
t.PressureTillDate = date
}
func (t *Pressure) SetCreationDate(date *time.Time) {
t.CreationDate = date
}
func (t *Pressure) SetUpdateDate(date *time.Time) {
t.UpdateDate = date
}

View File

@ -1,64 +0,0 @@
package types
import (
"time"
)
// Temperature ...
type Temperature struct {
TemperatureID string `json:"temperature_id" xml:"temperature_id"`
TemperatureValue float64 `json:"temperature_value,string" xml:"temperature_value,string"`
TemperatureFromDate time.Time `json:"temperature_from_date" xml:"temperature_from_date"`
TemperatureTillDate time.Time `json:"temperature_till_date" xml:"temperature_till_date"`
SensorID string `json:"sensor_id" xml:"sensor_id"`
CreationDate *time.Time `json:"creation_date" xml:"creation_date"`
UpdateDate *time.Time `json:"update_date" xml:"update_date"`
}
func (t *Temperature) GetID() string {
return t.TemperatureID
}
func (t *Temperature) GetValue() float64 {
return t.TemperatureValue
}
func (t *Temperature) GetFromDate() time.Time {
return t.TemperatureFromDate
}
func (t *Temperature) GetTillDate() time.Time {
return t.TemperatureTillDate
}
func (t *Temperature) GetSensorID() string {
return t.SensorID
}
func (t *Temperature) GetCreationDate() *time.Time {
return t.CreationDate
}
func (t *Temperature) GetUpdateDate() *time.Time {
return t.UpdateDate
}
func (t *Temperature) GetMeasuredValueType() MeasuredValueType {
return MeasuredValueTypeTemperature
}
func (t *Temperature) SetValue(value float64) {
t.TemperatureValue = value
}
func (t *Temperature) SetTillDate(date time.Time) {
t.TemperatureTillDate = date
}
func (t *Temperature) SetCreationDate(date *time.Time) {
t.CreationDate = date
}
func (t *Temperature) SetUpdateDate(date *time.Time) {
t.UpdateDate = date
}

View File

@ -1,31 +0,0 @@
package typeswitch
import (
"github.com/go-flucky/flucky/pkg/types"
)
func HumidityValues(measuredValues []types.MeasuredValue) []types.MeasuredValue {
cachedMeasuredValues := make([]types.MeasuredValue, 0)
for _, measuredValue := range measuredValues {
switch v := measuredValue.(type) {
case *types.Humidity:
cachedMeasuredValues = append(cachedMeasuredValues, v)
}
}
return cachedMeasuredValues
}
func TemperatureValues(measuredValues []types.MeasuredValue) []types.MeasuredValue {
cachedMeasuredValues := make([]types.MeasuredValue, 0)
for _, measuredValue := range measuredValues {
switch v := measuredValue.(type) {
case *types.Temperature:
cachedMeasuredValues = append(cachedMeasuredValues, v)
}
}
return cachedMeasuredValues
}