forked from kidoman/embd
-
Notifications
You must be signed in to change notification settings - Fork 1
/
watersensor.go
60 lines (48 loc) · 1.01 KB
/
watersensor.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
// Package watersensor allows interfacing with the water sensor.
package watersensor
import (
"sync"
"github.com/golang/glog"
"github.com/kidoman/embd"
)
// WaterSensor represents a water sensor.
type WaterSensor struct {
Pin embd.DigitalPin
initialized bool
mu sync.RWMutex
}
// New creates a new WaterSensor struct
func New(pin embd.DigitalPin) *WaterSensor {
return &WaterSensor{Pin: pin}
}
func (d *WaterSensor) setup() error {
d.mu.RLock()
if d.initialized {
d.mu.RUnlock()
return nil
}
d.mu.RUnlock()
d.mu.Lock()
defer d.mu.Unlock()
if err := d.Pin.SetDirection(embd.In); err != nil {
return err
}
d.initialized = true
return nil
}
// IsWet determines if there is water present on the sensor
func (d *WaterSensor) IsWet() (bool, error) {
if err := d.setup(); err != nil {
return false, err
}
glog.V(1).Infof("watersensor: reading")
value, err := d.Pin.Read()
if err != nil {
return false, err
}
if value == embd.High {
return true, nil
} else {
return false, nil
}
}