Skip to content

Commit b007806

Browse files
author
xdylanm
committed
Fixed length calculation when payload exceeds 128bytes
1 parent e524b5f commit b007806

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

Adafruit_MQTT.cpp

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -728,19 +728,20 @@ uint16_t Adafruit_MQTT::publishPacket(uint8_t *packet, const char *topic,
728728
// Calculate additional bytes for length field (if any)
729729
uint16_t additionalLen = packetAdditionalLen(len + bLen);
730730

731-
// Payload length. When maxPacketLen provided is 0, let's
731+
// Payload remaining length. When maxPacketLen provided is 0, let's
732732
// assume buffer is big enough. Fingers crossed.
733-
if (maxPacketLen == 0 || (len + bLen + 2 + additionalLen <= maxPacketLen)) {
734-
len += bLen + additionalLen;
735-
} else {
733+
// 2 + additionalLen: header byte + remaining length field (from 1 to 4 bytes)
734+
// len = topic size field + value (string)
735+
// bLen = buffer size
736+
if (!(maxPacketLen == 0 || (len + bLen + 2 + additionalLen <= maxPacketLen))) {
736737
// If we make it here, we got a pickle: the payload is not going
737738
// to fit in the packet buffer. Instead of corrupting memory, let's
738739
// do something less damaging by reducing the bLen to what we are
739740
// able to accomodate. Alternatively, consider using a bigger
740741
// maxPacketLen.
741742
bLen = maxPacketLen - (len + 2 + packetAdditionalLen(maxPacketLen));
742-
len = maxPacketLen - 4;
743743
}
744+
len += bLen; // remaining len excludes header byte & length field
744745

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

0 commit comments

Comments
 (0)