Page 1 of 1

MQTT & MQTTS - Sample implementation for ESP32

Posted: Thu Apr 23, 2020 9:13 pm
by martinius96
Hello, today I would like to show you sample implementations for connection and Publish / Subscribe to MQTT Broker.
Example is using public MQTT Broker located in Slovakia - use only for development (not my Broker)... Everyone can see / modify your datas there.
MQTT Broker details:
Image
Webpage of MQTT Broker: https://mqtt.iotindustries.sk/
Implementations are for MQTT and secure MQTT (MQTTS) connection with that Broker. ESP32 is using socket for connection based on WiFi.h library or secured socket under WiFiClientSecure.h. Implementation for MQTT is for WPA/WPA2 PSK and also for Enterprise networks (such as eduroam, Ziggo). Each implementation is Publish-ing increment value from counter... Datas are send each 10 seconds and they are also Subscribed from same board (verify of sent datas).
Implementations are ESP8266, ESP32, Arduino + Ethernet compatible (MQTTS only for ESP8266, ESP32).
Topic for Publish / Sebscribe in example: esp32/pocitadlo
Output in Serial monitor:
Image
If you want to read all topics on MQTT broker, ask for topic #.
You can see user datas about temperature, humidity, users in channels (chat) and so on. That MQTT Broker is public and anyone can modify / delete / read your datas too. For that you can use that server as backup or for testing / developing purposes.
Output will be:
Image
Implementations available also at: https://github.com/martinius96/MQTT-Bro ... Industries
MQTT connection - WPA/WPA2 - PSK

Code: Select all

//ESP32, ESP8266, Arduino + Ethernet - Publish / Subscribe
//Author: Martin Chlebovec (martinius96)
//Web: https://arduino.php5.sk
//Donate for more: https://paypal.me/chlebovec

#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#include <SPI.h>
#include <Ethernet.h>
//#include <Ethernet2.h> //for Wiznet W5500 Ethernet module
#elif defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <PubSubClient.h>

#if defined(ESP32) || defined(ESP8266)
WiFiClient espClient;
const char* ssid = "WIFI_NAME";
const char* password = "WIFI_PASSWORD";
#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
EthernetClient espClient;
byte mac[] = { 0xAA, 0xBB, 0xCC, 0x81, 0x7B, 0x4A };
//IPAddress ip(192, 168, 0, 2);
//IPAddress dnServer(192, 168, 0, 1);
//IPAddress gateway(192, 168, 0, 1);
//IPAddress subnet(255, 255, 255, 0);
#endif
const char* mqtt_server = "mqtt.iotindustries.sk";
PubSubClient client(espClient);
unsigned long lastMsg = 0;
char msg[50];
int pocitadlo = 0;
void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("esp32/output");
    } 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() {
  Serial.begin(115200);
  Serial.println("UART ready");
#if defined(ESP32) || defined(ESP8266)
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  if (Ethernet.begin(mac) == 0) {
    Ethernet.begin(mac);
    //Ethernet.begin(mac, ip);
    //Ethernet.begin(mac, ip, dns);
    //Ethernet.begin(mac, ip, dns, gateway);
    //Ethernet.begin(mac, ip, dns, gateway, subnet);
  }
  Serial.print("  DHCP assigned IP ");
  Serial.println(Ethernet.localIP());
#endif
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
#if defined(ESP32) || defined(ESP8266)
  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid, password);
  }
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  if (Ethernet.begin(mac) == 0) {
    Ethernet.begin(mac);
    //Ethernet.begin(mac, ip);
    //Ethernet.begin(mac, ip, dns);
    //Ethernet.begin(mac, ip, dns, gateway);
    //Ethernet.begin(mac, ip, dns, gateway, subnet);
  }
