gobot.io/x/gobot/v2@v2.1.0/device.go (about) 1 package gobot 2 3 import ( 4 "log" 5 "reflect" 6 7 multierror "github.com/hashicorp/go-multierror" 8 ) 9 10 // JSONDevice is a JSON representation of a Device. 11 type JSONDevice struct { 12 Name string `json:"name"` 13 Driver string `json:"driver"` 14 Connection string `json:"connection"` 15 Commands []string `json:"commands"` 16 } 17 18 // NewJSONDevice returns a JSONDevice given a Device. 19 func NewJSONDevice(device Device) *JSONDevice { 20 jsonDevice := &JSONDevice{ 21 Name: device.Name(), 22 Driver: reflect.TypeOf(device).String(), 23 Commands: []string{}, 24 Connection: "", 25 } 26 if device.Connection() != nil { 27 jsonDevice.Connection = device.Connection().Name() 28 } 29 if commander, ok := device.(Commander); ok { 30 for command := range commander.Commands() { 31 jsonDevice.Commands = append(jsonDevice.Commands, command) 32 } 33 } 34 return jsonDevice 35 } 36 37 // A Device is an instnace of a Driver 38 type Device Driver 39 40 // Devices represents a collection of Device 41 type Devices []Device 42 43 // Len returns devices length 44 func (d *Devices) Len() int { 45 return len(*d) 46 } 47 48 // Each enumerates through the Devices and calls specified callback function. 49 func (d *Devices) Each(f func(Device)) { 50 for _, device := range *d { 51 f(device) 52 } 53 } 54 55 // Start calls Start on each Device in d 56 func (d *Devices) Start() (err error) { 57 log.Println("Starting devices...") 58 for _, device := range *d { 59 info := "Starting device " + device.Name() 60 61 if pinner, ok := device.(Pinner); ok { 62 info = info + " on pin " + pinner.Pin() 63 } 64 65 log.Println(info + "...") 66 if derr := device.Start(); derr != nil { 67 err = multierror.Append(err, derr) 68 } 69 } 70 return err 71 } 72 73 // Halt calls Halt on each Device in d 74 func (d *Devices) Halt() (err error) { 75 for _, device := range *d { 76 if derr := device.Halt(); derr != nil { 77 err = multierror.Append(err, derr) 78 } 79 } 80 return err 81 }