From 4bae510120a78cda9553f9559ca8be41698e8b59 Mon Sep 17 00:00:00 2001 From: Markus Pesch Date: Mon, 4 Mar 2019 11:05:02 +0100 Subject: [PATCH] feat: implementation of dht22 sensor --- pkg/sensor/dht22.go | 65 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/pkg/sensor/dht22.go b/pkg/sensor/dht22.go index 22bfd41..7343250 100644 --- a/pkg/sensor/dht22.go +++ b/pkg/sensor/dht22.go @@ -1,9 +1,12 @@ package sensor import ( - "log" + "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 { @@ -11,11 +14,63 @@ type DHT22Sensor struct { } func (s *DHT22Sensor) ReadHumidity() (*types.Humidity, error) { - log.Println("DHT11 Read Method not yet implemented") - return nil, nil + 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) { - log.Println("DHT22 Read Method not yet implemented") - return nil, nil + 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 }