Skip to content

Commit 37e175d

Browse files
authored
Merge pull request #196 from xdylanm/send_long_packet_fix
Fixed length calculation when payload exceeds 128bytes
2 parents d466773 + a2bdbac commit 37e175d

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

Adafruit_MQTT.cpp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -756,19 +756,21 @@ uint16_t Adafruit_MQTT::publishPacket(uint8_t *packet, const char *topic,
756756
// Calculate additional bytes for length field (if any)
757757
uint16_t additionalLen = packetAdditionalLen(len + bLen);
758758

759-
// Payload length. When maxPacketLen provided is 0, let's
759+
// Payload remaining length. When maxPacketLen provided is 0, let's
760760
// assume buffer is big enough. Fingers crossed.
761-
if (maxPacketLen == 0 || (len + bLen + 2 + additionalLen <= maxPacketLen)) {
762-
len += bLen + additionalLen;
763-
} else {
761+
// 2 + additionalLen: header byte + remaining length field (from 1 to 4 bytes)
762+
// len = topic size field + value (string)
763+
// bLen = buffer size
764+
if (!(maxPacketLen == 0 ||
765+
(len + bLen + 2 + additionalLen <= maxPacketLen))) {
764766
// If we make it here, we got a pickle: the payload is not going
765767
// to fit in the packet buffer. Instead of corrupting memory, let's
766768
// do something less damaging by reducing the bLen to what we are
767769
// able to accomodate. Alternatively, consider using a bigger
768770
// maxPacketLen.
769771
bLen = maxPacketLen - (len + 2 + packetAdditionalLen(maxPacketLen));
770-
len = maxPacketLen - 4;
771772
}
773+
len += bLen; // remaining len excludes header byte & length field
772774

773775
// Now you can start generating the packet!
774776
p[0] = MQTT_CTRL_PUBLISH << 4 | qos << 1;

0 commit comments

Comments
 (0)