-
Notifications
You must be signed in to change notification settings - Fork 1
/
mqttclient.go
358 lines (305 loc) · 10.1 KB
/
mqttclient.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package pubsub
import (
"fmt"
"math/big"
"sync"
CRAND "crypto/rand"
PahoMQTT "github.com/eclipse/paho.mqtt.golang"
)
const (
defaultBrokerURI = "tcp://localhost:1883"
disconnectWaitMS uint = 300
)
var (
// Sets whether AutoReconnect will be set
AutoReconnect bool = true
)
type MQTTClient struct {
mqtt PahoMQTT.Client
defaultQoS MQTTQoS
defaultPersistence bool
lock sync.Mutex // lock to ensure topics is consistent with subs
topics map[string]byte // for reconnect subscriptions (byte is QoS)
publock sync.RWMutex // lock for publish to check for connected
connectedSubs sync.Cond // onConnect signal for subscribers and unsubscribers
connectedPubs sync.Cond // onConnect signal for publishers
}
type MQTTQoS byte
const (
QoSAtMostOnce = MQTTQoS(0)
QoSAtLeastOnce = MQTTQoS(1)
QoSExactlyOnce = MQTTQoS(2)
QoSUnknown = MQTTQoS(0xFF)
)
func ParseMQTTQoS(QoS string) MQTTQoS {
switch QoS {
case "QoSAtMostOnce", "0":
return QoSAtMostOnce
case "QoSAtLeastOnce", "1":
return QoSAtLeastOnce
case "QoSExactlyOnce", "2":
return QoSExactlyOnce
default:
return QoSUnknown
}
}
// GenMQTTClientID generates a random client id for mqtt
func GenMQTTClientID(prefix string) (string, error) {
r, err := CRAND.Int(CRAND.Reader, new(big.Int).SetInt64(100000))
if err != nil {
return "", fmt.Errorf("Failed to generate MQTT client ID: %v", err)
}
return prefix + r.String(), nil
}
// NewMQTTClient creates and connects an MQTT client that implements the
// PubSub interface
func NewMQTTClient(
brokerURI, user, pass string,
defaultQoS MQTTQoS,
defaultPersistence bool) (*MQTTClient, error) {
c := new(MQTTClient)
c.defaultQoS = defaultQoS
c.defaultPersistence = defaultPersistence
c.topics = make(map[string]byte)
c.connectedSubs.L = &c.lock
c.connectedPubs.L = c.publock.RLocker()
/* Generate random client id for MQTT */
clientID, err := GenMQTTClientID("client")
if err != nil {
return nil, err
}
/* Connect the MQTT connection */
opts := PahoMQTT.NewClientOptions()
if brokerURI == "" {
brokerURI = defaultBrokerURI
}
opts.AddBroker(brokerURI)
opts.SetClientID(clientID)
// http://www.hivemq.com/blog/mqtt-security-fundamentals-authentication-username-password:
// "The spec also states that a username without password is possible.
// It’s not possible to just send a password without username."
if len(user) > 0 {
// we do not allow absent passwords yet
opts.SetUsername(user).SetPassword(pass)
}
opts.SetAutoReconnect(AutoReconnect)
opts.SetOnConnectHandler(c.onConnect)
/* Create and start a client using the above ClientOptions */
c.mqtt = PahoMQTT.NewClient(opts)
if token := c.mqtt.Connect(); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
return c, nil
}
// NewMQTTWillClient creates and connects an MQTT client that implements the
// PubSub interface and sets a will message.
func NewMQTTWillClient(
brokerURI, user, pass string,
defaultQoS MQTTQoS,
defaultPersistence bool,
willTopic string,
willPayload []byte) (*MQTTClient, error) {
c := new(MQTTClient)
c.defaultQoS = defaultQoS
c.defaultPersistence = defaultPersistence
c.topics = make(map[string]byte)
c.connectedSubs.L = &c.lock
c.connectedPubs.L = c.publock.RLocker()
/* Generate random client id for MQTT */
clientID, err := GenMQTTClientID("client")
if err != nil {
return nil, err
}
/* Connect the MQTT connection */
opts := PahoMQTT.NewClientOptions()
if brokerURI == "" {
brokerURI = defaultBrokerURI
}
opts.AddBroker(brokerURI)
opts.SetClientID(clientID)
// http://www.hivemq.com/blog/mqtt-security-fundamentals-authentication-username-password:
// "The spec also states that a username without password is possible.
// It’s not possible to just send a password without username."
if len(user) > 0 {
// we do not allow absent passwords yet
opts.SetUsername(user).SetPassword(pass)
}
opts.SetAutoReconnect(AutoReconnect)
opts.SetOnConnectHandler(c.onConnect)
if willTopic != "" {
opts.SetBinaryWill(willTopic, willPayload, byte(defaultQoS), defaultPersistence)
}
/* Create and start a client using the above ClientOptions */
c.mqtt = PahoMQTT.NewClient(opts)
if token := c.mqtt.Connect(); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
return c, nil
}
// NewMQTTBridgeClient creates and connects an MQTT client that implements the
// PubSub interface. This special variant will indicate to the broker that you
// are operating as a MQTT bridge. In this case, you will not receive an echo
// of messages you publish to a topic you have subscribed to.
// Note, this is not an official MQTT feature and is only supported by a few
// brokers.
// Checkout https://github.com/mqtt/mqtt.github.io/wiki/bridge_protocol
// for more info.
func NewMQTTBridgeClient(
brokerURI, user, pass string,
defaultQoS MQTTQoS,
defaultPersistence bool) (*MQTTClient, error) {
c := new(MQTTClient)
c.defaultQoS = defaultQoS
c.defaultPersistence = defaultPersistence
c.topics = make(map[string]byte)
c.connectedSubs.L = &c.lock
c.connectedPubs.L = c.publock.RLocker()
/* Generate random client id for MQTT */
clientID, err := GenMQTTClientID("bridge")
if err != nil {
return nil, err
}
/* Connect the MQTT connection */
opts := PahoMQTT.NewClientOptions()
if brokerURI == "" {
brokerURI = defaultBrokerURI
}
opts.AddBroker(brokerURI)
opts.SetClientID(clientID)
// http://www.hivemq.com/blog/mqtt-security-fundamentals-authentication-username-password:
// "The spec also states that a username without password is possible.
// It’s not possible to just send a password without username."
if len(user) > 0 {
// we do not allow absent passwords yet
opts.SetUsername(user).SetPassword(pass)
}
opts.SetAutoReconnect(AutoReconnect)
opts.SetOnConnectHandler(c.onConnect)
opts.SetProtocolVersion(4 | 0x80) // indicate bridge
/* Create and start a client using the above ClientOptions */
c.mqtt = PahoMQTT.NewClient(opts)
if token := c.mqtt.Connect(); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
return c, nil
}
// NewMQTTWillBridgeClient creates and connects an MQTT client that implements
// the PubSub interface and sets a will message.
// This special variant will indicate to the broker that you are operating as
// a MQTT bridge. In this case, you will not receive an echo of messages you
// publish to a topic you have subscribed to.
// Note, this is not an official MQTT feature and is only supported by a few
// brokers.
// Checkout https://github.com/mqtt/mqtt.github.io/wiki/bridge_protocol
// for more info.
func NewMQTTWillBridgeClient(
brokerURI, user, pass string,
defaultQoS MQTTQoS,
defaultPersistence bool,
willTopic string,
willPayload []byte) (*MQTTClient, error) {
c := new(MQTTClient)
c.defaultQoS = defaultQoS
c.defaultPersistence = defaultPersistence
c.topics = make(map[string]byte)
c.connectedSubs.L = &c.lock
c.connectedPubs.L = c.publock.RLocker()
/* Generate random client id for MQTT */
clientID, err := GenMQTTClientID("bridge")
if err != nil {
return nil, err
}
/* Connect the MQTT connection */
opts := PahoMQTT.NewClientOptions()
if brokerURI == "" {
brokerURI = defaultBrokerURI
}
opts.AddBroker(brokerURI)
opts.SetClientID(clientID)
// http://www.hivemq.com/blog/mqtt-security-fundamentals-authentication-username-password:
// "The spec also states that a username without password is possible.
// It’s not possible to just send a password without username."
if len(user) > 0 {
// we do not allow absent passwords yet
opts.SetUsername(user).SetPassword(pass)
}
opts.SetAutoReconnect(AutoReconnect)
opts.SetOnConnectHandler(c.onConnect)
opts.SetProtocolVersion(4 | 0x80) // indicate bridge
if willTopic != "" {
opts.SetBinaryWill(willTopic, willPayload, byte(defaultQoS), defaultPersistence)
}
/* Create and start a client using the above ClientOptions */
c.mqtt = PahoMQTT.NewClient(opts)
if token := c.mqtt.Connect(); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
return c, nil
}
// onConnect will be called from within the Paho MQTT library when the
// the connection is made initially and on reconnect. The function within
// this library is to resubscribe to topic we originally subscribed to.
//
// This function is called from within the mqtt client and should not be
// capable of deadlocking, since this callback is called from it's own goroutine.
func (c *MQTTClient) onConnect(client PahoMQTT.Client) {
c.lock.Lock()
defer c.lock.Unlock()
c.publock.Lock()
defer c.publock.Unlock()
fmt.Println("onConnect")
if len(c.topics) > 0 {
// resubscribe - internal router should have kept original
// callbacks intact
if token := client.SubscribeMultiple(c.topics, nil); token.Wait() && token.Error() != nil {
return // don't signal that we have a connection yet
}
}
c.connectedSubs.Broadcast()
c.connectedPubs.Broadcast()
}
func (c *MQTTClient) Disconnect() {
c.lock.Lock()
defer c.lock.Unlock()
c.mqtt.Disconnect(disconnectWaitMS)
}
func (c *MQTTClient) Subscribe(topic string, callback func(topic string, payload []byte)) error {
c.lock.Lock()
defer c.lock.Unlock()
if !c.mqtt.IsConnected() {
c.connectedSubs.Wait()
}
token := c.mqtt.Subscribe(topic, byte(c.defaultQoS), func(client PahoMQTT.Client, msg PahoMQTT.Message) {
callback(msg.Topic(), msg.Payload())
})
if _, err := token.Wait(), token.Error(); err != nil {
return err
}
c.topics[topic] = byte(c.defaultQoS)
return nil
}
func (c *MQTTClient) Unsubscribe(topics ...string) error {
c.lock.Lock()
defer c.lock.Unlock()
if !c.mqtt.IsConnected() {
c.connectedSubs.Wait()
}
token := c.mqtt.Unsubscribe(topics...)
if _, err := token.Wait(), token.Error(); err != nil {
return err
}
for _, topic := range topics {
delete(c.topics, topic)
}
return nil
}
func (c *MQTTClient) Publish(topic string, payload interface{}) error {
c.publock.RLock()
defer c.publock.RUnlock()
if !c.mqtt.IsConnected() {
c.connectedPubs.Wait()
}
token := c.mqtt.Publish(topic, byte(c.defaultQoS), c.defaultPersistence, payload)
token.Wait()
return token.Error()
}