PubSubClient.cpp 21.6 KB
Newer Older
1
2
/*

Eric Duminil's avatar
Eric Duminil committed
3
4
5
6
 PubSubClient.cpp - A simple client for MQTT.
 Nick O'Leary
 http://knolleary.net
 */
7
8
9
10
11

#include "PubSubClient.h"
#include "Arduino.h"

PubSubClient::PubSubClient() {
Eric Duminil's avatar
Eric Duminil committed
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
  this->_state = MQTT_DISCONNECTED;
  this->_client = NULL;
  this->stream = NULL;
  setCallback(NULL);
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}

PubSubClient::PubSubClient(Client &client) {
  this->_state = MQTT_DISCONNECTED;
  setClient(client);
  this->stream = NULL;
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}

PubSubClient::PubSubClient(IPAddress addr, uint16_t port, Client &client) {
  this->_state = MQTT_DISCONNECTED;
  setServer(addr, port);
  setClient(client);
  this->stream = NULL;
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}
PubSubClient::PubSubClient(IPAddress addr, uint16_t port, Client &client, Stream &stream) {
  this->_state = MQTT_DISCONNECTED;
  setServer(addr, port);
  setClient(client);
  setStream(stream);
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}
PubSubClient::PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client) {
  this->_state = MQTT_DISCONNECTED;
  setServer(addr, port);
  setCallback(callback);
  setClient(client);
  this->stream = NULL;
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}
PubSubClient::PubSubClient(IPAddress addr, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client, Stream &stream) {
  this->_state = MQTT_DISCONNECTED;
  setServer(addr, port);
  setCallback(callback);
  setClient(client);
  setStream(stream);
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}

PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, Client &client) {
  this->_state = MQTT_DISCONNECTED;
  setServer(ip, port);
  setClient(client);
  this->stream = NULL;
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}
PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, Client &client, Stream &stream) {
  this->_state = MQTT_DISCONNECTED;
  setServer(ip, port);
  setClient(client);
  setStream(stream);
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}
PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client) {
  this->_state = MQTT_DISCONNECTED;
  setServer(ip, port);
  setCallback(callback);
  setClient(client);
  this->stream = NULL;
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}
PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client, Stream &stream) {
  this->_state = MQTT_DISCONNECTED;
  setServer(ip, port);
  setCallback(callback);
  setClient(client);
  setStream(stream);
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}

PubSubClient::PubSubClient(const char *domain, uint16_t port, Client &client) {
  this->_state = MQTT_DISCONNECTED;
  setServer(domain, port);
  setClient(client);
  this->stream = NULL;
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}
PubSubClient::PubSubClient(const char *domain, uint16_t port, Client &client, Stream &stream) {
  this->_state = MQTT_DISCONNECTED;
  setServer(domain, port);
  setClient(client);
  setStream(stream);
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}
PubSubClient::PubSubClient(const char *domain, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client) {
  this->_state = MQTT_DISCONNECTED;
  setServer(domain, port);
  setCallback(callback);
  setClient(client);
  this->stream = NULL;
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
}
PubSubClient::PubSubClient(const char *domain, uint16_t port, MQTT_CALLBACK_SIGNATURE, Client &client, Stream &stream) {
  this->_state = MQTT_DISCONNECTED;
  setServer(domain, port);
  setCallback(callback);
  setClient(client);
  setStream(stream);
  this->bufferSize = 0;
  setBufferSize(MQTT_MAX_PACKET_SIZE);
  setKeepAlive(MQTT_KEEPALIVE);
  setSocketTimeout(MQTT_SOCKET_TIMEOUT);
159
160
161
162
163
164
165
}

PubSubClient::~PubSubClient() {
  free(this->buffer);
}

boolean PubSubClient::connect(const char *id) {
Eric Duminil's avatar
Eric Duminil committed
166
  return connect(id, NULL, NULL, 0, 0, 0, 0, 1);
167
168
169
}

boolean PubSubClient::connect(const char *id, const char *user, const char *pass) {
Eric Duminil's avatar
Eric Duminil committed
170
  return connect(id, user, pass, 0, 0, 0, 0, 1);
171
172
}

