2019-02-22 12:08:58 +00:00
|
|
|
package sensor
|
|
|
|
|
|
|
|
import (
|
2019-03-04 10:05:02 +00:00
|
|
|
"fmt"
|
2020-05-03 12:04:08 +00:00
|
|
|
"sync"
|
2019-02-22 12:08:58 +00:00
|
|
|
|
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"
|
2020-05-03 12:04:08 +00:00
|
|
|
"github.com/volker-raschek/flucky/pkg/internal/format"
|
|
|
|
"github.com/volker-raschek/flucky/pkg/types"
|
2019-02-22 12:08:58 +00:00
|
|
|
)
|
|
|
|
|
2019-06-13 19:25:32 +00:00
|
|
|
// DHT22 is a sensor to measure humidity and temperature.
|
|
|
|
type DHT22 struct {
|
2019-02-22 12:08:58 +00:00
|
|
|
*types.Sensor
|
2020-05-03 12:04:08 +00:00
|
|
|
mutex *sync.Mutex
|
2019-06-13 19:25:32 +00:00
|
|
|
}
|
|
|
|
|
2019-06-25 20:22:34 +00:00
|
|
|
// Read measured values
|
2020-05-03 12:04:08 +00:00
|
|
|
func (dht22 *DHT22) Read() ([]*types.MeasuredValue, error) {
|
2019-06-25 20:22:34 +00:00
|
|
|
|
2020-05-03 12:04:08 +00:00
|
|
|
// Lock multiple access
|
|
|
|
dht22.mutex.Lock()
|
|
|
|
defer dht22.mutex.Unlock()
|
2019-03-04 10:05:02 +00:00
|
|
|
|
2020-05-03 12:04:08 +00:00
|
|
|
err := dht.HostInit()
|
2019-03-04 10:05:02 +00:00
|
|
|
if err != nil {
|
2020-05-03 12:04:08 +00:00
|
|
|
return nil, fmt.Errorf("Failed to initialize periph: %v", err)
|
2019-03-04 10:05:02 +00:00
|
|
|
}
|
|
|
|
|
2020-05-03 12:04:08 +00:00
|
|
|
dht, err := dht.NewDHT(dht22.GPIONumber, dht.Celsius, "")
|
2019-03-04 10:05:02 +00:00
|
|
|
if err != nil {
|
2020-05-03 12:04:08 +00:00
|
|
|
return nil, fmt.Errorf("Failed to initialize new DHT22 sensor: %v", err)
|
2019-03-04 10:05:02 +00:00
|
|
|
}
|
|
|
|
|
2019-06-25 20:22:34 +00:00
|
|
|
humidityValue, temperatureValue, err := dht.Read()
|
2019-03-04 10:05:02 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Read error: %v", err)
|
|
|
|
}
|
|
|
|
|
2019-07-02 20:33:01 +00:00
|
|
|
measuredValues := []*types.MeasuredValue{
|
2020-05-03 12:04:08 +00:00
|
|
|
{
|
2019-07-02 20:33:01 +00:00
|
|
|
ID: uuid.NewV4().String(),
|
|
|
|
Value: float64(humidityValue),
|
2020-05-03 12:04:08 +00:00
|
|
|
ValueType: "humidity",
|
2020-05-31 22:52:54 +00:00
|
|
|
Date: format.FormatedTime(),
|
2020-05-03 12:04:08 +00:00
|
|
|
SensorID: dht22.ID,
|
2019-06-25 20:22:34 +00:00
|
|
|
},
|
2020-05-03 12:04:08 +00:00
|
|
|
{
|
2019-07-02 20:33:01 +00:00
|
|
|
ID: uuid.NewV4().String(),
|
|
|
|
Value: float64(temperatureValue),
|
2020-05-03 12:04:08 +00:00
|
|
|
ValueType: "temperature",
|
2020-05-31 22:52:54 +00:00
|
|
|
Date: format.FormatedTime(),
|
2020-05-03 12:04:08 +00:00
|
|
|
SensorID: dht22.ID,
|
2019-06-25 20:22:34 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
return measuredValues, nil
|
2019-02-24 21:46:36 +00:00
|
|
|
}
|