Skip to content

Commit

Permalink
[MQTT] PubSubClient checks when callback + publish happen simultaneous
Browse files Browse the repository at this point in the history
After discussion with @arjenhiemstra on issue: knolleary/pubsubclient#832
  • Loading branch information
TD-er committed Feb 20, 2021
1 parent f2e4ac6 commit bdef2b3
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions lib/pubsubclient/src/PubSubClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -330,16 +330,22 @@ bool PubSubClient::loop_read() {
case MQTTPUBLISH:
{
if (callback) {
uint16_t tl = (buffer[llen+1]<<8)+buffer[llen+2]; /* topic length in bytes */
memmove(buffer+llen+2,buffer+llen+3,tl); /* move topic inside buffer 1 byte to front */
buffer[llen+2+tl] = 0; /* end the topic as a 'C' string with \x00 */
char *topic = (char*) buffer+llen+2;
const uint16_t tl_offset = llen+1;
const uint16_t tl = (buffer[tl_offset]<<8)+buffer[tl_offset+1]; /* topic length in bytes */
const uint16_t topic_offset = tl_offset+2;
const uint16_t msgId_offset = topic_offset+tl;
const uint16_t payload_offset = msgId_offset+2;
if (payload_offset >= MQTT_MAX_PACKET_SIZE) return false;
if (len < payload_offset) return false;
memmove(buffer+topic_offset-1,buffer+topic_offset,tl); /* move topic inside buffer 1 byte to front */
buffer[topic_offset-1+tl] = 0; /* end the topic as a 'C' string with \x00 */
char *topic = (char*) buffer+topic_offset-1;
uint8_t *payload;
// msgId only present for QOS>0
if ((buffer[0]&0x06) == MQTTQOS1) {
const uint16_t msgId = (buffer[llen+3+tl]<<8)+buffer[llen+3+tl+1];
payload = buffer+llen+3+tl+2;
callback(topic,payload,len-llen-3-tl-2);
const uint16_t msgId = (buffer[msgId_offset]<<8)+buffer[msgId_offset+1];
payload = buffer+payload_offset;
callback(topic,payload,len-payload_offset);
if (_client->connected()) {
buffer[0] = MQTTPUBACK;
buffer[1] = 2;
Expand All @@ -350,8 +356,9 @@ bool PubSubClient::loop_read() {
}
}
} else {
payload = buffer+llen+3+tl;
callback(topic,payload,len-llen-3-tl);
// No msgId, thus payload starts 2 bytes earlier.
payload = buffer+payload_offset-2;
callback(topic,payload,len-(payload_offset-2));
}
}
break;
Expand Down

0 comments on commit bdef2b3

Please sign in to comment.