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

75 lines
1.4 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-12 20:58:54 -07:00
Robots []*Robot
Commands map[string]func(map[string]interface{}) interface{}
trap func(chan os.Signal)
2014-04-29 13:20:32 -07:00
}
func NewGobot() *Gobot {
return &Gobot{
2014-06-12 20:58:54 -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)
},
}
}
2014-06-12 21:33:25 -07:00
func (g *Gobot) AddRobot(r *Robot) *Robot {
g.Robots = append(g.Robots, r)
return r
}
2014-06-12 20:58:54 -07:00
func (g *Gobot) AddCommand(name string, f func(map[string]interface{}) interface{}) {
g.Commands[name] = f
}
2014-04-29 13:20:32 -07:00
func (g *Gobot) Start() {
2014-04-30 08:10:44 -07:00
Robots(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-04-30 08:10:44 -07:00
Robots(g.Robots).Each(func(r *Robot) {
log.Println("Stopping Robot", r.Name, "...")
r.Devices().Halt()
r.Connections().Finalize()
2014-04-29 13:20:32 -07:00
})
}
2014-04-30 08:10:44 -07:00
func (g *Gobot) Robot(name string) *Robot {
2014-04-29 13:20:32 -07:00
for _, r := range g.Robots {
if r.Name == name {
return r
}
}
return nil
}
2014-06-12 20:58:54 -07:00
func (g *Gobot) ToJSON() *JSONGobot {
jsonGobot := &JSONGobot{
Robots: []*JSONRobot{},
Commands: []string{},
}
for command := range g.Commands {
jsonGobot.Commands = append(jsonGobot.Commands, command)
}
for _, robot := range g.Robots {
jsonGobot.Robots = append(jsonGobot.Robots, robot.ToJSON())
}
return jsonGobot
}