1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-05-11 19:29:20 +08:00
hybridgroup.gobot/platforms/gpio/analog_sensor_driver.go

61 lines
1.5 KiB
Go
Raw Normal View History

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{
Driver: *gobot.NewDriver(
name,
"AnalogSensorDriver",
a.(gobot.AdaptorInterface),
pin,
),
2014-04-27 19:34:16 -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-06-11 17:41:04 -07:00
return d
2014-04-27 19:34:16 -07:00
}
func (a *AnalogSensorDriver) adaptor() AnalogReader {
2014-07-09 18:32:27 -07:00
return a.Adaptor().(AnalogReader)
}
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
gobot.Every(a.Interval(), func() {
2014-06-28 17:18:16 -07:00
newValue := a.Read()
if newValue != value && newValue != -1 {
value = newValue
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 {
return a.adaptor().AnalogRead(a.Pin())
2014-04-27 19:34:16 -07:00
}