#endif
  client.loop();
  if (millis() - lastMsg > 10000) {
    char pocitadlo_pole[8];
    pocitadlo  = pocitadlo + 1;
    dtostrf(pocitadlo, 1, 2, pocitadlo_pole);
    client.publish("esp32/pocitadlo", pocitadlo_pole);
    client.subscribe("esp32/pocitadlo");
    lastMsg = millis();
  }
}
MQTT connection - WPA/WPA2 - Enterprise (eduroam, Ziggo)

Code: Select all

#include <WiFi.h>
#include "esp_wpa2.h" //wpa2 library for connections to Enterprise networks
#include <PubSubClient.h>


char EAP_ANONYMOUS_IDENTITY[] = "anonymous@example.com";
char EAP_IDENTITY[] = "id@example.com";
char EAP_PASSWORD[] = "EDUROAM_PASSWORD";
const char* ssid = "eduroam"; // eduroam SSID
const char* mqtt_server = "mqtt.iotindustries.sk";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
char msg[50];
int pocitadlo = 0;
void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("esp32/output");
    } 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() {
  Serial.begin(115200);
  esp_wifi_sta_wpa2_ent_set_identity((uint8_t *)EAP_ANONYMOUS_IDENTITY, strlen(EAP_ANONYMOUS_IDENTITY));
  esp_wifi_sta_wpa2_ent_set_username((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY));
  esp_wifi_sta_wpa2_ent_set_password((uint8_t *)EAP_PASSWORD, strlen(EAP_PASSWORD));
  esp_wpa2_config_t config = WPA2_CONFIG_INIT_DEFAULT(); //set config settings to default
  esp_wifi_sta_wpa2_ent_enable(&config); //set config settings to enable function
  WiFi.begin(ssid); //connect to wifi network under Enterprise 802.1x
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid);
  }
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  client.loop();
  if (millis() - lastMsg > 10000) {
    char pocitadlo_pole[8];
    pocitadlo  = pocitadlo + 1;
    dtostrf(pocitadlo, 1, 2, pocitadlo_pole);
    client.publish("esp32/pocitadlo", pocitadlo_pole);
    client.subscribe("esp32/pocitadlo");
    lastMsg = millis();
  }
}
MQTTS connection - WPA/WPA2 - PSK (SECURED MQTT)

Code: Select all

//ESP32, ESP8266 - Publish / Subscribe - MQTTS
//Author: Martin Chlebovec (martinius96)
//Web: https://arduino.php5.sk
//ESP8266 COMPATIBLE CORE 2.5.0, 2.5.2
//Donate for more: https://paypal.me/chlebovec

#include <PubSubClient.h>
#include <WiFiClientSecure.h>
const char* ssid = "WIFI_NAME";
const char* password = "WIFI_PASSWORD";

#if defined(ESP32)
#include <WiFi.h>

