Wifi and MQTT handling for ESP8266 and ESP32
Alternatives To Espmqttclient
Project NameStarsDownloadsRepos Using ThisPackages Using ThisMost Recent CommitTotal ReleasesLatest ReleaseOpen IssuesLicenseLanguage
7 hours ago14gpl-3.0C
Alternative firmware for ESP8266 and ESP32 based devices with easy configuration using webUI, OTA updates, automation using timers or rules, expandability and entirely local control over MQTT, HTTP, Serial or KNX. Full documentation at
17 hours ago4August 03, 2021309mitC++
Control WS2812B and many more types of digital RGB LEDs with an ESP8266 or ESP32 over WiFi!
Nodemcu Firmware7,276
2 months ago99mitC
Lua based interactive firmware for ESP8266, ESP8285 and ESP32
Platformio Core6,673
6 days ago16August 12, 2022184apache-2.0Python
A professional collaborative platform for embedded development :alien:
4 days ago24mitC++
📟 JSON library for Arduino and embedded C++. Simple and efficient.
Esphome6,0151111 hours ago200June 22, 2022157otherC++
ESPHome is a system to control your ESP8266/ESP32 by simple yet powerful configuration files and control them remotely through Home Automation systems.
Blynk Library3,597
5 days ago9mitC++
Blynk library for embedded hardware. Works with Arduino, ESP8266, Raspberry Pi, Intel Edison/Galileo, LinkIt ONE, Particle Core/Photon, Energia, ARM mbed, etc.
9 hours ago97gpl-3.0C++
MQTT gateway for ESP8266, ESP32, Sonoff RF Bridge or Arduino with bidirectional 433mhz/315mhz/868mhz, Infrared communications, BLE, Bluetooth, beacons detection, mi flora, mi jia, LYWSD02, LYWSD03MMC, Mi Scale, TPMS, BBQ thermometer compatibility, SMS & LORA.
9 days ago6otherC
Arduino and PlatformIO IDE compatible TFT library optimised for the Raspberry Pi Pico (RP2040), STM32, ESP8266 and ESP32 that supports different driver chips
12 days ago31lgpl-2.1C++
Infrared remote library for ESP8266/ESP32: send and receive infrared signals with multiple protocols. Based on:
Alternatives To Espmqttclient
Select To Compare

Alternative Project Comparisons

MQTT and Wifi handling for ESP8266 and ESP32