Eric Duminil's avatar
Eric Duminil committed
173
174
175
boolean PubSubClient::connect(const char *id, const char *willTopic, uint8_t willQos, boolean willRetain,
    const char *willMessage) {
  return connect(id, NULL, NULL, willTopic, willQos, willRetain, willMessage, 1);
176
177
}

Eric Duminil's avatar
Eric Duminil committed
178
179
180
boolean PubSubClient::connect(const char *id, const char *user, const char *pass, const char *willTopic,
    uint8_t willQos, boolean willRetain, const char *willMessage) {
  return connect(id, user, pass, willTopic, willQos, willRetain, willMessage, 1);
181
182
}

Eric Duminil's avatar
Eric Duminil committed
183
184
185
186
boolean PubSubClient::connect(const char *id, const char *user, const char *pass, const char *willTopic,
    uint8_t willQos, boolean willRetain, const char *willMessage, boolean cleanSession) {
  if (!connected()) {
    int result = 0;
187

Eric Duminil's avatar
Eric Duminil committed
188
189
190
191
192
193
194
195
196
    if (_client->connected()) {
      result = 1;
    } else {
      if (domain != NULL) {
        result = _client->connect(this->domain, this->port);
      } else {
        result = _client->connect(this->ip, this->port);
      }
    }
197

Eric Duminil's avatar
Eric Duminil committed
198
199
200
201
202
    if (result == 1) {
      nextMsgId = 1;
      // Leave room in the buffer for header and variable length field
      uint16_t length = MQTT_MAX_HEADER_SIZE;
      unsigned int j;
203
204
205
206
207

#if MQTT_VERSION == MQTT_VERSION_3_1
            uint8_t d[9] = {0x00,0x06,'M','Q','I','s','d','p', MQTT_VERSION};
#define MQTT_HEADER_VERSION_LENGTH 9
#elif MQTT_VERSION == MQTT_VERSION_3_1_1
Eric Duminil's avatar
Eric Duminil committed
208
      uint8_t d[7] = { 0x00, 0x04, 'M', 'Q', 'T', 'T', MQTT_VERSION };
209
210
#define MQTT_HEADER_VERSION_LENGTH 7
#endif
Eric Duminil's avatar
Eric Duminil committed
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
      for (j = 0; j < MQTT_HEADER_VERSION_LENGTH; j++) {
        this->buffer[length++] = d[j];
      }

      uint8_t v;
      if (willTopic) {
        v = 0x04 | (willQos << 3) | (willRetain << 5);
      } else {
        v = 0x00;
      }
      if (cleanSession) {
        v = v | 0x02;
      }

      if (user != NULL) {
        v = v | 0x80;

        if (pass != NULL) {
          v = v | (0x80 >> 1);
        }
      }
      this->buffer[length++] = v;

      this->buffer[length++] = ((this->keepAlive) >> 8);
      this->buffer[length++] = ((this->keepAlive) & 0xFF);

      CHECK_STRING_LENGTH(length, id)
      length = writeString(id, this->buffer, length);
      if (willTopic) {
        CHECK_STRING_LENGTH(length, willTopic)
        length = writeString(willTopic, this->buffer, length);
        CHECK_STRING_LENGTH(length, willMessage)
        length = writeString(willMessage, this->buffer, length);
      }

      if (user != NULL) {
        CHECK_STRING_LENGTH(length, user)
        length = writeString(user, this->buffer, length);
        if (pass != NULL) {
          CHECK_STRING_LENGTH(length, pass)
          length = writeString(pass, this->buffer, length);
        }
      }
254

Eric Duminil's avatar
Eric Duminil committed
255
      write(MQTTCONNECT, this->buffer, length - MQTT_MAX_HEADER_SIZE);
256

Eric Duminil's avatar
Eric Duminil committed
257
      lastInActivity = lastOutActivity = millis();
258

Eric Duminil's avatar
Eric Duminil committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
      while (!_client->available()) {
        unsigned long t = millis();
        if (t - lastInActivity >= ((int32_t) this->socketTimeout * 1000UL)) {
          _state = MQTT_CONNECTION_TIMEOUT;
          _client->stop();
          return false;
        }
      }
      uint8_t llen;
      uint32_t len = readPacket(&llen);

      if (len == 4) {
        if (buffer[3] == 0) {
          lastInActivity = millis();
          pingOutstanding = false;
          _state = MQTT_CONNECTED;
          return true;
276
        } else {
Eric Duminil's avatar
Eric Duminil committed
277
          _state = buffer[3];
278
        }
Eric Duminil's avatar
Eric Duminil committed
279
280
281
282
      }
      _client->stop();
    } else {
      _state = MQTT_CONNECT_FAILED;
283
    }
Eric Duminil's avatar
Eric Duminil committed
284
285
286
    return false;
  }
  return true;
287
288
289
}

