PubSubClient is an Arduino library to do simple publish/subscribe commands against a MQTT server. This library works with various hardware including the ESP8266 and ESP32.

Usage[edit | edit source]

Install the library from the Arduino library manager. The setup code involves setting the servername and port. The loop code ensures that the MQTT connection is kept alive.

#include <PubSubClient.h>
PubSubClient client(espClient);

long lastReconnectAttempt = 0;

void setup() {
	client.setServer(mqtt_server, atoi(mqtt_port));
	client.setCallback(mqtt_callback);
}

void loop() {
	if (!client.connected()) {
		long now = millis();
		
		if (now - lastReconnectAttempt > 5000) {
			lastReconnectAttempt = now;
			// Attempt to reconnect
			if (mqtt_reconnect()) {
				lastReconnectAttempt = 0;
			}
		}
	} else {
		// Client connected
		client.loop();
	}
}

bool mqtt_reconnect() {
	// use a demo client name for now
	if (client.connect("ESPDemo")) {
		// send to system a reconnected message.
		client.publish("system", "MQTT connection established");
	}
	
	return client.connected();
}


void mqtt_callback(char* topic, byte* payload, unsigned int length) {
}

void mqtt_publish(char* message) {
	client.publish(mqtt_topic, msg);
}

Troubleshooting[edit | edit source]

Messages not sent[edit | edit source]

There is a default maximum packet size of 128 bytes. If you try to publish a message which results in a packet greater than 128 bytes, the message will be silently dropped. To fix this, you will need to edit MQTT_MAX_PACKET_SIZE value to a sufficiently large value. I tried to define before including the PubSubClient.h header but it didn't appear to work. You may need tot actually edit the header file directly located at %USERPROFILE%\Documents\Arduino\libraries\PubSubClient\src.

// MQTT_MAX_PACKET_SIZE : Maximum packet size
#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 512
#endif


See Also[edit | edit source]