// Root CA
const static char* test_root_ca PROGMEM = \
    "-----BEGIN CERTIFICATE-----\n" \
    "MIIFdzCCBF+gAwIBAgIQE+oocFv07O0MNmMJgGFDNjANBgkqhkiG9w0BAQwFADBv\n" \
    "MQswCQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFk\n" \
    "ZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYDVQQDExlBZGRUcnVzdCBF\n" \
    "eHRlcm5hbCBDQSBSb290MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEwNDgzOFow\n" \
    "gYgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpOZXcgSmVyc2V5MRQwEgYDVQQHEwtK\n" \
    "ZXJzZXkgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMS4wLAYD\n" \
    "VQQDEyVVU0VSVHJ1c3QgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjAN\n" \
    "BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAgBJlFzYOw9sIs9CsVw127c0n00yt\n" \
    "UINh4qogTQktZAnczomfzD2p7PbPwdzx07HWezcoEStH2jnGvDoZtF+mvX2do2NC\n" \
    "tnbyqTsrkfjib9DsFiCQCT7i6HTJGLSR1GJk23+jBvGIGGqQIjy8/hPwhxR79uQf\n" \
    "jtTkUcYRZ0YIUcuGFFQ/vDP+fmyc/xadGL1RjjWmp2bIcmfbIWax1Jt4A8BQOujM\n" \
    "8Ny8nkz+rwWWNR9XWrf/zvk9tyy29lTdyOcSOk2uTIq3XJq0tyA9yn8iNK5+O2hm\n" \
    "AUTnAU5GU5szYPeUvlM3kHND8zLDU+/bqv50TmnHa4xgk97Exwzf4TKuzJM7UXiV\n" \
    "Z4vuPVb+DNBpDxsP8yUmazNt925H+nND5X4OpWaxKXwyhGNVicQNwZNUMBkTrNN9\n" \
    "N6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n" \
    "0fKtirOMxyHNwu8=\n" \
    "-----END CERTIFICATE-----\n";
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
const static char fingerprint[] PROGMEM = "f6 15 f1 2a fb b5 ec a1 39 a1 79 30 2a bf 97 bc ce 49 14 5e"; //SHA1 FINGERPRINT
#endif
#if defined(ESP32) || defined(ESP8266)
WiFiClientSecure  espClient;
#endif
const char* mqtt_server = "mqtt.iotindustries.sk";
PubSubClient client(espClient);
unsigned long lastMsg = 0;
char msg[50];
int pocitadlo = 0;
void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("esp32/output");
    } 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() {
  Serial.begin(115200);
  Serial.println("UART ready");
#if defined(ESP32)
  espClient.setCACert(test_root_ca);
#elif defined(ESP8266)
  espClient.setFingerprint(fingerprint);
#endif
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  client.setServer(mqtt_server, 8883);
  client.setCallback(callback);
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid, password);
  }
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  client.loop();
  if (millis() - lastMsg > 10000) {
    char pocitadlo_pole[8];
    pocitadlo  = pocitadlo + 1;
    dtostrf(pocitadlo, 1, 2, pocitadlo_pole);
    client.publish("esp32/pocitadlo", pocitadlo_pole);
    client.subscribe("esp32/pocitadlo");
    lastMsg = millis();
  }
}
MQTTS connection - WPA/WPA2 - Enterprise (eduroam, Ziggo)

Code: Select all

//ESP32 - Publish / Subscribe - MQTTS - WPA/WPA2 Enterprise
//Author: Martin Chlebovec (martinius96)
//Web: https://arduino.php5.sk
//Donate for more: https://paypal.me/chlebovec

#include <WiFi.h>
#include "esp_wpa2.h" //wpa2 library for connections to Enterprise networks
#include <WiFiClientSecure.h>
#include <PubSubClient.h>

char EAP_ANONYMOUS_IDENTITY[] = "anonymous@example.com";
char EAP_IDENTITY[] = "id@example.com";
char EAP_PASSWORD[] = "EDUROAM_PASSWORD";
const char* ssid = "eduroam"; // eduroam SSID

// Root CA
const static char* test_root_ca PROGMEM = \
    "-----BEGIN CERTIFICATE-----\n" \
    "MIIFdzCCBF+gAwIBAgIQE+oocFv07O0MNmMJgGFDNjANBgkqhkiG9w0BAQwFADBv\n" \
    "MQswCQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFk\n" \
    "ZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYDVQQDExlBZGRUcnVzdCBF\n" \
    "eHRlcm5hbCBDQSBSb290MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEwNDgzOFow\n" \
    "gYgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpOZXcgSmVyc2V5MRQwEgYDVQQHEwtK\n" \
    "ZXJzZXkgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMS4wLAYD\n" \
    "VQQDEyVVU0VSVHJ1c3QgUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjAN\n" \
    "BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAgBJlFzYOw9sIs9CsVw127c0n00yt\n" \
    "UINh4qogTQktZAnczom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3NwLnVzZXJ0cnVzdC5jb20wDQYJKoZIhvcNAQEMBQADggEBAJNl9jeD\n" \
    "lQ9ew4IcH9Z35zyKwKoJ8OkLJvHgwmp1ocd5yblSYMgpEg7wrQPWCcR23+WmgZWn\n" \
    "RtqCV6mVksW2jwMibDN3wXsyF24HzloUQToFJBv2FAY7qCUkDrvMKnXduXBBP3zQ\n" \
    "YzYhBx9G/2CkkeFnvN4ffhkUyWNnkepnB2u0j4vAbkN9w6GAbLIevFOFfdyQoaS8\n" \
    "Le9Gclc1Bb+7RrtubTeZtv8jkpHGbkD4jylW6l/VXxRTrPBPYer3IsynVgviuDQf\n" \
    "Jtl7GQVoP7o81DgGotPmjw7jtHFtQELFhLRAlSv0ZaBIefYdgWOWnU914Ph85I6p\n" \
    "0fKtirOMxyHNwu8=\n" \
    "-----END CERTIFICATE-----\n";
