1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-24 13:48:49 +08:00

89 lines
1.7 KiB
Go
Raw Normal View History

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