1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-26 13:48:49 +08:00
hybridgroup.gobot/device.go

83 lines
1.7 KiB
Go
Raw Normal View History

2014-04-30 08:10:44 -07:00
package gobot
2014-04-29 13:20:32 -07:00
import (
"errors"
2014-11-12 11:21:50 -08:00
"fmt"
2014-04-29 13:20:32 -07:00
"log"
"reflect"
2014-04-29 13:20:32 -07:00
)
2014-10-15 12:57:07 -05:00
// JSONDevice is a JSON representation of a Gobot Device.
2014-06-10 15:16:11 -07:00
type JSONDevice struct {
2014-07-24 16:39:27 -07:00
Name string `json:"name"`
Driver string `json:"driver"`
Connection string `json:"connection"`
Commands []string `json:"commands"`
2014-05-15 11:50:45 -07:00
}
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()
}
for command := range device.(Commander).Commands() {
jsonDevice.Commands = append(jsonDevice.Commands, command)
}
return jsonDevice
}
type Device Driver
2014-07-09 09:38:43 -07:00
type devices []Device
2014-06-23 20:33:59 -07:00
2014-10-15 12:57:07 -05:00
// Len returns devices length
2014-06-23 20:33:59 -07:00
func (d *devices) Len() int {
2014-07-09 09:38:43 -07:00
return len(*d)
2014-04-29 13:20:32 -07:00
}
2014-10-15 12:57:07 -05:00
// Each calls `f` function each device
func (d *devices) Each(f func(Device)) {
2014-07-09 09:38:43 -07:00
for _, device := range *d {
2014-06-23 20:33:59 -07:00
f(device)
}
}
2014-04-29 13:20:32 -07:00
2014-10-15 12:57:07 -05:00
// Start starts all the devices.
func (d *devices) Start() (errs []error) {
2014-04-29 13:20:32 -07:00
log.Println("Starting devices...")
2014-07-09 09:38:43 -07:00
for _, device := range *d {
info := "Starting device " + device.Name()
2014-11-21 19:35:01 -08:00
if piner, ok := device.(Piner); ok {
info = info + " on pin " + piner.Pin()
2014-07-09 09:38:43 -07:00
}
2014-11-21 19:35:01 -08:00
2014-07-09 09:38:43 -07:00
log.Println(info + "...")
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-29 13:20:32 -07:00
}
}
return
2014-04-29 13:20:32 -07:00
}
2014-10-15 12:57:07 -05:00
// Halt stop all the devices.
func (d *devices) Halt() (errs []error) {
2014-07-09 09:38:43 -07:00
for _, device := range *d {
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-29 13:20:32 -07:00
}
return
2014-04-29 13:20:32 -07:00
}