WiFiClientSecure  espClient;
const char* mqtt_server = "mqtt.iotindustries.sk";
PubSubClient client(espClient);
unsigned long lastMsg = 0;
char msg[50];
int pocitadlo = 0;

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;

  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe("esp32/output");
    } 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() {
  Serial.begin(115200);
  Serial.println("UART ready");
  espClient.setCACert(test_root_ca);
  esp_wifi_sta_wpa2_ent_set_identity((uint8_t *)EAP_ANONYMOUS_IDENTITY, strlen(EAP_ANONYMOUS_IDENTITY));
  esp_wifi_sta_wpa2_ent_set_username((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY));
  esp_wifi_sta_wpa2_ent_set_password((uint8_t *)EAP_PASSWORD, strlen(EAP_PASSWORD));
  esp_wpa2_config_t config = WPA2_CONFIG_INIT_DEFAULT(); //set config settings to default
  esp_wifi_sta_wpa2_ent_enable(&config); //set config settings to enable function
  WiFi.begin(ssid); //connect to wifi network under Enterprise 802.1x
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  client.setServer(mqtt_server, 8883);
  client.setCallback(callback);
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid);
  }
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  client.loop();
  if (millis() - lastMsg > 10000) {
    char pocitadlo_pole[8];
    pocitadlo  = pocitadlo + 1;
    dtostrf(pocitadlo, 1, 2, pocitadlo_pole);
    client.publish("esp32/pocitadlo", pocitadlo_pole);
    client.subscribe("esp32/pocitadlo");
    lastMsg = millis();
  }
}
More projects from my portfolio: https://arduino.php5.sk/?lang=en

Re: MQTT & MQTTS - Sample implementation for ESP32

Posted: Tue Apr 20, 2021 9:13 am
by sanketa
Hi
You have done a nice work.
Can u Please help me with using MQTT and MQTTS in one code and according to the configuration it should switch between the two clients ( i.e SECURED and NON-SECURED).

Re: MQTT & MQTTS - Sample implementation for ESP32

Posted: Fri Jun 11, 2021 8:22 pm
by martinius96
And where is problem? What have you tried?
Everything is in there example implementations, you only need to combine both examples.
You will create two objects, one for WiFiClient class and other for WiFiClientSecure class.
Then you will use these objects for MQTT. WiFiClient object will be used for non-secured 1883 port and WiFiClientSecure object for 8883 secured MQTT port with Root CA cert, nothing more. Few rows of code.

Re: MQTT & MQTTS - Sample implementation for ESP32

Posted: Tue Oct 17, 2023 11:24 am
by pradeepa
Hi,
I was trying with your "MQTTs connnection - WPA/WPA2 - PSK (SECURED MQTT)".
It worked exactly what I was expecting. Now if i want to use my own MQTT server, can you please guide me on the steps & the required changes.

Thanks in advance.

Re: MQTT & MQTTS - Sample implementation for ESP32

Posted: Sat Dec 09, 2023 2:24 pm
by martinius96
It is required to change url, target topic, CA certificate that issued certificate for your server.
I think there should be also possible to use Certificate bundle, so it will be used "automatically" if its standard Root CA and not self-signed CA.