PubSubClient

From Leo's Notes
Revision as of 17:25, 26 July 2020 by Leo (talk | contribs) (Created page with "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. ==...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
This page was last edited on 26 July 2020, at 17:25.

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

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);
}

See Also