This library is intended to encapsulate the handling of WiFi and MQTT connections of an ESP8266/ESP32. You just need to provide your credentials and it will manage the following things:

  • Connecting to a WiFi network.
  • Connecting to a MQTT broker.
  • Automatically detecting connection lost either from the WiFi client or the MQTT broker and it will retry a connection automatically.
  • Subscribing/unsubscribing to/from MQTT topics by a friendly callback system.
  • Supports wildcards (+, #) in subscriptions
  • Provide a callback handling to advise once everything is connected (Wifi and MQTT).
  • Provide a function to enable printing of useful debug information related to MQTT and Wifi connections.
  • Provide some other useful utilities for MQTT and Wifi management.
  • Provide a function to enable an HTTP Update server secured by a password to allow remote update.
  • Provide a function to enable OTA secured by a password to allow remote update.


The MQTT communication depends on the PubSubClient Library.


#include "EspMQTTClient.h"

EspMQTTClient client(
  "",  // MQTT Broker server ip
  "MQTTUsername",   // Can be omitted if not needed
  "MQTTPassword",   // Can be omitted if not needed
  "TestClient"      // Client name that uniquely identify your device

void setup() {}

void onConnectionEstablished() {

  client.subscribe("mytopic/test", [] (const String &payload)  {

  client.publish("mytopic/test", "This is a message");

void loop() {

See SimpleMQTTClient.ino for the complete example.



For Wifi and MQTT connection handling (Recommended):

    const char* wifiSsid,
    const char* wifiPassword,
    const char* mqttServerIp,
    const char* mqttUsername,  // Omit this parameter to disable MQTT authentification
    const char* mqttPassword,  // Omit this parameter to disable MQTT authentification
    const char* mqttClientName = "ESP8266",
    const uint16_t mqttServerPort = 1883);

MQTT connection handling only:

    const char* mqttServerIp,
    const uint16_t mqttServerPort,  // It is mandatory here to allow these constructors to be distinct from those with the Wifi handling parameters
    const char* mqttUsername,    // Omit this parameter to disable MQTT authentification
    const char* mqttPassword,    // Omit this parameter to disable MQTT authentification
    const char* mqttClientName = "ESP8266");


IMPORTANT: Must be called at each loop() of your sketch

void loop();

Basic functions for MQTT communications.

bool publish(const String &topic, const String &payload, bool retain = false);
bool subscribe(const String &topic, MessageReceivedCallback messageReceivedCallback, uint8_t qos = 0);
bool unsubscribe(const String &topic);

Change the maximum packet size that can be sent over MQTT. The default is 128 bytes.

bool setMaxPacketSize(const uint16_t size);

Change the keep alive interval (15 seconds by default)

void setKeepAlive(uint16_t keepAliveSeconds);

Enable debugging messages that will output to serial.

void enableDebuggingMessages(const bool enabled = true);

Enable the web updater. This will host a simple form that will allow firmware upgrade (using, e.g., the .bin file produced by "Export Compiled Binary" in the Arduino IDE's "Sketch" menu). Must be set before the first loop() call.

void enableHTTPWebUpdater(const char* username, const char* password, const char* address = "/");

// this one will set user and password equal to those set for the MQTT connection.
void enableHTTPWebUpdater(const char* address = "/");

Enable last will message. Must be set before the first loop() call.

void enableLastWillMessage(const char* topic, const char* message, const bool retain = false);

Tell the broker to establish a persistent connection. Disabled by default. Must be called before the first loop() execution

void enableMQTTPersistence();

Change the delay between each MQTT reconnection attempt. Default is 15 seconds.

void setMqttReconnectionAttemptDelay(const unsigned int milliseconds);

Change the delay between each Wifi reconnection attempt. Default is 60 seconds.

void setWifiReconnectionAttemptDelay(const unsigned int milliseconds);

Connection status

bool isConnected(); // Return true if everything is connected.
bool isWifiConnected(); // Return true if WiFi is connected.
bool isMqttConnected(); // Return true if MQTT is connected.
bool getConnectionEstablishedCount() // Return the number of time onConnectionEstablished has been called since the beginning.

As ESP8266 does not like to be interrupted too long with the delay() function, this function will allow a delayed execution of a function without interrupting the sketch.

void executeDelayed(const long delay, DelayedExecutionCallback callback);

Some useful getters

const char* getMqttClientName();
const char* getMqttServerIp();
const uint16_t getMqttServerPort();

Connection established callback

To allow this library to work, you need to implement the onConnectionEstablished() function in your sketch.

void onConnectionEstablished()
  // Here you are sure that everything is connected.

In some special cases, like if you want to handle more than one MQTT connection in the same sketch, you can override this callback to another one for the second MQTT client using this function:

void setOnConnectionEstablishedCallback(ConnectionEstablishedCallback callback);

See example twoMQTTClientHandling.ino for more details.

Subscribing to topics

The function subscribe allows subscribing a specific topic.

For example, if you want to subscribe to topic test/mytopic, you can do this:

void onTestMessageReceived(const String& message) {
  Serial.print("message received from test/mytopic: " + message);

client.subscribe("test/mytopic", onTestMessageReceived);

You can also use lambdas to shorten the code like this:

client.subscribe("test/mytopic", [](const String& message) {
  Serial.print("message received from test/mytopic: " + message;


This library also handle MQTT topic wildcards. Most of the time, you will want to see what was the original topic when the callback is called. Here is how to do that.

Example: Subscribe to wildcardtest/# and display received topic and message to Serial

void onMessageReceived(const String& topic, const String& message) {
  Serial.println(topic + ": " + message);

client.subscribe("wildcardtest/#", onMessageReceived);

The same thing with lambdas:

  client.subscribe("wildcardtest/#", [](const String& topic, const String& message) {
    Serial.println(topic + ": " + message);
Popular Esp32 Projects
Popular Esp8266 Projects
Popular Hardware Categories
Related Searches

Get A Weekly Email With Trending Projects For These Categories
No Spam. Unsubscribe easily at any time.
C Plus Plus
Internet Of Things
Arduino Library