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