1
0
mirror of https://github.com/kidoman/embd synced 2024-12-22 21:00:05 +01:00
embd/sensor/watersensor/watersensor.go

61 lines
1.0 KiB
Go
Raw Normal View History

2014-03-23 15:47:58 +05:30
// Package watersensor allows interfacing with the water sensor.
2013-12-23 16:39:02 +05:30
package watersensor
import (
2014-03-02 12:21:29 +05:30
"sync"
2013-12-23 16:39:02 +05:30
2014-03-02 12:21:29 +05:30
"github.com/golang/glog"
2014-03-03 00:51:23 +05:30
"github.com/kidoman/embd"
2014-03-02 12:21:29 +05:30
)
2013-12-23 16:48:00 +05:30
2014-03-23 15:47:58 +05:30
// WaterSensor represents a water sensor.
2014-03-02 12:21:29 +05:30
type WaterSensor struct {
2014-03-03 00:51:23 +05:30
Pin embd.DigitalPin
2013-12-23 16:48:00 +05:30
2014-03-02 12:21:29 +05:30
initialized bool
mu sync.RWMutex
2013-12-23 16:39:02 +05:30
}
2014-03-02 12:21:29 +05:30
// New creates a new WaterSensor struct
2014-03-03 00:51:23 +05:30
func New(pin embd.DigitalPin) *WaterSensor {
2014-03-02 12:21:29 +05:30
return &WaterSensor{Pin: pin}
2013-12-23 16:39:02 +05:30
}
2014-03-02 12:21:29 +05:30
func (d *WaterSensor) setup() error {
d.mu.RLock()
if d.initialized {
d.mu.RUnlock()
return nil
}
d.mu.RUnlock()
2013-12-23 16:39:02 +05:30
2014-03-02 12:21:29 +05:30
d.mu.Lock()
defer d.mu.Unlock()
2013-12-23 16:39:02 +05:30
2014-03-03 00:51:23 +05:30
if err := d.Pin.SetDirection(embd.In); err != nil {
2014-03-02 12:21:29 +05:30
return err
}
d.initialized = true
2013-12-23 16:39:02 +05:30
2014-03-02 12:21:29 +05:30
return nil
2013-12-23 16:39:02 +05:30
}
2013-12-23 16:48:00 +05:30
// IsWet determines if there is water present on the sensor
2014-03-02 12:21:29 +05:30
func (d *WaterSensor) IsWet() (bool, error) {
if err := d.setup(); err != nil {
return false, err
}
glog.V(1).Infof("watersensor: reading")
2014-03-02 12:21:29 +05:30
value, err := d.Pin.Read()
if err != nil {
return false, err
}
2014-03-03 00:51:23 +05:30
if value == embd.High {
2014-03-02 12:21:29 +05:30
return true, nil
} else {
return false, nil
}
2013-12-23 16:39:02 +05:30
}