Uses NewTimer() instead of time.After() to be more

efficient since the later creates new timers in a
tight loop.

- Adds more assertions to tests
- Adds some comments to help contributors understand
that the send occurs after the Once.

Signed-off-by: Warren Fernandes <warren.f.fernandes@gmail.com>
This commit is contained in:
Warren Fernandes 2016-10-27 03:01:51 -06:00
parent 54d9b16141
commit 922e6d98f7
2 changed files with 14 additions and 8 deletions

View File

@ -58,6 +58,8 @@ func NewAnalogSensorDriver(a AnalogReader, pin string, v ...time.Duration) *Anal
func (a *AnalogSensorDriver) Start() (errs []error) {
value := 0
go func() {
timer := time.NewTimer(a.interval)
timer.Stop()
for {
newValue, err := a.Read()
if err != nil {
@ -66,9 +68,12 @@ func (a *AnalogSensorDriver) Start() (errs []error) {
value = newValue
a.Publish(a.Event(Data), value)
}
timer.Reset(a.interval)
select {
case <-time.After(a.interval):
case <-timer.C:
case <-a.halt:
timer.Stop()
return
}
}

View File

@ -14,8 +14,11 @@ var _ gobot.Driver = (*AnalogSensorDriver)(nil)
func TestAnalogSensorDriver(t *testing.T) {
d := NewAnalogSensorDriver(newGpioTestAdaptor(), "1")
gobottest.Refute(t, d.Connection(), nil)
// default interval
gobottest.Assert(t, d.interval, 10*time.Millisecond)
d = NewAnalogSensorDriver(newGpioTestAdaptor(), "1", 30*time.Second)
d = NewAnalogSensorDriver(newGpioTestAdaptor(), "42", 30*time.Second)
gobottest.Assert(t, d.Pin(), "42")
gobottest.Assert(t, d.interval, 30*time.Second)
testAdaptorAnalogRead = func() (val int, err error) {
@ -33,18 +36,15 @@ func TestAnalogSensorDriverStart(t *testing.T) {
d := NewAnalogSensorDriver(newGpioTestAdaptor(), "1")
testAdaptorAnalogRead = func() (val int, err error) {
val = 0
return
}
gobottest.Assert(t, len(d.Start()), 0)
// data was received
// expect data to be received
d.Once(d.Event(Data), func(data interface{}) {
gobottest.Assert(t, data.(int), 100)
sem <- true
})
// send data
testAdaptorAnalogRead = func() (val int, err error) {
val = 100
return
@ -56,12 +56,13 @@ func TestAnalogSensorDriverStart(t *testing.T) {
t.Errorf("AnalogSensor Event \"Data\" was not published")
}
// read error
// expect error to be received
d.Once(d.Event(Error), func(data interface{}) {
gobottest.Assert(t, data.(error).Error(), "read error")
sem <- true
})
// send error
testAdaptorAnalogRead = func() (val int, err error) {
err = errors.New("read error")
return