PKGBUILD/pkg/sensor/dht22.go

60 lines
1.3 KiB
Go
Raw Normal View History

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