2014-04-30 23:10:44 +08:00
|
|
|
package gobot
|
2014-04-30 04:20:32 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"log"
|
|
|
|
"reflect"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Device interface {
|
|
|
|
Start() bool
|
|
|
|
Halt() bool
|
|
|
|
}
|
|
|
|
|
|
|
|
type device struct {
|
2014-04-30 23:10:44 +08:00
|
|
|
Name string `json:"name"`
|
|
|
|
Type string `json:"driver"`
|
|
|
|
Interval string `json:"-"`
|
|
|
|
Robot *Robot `json:"-"`
|
|
|
|
Driver DriverInterface `json:"-"`
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type devices []*device
|
|
|
|
|
|
|
|
// Start() starts all the devices.
|
|
|
|
func (d devices) Start() error {
|
|
|
|
var err error
|
|
|
|
log.Println("Starting devices...")
|
|
|
|
for _, device := range d {
|
|
|
|
log.Println("Starting device " + device.Name + "...")
|
|
|
|
if device.Start() == false {
|
2014-04-30 23:10:44 +08:00
|
|
|
err = errors.New("Could not start device")
|
2014-04-30 04:20:32 +08:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Halt() stop all the devices.
|
|
|
|
func (d devices) Halt() {
|
|
|
|
for _, device := range d {
|
|
|
|
device.Halt()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-04-30 23:10:44 +08:00
|
|
|
func NewDevice(driver DriverInterface, r *Robot) *device {
|
2014-04-30 04:20:32 +08:00
|
|
|
d := new(device)
|
|
|
|
s := reflect.ValueOf(driver).Type().String()
|
|
|
|
d.Type = s[1:len(s)]
|
2014-04-30 23:10:44 +08:00
|
|
|
d.Name = FieldByNamePtr(driver, "Name").String()
|
2014-04-30 04:20:32 +08:00
|
|
|
d.Robot = r
|
2014-04-30 23:10:44 +08:00
|
|
|
if FieldByNamePtr(driver, "Interval").String() == "" {
|
|
|
|
FieldByNamePtr(driver, "Interval").SetString("0.1s")
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|
|
|
|
d.Driver = driver
|
|
|
|
return d
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *device) Start() bool {
|
|
|
|
log.Println("Device " + d.Name + " started")
|
|
|
|
return d.Driver.Start()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *device) Halt() bool {
|
|
|
|
log.Println("Device " + d.Name + " halted")
|
|
|
|
return d.Driver.Halt()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *device) Commands() interface{} {
|
2014-04-30 23:10:44 +08:00
|
|
|
return FieldByNamePtr(d.Driver, "Commands").Interface()
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|