knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.83k stars 1.47k forks source link

MQTT Max Packet Size does not support Azure IoT Hub #596

Open CoolNamesAllTaken opened 5 years ago

CoolNamesAllTaken commented 5 years ago

The MQTT_MAX_PACKET_SIZE of 128 bytes is currently too small to adequately transmit packets to Azure IoT Hub, since the SAS tokens are so long. This led me down a 5-hour path of heartache, and it would be really great if we could find a way to bump the byte count up a little bit so that Azure can be supported. Is there a reason that the byte count is currently so small?

If anyone else is also trying to get PubSubClient to work with Azure IoT Hub on the ESP32, the return value of -1 "MQTT_DISCONNECTED" may very well be caused by your packet size being too small. I bumped up the maximum packet size from 128 bytes to 1280 bytes and my connection issues disappeared. Things work fine with WiFiClientSecure using no verification.

knolleary commented 5 years ago

The value of 128 bytes dates back to the early days of the library when the devices it was used on couldn't spare any more memory then that.

As the docs describe, you change the value by editing PubSubClient.h. It's been a long standing decision to not allow the value to be dynamically changed - so the required memory is statically reserved at compile time.

It may be worth reviewing the current state of the typically devices this lib is used with, to see if we can bump the default.

CoolNamesAllTaken commented 5 years ago

I think that the most commonly used devices today probably have more than 128 bytes to spare, and it might be worth supporting them by default, especially in mainstream MQTT applications like Azure IoT.

At the very least, some sort of error check that makes sure the packets aren't being truncated would be really helpful. I kept getting the rc=-1 MQTT_DISCONNECTED error, which led me down the wrong path hunting issues with my network connection, hostname, port, username, password, etc. A clear indication that the packet length is at fault would be incredibly useful for debugging.

ChuckVanzant commented 5 years ago

I don't know what build environment you are using but you can probably use build flags in your environment to set the max packet size.

As an example in the PlatformIO build environment, you can specify the following build flag for each project environment specified in the project platformio.ini file:

build_flags = -D MQTT_MAX_PACKET_SIZE=1024