Skip to content

Commit

Permalink
Adds back in OS trap for clean automatic shutdown. Also adds new meth…
Browse files Browse the repository at this point in the history
…od to disable this feature, and allow devs to handle shutdown themselves.
  • Loading branch information
deadprogram committed Oct 22, 2015
1 parent 187d79f commit 632058c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
28 changes: 26 additions & 2 deletions gobot.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package gobot

import (
"log"
"os"
"os/signal"
)

// JSONGobot is a JSON representation of a Gobot.
Expand Down Expand Up @@ -30,15 +32,21 @@ func NewJSONGobot(gobot *Gobot) *JSONGobot {
// Gobot is the main type of your Gobot application and contains a collection of
// Robots, API commands and Events.
type Gobot struct {
robots *Robots
robots *Robots
trap func(chan os.Signal)
AutoStop bool
Commander
Eventer
}

// NewGobot returns a new Gobot
func NewGobot() *Gobot {
return &Gobot{
robots: &Robots{},
robots: &Robots{},
trap: func(c chan os.Signal) {
signal.Notify(c, os.Interrupt)
},
AutoStop: true,
Commander: NewCommander(),
Eventer: NewEventer(),
}
Expand All @@ -55,6 +63,22 @@ func (g *Gobot) Start() (errs []error) {
}
}

if g.AutoStop {
c := make(chan os.Signal, 1)
g.trap(c)
if len(errs) > 0 {
// there was an error during start, so we immediatly pass the interrupt
// in order to disconnect the initialized robots, connections and devices
c <- os.Interrupt
}

// waiting for interrupt coming on the channel
_ = <-c

// Stop calls the Stop method on each robot in its collection of robots.
g.Stop()
}

return errs
}

Expand Down
8 changes: 8 additions & 0 deletions gobot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gobot
import (
"errors"
"log"
"os"
"testing"
)

Expand All @@ -19,6 +20,9 @@ func TestConnectionEach(t *testing.T) {
func initTestGobot() *Gobot {
log.SetOutput(&NullReadWriteCloser{})
g := NewGobot()
g.trap = func(c chan os.Signal) {
c <- os.Interrupt
}
g.AddRobot(newTestRobot("Robot1"))
g.AddRobot(newTestRobot("Robot2"))
g.AddRobot(newTestRobot(""))
Expand Down Expand Up @@ -102,6 +106,10 @@ func TestGobotStartErrors(t *testing.T) {
testDriverStart = func() (errs []error) { return }
testAdaptorConnect = func() (errs []error) { return }

g.trap = func(c chan os.Signal) {
c <- os.Interrupt
}

testDriverHalt = func() (errs []error) {
return []error{
errors.New("driver halt error 1"),
Expand Down

0 comments on commit 632058c

Please sign in to comment.