// reads a byte into result
Eric Duminil's avatar
Eric Duminil committed
290
291
292
293
294
295
296
297
298
299
300
boolean PubSubClient::readByte(uint8_t *result) {
  uint32_t previousMillis = millis();
  while (!_client->available()) {
    yield();
    uint32_t currentMillis = millis();
    if (currentMillis - previousMillis >= ((int32_t) this->socketTimeout * 1000)) {
      return false;
    }
  }
  *result = _client->read();
  return true;
301
302
303
}

// reads a byte into result[*index] and increments index
Eric Duminil's avatar
Eric Duminil committed
304
boolean PubSubClient::readByte(uint8_t *result, uint16_t *index) {
305
  uint16_t current_index = *index;
Eric Duminil's avatar
Eric Duminil committed
306
307
  uint8_t *write_address = &(result[current_index]);
  if (readByte(write_address)) {
308
309
310
311
312
313
    *index = current_index + 1;
    return true;
  }
  return false;
}

Eric Duminil's avatar
Eric Duminil committed
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
uint32_t PubSubClient::readPacket(uint8_t *lengthLength) {
  uint16_t len = 0;
  if (!readByte(this->buffer, &len))
    return 0;
  bool isPublish = (this->buffer[0] & 0xF0) == MQTTPUBLISH;
  uint32_t multiplier = 1;
  uint32_t length = 0;
  uint8_t digit = 0;
  uint16_t skip = 0;
  uint32_t start = 0;

  do {
    if (len == 5) {
      // Invalid remaining length encoding - kill the connection
      _state = MQTT_DISCONNECTED;
      _client->stop();
      return 0;
331
    }
Eric Duminil's avatar
Eric Duminil committed
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
    if (!readByte(&digit))
      return 0;
    this->buffer[len++] = digit;
    length += (digit & 127) * multiplier;
    multiplier <<= 7; //multiplier *= 128
  } while ((digit & 128) != 0);
  *lengthLength = len - 1;

  if (isPublish) {
    // Read in topic length to calculate bytes to skip over for Stream writing
    if (!readByte(this->buffer, &len))
      return 0;
    if (!readByte(this->buffer, &len))
      return 0;
    skip = (this->buffer[*lengthLength + 1] << 8) + this->buffer[*lengthLength + 2];
    start = 2;
    if (this->buffer[0] & MQTTQOS1) {
      // skip message id
      skip += 2;
    }
  }
  uint32_t idx = len;

  for (uint32_t i = start; i < length; i++) {
    if (!readByte(&digit))
      return 0;
    if (this->stream) {
      if (isPublish && idx - *lengthLength - 2 > skip) {
        this->stream->write(digit);
      }
362
363
    }

Eric Duminil's avatar
Eric Duminil committed
364
365
366
    if (len < this->bufferSize) {
      this->buffer[len] = digit;
      len++;
367
    }
Eric Duminil's avatar
Eric Duminil committed
368
369
370
371
372
373
374
    idx++;
  }

  if (!this->stream && idx > this->bufferSize) {
    len = 0; // This will cause the packet to be ignored.
  }
  return len;
375
376
377
}

