2014-04-27 19:34:16 -07:00
|
|
|
package gpio
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/hybridgroup/gobot"
|
|
|
|
)
|
|
|
|
|
2014-09-27 11:34:13 -07:00
|
|
|
// Represents an Analog Sensor
|
2014-04-27 19:34:16 -07:00
|
|
|
type AnalogSensorDriver struct {
|
|
|
|
gobot.Driver
|
|
|
|
}
|
|
|
|
|
2014-09-27 11:34:13 -07:00
|
|
|
// NewAnalogSensorDriver returns a new AnalogSensorDriver given an AnalogReader, name and pin.
|
|
|
|
//
|
|
|
|
// Adds the following API Commands:
|
|
|
|
// "Read" - See AnalogSensor.Read
|
2014-06-06 16:58:58 -07:00
|
|
|
func NewAnalogSensorDriver(a AnalogReader, name string, pin string) *AnalogSensorDriver {
|
2014-06-11 17:41:04 -07:00
|
|
|
d := &AnalogSensorDriver{
|
2014-07-03 19:14:04 -07:00
|
|
|
Driver: *gobot.NewDriver(
|
|
|
|
name,
|
|
|
|
"AnalogSensorDriver",
|
|
|
|
a.(gobot.AdaptorInterface),
|
|
|
|
pin,
|
|
|
|
),
|
2014-04-27 19:34:16 -07:00
|
|
|
}
|
2014-07-03 19:14:04 -07:00
|
|
|
|
2014-07-07 22:04:02 -07:00
|
|
|
d.AddEvent("data")
|
2014-07-09 18:32:27 -07:00
|
|
|
d.AddCommand("Read", func(params map[string]interface{}) interface{} {
|
2014-06-11 17:41:04 -07:00
|
|
|
return d.Read()
|
|
|
|
})
|
2014-07-03 19:14:04 -07:00
|
|
|
|
2014-06-11 17:41:04 -07:00
|
|
|
return d
|
2014-04-27 19:34:16 -07:00
|
|
|
}
|
|
|
|
|
2014-06-15 17:22:50 -07:00
|
|
|
func (a *AnalogSensorDriver) adaptor() AnalogReader {
|
2014-07-09 18:32:27 -07:00
|
|
|
return a.Adaptor().(AnalogReader)
|
2014-06-15 17:22:50 -07:00
|
|
|
}
|
|
|
|
|
2014-09-27 11:34:13 -07:00
|
|
|
// Starts the AnalogSensorDriver and reads the Analog Sensor at the given Driver.Interval().
|
|
|
|
// Returns true on successful start of the driver.
|
|
|
|
// Emits the Events:
|
|
|
|
// "data" int - Event is emitted on change and represents the current reading from the sensor.
|
2014-06-28 17:18:16 -07:00
|
|
|
func (a *AnalogSensorDriver) Start() bool {
|
|
|
|
value := 0
|
2014-07-07 22:04:02 -07:00
|
|
|
gobot.Every(a.Interval(), func() {
|
2014-06-28 17:18:16 -07:00
|
|
|
newValue := a.Read()
|
|
|
|
if newValue != value && newValue != -1 {
|
|
|
|
value = newValue
|
2014-07-07 22:04:02 -07:00
|
|
|
gobot.Publish(a.Event("data"), value)
|
2014-06-28 17:18:16 -07:00
|
|
|
}
|
|
|
|
})
|
|
|
|
return true
|
|
|
|
}
|
2014-09-27 11:34:13 -07:00
|
|
|
|
|
|
|
// Halt returns true on a successful halt of the driver
|
2014-06-28 17:18:16 -07:00
|
|
|
func (a *AnalogSensorDriver) Halt() bool { return true }
|
2014-04-27 19:34:16 -07:00
|
|
|
|
2014-09-27 11:34:13 -07:00
|
|
|
// Read returns the current reading from the Analog Sensor
|
2014-04-27 19:34:16 -07:00
|
|
|
func (a *AnalogSensorDriver) Read() int {
|
2014-07-03 19:14:04 -07:00
|
|
|
return a.adaptor().AnalogRead(a.Pin())
|
2014-04-27 19:34:16 -07:00
|
|
|
}
|