PKGBUILD/pkg/sensor/dht22.go

98 lines
2.2 KiB
Go
Raw Normal View History

2019-02-22 12:08:58 +00:00
package sensor
import (
"context"
2019-03-04 10:05:02 +00:00
"fmt"
"sync"
2019-03-04 10:05:02 +00:00
"time"
2019-02-22 12:08:58 +00:00
2019-06-15 13:58:41 +00:00
"github.com/go-flucky/flucky/pkg/types"
2019-06-15 15:07:50 +00:00
"github.com/go-flucky/go-dht"
2019-03-04 10:05:02 +00:00
uuid "github.com/satori/go.uuid"
2019-02-22 12:08:58 +00:00
)
// DHT22 is a sensor to measure humidity and temperature.
type DHT22 struct {
2019-02-22 12:08:58 +00:00
*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) {
2019-03-04 10:05:02 +00:00
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()
2019-03-04 10:05:02 +00:00
if err != nil {
return nil, fmt.Errorf("Read error: %v", err)
}
measuredValues := []types.MeasuredValue{
&types.Humidity{
HumidityID: uuid.NewV4().String(),
HumidityValue: humidityValue,
HumidityFromDate: time.Now(),
HumidityTillDate: time.Now(),
SensorID: s.SensorID,
},
&types.Temperature{
TemperatureID: uuid.NewV4().String(),
TemperatureValue: temperatureValue,
TemperatureFromDate: time.Now(),
TemperatureTillDate: time.Now(),
SensorID: s.SensorID,
},
}
return measuredValues, nil
2019-02-24 21:46:36 +00:00
}
// 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)
}
}
}