boolean PubSubClient::loop() {
Eric Duminil's avatar
Eric Duminil committed
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
  if (connected()) {
    unsigned long t = millis();
    if ((t - lastInActivity > this->keepAlive * 1000UL) || (t - lastOutActivity > this->keepAlive * 1000UL)) {
      if (pingOutstanding) {
        this->_state = MQTT_CONNECTION_TIMEOUT;
        _client->stop();
        return false;
      } else {
        this->buffer[0] = MQTTPINGREQ;
        this->buffer[1] = 0;
        _client->write(this->buffer, 2);
        lastOutActivity = t;
        lastInActivity = t;
        pingOutstanding = true;
      }
    }
    if (_client->available()) {
      uint8_t llen;
      uint16_t len = readPacket(&llen);
      uint16_t msgId = 0;
      uint8_t *payload;
      if (len > 0) {
        lastInActivity = t;
        uint8_t type = this->buffer[0] & 0xF0;
        if (type == MQTTPUBLISH) {
          if (callback) {
            uint16_t tl = (this->buffer[llen + 1] << 8) + this->buffer[llen + 2]; /* topic length in bytes */
            memmove(this->buffer + llen + 2, this->buffer + llen + 3, tl); /* move topic inside buffer 1 byte to front */
            this->buffer[llen + 2 + tl] = 0; /* end the topic as a 'C' string with \x00 */
            char *topic = (char*) this->buffer + llen + 2;
            // msgId only present for QOS>0
            if ((this->buffer[0] & 0x06) == MQTTQOS1) {
              msgId = (this->buffer[llen + 3 + tl] << 8) + this->buffer[llen + 3 + tl + 1];
              payload = this->buffer + llen + 3 + tl + 2;
              callback(topic, payload, len - llen - 3 - tl - 2);

              this->buffer[0] = MQTTPUBACK;
              this->buffer[1] = 2;
              this->buffer[2] = (msgId >> 8);
              this->buffer[3] = (msgId & 0xFF);
              _client->write(this->buffer, 4);
              lastOutActivity = t;

421
            } else {
Eric Duminil's avatar
Eric Duminil committed
422
423
              payload = this->buffer + llen + 3 + tl;
              callback(topic, payload, len - llen - 3 - tl);
424
            }
Eric Duminil's avatar
Eric Duminil committed
425
426
427
428
429
430
431
          }
        } else if (type == MQTTPINGREQ) {
          this->buffer[0] = MQTTPINGRESP;
          this->buffer[1] = 0;
          _client->write(this->buffer, 2);
        } else if (type == MQTTPINGRESP) {
          pingOutstanding = false;
432
        }
Eric Duminil's avatar
Eric Duminil committed
433
434
435
436
      } else if (!connected()) {
        // readPacket has closed the connection
        return false;
      }
437
    }
Eric Duminil's avatar
Eric Duminil committed
438
439
440
    return true;
  }
  return false;
441
442
}

Eric Duminil's avatar
Eric Duminil committed
443
444
boolean PubSubClient::publish(const char *topic, const char *payload) {
  return publish(topic, (const uint8_t*) payload, payload ? strnlen(payload, this->bufferSize) : 0, false);
445
446
}

Eric Duminil's avatar
Eric Duminil committed
447
448
boolean PubSubClient::publish(const char *topic, const char *payload, boolean retained) {
  return publish(topic, (const uint8_t*) payload, payload ? strnlen(payload, this->bufferSize) : 0, retained);
449
450
}

Eric Duminil's avatar
Eric Duminil committed
451
452
boolean PubSubClient::publish(const char *topic, const uint8_t *payload, unsigned int plength) {
  return publish(topic, payload, plength, false);
453
454
}

Eric Duminil's avatar
Eric Duminil committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
boolean PubSubClient::publish(const char *topic, const uint8_t *payload, unsigned int plength, boolean retained) {
  if (connected()) {
    if (this->bufferSize < MQTT_MAX_HEADER_SIZE + 2 + strnlen(topic, this->bufferSize) + plength) {
      // Too long
      return false;
    }
    // Leave room in the buffer for header and variable length field
    uint16_t length = MQTT_MAX_HEADER_SIZE;
    length = writeString(topic, this->buffer, length);

    // Add payload
    uint16_t i;
    for (i = 0; i < plength; i++) {
      this->buffer[length++] = payload[i];
    }
470

Eric Duminil's avatar
Eric Duminil committed
471
472
473
474
    // Write the header
    uint8_t header = MQTTPUBLISH;
    if (retained) {
      header |= 1;
475
    }
Eric Duminil's avatar
Eric Duminil committed
476
477
478
    return write(header, this->buffer, length - MQTT_MAX_HEADER_SIZE);
  }
  return false;
479
480
}

