-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmqtt.go
287 lines (248 loc) · 5.78 KB
/
mqtt.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
package mqttpubsub
import (
"bytes"
"context"
"encoding/gob"
"errors"
"github.com/google/uuid"
"gocloud.dev/gcerrors"
"gocloud.dev/pubsub/driver"
"strings"
"sync"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
const (
defaultTimeout = 2 * time.Second
defaultQOS = 0
defaultPubID = "go-cloud-publisher"
defaultSubID = "go-cloud-subscriber"
delimiter = "-"
)
var (
errNoURLEnv = errors.New("mqttpubsub: no url env provided ")
errInvalidMessage = errors.New("mqttpubsub: invalid or empty message")
errConnRequired = errors.New("mqttpubsub: mqtt connection is required")
errStillConnected = errors.New("mqttpubsub: still connected. Kill all processes manually")
errMQTTDisconnected = errors.New("mqttpubsub: disconnected")
)
type (
Subscriber interface {
Subscribe(topic string, handler mqtt.MessageHandler, qos *byte) error
UnSubscribe(topic string) error
Close() error
}
Publisher interface {
Publish(topic string, payload interface{}, qos *byte) error
Stop() error
}
subscriber struct {
subConnect mqtt.Client
qos byte
timeout time.Duration
}
publisher struct {
pubConnect mqtt.Client
qos byte
timeout time.Duration
isStopped bool
wg *sync.WaitGroup
}
)
func NewSubscriber(cli mqtt.Client, qos byte, timeout time.Duration) Subscriber {
return &subscriber{
subConnect: cli,
qos: qos,
timeout: timeout,
}
}
func NewPublisher(cli mqtt.Client, qos byte, timeout time.Duration) Publisher {
return &publisher{
pubConnect: cli,
qos: qos,
timeout: timeout,
wg: new(sync.WaitGroup),
}
}
func defaultSubClient(url string) (_ Subscriber, err error) {
if url == "" {
return nil, errNoURLEnv
}
var subConnect mqtt.Client
subConnect, err = makeDefaultConnect(defaultSubID, url)
if err != nil {
return nil, err
}
return &subscriber{
subConnect: subConnect,
timeout: defaultTimeout,
qos: defaultQOS,
}, nil
}
func defaultPubClient(url string) (_ Publisher, err error) {
if url == "" {
return nil, errNoURLEnv
}
var pubConnect mqtt.Client
pubConnect, err = makeDefaultConnect(defaultPubID, url)
if err != nil {
return nil, err
}
return &publisher{
pubConnect: pubConnect,
wg: new(sync.WaitGroup),
timeout: defaultTimeout,
qos: defaultQOS,
}, nil
}
func makeDefaultConnect(clientID, url string) (mqtt.Client, error) {
connID := uuid.New().String()
opts := mqtt.NewClientOptions()
opts = opts.AddBroker(url)
opts.ClientID = clientID + delimiter + connID
mqttClient := mqtt.NewClient(opts)
token := mqttClient.Connect()
token.Wait()
if token.Error() != nil {
return nil, token.Error()
}
if !mqttClient.IsConnectionOpen() {
return nil, errMQTTDisconnected
}
return mqttClient, nil
}
// qos is optional
func (p *publisher) Publish(topic string, payload interface{}, qos *byte) error {
if p.isStopped {
return nil
}
var q = p.qos
if qos != nil {
q = *qos
}
token := p.pubConnect.Publish(topic, q, false, payload)
if token.WaitTimeout(p.timeout) && token.Error() != nil {
return token.Error()
}
return nil
}
func (p *publisher) Stop() error {
if p.pubConnect == nil {
return nil
}
if p.isStopped {
return nil
}
p.isStopped = true
p.wg.Wait()
p.pubConnect.Disconnect(0)
if p.pubConnect.IsConnected() {
return errStillConnected
}
return nil
}
// qos is optional
func (s *subscriber) Subscribe(topic string, handler mqtt.MessageHandler, qos *byte) error {
if !s.subConnect.IsConnected() {
return errMQTTDisconnected
}
topic = strings.TrimSuffix(strings.TrimPrefix(topic, "/"), "/")
var q = s.qos
if qos != nil {
q = *qos
}
token := s.subConnect.Subscribe(
topic,
q,
handler,
)
if token.WaitTimeout(s.timeout) && token.Error() != nil {
return token.Error()
}
return nil
}
func (s *subscriber) UnSubscribe(topic string) error {
if !s.subConnect.IsConnected() {
return errMQTTDisconnected
}
token := s.subConnect.Unsubscribe(topic)
if token.WaitTimeout(s.timeout) && token.Error() != nil {
return token.Error()
}
return nil
}
func (s *subscriber) Close() error {
if s.subConnect == nil {
return nil
}
if !s.subConnect.IsConnected() {
return nil
}
s.subConnect.Disconnect(0)
if s.subConnect.IsConnected() {
return errStillConnected
}
return nil
}
// Convert MQTT msgs to *driver.Message.
func decode(msg mqtt.Message) (*driver.Message, error) {
if msg == nil {
return nil, errInvalidMessage
}
var dm driver.Message
if err := decodeMessage(msg.Payload(), &dm); err != nil {
return nil, err
}
dm.AckID = msg.MessageID() // uint16
dm.AsFunc = messageAsFunc(msg)
return &dm, nil
}
func messageAsFunc(msg mqtt.Message) func(interface{}) bool {
return func(i interface{}) bool {
p, ok := i.(*mqtt.Message)
if !ok {
return false
}
*p = msg
return true
}
}
func encodeMessage(dm *driver.Message) ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
if len(dm.Metadata) == 0 {
return dm.Body, nil
}
if err := enc.Encode(dm.Metadata); err != nil {
return nil, err
}
if err := enc.Encode(dm.Body); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func decodeMessage(data []byte, dm *driver.Message) error {
buf := bytes.NewBuffer(data)
dec := gob.NewDecoder(buf)
if err := dec.Decode(&dm.Metadata); err != nil {
dm.Metadata = nil
dm.Body = data
return nil
}
return dec.Decode(&dm.Body)
}
func whichError(err error) gcerrors.ErrorCode {
switch err {
case nil:
return gcerrors.OK
case context.Canceled:
return gcerrors.Canceled
case errMQTTDisconnected, errConnRequired:
return gcerrors.NotFound
case mqtt.ErrInvalidTopicEmptyString, mqtt.ErrInvalidQos, mqtt.ErrInvalidTopicMultilevel, errInvalidMessage:
return gcerrors.FailedPrecondition
case errStillConnected:
return gcerrors.Internal
}
return gcerrors.Unknown
}