hybridgroup.gobot/device.go

84 lines
1.8 KiB
Go
Raw Normal View History

2014-04-30 23:10:44 +08:00
package gobot
2014-04-30 04:20:32 +08:00
import (
"log"
"reflect"
multierror "github.com/hashicorp/go-multierror"
2014-04-30 04:20:32 +08:00
)
// JSONDevice is a JSON representation of a 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
}
// NewJSONDevice returns a JSONDevice given a Device.
func NewJSONDevice(device Device) *JSONDevice {
jsonDevice := &JSONDevice{
Name: device.Name(),
Driver: reflect.TypeOf(device).String(),
Commands: []string{},
Connection: "",
}
if device.Connection() != nil {
jsonDevice.Connection = device.Connection().Name()
}
if commander, ok := device.(Commander); ok {
for command := range commander.Commands() {
jsonDevice.Commands = append(jsonDevice.Commands, command)
}
}
return jsonDevice
}
// A Device is an instnace of a Driver
type Device Driver
// Devices represents a collection of Device
type Devices []Device
2014-06-24 11:33:59 +08:00
2014-10-16 01:57:07 +08:00
// Len returns devices length
func (d *Devices) Len() int {
2014-07-10 00:38:43 +08:00
return len(*d)
2014-04-30 04:20:32 +08:00
}
// Each enumerates through the Devices and calls specified callback function.
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
// Start calls Start on each Device in d
func (d *Devices) Start() error {
2014-04-30 04:20:32 +08:00
log.Println("Starting devices...")
var err error
2014-07-10 00:38:43 +08:00
for _, device := range *d {
info := "Starting device " + device.Name()
2014-11-22 11:35:01 +08:00
2014-11-29 11:04:22 +08:00
if pinner, ok := device.(Pinner); ok {
info = info + " on pin " + pinner.Pin()
2014-07-10 00:38:43 +08:00
}
2014-11-22 11:35:01 +08:00
2014-07-10 00:38:43 +08:00
log.Println(info + "...")
if derr := device.Start(); derr != nil {
err = multierror.Append(err, derr)
2014-04-30 04:20:32 +08:00
}
}
return err
2014-04-30 04:20:32 +08:00
}
// Halt calls Halt on each Device in d
func (d *Devices) Halt() error {
var err error
2014-07-10 00:38:43 +08:00
for _, device := range *d {
if derr := device.Halt(); derr != nil {
err = multierror.Append(err, derr)
}
2014-04-30 04:20:32 +08:00
}
return err
2014-04-30 04:20:32 +08:00
}