hybridgroup.gobot/robot.go

98 lines
2.1 KiB
Go
Raw Normal View History

2013-10-23 07:45:31 +08:00
package gobot
import (
2013-11-14 12:44:54 +08:00
"fmt"
"math/rand"
"time"
2013-10-23 07:45:31 +08:00
)
type Robot struct {
Connections []Connection
Devices []Device
2013-11-28 12:05:45 +08:00
Name string
Commands map[string]interface{} `json:"-"`
2013-12-03 03:39:10 +08:00
RobotCommands []string `json:"Commands"`
Work func() `json:"-"`
connections []*connection `json:"-"`
devices []*device `json:"-"`
2013-10-23 07:45:31 +08:00
}
func (r *Robot) Start() {
2013-12-19 15:50:42 +08:00
m := GobotMaster()
m.Robots = []Robot{*r}
m.Start()
}
func (r *Robot) startRobot() {
r.initName()
2013-12-03 10:59:28 +08:00
r.initCommands()
2013-11-14 12:44:54 +08:00
r.initConnections()
r.initDevices()
r.startConnections()
r.startDevices()
2013-12-04 07:51:17 +08:00
if r.Work != nil {
r.Work()
}
2013-10-23 07:45:31 +08:00
}
func (r *Robot) initName() {
if r.Name == "" {
rand.Seed(time.Now().UTC().UnixNano())
i := rand.Int()
r.Name = fmt.Sprintf("Robot %v", i)
}
}
2013-12-03 10:59:28 +08:00
func (r *Robot) initCommands() {
for k, _ := range r.Commands {
r.RobotCommands = append(r.RobotCommands, k)
}
}
2013-10-25 13:04:58 +08:00
func (r *Robot) initConnections() {
r.connections = make([]*connection, len(r.Connections))
2013-11-14 12:44:54 +08:00
fmt.Println("Initializing connections...")
for i := range r.Connections {
fmt.Sprintln("Initializing connection %v...", FieldByNamePtr(r.Connections[i], "Name"))
2013-11-14 12:44:54 +08:00
r.connections[i] = NewConnection(r.Connections[i], r)
}
2013-10-23 07:45:31 +08:00
}
2013-10-25 13:04:58 +08:00
func (r *Robot) initDevices() {
r.devices = make([]*device, len(r.Devices))
2013-11-14 12:44:54 +08:00
fmt.Println("Initializing devices...")
for i := range r.Devices {
fmt.Sprintln("Initializing device %v...", FieldByNamePtr(r.Devices[i], "Name"))
2013-11-14 12:44:54 +08:00
r.devices[i] = NewDevice(r.Devices[i], r)
}
2013-10-23 07:45:31 +08:00
}
2013-10-24 13:00:03 +08:00
func (r *Robot) startConnections() {
2013-11-14 12:44:54 +08:00
fmt.Println("Starting connections...")
for i := range r.connections {
fmt.Println("Starting connection " + r.connections[i].Name + "...")
r.connections[i].Connect()
}
2013-10-23 07:45:31 +08:00
}
2013-10-24 13:00:03 +08:00
func (r *Robot) startDevices() {
2013-11-14 12:44:54 +08:00
fmt.Println("Starting devices...")
for i := range r.devices {
fmt.Println("Starting device " + r.devices[i].Name + "...")
r.devices[i].Start()
}
2013-10-23 07:45:31 +08:00
}
2013-11-24 01:12:57 +08:00
func (r *Robot) GetDevices() []*device {
2013-11-24 02:36:08 +08:00
return r.devices
}
func (r *Robot) GetDevice(name string) *device {
2013-11-24 01:12:57 +08:00
for i := range r.devices {
if r.devices[i].Name == name {
return r.devices[i]
}
}
return nil
}