Eric Duminil's avatar
Eric Duminil committed
481
482
boolean PubSubClient::publish_P(const char *topic, const char *payload, boolean retained) {
  return publish_P(topic, (const uint8_t*) payload, payload ? strnlen(payload, this->bufferSize) : 0, retained);
483
484
}

Eric Duminil's avatar
Eric Duminil committed
485
486
487
488
489
490
491
492
493
494
boolean PubSubClient::publish_P(const char *topic, const uint8_t *payload, unsigned int plength, boolean retained) {
  uint8_t llen = 0;
  uint8_t digit;
  unsigned int rc = 0;
  uint16_t tlen;
  unsigned int pos = 0;
  unsigned int i;
  uint8_t header;
  unsigned int len;
  uint32_t expectedLength;
495

Eric Duminil's avatar
Eric Duminil committed
496
497
498
  if (!connected()) {
    return false;
  }
499

Eric Duminil's avatar
Eric Duminil committed
500
  tlen = strnlen(topic, this->bufferSize);
501

Eric Duminil's avatar
Eric Duminil committed
502
503
504
505
506
507
508
509
510
511
512
  header = MQTTPUBLISH;
  if (retained) {
    header |= 1;
  }
  this->buffer[pos++] = header;
  len = plength + 2 + tlen;
  do {
    digit = len & 127; //digit = len %128
    len >>= 7; //len = len / 128
    if (len > 0) {
      digit |= 0x80;
513
    }
Eric Duminil's avatar
Eric Duminil committed
514
515
516
    this->buffer[pos++] = digit;
    llen++;
  } while (len > 0);
517

Eric Duminil's avatar
Eric Duminil committed
518
  pos = writeString(topic, this->buffer, pos);
519

Eric Duminil's avatar
Eric Duminil committed
520
  rc += _client->write(this->buffer, pos);
521

Eric Duminil's avatar
Eric Duminil committed
522
523
524
  for (i = 0; i < plength; i++) {
    rc += _client->write((char) pgm_read_byte_near(payload + i));
  }
525

Eric Duminil's avatar
Eric Duminil committed
526
  lastOutActivity = millis();
527

Eric Duminil's avatar
Eric Duminil committed
528
  expectedLength = 1 + llen + 2 + tlen + plength;
529

Eric Duminil's avatar
Eric Duminil committed
530
  return (rc == expectedLength);
531
532
}

Eric Duminil's avatar
Eric Duminil committed
533
534
535
536
537
538
539
540
boolean PubSubClient::beginPublish(const char *topic, unsigned int plength, boolean retained) {
  if (connected()) {
    // Send the header and variable length field
    uint16_t length = MQTT_MAX_HEADER_SIZE;
    length = writeString(topic, this->buffer, length);
    uint8_t header = MQTTPUBLISH;
    if (retained) {
      header |= 1;
541
    }
Eric Duminil's avatar
Eric Duminil committed
542
543
544
545
546
547
    size_t hlen = buildHeader(header, this->buffer, plength + length - MQTT_MAX_HEADER_SIZE);
    uint16_t rc = _client->write(this->buffer + (MQTT_MAX_HEADER_SIZE - hlen), length - (MQTT_MAX_HEADER_SIZE - hlen));
    lastOutActivity = millis();
    return (rc == (length - (MQTT_MAX_HEADER_SIZE - hlen)));
  }
  return false;
548
549
550
}

int PubSubClient::endPublish() {
Eric Duminil's avatar
Eric Duminil committed
551
  return 1;
552
553
554
}

size_t PubSubClient::write(uint8_t data) {
Eric Duminil's avatar
Eric Duminil committed
555
556
  lastOutActivity = millis();
  return _client->write(data);
557
558
559
}

size_t PubSubClient::write(const uint8_t *buffer, size_t size) {
Eric Duminil's avatar
Eric Duminil committed
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
  lastOutActivity = millis();
  return _client->write(buffer, size);
}

