-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhardware.go
More file actions
89 lines (78 loc) · 1.97 KB
/
hardware.go
File metadata and controls
89 lines (78 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"errors"
"fmt"
"os"
"github.com/xanecs/lighthouse/config"
"github.com/xanecs/lighthouse/driver"
"gobot.io/x/gobot"
"gobot.io/x/gobot/platforms/firmata"
)
// Hardware represents all connected controllers
type Hardware struct {
connections []gobot.Connection
devices map[string]driver.Device
}
// NewHardware creates a new Hardware object from a board config
func NewHardware(cfg map[string]config.BoardConfig) (*Hardware, error) {
connections := make([]gobot.Connection, 0)
devices := make(map[string]driver.Device)
for _, boardConfig := range cfg {
adaptor := firmata.NewAdaptor(boardConfig.Serial)
connections = append(connections, adaptor)
for deviceName, deviceConfig := range boardConfig.Dev {
if devices[deviceName] != nil {
return nil, errors.New("Name " + deviceName + " has been given twice")
}
device, err := driver.NewDriver(deviceConfig, adaptor)
if err != nil {
return nil, err
}
devices[deviceName] = device
}
}
return &Hardware{connections, devices}, nil
}
// Start connects to the boards
func (h *Hardware) Start() (err error) {
for _, c := range h.connections {
err = c.Connect()
if err != nil {
return
}
}
return
}
// Stop disconnects from the boards
func (h *Hardware) Stop() {
for _, c := range h.connections {
c.Finalize()
}
}
// Restore all Hardware from database
func (h *Hardware) Restore(b *broker) {
for name, dev := range h.devices {
status, err := b.fetchStatus(name)
if err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
dev.Restore(status)
}
}
// Listen processes Messages from a channel
func (h *Hardware) Listen(in chan Message, out chan Status, chanErr chan error) {
for {
msg := <-in
dev := h.devices[msg.Device]
if dev == nil {
chanErr <- errors.New("Device '" + msg.Device + "' not found")
continue
}
if err := dev.HandleMessage(msg.Action, msg.Params); err != nil {
chanErr <- err
continue
}
out <- Status{msg.Device, dev.Status()}
}
}