-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmqtt.client.go
More file actions
266 lines (228 loc) · 6.82 KB
/
mqtt.client.go
File metadata and controls
266 lines (228 loc) · 6.82 KB
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
package elio
import (
"encoding/hex"
"fmt"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
const (
defaultToSubscribe = 500 * time.Millisecond
defaultToPublish = 500 * time.Millisecond
defaultToquiesceMs uint = 1000
)
// MqttClient mqtt client
type MqttClient struct {
client mqtt.Client
qos byte
toSubscribe time.Duration
toPublish time.Duration
toquiesce uint
broker string
}
// NewMqttClient new mqtt client
func NewMqttClient(broker string, onConnect mqtt.OnConnectHandler) (m *MqttClient) {
if m = new(MqttClient); nil != m {
opts := mqtt.NewClientOptions()
m.broker = broker
opts.AddBroker(broker)
//opts.SetWriteTimeout(1 * time.Second)
//opts.SetClientID(*id)
//opts.SetUsername(*user)
//opts.SetPassword(*password)
//opts.SetCleanSession(*cleansess) // default false
//opts.SetAutoReconnect(true)
if nil != onConnect {
opts.SetOnConnectHandler(onConnect)
}
//if nil != onLost {
// opts.SetConnectionLostHandler(onLost)
//}
//if DebugEnabled() {
// mqtt.DEBUG = log.New(os.Stdout, "DEBUG ", 0)
// mqtt.WARN = log.New(os.Stdout, "WARN ", 0)
// mqtt.CRITICAL = log.New(os.Stdout, "CRITICAL ", 0)
// mqtt.ERROR = log.New(os.Stdout, "ERROR ", 0)
// }
m.client = mqtt.NewClient(opts)
m.qos = 1
m.toSubscribe = defaultToSubscribe
m.toPublish = defaultToPublish
m.toquiesce = defaultToquiesceMs
}
return m
}
// func onLost(c mqtt.Client, err error) {
// c.Disconnect(100)
// }
// String object to string
func (m *MqttClient) String() string {
return fmt.Sprintf("MqttClient::%p", m)
}
// Connect connect
func (m *MqttClient) Connect() (err error) {
if token := m.client.Connect(); token.Wait() && token.Error() != nil {
err = fmt.Errorf("connect failed with timeout:%v", m.toPublish)
AppError().Str(LogObject, m.String()).Err(token.Error()).
Msgf("failed to connect to %s", m.broker)
}
return err
}
// Close close
func (m *MqttClient) Close() {
m.client.Disconnect(m.toquiesce)
}
// SafeClose safe close
func (m *MqttClient) SafeClose() {
m.client.Disconnect(m.toquiesce)
m.client = nil
}
// IsConnected is connected
func (m *MqttClient) IsConnected() bool {
return m.client.IsConnected()
}
// Publish publish
// token.Wait(): Can also use '<-t.Done()' in releases > 1.2.0
func (m *MqttClient) Publish(topic string, retained bool, payload []byte) (err error) {
token := m.client.Publish(topic, m.qos, retained, payload)
go func() {
if false == token.WaitTimeout(m.toPublish) {
err = fmt.Errorf("failed to publish:%s retain:%v payload.len:%d", topic, retained, len(payload))
} else {
err = token.Error()
}
//_ = token.Wait()
//err = token.Error()
if nil != err {
AppError().Str(LogObject, m.String()).Err(err).
Msgf("failed to publish:%s with len:%d", topic, len(payload))
} else {
AppTrace().Str(LogObject, m.String()).Str(LogPayload, hex.Dump(payload)).
Msgf("succeed to publish:%s with len:%d", topic, len(payload))
}
}()
return nil
}
// Subscribe subscribe
func (m *MqttClient) Subscribe(topic string, callback mqtt.MessageHandler) (err error) {
token := m.client.Subscribe(topic, m.qos, callback)
_ = token.Wait()
err = token.Error()
if nil != err {
AppError().Str(LogObject, m.String()).Err(err).
Msgf("failed to subscribe:%s", topic)
} else {
AppTrace().Str(LogObject, m.String()).
Msgf("succeed to subscribe:%s", topic)
}
return err
}
// SubscribeMulti subscribe multi
func (m *MqttClient) SubscribeMulti(topics map[string]byte, callback mqtt.MessageHandler) (err error) {
token := m.client.SubscribeMultiple(topics, callback)
_ = token.Wait()
err = token.Error()
if nil != err {
AppError().Str(LogObject, m.String()).Err(err).
Msgf("failed to subscribemulti:%v", topics)
} else {
AppTrace().Str(LogObject, m.String()).
Msgf("succeed to subscribemulti:%v", topics)
}
return err
}
// Unsubscribe unsubscribe
func (m *MqttClient) Unsubscribe(topics ...string) (err error) {
if false == m.IsConnected() {
return nil
}
token := m.client.Unsubscribe(topics...)
_ = token.Wait()
err = token.Error()
if nil != err {
AppError().Str(LogObject, m.String()).Err(err).
Msgf("failed to unsubscribe:%s", topics)
} else {
AppTrace().Str(LogObject, m.String()).
Msgf("succeed to unsubscribe:%s", topics)
}
return err
}
// PublishNoWait publish no wait
func (m *MqttClient) PublishNoWait(topic string, retained bool, payload []byte) {
token := m.client.Publish(topic, m.qos, retained, payload)
go func() {
var err error
if false == token.WaitTimeout(m.toPublish) {
err = fmt.Errorf("publish:%s failed with timeout:%v", topic, m.toPublish)
} else {
err = token.Error()
}
if nil != err {
AppError().Str(LogObject, m.String()).Err(token.Error()).
Msgf("failed to publish:%s with len:%d", topic, len(payload))
m.Close()
} else {
AppTrace().Str(LogObject, m.String()).Str(LogPayload, hex.Dump(payload)).
Msgf("succeed to publish:%s with len:%d", topic, len(payload))
}
}()
}
// SubscribeNoWait subscribe async no wait
func (m *MqttClient) SubscribeNoWait(topic string, callback mqtt.MessageHandler) {
token := m.client.Subscribe(topic, m.qos, callback)
go func() {
var err error
if false == token.WaitTimeout(m.toSubscribe) {
err = fmt.Errorf("publish:%s failed with timeout:%v", topic, m.toPublish)
} else {
err = token.Error()
}
if nil != err {
//fmt.Printf("subscribe:%s failed with error:%s\n", topic, token.Error().Error())
AppError().Str(LogObject, m.String()).Err(token.Error()).
Msgf("failed to subscribe:%s", topic)
m.Close()
}
}()
}
// SubscribeMultiNoWait subscribe multi no wait
func (m *MqttClient) SubscribeMultiNoWait(topics map[string]byte, callback mqtt.MessageHandler) {
token := m.client.SubscribeMultiple(topics, callback)
go func() {
var err error
if false == token.WaitTimeout(m.toSubscribe) {
err = fmt.Errorf("publish:%v failed with timeout:%v", topics, m.toPublish)
} else {
err = token.Error()
}
if nil != err {
//fmt.Printf("subscribemulti:%s failed with error:%s\n", topic, token.Error().Error())
AppError().Str(LogObject, m.String()).Err(err).
Msgf("failed to subscribemulti:%v", topics)
m.Close()
}
}()
}
// UnsubscribeNoWait unsubscribe no wait
func (m *MqttClient) UnsubscribeNoWait(topics ...string) {
if false == m.IsConnected() {
AppDebug().Str(LogObject, m.String()).
Msgf("cannot unsubscribe:%v invalid connection", topics)
return
}
token := m.client.Unsubscribe(topics...)
go func() {
var err error
if false == token.WaitTimeout(m.toSubscribe) {
err = fmt.Errorf("unsubscribe:%v failed with timeout:%v", topics, m.toSubscribe)
} else {
err = token.Error()
}
if nil != err {
//fmt.Printf("unsubscribe:%s failed with error:%v\n", topic, err)
AppError().Str(LogObject, m.String()).Err(err).
Msgf("unsubscribe:%v failed", topics)
m.Close()
}
}()
}