size_t PubSubClient::buildHeader(uint8_t header, uint8_t *buf, uint16_t length) {
  uint8_t lenBuf[4];
  uint8_t llen = 0;
  uint8_t digit;
  uint8_t pos = 0;
  uint16_t len = length;
  do {

    digit = len & 127; //digit = len %128
    len >>= 7; //len = len / 128
    if (len > 0) {
      digit |= 0x80;
576
    }
Eric Duminil's avatar
Eric Duminil committed
577
578
579
580
581
582
583
584
585
    lenBuf[pos++] = digit;
    llen++;
  } while (len > 0);

  buf[4 - llen] = header;
  for (int i = 0; i < llen; i++) {
    buf[MQTT_MAX_HEADER_SIZE - llen + i] = lenBuf[i];
  }
  return llen + 1; // Full header size is variable length bit plus the 1-byte fixed header
586
587
}

Eric Duminil's avatar
Eric Duminil committed
588
589
590
boolean PubSubClient::write(uint8_t header, uint8_t *buf, uint16_t length) {
  uint16_t rc;
  uint8_t hlen = buildHeader(header, buf, length);
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605

#ifdef MQTT_MAX_TRANSFER_SIZE
    uint8_t* writeBuf = buf+(MQTT_MAX_HEADER_SIZE-hlen);
    uint16_t bytesRemaining = length+hlen;  //Match the length type
    uint8_t bytesToWrite;
    boolean result = true;
    while((bytesRemaining > 0) && result) {
        bytesToWrite = (bytesRemaining > MQTT_MAX_TRANSFER_SIZE)?MQTT_MAX_TRANSFER_SIZE:bytesRemaining;
        rc = _client->write(writeBuf,bytesToWrite);
        result = (rc == bytesToWrite);
        bytesRemaining -= rc;
        writeBuf += rc;
    }
    return result;
#else
Eric Duminil's avatar
Eric Duminil committed
606
607
608
  rc = _client->write(buf + (MQTT_MAX_HEADER_SIZE - hlen), length + hlen);
  lastOutActivity = millis();
  return (rc == hlen + length);
609
610
611
#endif
}

Eric Duminil's avatar
Eric Duminil committed
612
613
boolean PubSubClient::subscribe(const char *topic) {
  return subscribe(topic, 0);
614
615
}

Eric Duminil's avatar
Eric Duminil committed
616
617
618
619
620
621
boolean PubSubClient::subscribe(const char *topic, uint8_t qos) {
  size_t topicLength = strnlen(topic, this->bufferSize);
  if (topic == 0) {
    return false;
  }
  if (qos > 1) {
622
    return false;
Eric Duminil's avatar
Eric Duminil committed
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
  }
  if (this->bufferSize < 9 + topicLength) {
    // Too long
    return false;
  }
  if (connected()) {
    // Leave room in the buffer for header and variable length field
    uint16_t length = MQTT_MAX_HEADER_SIZE;
    nextMsgId++;
    if (nextMsgId == 0) {
      nextMsgId = 1;
    }
    this->buffer[length++] = (nextMsgId >> 8);
    this->buffer[length++] = (nextMsgId & 0xFF);
    length = writeString((char*) topic, this->buffer, length);
    this->buffer[length++] = qos;
    return write(MQTTSUBSCRIBE | MQTTQOS1, this->buffer, length - MQTT_MAX_HEADER_SIZE);
  }
  return false;
642
643
}

Eric Duminil's avatar
Eric Duminil committed
644
645
646
boolean PubSubClient::unsubscribe(const char *topic) {
  size_t topicLength = strnlen(topic, this->bufferSize);
  if (topic == 0) {
647
    return false;
Eric Duminil's avatar
Eric Duminil committed
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
  }
  if (this->bufferSize < 9 + topicLength) {
    // Too long
    return false;
  }
  if (connected()) {
    uint16_t length = MQTT_MAX_HEADER_SIZE;
    nextMsgId++;
    if (nextMsgId == 0) {
      nextMsgId = 1;
    }
    this->buffer[length++] = (nextMsgId >> 8);
    this->buffer[length++] = (nextMsgId & 0xFF);
    length = writeString(topic, this->buffer, length);
    return write(MQTTUNSUBSCRIBE | MQTTQOS1, this->buffer, length - MQTT_MAX_HEADER_SIZE);
  }
  return false;
665
666
667
}

