/
devmgmt.go
180 lines (158 loc) · 5.43 KB
/
devmgmt.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package devmgmt
import (
"bytes"
"context"
"crypto/ed25519"
"encoding/base64"
"encoding/binary"
"encoding/json"
"fmt"
"log"
"os"
"time"
"github.com/gbaranski/houseflow/pkg/types"
"github.com/gbaranski/houseflow/pkg/utils"
"github.com/sirupsen/logrus"
paho "github.com/eclipse/paho.mqtt.golang"
)
const (
// RequestIDSize is size of RequestID
RequestIDSize = 16
)
// Devmgmt is some abstraction layer over paho mqtt
type Devmgmt struct {
Client paho.Client
opts Options
}
// New is constructor for MQTT, connects to broker
func New(opts Options) (Devmgmt, error) {
opts.Parse()
paho.ERROR = log.New(os.Stdout, "[ERROR] ", 0)
paho.CRITICAL = log.New(os.Stdout, "[CRIT] ", 0)
paho.WARN = log.New(os.Stdout, "[WARN] ", 0)
// mqtt.DEBUG = log.New(os.Stdout, "[DEBUG] ", 0)
username := base64.StdEncoding.EncodeToString(opts.ServerPublicKey)
ts := make([]byte, 32/8)
binary.BigEndian.PutUint32(ts, uint32(time.Now().Unix()))
password := make([]byte, ed25519.SignatureSize+32/8)
copy(password, ed25519.Sign(opts.ServerPrivateKey, ts))
copy(password[ed25519.SignatureSize:], ts)
copts := paho.
NewClientOptions().
AddBroker(opts.BrokerURL).
SetClientID(opts.ClientID).
SetUsername(username).
SetPassword(base64.StdEncoding.EncodeToString(password)).
SetAutoReconnect(true).
SetConnectRetry(true)
c := paho.NewClient(copts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
return Devmgmt{}, token.Error()
}
return Devmgmt{
Client: c,
opts: opts,
}, nil
}
// PublishWithResponse publishes message and waits for response and returns its body
func (devmgmt Devmgmt) PublishWithResponse(ctx context.Context, body []byte, topic ResponseTopic, pkey ed25519.PublicKey) ([]byte, error) {
msgCh := make(chan paho.Message)
if token := devmgmt.Client.Subscribe(topic.Response, 0, func(c paho.Client, m paho.Message) {
msgCh <- m
}); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
defer func() {
devmgmt.Client.Unsubscribe(topic.Response)
}()
requestID, err := utils.NewRequestID(RequestIDSize)
if err != nil {
return nil, fmt.Errorf("fail gen requestID %s", err.Error())
}
payload := make([]byte, ed25519.SignatureSize+RequestIDSize+len(body))
copy(payload[0:ed25519.SignatureSize], ed25519.Sign(devmgmt.opts.ServerPrivateKey, append(requestID, body...)))
copy(payload[ed25519.SignatureSize:ed25519.SignatureSize+RequestIDSize], requestID)
copy(payload[ed25519.SignatureSize+RequestIDSize:], body)
if token := devmgmt.Client.Publish(topic.Request, 0, false, payload); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
loop:
for {
select {
case <-ctx.Done():
return nil, ErrDeviceTimeout
case msg, ok := <-msgCh:
{
if !ok {
logrus.Infoln("fail on message channel")
continue loop
}
responsePayload := msg.Payload()
responseSignature := responsePayload[0:ed25519.SignatureSize]
responseRequestID := responsePayload[ed25519.SignatureSize : ed25519.SignatureSize+RequestIDSize]
msgBody := responsePayload[ed25519.SignatureSize+RequestIDSize:]
if !bytes.Equal(responseRequestID, requestID) {
logrus.Infof("skipping message due to requestID mismatch exp: %v, rec: %v\n", requestID, responseRequestID)
continue loop
}
valid := ed25519.Verify(pkey, append(responseRequestID, msgBody...), responseSignature)
if !valid {
return nil, ErrInvalidSignature
}
return msgBody, nil
}
}
}
}
// FetchDeviceState sends rqeuest to device with question about his device state
func (devmgmt Devmgmt) FetchDeviceState(ctx context.Context, device types.Device) (types.DeviceResponse, error) {
publicKey, err := base64.StdEncoding.DecodeString(device.PublicKeyBase64)
if err != nil {
return types.DeviceResponse{}, fmt.Errorf("fail decode public key %s", err.Error())
}
deviceResponseJSON, err := devmgmt.PublishWithResponse(ctx, nil, ResponseTopic{
Request: fmt.Sprintf("%s/state/request", device.ID),
Response: fmt.Sprintf("%s/state/response", device.ID),
}, ed25519.PublicKey(publicKey))
if err != nil {
return types.DeviceResponse{}, err
}
var deviceResponse types.DeviceResponse
if err = json.Unmarshal(deviceResponseJSON, &deviceResponse); err != nil {
return types.DeviceResponse{}, fmt.Errorf("fail unmarshall device response %s", err.Error())
}
return deviceResponse, nil
}
// SendActionCommand sends action command and returns device response to it
func (devmgmt Devmgmt) SendActionCommand(
ctx context.Context,
device types.Device,
command string,
params map[string]interface{},
) (types.DeviceResponse, error) {
deviceRequest := types.DeviceRequest{
Params: params,
Command: command,
}
deviceRequestJSON, err := json.Marshal(deviceRequest)
if err != nil {
return types.DeviceResponse{}, nil
}
publicKey, err := base64.StdEncoding.DecodeString(device.PublicKeyBase64)
if err != nil {
return types.DeviceResponse{}, fmt.Errorf("fail decode public key %s", err.Error())
}
deviceResponseJSON, err := devmgmt.PublishWithResponse(ctx, deviceRequestJSON, ResponseTopic{
Request: fmt.Sprintf("%s/command/request", device.ID),
Response: fmt.Sprintf("%s/command/response", device.ID),
}, ed25519.PublicKey(publicKey))
if err != nil {
return types.DeviceResponse{}, err
}
var deviceResponse types.DeviceResponse
err = json.Unmarshal(deviceResponseJSON, &deviceResponse)
if err != nil {
return types.DeviceResponse{}, fmt.Errorf("invalid json %s", err.Error())
}
return deviceResponse, nil
}