Today, I will show how to combine three commonly used IoT libraries;
WiFimanager, AsyncElegantOTA, and MQTT To become a common IoT code base. So, for our future projects, ESP8266 or ESP32, would have these basic functions.
Let's first look at these three libraries:
Wifimanager = Wi-Fi password management, no need to re-burn the code to change the Wi-Fi SSID & password
FOTA = Use Wi-Fi to update ESP32 code, you can burn code without connecting to USB
MQTT = Streamlined and lightweight communication protocol (Message Queueing Telemetry Transport)
This episode will only introduce how to integrate MQTT into Wifimanager + AsyncElegantFOTA.
To learn how to start Wifimanager + AsyncElegantOTA, Please watch Android #27 Wifimanager + OTA for ESP32/ESP8266 (ESPAsyncWifimanager / ESPAsyncElegantOTA)) https://youtu.be/UlRLTvl4DRc
If you don't have enough time, you can also select the part you want to watch from the timeline below!
Video Timeline:
00:00 Start
01:39 Demonstration of project results
01:57 mqttgo.io MQTT server, free, fast, & stable
05:52 Install three libraries
07:14 Added two ESP32 PINs as MQTT example
07:41 Encrypt the firmware update (ElegantOTA) page
11:44 Explain how the MQTT callback function works
13:07 Control ESP32 I/O pins with MQTT
15:16 Future program can be written from here
/**
* Arduino code base for IoT Projects
* By: Stonez56 aka Kevin Chen 2022-08-16
*
* This source code combined three most common Arduino libraries for IoT Projects,
* ESPAsync_Wifimanager, AsyncElegantOTA, & Pubsubclient MQTT Client.
*
* 1. ESPAsync_WiFiManager: https://github.com/khoih-prog/ESPAsync_WiFiManager
* 2. AsyncElegantOTA: https://github.com/ayushsharma82/AsyncElegantOTA
* 3. Pubsubclient MQTT Client: https://github.com/knolleary/pubsubclient
*
* YouTube video: https://youtu.be/giFHp9RSMvQ
* Source code is available my blog: https://stonez56.blogspot.com/2022/08/android-36-iot-wifimanager-fota-mqtt.html
**/
/*
* Define Relay pins as examples to send/receive MQTT messages
* **/
#define RELAY_PIN_1 12
#define RELAY_PIN_2 14
/**
* Perform OTAs for ESP8266 / ESP32 Elegantly with password protection!
* https://github.com/ayushsharma82/AsyncElegantOTA
* **/
#include <AsyncElegantOTA.h>
const char *FOTA_USERNAME = "un";
const char *FOTA_PASSWORD = "pw";
/**
* Add MQTT client here` PubSubClient V2.8 by Nick O'Leary
* https://github.com/knolleary/pubsubclient
*/
#include <WiFiClient.h>
#include <PubSubClient.h>
#define MSG_BUFFER_SIZE (1024)
char msg[MSG_BUFFER_SIZE];
/** Taiwan No. 1 Free MQTT Server!! **/
const char *mqtt_server = "mqttgo.io";
const int mqtt_port = 1883;
/****************************************************************************************************************************
Async_AutoConnect_ESP32_minimal.ino
For ESP8266 / ESP32 boards
Built by Khoi Hoang https://github.com/khoih-prog/ESPAsync_WiFiManager
Licensed under MIT license
*****************************************************************************************************************************/
#if !(defined(ESP32))
#error This code is intended to run on the ESP32 platform! Please check your Tools->Board setting.
#endif
#include <ESPAsync_WiFiManager.h>
AsyncWebServer webServer(80);
//Start DNS server
DNSServer dnsServer;
//MQTT - Start WiFi client and connect to MQTT server
WiFiClient espClient;
PubSubClient mqtt_client(espClient);
//Define device name
String DEVICE_NAME = "Dual_Relay_Switch";
String home_page_message = "";
void setup()
{
Serial.begin(115200);
pinMode(RELAY_PIN_1, OUTPUT);
pinMode(RELAY_PIN_2, OUTPUT);
while (!Serial)
;
delay(200);
Serial.print("\nAsyncWifimanager started on " + String(ARDUINO_BOARD) + "\n");
//Initialize ESPAsyncWifimanager instance and assign Wi-Fi Client name "AsyncAutoConnect"!
//This name and IP address can be checked from the router
ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, "Dual_Relay_Switch");
//####### RESET SAVED WIFI SETTINGS #############
//ESPAsync_wifiManager.resetSettings();
//ESPAsync_wifiManager.setAPStaticIPConfig(IPAddress(192, 168, 132, 1), IPAddress(192, 168, 132, 1), IPAddress(255, 255, 255, 0));
//ESPAsync_wifiManager.autoConnect("Stonez_ESP32S", "AP-NAME", "AP-PASSWORD");
ESPAsync_wifiManager.autoConnect("Dual_Switch_ESP32S");
if (WiFi.status() == WL_CONNECTED)
{
Serial.print(DEVICE_NAME);
Serial.print(" is on Local IP: ");
Serial.println(WiFi.localIP());
}
else
{
Serial.println(ESPAsync_wifiManager.getStatus(WiFi.status()));
}
//Setup home page access content when visite
home_page_message = "<!DOCTYPE html><html><head><title>" + DEVICE_NAME
+ "</title></head><body><p><h2> Hi! This is " + DEVICE_NAME + "</h2>"
+ "To update firmware, <a href='/update'>Click here!!</a><br/><span>Username & Password required!</span></p><body></html>";
webServer.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(200, "text/html", home_page_message); });
//AsyncElegantOTA.begin(&webServer); // Start ElegantOTA WITHOUT username & password
AsyncElegantOTA.begin(&webServer, FOTA_USERNAME, FOTA_PASSWORD); // Start ElegantOTA with username & password
webServer.begin();
Serial.println("AsyncElegantOTA server started @URL/update");
//MQTT starts here!
mqtt_client.setServer(mqtt_server, mqtt_port);
mqtt_client.setCallback(callback);
}
/**
//When MQTT lost connection, this function will be called to reconnect MQTT//
* Modified to accept multiple MQTT topics
* https://www.baldengineer.com/multiple-mqtt-topics-pubsubclient.html
*/
void callback(char *topic, byte *payload, unsigned int length)
{
//Print message received
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
//Process multiple topics here//
payload[length] = '\0';
String message = (char*)payload;
if (strcmp(topic, "studio/humd_switch") == 0)
{
if(message == "true"){
digitalWrite(RELAY_PIN_1, HIGH);
Serial.println("humd_switch true");
}
if(message == "false"){
digitalWrite(RELAY_PIN_1, LOW);
Serial.println("humd_switch false");
}
}
if (strcmp(topic, "studio/humd_switch2") == 0)
{
if(message == "true"){
digitalWrite(RELAY_PIN_2, HIGH);
Serial.println("humd_switch2 true");
}
if(message == "false"){
digitalWrite(RELAY_PIN_2, LOW);
Serial.println("humd_switch2 false");
}
}
}
//============= MQTT ===================
//When MQTT lost connection, this function will be called to reconnect MQTT//
void reconnect(){
//Loop while MQTT connected
while (!mqtt_client.connected())
{
Serial.print("Attempting MQTT connection... ");
// Create a random client ID
String clientId = "Stonez_ESP32Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (mqtt_client.connect(clientId.c_str()))
{
Serial.print("connected to ");
Serial.print(mqtt_server);
// Once connected, publish an announcement...
mqtt_client.publish("outTopic", "Hello world");
// ... and resubscribe
mqtt_client.subscribe("studio/humd_switch");
mqtt_client.subscribe("studio/humd_switch2");
}
else
{
Serial.print("failed, rc=");
Serial.print(mqtt_client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
//============= MQTT ===================
//if can't connect to MQTT server, then re-connect
if (!mqtt_client.connected())
{ reconnect(); }
//constantly check MQTT to see for messages sending/receiving
mqtt_client.loop();
/**
* Write your own code here....
*
*/
}
Async_AutoConnect_ESP32_minimal.ino
/****************************************************************************************************************************
Async_AutoConnect_ESP32_minimal.ino
For ESP8266 / ESP32 boards
Built by Khoi Hoang https://github.com/khoih-prog/ESPAsync_WiFiManager
Licensed under MIT license
*****************************************************************************************************************************/
#if !(defined(ESP32) )
#error This code is intended to run on the ESP32 platform! Please check your Tools->Board setting.
#endif
#include <ESPAsync_WiFiManager.h> //https://github.com/khoih-prog/ESPAsync_WiFiManager
AsyncWebServer webServer(80);
DNSServer dnsServer;
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200); while (!Serial); delay(200);
Serial.print("\nStarting Async_AutoConnect_ESP32_minimal on " + String(ARDUINO_BOARD)); Serial.println(ESP_ASYNC_WIFIMANAGER_VERSION);
ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, "AutoConnectAP");
//ESPAsync_wifiManager.resetSettings(); //reset saved settings
ESPAsync_wifiManager.setAPStaticIPConfig(IPAddress(192,168,132,1), IPAddress(192,168,132,1), IPAddress(255,255,255,0));
ESPAsync_wifiManager.autoConnect("AutoConnectAP");
if (WiFi.status() == WL_CONNECTED) { Serial.print(F("Connected. Local IP: ")); Serial.println(WiFi.localIP()); }
else { Serial.println(ESPAsync_wifiManager.getStatus(WiFi.status())); }
}
void loop() { }
Async_AutoConnect_ESP8266_minimal.ino
/****************************************************************************************************************************
Async_AutoConnect_ESP8266_minimal.ino
For ESP8266 / ESP32 boards
Built by Khoi Hoang https://github.com/khoih-prog/ESPAsync_WiFiManager
Licensed under MIT license
*****************************************************************************************************************************/
#if !( defined(ESP8266) )
#error This code is intended to run on ESP8266 platform! Please check your Tools->Board setting.
#endif
#include <ESPAsync_WiFiManager.h> //https://github.com/khoih-prog/ESPAsync_WiFiManager
AsyncWebServer webServer(80);
DNSServer dnsServer;
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200); while (!Serial); delay(200);
Serial.print("\nStarting Async_AutoConnect_ESP8266_minimal on " + String(ARDUINO_BOARD)); Serial.println(ESP_ASYNC_WIFIMANAGER_VERSION);
ESPAsync_WiFiManager ESPAsync_wifiManager(&webServer, &dnsServer, "AutoConnectAP");
//ESPAsync_wifiManager.resetSettings(); //reset saved settings
//ESPAsync_wifiManager.setAPStaticIPConfig(IPAddress(192,168,186,1), IPAddress(192,168,186,1), IPAddress(255,255,255,0));
ESPAsync_wifiManager.autoConnect("AutoConnectAP");
if (WiFi.status() == WL_CONNECTED) { Serial.print(F("Connected. Local IP: ")); Serial.println(WiFi.localIP()); }
else { Serial.println(ESPAsync_wifiManager.getStatus(WiFi.status())); }
}
void loop() { }
/*
Basic ESP8266 MQTT example
This sketch demonstrates the capabilities of the pubsub library in combination
with the ESP8266 board/library.
It connects to an MQTT server then:
- publishes "hello world" to the topic "outTopic" every two seconds
- subscribes to the topic "inTopic", printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
- If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
else switch it off
It will reconnect to the server if the connection is lost using a blocking
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
achieve the same result without blocking the main loop.
To install the ESP8266 board, (using Arduino 1.6.4+):
- Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
http://arduino.esp8266.com/stable/package_esp8266com_index.json
- Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
- Select your ESP8266 in "Tools -> Board"
*/
#include <WiFi.h>
#include <PubSubClient.h>
#include <EasyButton.h>
#define LED 2 //built-in LED on ESP32
#include "DHT.h"
#define DHTPIN 23 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT11
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.
// Set up the temp / humidity update cycle
const int updateCycle = 5000;
// Update these with values suitable for your network.
const char *ssid = "Wi-Fi SSID";
const char *password = "Wi-Fi Password";
// Define your client ID on EMQX
String mqtt_ClientID = "stonez56_IOT_Station_";
// Define your topics to subscribe / publish
const char* sub_topic = "stonez56/esp32s";
const char* pub_led_topic = "stonez56/esp32s_led_state";
const char* pub_init_topic = "stonez56/esp32s_is_back";
const char* pub_temp_topic = "stonez56/esp32s_temp";
const char* pub_humd_topic = "stonez56/esp32s_humd";
// EMQX broker parameters
const char *mqtt_server = "broker.emqx.io";
const char *mqtt_userName = "emqx";
const char *mqtt_password = "public";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
char msg1[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi()
{
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
payload[length] = '\0';
String message = (char *)payload;
if (strcmp(topic, sub_topic) == 0)
{
if (message == "off")
{
digitalWrite(LED, LOW); //Turn off
client.publish(pub_led_topic, "off");
}
if (message == "on")
{
digitalWrite(LED, HIGH); //Turn on
client.publish(pub_led_topic, "on");
}
}
/* Switch on the LED if an 1 was received as first character
// if ((char)payload[0] == '1')
// {
// digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// // but actually the LED is on; this is because
// // it is active low on the ESP-01)
// }
// else
// {
// digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
// } */
}
void reconnect()
{
// Loop until we're reconnected
while (!client.connected())
{
Serial.println("Attempting EMQX MQTT connection...");
// Create a random client ID
mqtt_ClientID += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect((mqtt_ClientID, mqtt_userName, mqtt_password)))
{
Serial.print(" connected with Client ID: ");
Serial.println(mqtt_ClientID);
// Once connected, publish an announcement...
client.publish(pub_init_topic, "Hi, I'm online!");
// ... and resubscribe
client.subscribe(sub_topic);
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
//Start DH11 sensor
dht.begin();
pinMode(LED, OUTPUT); // Initialize the _LED pin as an output
digitalWrite(LED, LOW); //default ESP32 LOW is turn off
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > updateCycle)
{
lastMsg = now;
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humidity) || isnan(temperature))
{
Serial.println(F("Failed to read from DHT sensor!"));
return;
}else{ // publish the message
snprintf(msg, MSG_BUFFER_SIZE, "%.1lf°", temperature);
snprintf(msg1, MSG_BUFFER_SIZE,"%.0lf%%", humidity);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish(pub_temp_topic, msg);
client.publish(pub_humd_topic, msg1);
}
}
}
/*
Basic ESP8266 MQTT example
This sketch demonstrates the capabilities of the pubsub library in combination
with the ESP8266 board/library.
It connects to an MQTT server then:
- publishes "hello world" to the topic "outTopic" every two seconds
- subscribes to the topic "inTopic", printing out any messages
it receives. NB - it assumes the received payloads are strings not binary
- If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
else switch it off
It will reconnect to the server if the connection is lost using a blocking
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
achieve the same result without blocking the main loop.
To install the ESP8266 board, (using Arduino 1.6.4+):
- Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
http://arduino.esp8266.com/stable/package_esp8266com_index.json
- Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
- Select your ESP8266 in "Tools -> Board"
*/
#include <WiFi.h>
#include <PubSubClient.h>
#include <EasyButton.h>
#define LED 2 //built-in LED on ESP32
// Update these with values suitable for your network.
const char *ssid = "WiFi-SSID";
const char *password = "WiFi-PASSWORD";
// Define your client ID on EMQX
String mqtt_ClientID = "stonez56_IOT_Station_";
// Define your topics to subscribe / publish
const char* sub_topic = "stonez56/esp32s";
const char* pub_led_topic = "stonez56/esp32s_led_state";
const char* pub_init_topic = "stonez56/esp32s_is_back";
// EMQX broker parameters
const char *mqtt_server = "broker.emqx.io";
const char *mqtt_userName = "emqx";
const char *mqtt_password = "public";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi()
{
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
payload[length] = '\0';
String message = (char *)payload;
if (strcmp(topic, sub_topic) == 0)
{
if (message == "off")
{
digitalWrite(LED, LOW); //Turn off
client.publish(pub_led_topic, "off");
}
if (message == "on")
{
digitalWrite(LED, HIGH); //Turn on
client.publish(pub_led_topic, "on");
}
}
/* Switch on the LED if an 1 was received as first character
// if ((char)payload[0] == '1')
// {
// digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// // but actually the LED is on; this is because
// // it is active low on the ESP-01)
// }
// else
// {
// digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
// } */
}
void reconnect()
{
// Loop until we're reconnected
while (!client.connected())
{
Serial.println("Attempting EMQX MQTT connection...");
// Create a random client ID
mqtt_ClientID += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect((mqtt_ClientID, mqtt_userName, mqtt_password)))
{
Serial.print(" connected with Client ID: ");
Serial.println(mqtt_ClientID);
// Once connected, publish an announcement...
client.publish(pub_init_topic, "Hi, I'm online!");
// ... and resubscribe
client.subscribe(sub_topic);
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
pinMode(LED, OUTPUT); // Initialize the _LED pin as an output
digitalWrite(LED, LOW); //default ESP32 LOW is turn off
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
/* unsigned long now = millis();
// if (now - lastMsg > 2000)
// {
// lastMsg = now;
// ++value;
// snprintf(msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
// Serial.print("Publish message: ");
// Serial.println(msg);
// client.publish("stonez56/esp32s_button_pushed", msg);
// } */
}