1
0
mirror of https://github.com/kidoman/embd synced 2024-12-23 05:10:05 +01:00
embd/sensor/watersensor/watersensor.go
2014-03-03 00:51:23 +05:30

64 lines
1017 B
Go

// Package watersensor allows interfacing with the water sensor
package watersensor
import (
"sync"
"github.com/golang/glog"
"github.com/kidoman/embd"
)
type WaterSensor struct {
Pin embd.DigitalPin
initialized bool
mu sync.RWMutex
Debug bool
}
// 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
}
if d.Debug {
glog.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
}
}