Adds back in OS trap for clean automatic shutdown. Also adds new method to disable this feature, and allow devs to handle shutdown themselves.

This commit is contained in:
deadprogram 2015-10-22 00:12:00 -07:00
parent 187d79f360
commit 632058c47a
2 changed files with 34 additions and 2 deletions

View File

@ -2,6 +2,8 @@ package gobot
import (
"log"
"os"
"os/signal"
)
// JSONGobot is a JSON representation of a Gobot.
@ -30,7 +32,9 @@ 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
}
@ -38,7 +42,11 @@ type Gobot struct {
// 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(),
}
@ -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
}

View File

@ -3,6 +3,7 @@ package gobot
import (
"errors"
"log"
"os"
"testing"
)
@ -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(""))
@ -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"),