2014-04-30 04:20:32 +08:00
|
|
|
package gobot
|
|
|
|
|
|
|
|
import (
|
2014-04-30 23:10:44 +08:00
|
|
|
"log"
|
2014-04-30 04:20:32 +08:00
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
)
|
|
|
|
|
2014-06-13 11:58:54 +08:00
|
|
|
type JSONGobot struct {
|
|
|
|
Robots []*JSONRobot `json:"robots"`
|
|
|
|
Commands []string `json:"commands"`
|
|
|
|
}
|
|
|
|
|
2014-04-30 04:20:32 +08:00
|
|
|
type Gobot struct {
|
2014-06-24 11:33:59 +08:00
|
|
|
robots *robots
|
2014-07-03 09:08:44 +08:00
|
|
|
commands map[string]func(map[string]interface{}) interface{}
|
2014-06-13 11:58:54 +08:00
|
|
|
trap func(chan os.Signal)
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewGobot() *Gobot {
|
|
|
|
return &Gobot{
|
2014-06-24 11:33:59 +08:00
|
|
|
robots: &robots{},
|
2014-07-03 09:08:44 +08:00
|
|
|
commands: make(map[string]func(map[string]interface{}) interface{}),
|
2014-04-30 04:20:32 +08:00
|
|
|
trap: func(c chan os.Signal) {
|
|
|
|
signal.Notify(c, os.Interrupt)
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-07-03 09:08:44 +08:00
|
|
|
func (g *Gobot) Commands() map[string]func(map[string]interface{}) interface{} {
|
2014-06-24 11:33:59 +08:00
|
|
|
return g.commands
|
2014-06-13 11:58:54 +08:00
|
|
|
}
|
|
|
|
|
2014-04-30 04:20:32 +08:00
|
|
|
func (g *Gobot) Start() {
|
2014-06-24 11:33:59 +08:00
|
|
|
g.robots.Start()
|
2014-04-30 04:20:32 +08:00
|
|
|
|
|
|
|
c := make(chan os.Signal, 1)
|
|
|
|
g.trap(c)
|
|
|
|
|
|
|
|
// waiting for interrupt coming on the channel
|
|
|
|
_ = <-c
|
2014-06-24 11:33:59 +08:00
|
|
|
g.robots.Each(func(r *Robot) {
|
2014-04-30 23:10:44 +08:00
|
|
|
log.Println("Stopping Robot", r.Name, "...")
|
|
|
|
r.Devices().Halt()
|
|
|
|
r.Connections().Finalize()
|
2014-04-30 04:20:32 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2014-06-24 11:33:59 +08:00
|
|
|
func (g *Gobot) Robots() *robots {
|
|
|
|
return g.robots
|
|
|
|
}
|
|
|
|
|
2014-04-30 23:10:44 +08:00
|
|
|
func (g *Gobot) Robot(name string) *Robot {
|
2014-06-24 11:33:59 +08:00
|
|
|
for _, robot := range g.Robots().robots {
|
|
|
|
if robot.Name == name {
|
|
|
|
return robot
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2014-06-13 11:58:54 +08:00
|
|
|
|
|
|
|
func (g *Gobot) ToJSON() *JSONGobot {
|
|
|
|
jsonGobot := &JSONGobot{
|
|
|
|
Robots: []*JSONRobot{},
|
|
|
|
Commands: []string{},
|
|
|
|
}
|
2014-06-24 11:33:59 +08:00
|
|
|
|
2014-07-03 09:08:44 +08:00
|
|
|
for command := range g.Commands() {
|
|
|
|
jsonGobot.Commands = append(jsonGobot.Commands, command)
|
|
|
|
}
|
2014-06-24 11:33:59 +08:00
|
|
|
|
|
|
|
g.robots.Each(func(r *Robot) {
|
|
|
|
jsonGobot.Robots = append(jsonGobot.Robots, r.ToJSON())
|
|
|
|
})
|
2014-06-13 11:58:54 +08:00
|
|
|
return jsonGobot
|
|
|
|
}
|