void PubSubClient::disconnect() {
Eric Duminil's avatar
Eric Duminil committed
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
  this->buffer[0] = MQTTDISCONNECT;
  this->buffer[1] = 0;
  _client->write(this->buffer, 2);
  _state = MQTT_DISCONNECTED;
  _client->flush();
  _client->stop();
  lastInActivity = lastOutActivity = millis();
}

uint16_t PubSubClient::writeString(const char *string, uint8_t *buf, uint16_t pos) {
  const char *idp = string;
  uint16_t i = 0;
  pos += 2;
  while (*idp) {
    buf[pos++] = *idp++;
    i++;
  }
  buf[pos - i - 2] = (i >> 8);
  buf[pos - i - 1] = (i & 0xFF);
  return pos;
688
689
690
}

boolean PubSubClient::connected() {
Eric Duminil's avatar
Eric Duminil committed
691
692
693
694
695
696
697
698
699
700
701
  boolean rc;
  if (_client == NULL) {
    rc = false;
  } else {
    rc = (int) _client->connected();
    if (!rc) {
      if (this->_state == MQTT_CONNECTED) {
        this->_state = MQTT_CONNECTION_LOST;
        _client->flush();
        _client->stop();
      }
702
    } else {
Eric Duminil's avatar
Eric Duminil committed
703
      return this->_state == MQTT_CONNECTED;
704
    }
Eric Duminil's avatar
Eric Duminil committed
705
706
  }
  return rc;
707
708
}

Eric Duminil's avatar
Eric Duminil committed
709
710
711
PubSubClient& PubSubClient::setServer(uint8_t *ip, uint16_t port) {
  IPAddress addr(ip[0], ip[1], ip[2], ip[3]);
  return setServer(addr, port);
712
713
714
}

PubSubClient& PubSubClient::setServer(IPAddress ip, uint16_t port) {
Eric Duminil's avatar
Eric Duminil committed
715
716
717
718
  this->ip = ip;
  this->port = port;
  this->domain = NULL;
  return *this;
719
720
}

Eric Duminil's avatar
Eric Duminil committed
721
722
723
724
PubSubClient& PubSubClient::setServer(const char *domain, uint16_t port) {
  this->domain = domain;
  this->port = port;
  return *this;
725
726
727
}

PubSubClient& PubSubClient::setCallback(MQTT_CALLBACK_SIGNATURE) {
Eric Duminil's avatar
Eric Duminil committed
728
729
  this->callback = callback;
  return *this;
730
731
}

Eric Duminil's avatar
Eric Duminil committed
732
733
734
PubSubClient& PubSubClient::setClient(Client &client) {
  this->_client = &client;
  return *this;
735
736
}

Eric Duminil's avatar
Eric Duminil committed
737
738
739
PubSubClient& PubSubClient::setStream(Stream &stream) {
  this->stream = &stream;
  return *this;
740
741
742
}

int PubSubClient::state() {
Eric Duminil's avatar
Eric Duminil committed
743
  return this->_state;
744
745
746
}

boolean PubSubClient::setBufferSize(uint16_t size) {
Eric Duminil's avatar
Eric Duminil committed
747
748
749
750
751
752
753
754
755
756
  if (size == 0) {
    // Cannot set it back to 0
    return false;
  }
  if (this->bufferSize == 0) {
    this->buffer = (uint8_t*) malloc(size);
  } else {
    uint8_t *newBuffer = (uint8_t*) realloc(this->buffer, size);
    if (newBuffer != NULL) {
      this->buffer = newBuffer;
757
    } else {
Eric Duminil's avatar
Eric Duminil committed
758
      return false;
759
    }
Eric Duminil's avatar
Eric Duminil committed
760
761
762
  }
  this->bufferSize = size;
  return (this->buffer != NULL);
763
764
765
}

uint16_t PubSubClient::getBufferSize() {
Eric Duminil's avatar
Eric Duminil committed
766
  return this->bufferSize;
767
768
}
PubSubClient& PubSubClient::setKeepAlive(uint16_t keepAlive) {
Eric Duminil's avatar
Eric Duminil committed
769
770
  this->keepAlive = keepAlive;
  return *this;
771
772
}
PubSubClient& PubSubClient::setSocketTimeout(uint16_t timeout) {
Eric Duminil's avatar
Eric Duminil committed
773
774
  this->socketTimeout = timeout;
  return *this;
775
}