77 lines
1.5 KiB
Go
77 lines
1.5 KiB
Go
package sensor
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.cryptic.systems/fh-trier/go-flucky/pkg/types"
|
|
"github.com/MichaelS11/go-dht"
|
|
uuid "github.com/satori/go.uuid"
|
|
)
|
|
|
|
type DHT22Sensor struct {
|
|
*types.Sensor
|
|
}
|
|
|
|
func (s *DHT22Sensor) ReadHumidity() (*types.Humidity, 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, _, err := dht.Read()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Read error: %v", err)
|
|
}
|
|
|
|
humidity := &types.Humidity{
|
|
HumidityID: uuid.NewV4().String(),
|
|
HumidityValue: humidityValue,
|
|
HumidityDate: time.Now(),
|
|
SensorID: s.SensorID,
|
|
}
|
|
|
|
return humidity, nil
|
|
}
|
|
|
|
func (s *DHT22Sensor) ReadTemperature() (*types.Temperature, 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)
|
|
}
|
|
|
|
_, temperatureValue, err := dht.Read()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("Read error: %v", err)
|
|
}
|
|
|
|
temperature := &types.Temperature{
|
|
TemperatureID: uuid.NewV4().String(),
|
|
TemperatureValue: temperatureValue,
|
|
TemperatureDate: time.Now(),
|
|
SensorID: s.SensorID,
|
|
}
|
|
|
|
return temperature, nil
|
|
}
|