-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmhist_connector.go
105 lines (90 loc) · 2.33 KB
/
mhist_connector.go
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package nervo
import (
"context"
"log"
"github.com/alexmorten/mhist/models"
"github.com/alexmorten/mhist/proto"
"google.golang.org/grpc"
)
// MhistConnector reads new messages from mhist and distributes them to the correct controller
type MhistConnector struct {
manager *Manager
client proto.MhistClient
filter *proto.Filter
writeStream proto.Mhist_StoreStreamClient
}
// NewMhistConnector returns a connected subscriber
func NewMhistConnector(address string, filter *proto.Filter, manager *Manager) (*MhistConnector, error) {
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
return nil, err
}
c := proto.NewMhistClient(conn)
stream, err := c.StoreStream(context.Background())
if err != nil {
return nil, err
}
return &MhistConnector{
manager: manager,
client: c,
filter: filter,
writeStream: stream,
}, nil
}
// WriteMessage to mhist
func (c *MhistConnector) WriteMessage(verb string, message string) {
err := c.writeStream.Send(&proto.MeasurementMessage{
Name: verb,
Measurement: proto.MeasurementFromModel(&models.Raw{
Value: []byte(message),
})})
if err != nil {
log.Println(err)
}
}
// ReadMessages reads the from the subscription and relays messages to the given controllers if possible
func (c *MhistConnector) ReadMessages() {
stream, err := c.client.Subscribe(context.Background(), c.filter)
if err != nil {
panic(err)
}
for {
m, err := stream.Recv()
if err != nil {
log.Println(err)
break
}
c.handleNewMessage(m)
}
}
func (c *MhistConnector) handleNewMessage(m *proto.MeasurementMessage) {
r := m.Measurement.GetRaw()
if r == nil {
log.Println("ignoring subscribed message, is not raw")
return
}
v := r.Value
legName, message, ok := ParseGaitAction(string(v))
if !ok {
log.Println("is not valid gait action:", v)
return
}
infos := c.manager.listControllers()
portName := controllerPortForName(legName, infos)
if portName == "" {
log.Println("could not find controller with name:", legName)
return
}
err := c.manager.writeToController(portName, []byte(message+"\n"))
if err != nil {
log.Println("writting resulted in error:", err)
}
}
func controllerPortForName(name string, controllers []controllerInfo) string {
for _, info := range controllers {
if info.name == name {
return info.portName
}
}
return ""
}