PKGBUILD/pkg/sensor/dht22.go
Markus Pesch dbef4f8241
fix(pkg/config): use storage endpoints
changes:
- Only one storage endpoint can be defined. This consists of a URL which
  can be used to specify whether the data is to be stored in a file or
  in a database.
2019-12-08 12:49:21 +01:00

101 lines
2.4 KiB
Go

package sensor
import (
"context"
"fmt"
"sync"
"github.com/go-flucky/flucky/pkg/internal/format"
"github.com/go-flucky/flucky/pkg/types"
"github.com/go-flucky/go-dht"
uuid "github.com/satori/go.uuid"
)
// DHT22 is a sensor to measure humidity and temperature.
type DHT22 struct {
*types.Sensor
}
// GetSensorModel returns the sensor model
func (s *DHT22) GetSensorModel() types.SensorModel {
return s.Sensor.SensorModel
}
// Read measured values
func (s *DHT22) Read() ([]*types.MeasuredValue, error) {
err := dht.HostInit()
if err != nil {
return nil, fmt.Errorf("HostInit error: %v", err)
}
gpio, err := types.GPIOToString(*s.GPIONumber)
if err != nil {
return nil, err
}
dht, err := dht.NewDHT(gpio, dht.Celsius, "")
if err != nil {
return nil, fmt.Errorf("NewDHT error: %v", err)
}
humidityValue, temperatureValue, err := dht.Read()
if err != nil {
return nil, fmt.Errorf("Read error: %v", err)
}
measuredValues := []*types.MeasuredValue{
&types.MeasuredValue{
ID: uuid.NewV4().String(),
Value: float64(humidityValue),
ValueType: types.MeasuredValueTypeHumidity,
FromDate: format.FormatedTime(),
TillDate: format.FormatedTime(),
SensorID: s.SensorID,
},
&types.MeasuredValue{
ID: uuid.NewV4().String(),
Value: float64(temperatureValue),
ValueType: types.MeasuredValueTypeTemperature,
FromDate: format.FormatedTime(),
TillDate: format.FormatedTime(),
SensorID: s.SensorID,
},
}
return measuredValues, nil
}
// ReadChannel reads the measured values from the sensor and writes them to a
// channel.
func (s *DHT22) ReadChannel(measuredValueChannel chan<- *types.MeasuredValue, errorChannel chan<- error, wg *sync.WaitGroup) {
if wg != nil {
defer wg.Done()
}
measuredValues, err := s.Read()
if err != nil {
errorChannel <- err
return
}
for _, measuredValue := range measuredValues {
measuredValueChannel <- measuredValue
}
}
// ReadContinously reads the measured values continously from the sensor and
// writes them to a channel.
func (s *DHT22) ReadContinously(ctx context.Context, measuredValueChannel chan<- *types.MeasuredValue, errorChannel chan<- error) {
for {
select {
case <-ctx.Done():
errorChannel <- fmt.Errorf("%v: Context closed: %v", s.SensorName, ctx.Err())
return
default:
s.ReadChannel(measuredValueChannel, errorChannel, nil)
}
}
}