forked from TheThingsArchive/ttn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
274 lines (226 loc) · 8.47 KB
/
client.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Copyright © 2016 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.
package mqtt
import (
"encoding/json"
"fmt"
"time"
"github.com/TheThingsNetwork/ttn/core"
"github.com/TheThingsNetwork/ttn/core/types"
"github.com/TheThingsNetwork/ttn/utils/random"
"github.com/apex/log"
MQTT "github.com/eclipse/paho.mqtt.golang"
)
const QoS = 0x02
// Client connects to the MQTT server and can publish/subscribe on uplink, downlink and activations from devices
type Client interface {
Connect() error
Disconnect()
IsConnected() bool
// Uplink pub/sub
PublishUplink(appEUI types.AppEUI, devEUI types.DevEUI, payload core.DataUpAppReq) Token
SubscribeDeviceUplink(appEUI types.AppEUI, devEUI types.DevEUI, handler UplinkHandler) Token
SubscribeAppUplink(appEUI types.AppEUI, handler UplinkHandler) Token
SubscribeUplink(handler UplinkHandler) Token
// Downlink pub/sub
PublishDownlink(appEUI types.AppEUI, devEUI types.DevEUI, payload core.DataDownAppReq) Token
SubscribeDeviceDownlink(appEUI types.AppEUI, devEUI types.DevEUI, handler DownlinkHandler) Token
SubscribeAppDownlink(appEUI types.AppEUI, handler DownlinkHandler) Token
SubscribeDownlink(handler DownlinkHandler) Token
// Activation pub/sub
PublishActivation(appEUI types.AppEUI, devEUI types.DevEUI, payload core.OTAAAppReq) Token
SubscribeDeviceActivations(appEUI types.AppEUI, devEUI types.DevEUI, handler ActivationHandler) Token
SubscribeAppActivations(appEUI types.AppEUI, handler ActivationHandler) Token
SubscribeActivations(handler ActivationHandler) Token
}
type Token interface {
Wait() bool
WaitTimeout(time.Duration) bool
Error() error
}
type simpleToken struct {
err error
}
// Wait always returns true
func (t *simpleToken) Wait() bool {
return true
}
// WaitTimeout always returns true
func (t *simpleToken) WaitTimeout(_ time.Duration) bool {
return true
}
// Error contains the error if present
func (t *simpleToken) Error() error {
return t.err
}
type UplinkHandler func(client Client, appEUI types.AppEUI, devEUI types.DevEUI, req core.DataUpAppReq)
type DownlinkHandler func(client Client, appEUI types.AppEUI, devEUI types.DevEUI, req core.DataDownAppReq)
type ActivationHandler func(client Client, appEUI types.AppEUI, devEUI types.DevEUI, req core.OTAAAppReq)
type defaultClient struct {
mqtt MQTT.Client
ctx log.Interface
}
func NewClient(ctx log.Interface, id, username, password string, brokers ...string) Client {
mqttOpts := MQTT.NewClientOptions()
for _, broker := range brokers {
mqttOpts.AddBroker(broker)
}
mqttOpts.SetClientID(fmt.Sprintf("%s-%s", id, random.String(16)))
mqttOpts.SetUsername(username)
mqttOpts.SetPassword(password)
// TODO: Some tuning of these values probably won't hurt:
mqttOpts.SetKeepAlive(30 * time.Second)
mqttOpts.SetPingTimeout(10 * time.Second)
// Usually this setting should not be used together with random ClientIDs, but
// we configured The Things Network's MQTT servers to handle this correctly.
mqttOpts.SetCleanSession(false)
mqttOpts.SetDefaultPublishHandler(func(client MQTT.Client, msg MQTT.Message) {
ctx.WithField("message", msg).Warn("Received unhandled message")
})
mqttOpts.SetConnectionLostHandler(func(client MQTT.Client, err error) {
ctx.WithError(err).Warn("Disconnected, reconnecting...")
})
mqttOpts.SetOnConnectHandler(func(client MQTT.Client) {
ctx.Debug("Connected")
})
return &defaultClient{
mqtt: MQTT.NewClient(mqttOpts),
ctx: ctx,
}
}
var (
// ConnectRetries says how many times the client should retry a failed connection
ConnectRetries = 10
// ConnectRetryDelay says how long the client should wait between retries
ConnectRetryDelay = time.Second
)
func (c *defaultClient) Connect() error {
if c.mqtt.IsConnected() {
return nil
}
var err error
for retries := 0; retries < ConnectRetries; retries++ {
token := c.mqtt.Connect()
token.Wait()
err = token.Error()
if err == nil {
break
}
<-time.After(ConnectRetryDelay)
}
if err != nil {
return fmt.Errorf("Could not connect: %s", err)
}
return nil
}
func (c *defaultClient) Disconnect() {
if !c.mqtt.IsConnected() {
return
}
c.mqtt.Disconnect(25)
}
func (c *defaultClient) IsConnected() bool {
return c.mqtt.IsConnected()
}
func (c *defaultClient) PublishUplink(appEUI types.AppEUI, devEUI types.DevEUI, dataUp core.DataUpAppReq) Token {
topic := DeviceTopic{appEUI, devEUI, Uplink}
msg, err := json.Marshal(dataUp)
if err != nil {
return &simpleToken{fmt.Errorf("Unable to marshal the message payload")}
}
return c.mqtt.Publish(topic.String(), QoS, false, msg)
}
func (c *defaultClient) SubscribeDeviceUplink(appEUI types.AppEUI, devEUI types.DevEUI, handler UplinkHandler) Token {
topic := DeviceTopic{appEUI, devEUI, Uplink}
return c.mqtt.Subscribe(topic.String(), QoS, func(mqtt MQTT.Client, msg MQTT.Message) {
// Determine the actual topic
topic, err := ParseDeviceTopic(msg.Topic())
if err != nil {
c.ctx.WithField("topic", msg.Topic()).WithError(err).Warn("Received message on invalid uplink topic")
return
}
// Unmarshal the payload
dataUp := &core.DataUpAppReq{}
err = json.Unmarshal(msg.Payload(), dataUp)
if err != nil {
c.ctx.WithError(err).Warn("Could not unmarshal uplink")
return
}
// Call the uplink handler
handler(c, topic.AppEUI, topic.DevEUI, *dataUp)
})
}
func (c *defaultClient) SubscribeAppUplink(appEUI types.AppEUI, handler UplinkHandler) Token {
return c.SubscribeDeviceUplink(appEUI, types.DevEUI{}, handler)
}
func (c *defaultClient) SubscribeUplink(handler UplinkHandler) Token {
return c.SubscribeDeviceUplink(types.AppEUI{}, types.DevEUI{}, handler)
}
func (c *defaultClient) PublishDownlink(appEUI types.AppEUI, devEUI types.DevEUI, dataDown core.DataDownAppReq) Token {
topic := DeviceTopic{appEUI, devEUI, Downlink}
msg, err := json.Marshal(dataDown)
if err != nil {
return &simpleToken{fmt.Errorf("Unable to marshal the message payload")}
}
return c.mqtt.Publish(topic.String(), QoS, false, msg)
}
func (c *defaultClient) SubscribeDeviceDownlink(appEUI types.AppEUI, devEUI types.DevEUI, handler DownlinkHandler) Token {
topic := DeviceTopic{appEUI, devEUI, Downlink}
return c.mqtt.Subscribe(topic.String(), QoS, func(mqtt MQTT.Client, msg MQTT.Message) {
// Determine the actual topic
topic, err := ParseDeviceTopic(msg.Topic())
if err != nil {
c.ctx.WithField("topic", msg.Topic()).WithError(err).Warn("Received message on invalid Downlink topic")
return
}
// Unmarshal the payload
dataDown := &core.DataDownAppReq{}
err = json.Unmarshal(msg.Payload(), dataDown)
if err != nil {
c.ctx.WithError(err).Warn("Could not unmarshal Downlink")
return
}
// Call the Downlink handler
handler(c, topic.AppEUI, topic.DevEUI, *dataDown)
})
}
func (c *defaultClient) SubscribeAppDownlink(appEUI types.AppEUI, handler DownlinkHandler) Token {
return c.SubscribeDeviceDownlink(appEUI, types.DevEUI{}, handler)
}
func (c *defaultClient) SubscribeDownlink(handler DownlinkHandler) Token {
return c.SubscribeDeviceDownlink(types.AppEUI{}, types.DevEUI{}, handler)
}
func (c *defaultClient) PublishActivation(appEUI types.AppEUI, devEUI types.DevEUI, activation core.OTAAAppReq) Token {
topic := DeviceTopic{appEUI, devEUI, Activations}
msg, err := json.Marshal(activation)
if err != nil {
return &simpleToken{fmt.Errorf("Unable to marshal the message payload")}
}
return c.mqtt.Publish(topic.String(), QoS, false, msg)
}
func (c *defaultClient) SubscribeDeviceActivations(appEUI types.AppEUI, devEUI types.DevEUI, handler ActivationHandler) Token {
topic := DeviceTopic{appEUI, devEUI, Activations}
return c.mqtt.Subscribe(topic.String(), QoS, func(mqtt MQTT.Client, msg MQTT.Message) {
// Determine the actual topic
topic, err := ParseDeviceTopic(msg.Topic())
if err != nil {
c.ctx.WithField("topic", msg.Topic()).WithError(err).Warn("Received message on invalid Activations topic")
return
}
// Unmarshal the payload
activation := &core.OTAAAppReq{}
err = json.Unmarshal(msg.Payload(), activation)
if err != nil {
c.ctx.WithError(err).Warn("Could not unmarshal Activation")
return
}
// Call the Activation handler
handler(c, topic.AppEUI, topic.DevEUI, *activation)
})
}
func (c *defaultClient) SubscribeAppActivations(appEUI types.AppEUI, handler ActivationHandler) Token {
return c.SubscribeDeviceActivations(appEUI, types.DevEUI{}, handler)
}
func (c *defaultClient) SubscribeActivations(handler ActivationHandler) Token {
return c.SubscribeDeviceActivations(types.AppEUI{}, types.DevEUI{}, handler)
}