-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsensor.go
61 lines (52 loc) · 1.42 KB
/
sensor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"fmt"
"github.com/MichaelS11/go-dht"
)
type Sensor struct {
config *Config
temperatureSymbol string
client *dht.DHT
}
const CelsiusSymbol = "C"
const FahrenheitSymbol = "F"
func newSensor(config *Config) *Sensor {
/**
Sensor constructor
*/
var err error
var client *dht.DHT
var temperatureSymbol string
lg.Info("Initializing the DHT22/AM2302 sensor on the host")
err = dht.HostInit()
if err != nil {
lg.Panic("Failed to initialized DHT22/AM2302 sensor on the host: ", err)
}
if config.temperatureUnit == "celsius" {
client, err = dht.NewDHT(config.gpio, dht.Celsius, "")
temperatureSymbol = CelsiusSymbol
} else {
client, err = dht.NewDHT(config.gpio, dht.Fahrenheit, "")
temperatureSymbol = FahrenheitSymbol
}
if err != nil {
lg.Panic("Failed to create new DHT client: ", err)
}
return &Sensor{
config: config,
temperatureSymbol: temperatureSymbol,
client: client,
}
}
func (s *Sensor) readRetry() (humidity float64, temperature float64, err error) {
/**
Reads the sensor data with retry
*/
humidity, temperature, err = s.client.ReadRetry(s.config.maxRetries)
if err != nil {
lg.Error("Cannot retrieve humidity and temperature from the sensor: ", err)
}
lg.Info(fmt.Sprintf("Retrieved humidity=%.2f%%, temperature=%.2f°%s from the sensor",
humidity, temperature, s.temperatureSymbol))
return humidity, temperature, err
}