-
Notifications
You must be signed in to change notification settings - Fork 238
/
Copy pathMQTTClient.cpp
554 lines (445 loc) · 13.5 KB
/
MQTTClient.cpp
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
#include "MQTTClient.h"
inline void lwmqtt_arduino_timer_set(void *ref, uint32_t timeout) {
// cast timer reference
auto t = (lwmqtt_arduino_timer_t *)ref;
// set timeout
t->timeout = timeout;
// set start
if (t->millis != nullptr) {
t->start = t->millis();
} else {
t->start = millis();
}
}
inline int32_t lwmqtt_arduino_timer_get(void *ref) {
// cast timer reference
auto t = (lwmqtt_arduino_timer_t *)ref;
// get now
uint32_t now;
if (t->millis != nullptr) {
now = t->millis();
} else {
now = millis();
}
// get difference (account for roll-overs)
uint32_t diff;
if (now < t->start) {
diff = UINT32_MAX - t->start + now;
} else {
diff = now - t->start;
}
// return relative time
if (diff > t->timeout) {
return -(diff - t->timeout);
} else {
return t->timeout - diff;
}
}
inline lwmqtt_err_t lwmqtt_arduino_network_read(void *ref, uint8_t *buffer, size_t len, size_t *read,
uint32_t timeout) {
// cast network reference
auto n = (lwmqtt_arduino_network_t *)ref;
// set timeout
uint32_t start = millis();
// reset counter
*read = 0;
// read until all bytes have been read or timeout has been reached
while (len > 0 && (millis() - start < timeout)) {
// read from connection
int r = n->client->read(buffer, len);
// handle read data
if (r > 0) {
buffer += r;
*read += r;
len -= r;
continue;
}
// wait/unblock for some time (RTOS based boards may otherwise fail since
// the wifi task cannot provide the data)
delay(1);
// otherwise check status
if (!n->client->connected()) {
return LWMQTT_NETWORK_FAILED_READ;
}
}
// check counter
if (*read == 0) {
return LWMQTT_NETWORK_TIMEOUT;
}
return LWMQTT_SUCCESS;
}
inline lwmqtt_err_t lwmqtt_arduino_network_write(void *ref, uint8_t *buffer, size_t len, size_t *sent,
uint32_t /*timeout*/) {
// cast network reference
auto n = (lwmqtt_arduino_network_t *)ref;
// write bytes
size_t partial_written = 0;
size_t written = 0;
while (true) {
if (len - written > n->segmentLength) {
partial_written = n->client->write(buffer + written, n->segmentLength);
written += partial_written;
}
else {
partial_written = n->client->write(buffer + written, len - written);
written += partial_written;
break;
}
delay(n->writeDelayMs);
if (partial_written <= 0) {
return LWMQTT_NETWORK_FAILED_WRITE;
}
}
*sent = written;
if (*sent <= 0) {
return LWMQTT_NETWORK_FAILED_WRITE;
}
return LWMQTT_SUCCESS;
}
static void MQTTClientHandler(lwmqtt_client_t * /*client*/, void *ref, lwmqtt_string_t topic,
lwmqtt_message_t message) {
// get callback
auto cb = (MQTTClientCallback *)ref;
// null terminate topic
char terminated_topic[topic.len + 1];
memcpy(terminated_topic, topic.data, topic.len);
terminated_topic[topic.len] = '\0';
// null terminate payload if available
if (message.payload != nullptr) {
message.payload[message.payload_len] = '\0';
}
// call the advanced callback and return if available
if (cb->advanced != nullptr) {
cb->advanced(cb->client, terminated_topic, (char *)message.payload, (int)message.payload_len);
return;
}
#if MQTT_HAS_FUNCTIONAL
if (cb->functionAdvanced != nullptr) {
cb->functionAdvanced(cb->client, terminated_topic, (char *)message.payload, (int)message.payload_len);
return;
}
#endif
// return if simple callback is not set
#if MQTT_HAS_FUNCTIONAL
if (cb->simple == nullptr && cb->functionSimple == nullptr) {
return;
}
#else
if (cb->simple == nullptr) {
return;
}
#endif
// create topic string
String str_topic = String(terminated_topic);
// create payload string
String str_payload;
if (message.payload != nullptr) {
str_payload = String((const char *)message.payload);
}
// call simple callback
#if MQTT_HAS_FUNCTIONAL
if (cb->functionSimple != nullptr) {
cb->functionSimple(str_topic, str_payload);
} else {
cb->simple(str_topic, str_payload);
}
#else
cb->simple(str_topic, str_payload);
#endif
}
MQTTClient::MQTTClient(int readBufSize, int writeBufSize) {
// allocate buffers
this->readBufSize = (size_t)readBufSize;
this->writeBufSize = (size_t)writeBufSize;
this->readBuf = (uint8_t *)malloc((size_t)readBufSize + 1);
this->writeBuf = (uint8_t *)malloc((size_t)writeBufSize);
}
MQTTClient::~MQTTClient() {
// free will
this->clearWill();
// free hostname
if (this->hostname != nullptr) {
free((void *)this->hostname);
}
// free buffers
free(this->readBuf);
free(this->writeBuf);
}
void MQTTClient::begin(Client &_client) {
// set client
this->netClient = &_client;
// initialize client
lwmqtt_init(&this->client, this->writeBuf, this->writeBufSize, this->readBuf, this->readBufSize);
// set timers
lwmqtt_set_timers(&this->client, &this->timer1, &this->timer2, lwmqtt_arduino_timer_set, lwmqtt_arduino_timer_get);
// set network
lwmqtt_set_network(&this->client, &this->network, lwmqtt_arduino_network_read, lwmqtt_arduino_network_write);
// set callback
lwmqtt_set_callback(&this->client, (void *)&this->callback, MQTTClientHandler);
this->network.segmentLength = this->_segmentLength;
this->network.writeDelayMs = this->_writeDelayMs;
}
void MQTTClient::onMessage(MQTTClientCallbackSimple cb) {
// set callback
this->callback.client = this;
this->callback.simple = cb;
this->callback.advanced = nullptr;
#if MQTT_HAS_FUNCTIONAL
this->callback.functionSimple = nullptr;
this->callback.functionAdvanced = nullptr;
#endif
}
void MQTTClient::onMessageAdvanced(MQTTClientCallbackAdvanced cb) {
// set callback
this->callback.client = this;
this->callback.simple = nullptr;
this->callback.advanced = cb;
#if MQTT_HAS_FUNCTIONAL
this->callback.functionSimple = nullptr;
this->callback.functionAdvanced = nullptr;
#endif
}
#if MQTT_HAS_FUNCTIONAL
void MQTTClient::onMessage(MQTTClientCallbackSimpleFunction cb) {
// set callback
this->callback.client = this;
this->callback.simple = nullptr;
this->callback.functionSimple = cb;
this->callback.advanced = nullptr;
this->callback.functionAdvanced = nullptr;
}
void MQTTClient::onMessageAdvanced(MQTTClientCallbackAdvancedFunction cb) {
// set callback
this->callback.client = this;
this->callback.simple = nullptr;
this->callback.functionSimple = nullptr;
this->callback.advanced = nullptr;
this->callback.functionAdvanced = cb;
}
#endif
void MQTTClient::setClockSource(MQTTClientClockSource cb) {
this->timer1.millis = cb;
this->timer2.millis = cb;
}
void MQTTClient::setHost(IPAddress _address, int _port) {
// set address and port
this->address = _address;
this->port = _port;
}
void MQTTClient::setHost(const char _hostname[], int _port) {
// free hostname if set
if (this->hostname != nullptr) {
free((void *)this->hostname);
}
// set hostname and port
this->hostname = strdup(_hostname);
this->port = _port;
}
void MQTTClient::setWill(const char topic[], const char payload[], bool retained, int qos) {
// return if topic is missing
if (topic == nullptr || strlen(topic) == 0) {
return;
}
// clear existing will
this->clearWill();
// allocate will
this->will = (lwmqtt_will_t *)malloc(sizeof(lwmqtt_will_t));
memset(this->will, 0, sizeof(lwmqtt_will_t));
// set topic
this->will->topic = lwmqtt_string(strdup(topic));
// set payload if available
if (payload != nullptr && strlen(payload) > 0) {
this->will->payload = lwmqtt_string(strdup(payload));
}
// set flags
this->will->retained = retained;
this->will->qos = (lwmqtt_qos_t)qos;
}
void MQTTClient::clearWill() {
// return if not set
if (this->will == nullptr) {
return;
}
// free payload if set
if (this->will->payload.len > 0) {
free(this->will->payload.data);
}
// free topic if set
if (this->will->topic.len > 0) {
free(this->will->topic.data);
}
// free will
free(this->will);
this->will = nullptr;
}
void MQTTClient::setKeepAlive(int _keepAlive) { this->keepAlive = _keepAlive; }
void MQTTClient::setCleanSession(bool _cleanSession) { this->cleanSession = _cleanSession; }
void MQTTClient::setTimeout(int _timeout) { this->timeout = _timeout; }
void MQTTClient::setNetworkSegmentedWrite(size_t segmentLength, uint32_t writeDelayMs) {
this->_segmentLength = segmentLength;
this->_writeDelayMs = writeDelayMs;
this->network.segmentLength = this->_segmentLength;
this->network.writeDelayMs = this->_writeDelayMs;
}
void MQTTClient::dropOverflow(bool enabled) {
// configure drop overflow
lwmqtt_drop_overflow(&this->client, enabled, &this->_droppedMessages);
}
bool MQTTClient::connect(const char clientID[], const char username[], const char password[], bool skip) {
// close left open connection if still connected
if (!skip && this->connected()) {
this->close();
}
// save client
this->network.client = this->netClient;
// connect to host
if (!skip) {
int ret;
if (this->hostname != nullptr) {
ret = this->netClient->connect(this->hostname, (uint16_t)this->port);
} else {
ret = this->netClient->connect(this->address, (uint16_t)this->port);
}
if (ret <= 0) {
this->_lastError = LWMQTT_NETWORK_FAILED_CONNECT;
return false;
}
}
// prepare options
lwmqtt_connect_options_t options = lwmqtt_default_connect_options;
options.keep_alive = this->keepAlive;
options.clean_session = this->cleanSession;
options.client_id = lwmqtt_string(clientID);
// set username and password if available
if (username != nullptr) {
options.username = lwmqtt_string(username);
}
if (password != nullptr) {
options.password = lwmqtt_string(password);
}
// connect to broker
this->_lastError = lwmqtt_connect(&this->client, &options, this->will, this->timeout);
// copy return code
this->_returnCode = options.return_code;
// handle error
if (this->_lastError != LWMQTT_SUCCESS) {
// close connection
this->close();
return false;
}
// copy session present flag
this->_sessionPresent = options.session_present;
// set flag
this->_connected = true;
return true;
}
bool MQTTClient::publish(const char topic[], const char payload[], int length, bool retained, int qos) {
// return immediately if not connected
if (!this->connected()) {
return false;
}
// prepare message
lwmqtt_message_t message = lwmqtt_default_message;
message.payload = (uint8_t *)payload;
message.payload_len = (size_t)length;
message.retained = retained;
message.qos = lwmqtt_qos_t(qos);
// prepare options
lwmqtt_publish_options_t options = lwmqtt_default_publish_options;
// set duplicate packet id if available
if (this->nextDupPacketID > 0) {
options.dup_id = &this->nextDupPacketID;
this->nextDupPacketID = 0;
}
// publish message
this->_lastError = lwmqtt_publish(&this->client, &options, lwmqtt_string(topic), message, this->timeout);
if (this->_lastError != LWMQTT_SUCCESS) {
// close connection
this->close();
return false;
}
return true;
}
uint16_t MQTTClient::lastPacketID() {
// get last packet id from client
return this->client.last_packet_id;
}
void MQTTClient::prepareDuplicate(uint16_t packetID) {
// set next duplicate packet id
this->nextDupPacketID = packetID;
}
bool MQTTClient::subscribe(const char topic[], int qos) {
// return immediately if not connected
if (!this->connected()) {
return false;
}
// subscribe to topic
this->_lastError = lwmqtt_subscribe_one(&this->client, lwmqtt_string(topic), (lwmqtt_qos_t)qos, this->timeout);
if (this->_lastError != LWMQTT_SUCCESS) {
// close connection
this->close();
return false;
}
return true;
}
bool MQTTClient::unsubscribe(const char topic[]) {
// return immediately if not connected
if (!this->connected()) {
return false;
}
// unsubscribe from topic
this->_lastError = lwmqtt_unsubscribe_one(&this->client, lwmqtt_string(topic), this->timeout);
if (this->_lastError != LWMQTT_SUCCESS) {
// close connection
this->close();
return false;
}
return true;
}
bool MQTTClient::loop() {
// return immediately if not connected
if (!this->connected()) {
return false;
}
// get available bytes on the network
int available = this->netClient->available();
// yield if data is available
if (available > 0) {
this->_lastError = lwmqtt_yield(&this->client, available, this->timeout);
if (this->_lastError != LWMQTT_SUCCESS) {
// close connection
this->close();
return false;
}
}
// keep the connection alive
this->_lastError = lwmqtt_keep_alive(&this->client, this->timeout);
if (this->_lastError != LWMQTT_SUCCESS) {
// close connection
this->close();
return false;
}
return true;
}
bool MQTTClient::connected() {
// a client is connected if the network is connected, a client is available and
// the connection has been properly initiated
return this->netClient != nullptr && this->netClient->connected() == 1 && this->_connected;
}
bool MQTTClient::disconnect() {
// return immediately if not connected anymore
if (!this->connected()) {
return false;
}
// cleanly disconnect
this->_lastError = lwmqtt_disconnect(&this->client, this->timeout);
// close
this->close();
return this->_lastError == LWMQTT_SUCCESS;
}
void MQTTClient::close() {
// set flag
this->_connected = false;
// close network
this->netClient->stop();
}