-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmod-htu21.go
executable file
·64 lines (54 loc) · 1.55 KB
/
mod-htu21.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
62
63
64
package main
import (
"context"
"fmt"
"log"
"sync"
"github.com/parMaster/htu21"
"github.com/parMaster/rpid/config"
"periph.io/x/conn/v3/i2c"
"periph.io/x/conn/v3/physic"
)
type Htu21Reporter struct {
data historical
cfg config.HTU21
htu21Data physic.Env
htu21Device *htu21.Dev
i2cBus i2c.BusCloser
mx sync.Mutex
}
func LoadHtu21Reporter(cfg config.HTU21, i2cBus i2c.BusCloser) (*Htu21Reporter, error) {
if !cfg.Enabled {
return nil, fmt.Errorf("Htu21Reporter is not enabled")
}
data := historical{
"humidity": {}, // Humidity from HTU21 in mRh
"temp": {}, // unused
}
htu21Device, err := htu21.NewI2C(i2cBus, cfg.Htu21Addr)
if err != nil {
return nil, fmt.Errorf("[ERROR] failed to initialize htu21: %v", err)
}
return &Htu21Reporter{data: data, htu21Device: htu21Device, i2cBus: i2cBus, cfg: cfg}, nil
}
func (r *Htu21Reporter) Name() string {
return "htu21"
}
func (r *Htu21Reporter) Collect(context.Context) error {
if err := r.htu21Device.Sense(&r.htu21Data); err != nil {
return err
}
humidMilliRH := r.htu21Data.Humidity / 10000
tempMilliC := int64(r.htu21Data.Temperature-physic.ZeroCelsius) / 1000000
r.mx.Lock()
r.data["humidity"] = append(r.data["humidity"], int(humidMilliRH))
r.data["temp"] = append(r.data["temp"], int(tempMilliC))
r.mx.Unlock()
log.Printf("[DEBUG] HTU21: %8s | %s (%d mRh) \n", r.htu21Data.Temperature, r.htu21Data.Humidity, humidMilliRH)
return nil
}
func (r *Htu21Reporter) Report() (interface{}, error) {
r.mx.Lock()
defer r.mx.Unlock()
return r.data, nil
}