hybridgroup.gobot/robot.go

66 lines
1.6 KiB
Go
Raw Normal View History

2013-10-23 07:45:31 +08:00
package gobot
import (
"time"
"fmt"
"math/rand"
2013-10-25 13:04:58 +08:00
"reflect"
2013-10-23 07:45:31 +08:00
)
type Robot struct {
2013-10-25 13:04:58 +08:00
Connections []interface{}
Devices []interface{}
2013-10-23 07:45:31 +08:00
Name string
Work func()
2013-10-26 05:15:31 +08:00
connections []*Connection
devices []*Device
2013-10-23 07:45:31 +08:00
}
func (r *Robot) Start() {
if r.Name == "" {
rand.Seed( time.Now().UTC().UnixNano())
i := rand.Int()
r.Name = fmt.Sprintf("Robot %v", i)
}
2013-10-25 13:04:58 +08:00
r.initConnections()
r.initDevices()
2013-10-24 13:00:03 +08:00
r.startConnections()
r.startDevices()
2013-10-23 07:45:31 +08:00
r.Work()
2013-10-25 13:04:58 +08:00
for{time.Sleep(10 * time.Millisecond)}
2013-10-23 07:45:31 +08:00
}
2013-10-25 13:04:58 +08:00
func (r *Robot) initConnections() {
2013-10-26 05:15:31 +08:00
r.connections = make([]*Connection, len(r.Connections))
2013-10-23 07:45:31 +08:00
fmt.Println("Initializing connections...")
2013-10-25 13:04:58 +08:00
for i := range r.Connections {
fmt.Println("Initializing connection " + reflect.ValueOf(r.Connections[i]).Elem().FieldByName("Name").String() + "...")
2013-10-26 05:15:31 +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() {
2013-10-26 05:15:31 +08:00
r.devices = make([]*Device, len(r.Devices))
2013-10-23 07:45:31 +08:00
fmt.Println("Initializing devices...")
2013-10-25 13:04:58 +08:00
for i := range r.Devices {
fmt.Println("Initializing device " + reflect.ValueOf(r.Devices[i]).Elem().FieldByName("Name").String() + "...")
2013-10-29 09:50:09 +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-10-23 07:45:31 +08:00
fmt.Println("Starting connections...")
2013-10-26 05:15:31 +08:00
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-10-23 07:45:31 +08:00
fmt.Println("Starting devices...")
2013-10-26 05:15:31 +08:00
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
}
}