2014-04-30 23:10:44 +08:00
|
|
|
package gobot
|
2014-04-30 04:20:32 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2014-11-13 03:21:50 +08:00
|
|
|
"fmt"
|
2014-04-30 04:20:32 +08:00
|
|
|
"log"
|
|
|
|
)
|
|
|
|
|
2014-10-16 01:57:07 +08:00
|
|
|
// JSONDevice is a JSON representation of a Gobot Device.
|
2014-06-11 06:16:11 +08:00
|
|
|
type JSONDevice struct {
|
2014-07-25 07:39:27 +08:00
|
|
|
Name string `json:"name"`
|
|
|
|
Driver string `json:"driver"`
|
|
|
|
Connection string `json:"connection"`
|
|
|
|
Commands []string `json:"commands"`
|
2014-05-16 02:50:45 +08:00
|
|
|
}
|
|
|
|
|
2014-07-03 08:12:13 +08:00
|
|
|
type Device DriverInterface
|
|
|
|
|
2014-07-10 00:38:43 +08:00
|
|
|
type devices []Device
|
2014-06-24 11:33:59 +08:00
|
|
|
|
2014-10-16 01:57:07 +08:00
|
|
|
// Len returns devices length
|
2014-06-24 11:33:59 +08:00
|
|
|
func (d *devices) Len() int {
|
2014-07-10 00:38:43 +08:00
|
|
|
return len(*d)
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|
|
|
|
|
2014-10-16 01:57:07 +08:00
|
|
|
// Each calls `f` function each device
|
2014-07-03 08:12:13 +08:00
|
|
|
func (d *devices) Each(f func(Device)) {
|
2014-07-10 00:38:43 +08:00
|
|
|
for _, device := range *d {
|
2014-06-24 11:33:59 +08:00
|
|
|
f(device)
|
|
|
|
}
|
|
|
|
}
|
2014-04-30 04:20:32 +08:00
|
|
|
|
2014-10-16 01:57:07 +08:00
|
|
|
// Start starts all the devices.
|
2014-11-20 15:21:19 +08:00
|
|
|
func (d *devices) Start() (errs []error) {
|
2014-04-30 04:20:32 +08:00
|
|
|
log.Println("Starting devices...")
|
2014-07-10 00:38:43 +08:00
|
|
|
for _, device := range *d {
|
|
|
|
info := "Starting device " + device.Name()
|
|
|
|
if device.Pin() != "" {
|
|
|
|
info = info + " on pin " + device.Pin()
|
|
|
|
}
|
|
|
|
log.Println(info + "...")
|
2014-11-20 15:21:19 +08:00
|
|
|
if errs = device.Start(); len(errs) > 0 {
|
|
|
|
for i, err := range errs {
|
|
|
|
errs[i] = errors.New(fmt.Sprintf("Device %q: %v", device.Name(), err))
|
|
|
|
}
|
|
|
|
return
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|
|
|
|
}
|
2014-11-20 15:21:19 +08:00
|
|
|
return
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|
|
|
|
|
2014-10-16 01:57:07 +08:00
|
|
|
// Halt stop all the devices.
|
2014-11-20 15:21:19 +08:00
|
|
|
func (d *devices) Halt() (errs []error) {
|
2014-07-10 00:38:43 +08:00
|
|
|
for _, device := range *d {
|
2014-11-20 15:21:19 +08:00
|
|
|
if derrs := device.Halt(); len(derrs) > 0 {
|
|
|
|
for i, err := range derrs {
|
|
|
|
derrs[i] = errors.New(fmt.Sprintf("Device %q: %v", device.Name(), err))
|
|
|
|
}
|
|
|
|
errs = append(errs, derrs...)
|
|
|
|
}
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|
2014-11-20 15:21:19 +08:00
|
|
|
return
|
2014-04-30 04:20:32 +08:00
|
|
|
}
|