From 5eac41a6bcd67011730a6aebec95b7917a049ff8 Mon Sep 17 00:00:00 2001 From: deadprogram Date: Sun, 16 Oct 2016 18:25:05 +0200 Subject: [PATCH] core: WIP on all work happening in separate goroutine Signed-off-by: deadprogram --- examples/firmata_blink_robot.go | 28 ++++++++++++++++++++++++++++ robot.go | 8 +++++++- 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 examples/firmata_blink_robot.go diff --git a/examples/firmata_blink_robot.go b/examples/firmata_blink_robot.go new file mode 100644 index 00000000..e27de4ce --- /dev/null +++ b/examples/firmata_blink_robot.go @@ -0,0 +1,28 @@ +package main + +import ( + "time" + + "github.com/hybridgroup/gobot" + "github.com/hybridgroup/gobot/drivers/gpio" + "github.com/hybridgroup/gobot/platforms/firmata" +) + +func main() { + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0") + led := gpio.NewLedDriver(firmataAdaptor, "13") + + work := func() { + gobot.Every(1*time.Second, func() { + led.Toggle() + }) + } + + robot := gobot.NewRobot("bot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{led}, + work, + ) + + robot.Start() +} diff --git a/robot.go b/robot.go index 46b0431b..b85b8ecc 100644 --- a/robot.go +++ b/robot.go @@ -42,6 +42,7 @@ type Robot struct { Work func() connections *Connections devices *Devices + done chan bool Commander Eventer } @@ -98,6 +99,7 @@ func NewRobot(v ...interface{}) *Robot { Name: fmt.Sprintf("%X", Rand(int(^uint(0)>>1))), connections: &Connections{}, devices: &Devices{}, + done: make(chan bool), Work: nil, Eventer: NewEventer(), Commander: NewCommander(), @@ -142,7 +144,10 @@ func (r *Robot) Start() (errs []error) { } if r.Work != nil { log.Println("Starting work...") - r.Work() + go func() { + r.Work() + <-r.done + }() } return } @@ -152,6 +157,7 @@ func (r *Robot) Stop() (errs []error) { log.Println("Stopping Robot", r.Name, "...") errs = append(errs, r.Devices().Halt()...) errs = append(errs, r.Connections().Finalize()...) + r.done <- true return errs }