cloudmqttiotesp32azure-eventgrid

How To USE EVENT GRID NAMESPACE MQTT HOSTNAME ON ESP32 OR ESP32 ONLINE LIKE WOKWI to send Data like Temperature Or Humidity Using DHT22 SENSOR


im on a experiment with ESP32 or ESP32 online like WOKWI using DHT22 Sensors to send data like Temperature and Humidity to MQTT Receiver like MQTTx maybe.

right now i am on a experiment using event grid espescially event grid namespace using MQTT Broker support there. After i enabled the broker and set to Public Connection, can i use the MQTT Hostname to my ESP32 or ESP32 ONLINE like at WOKWI ?

i just want a simple esp32 with dht22 sensor sending data like temperature and humidity to MQTT client like MQTTx maybe

to do this, do i need to use another resource in Azure ? Or just using azure event grid namespace ?

i've trid same documentation like this :

`#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>

// Wi-Fi settings
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// Azure Event Grid settings
const char* mqttBroker = "eventgrid1.southeastasia-1.ts.eventgrid.azure.net";
const int mqttPort = 8883;
const char* eventGridTopic = "Topics/topic1";
const char* username = "client1-authnID";
const char* deviceID = "client1-sessionID1";

// TLS/SSL client setup
WiFiClientSecure wifiClient;
PubSubClient mqttClient(wifiClient);

// Certificates
const char* caCert = "";

const char* clientCert = R"KEY(
-----BEGIN CERTIFICATE-----
MIIB7jCCAZSgAwIBAgIRAM86q1LIwWpvhSCeqIxrTmowCgYIKoZIzj0EAwIwRjEZ
MBcGA1UEChMQTXF0dEFwcFNhbXBsZXNDQTEpMCcGA1UEAxMgTXF0dEFwcFNhbXBs
ZXNDQSBJbnRlcm1lZGlhdGUgQ0EwHhcNMjMwNjE2MDYyNjMzWhcNMjMwOTI0MDYy
NjMwWjAaMRgwFgYDVQQDEw9jbGllbnQxLWF1dGhuSUQwWTATBgcqhkjOPQIBBggq
hkjOPQMBBwNCAASa8R2ZS4wE2c5GU6MApWM/u9F7/Qo1DRhS6VPsr2za0OTXuO9C
hOE3tpxu8G3/rsyM4bPj9I6DAZMebHXbbX/To4GOMIGLMA4GA1UdDwEB/wQEAwIH
gDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwHQYDVR0OBBYEFKkhXgJe
Id1zDD5sESQi3ABs33WIMB8GA1UdIwQYMBaAFIeMEpJCsKRfq+HjhXmE0uVfubMP
MBoGA1UdEQQTMBGCD2NsaWVudDEtYXV0aG5JRDAKBggqhkjOPQQDAgNIADBFAiAq
sZYheFfVrlgNk6De060blPZkrim13yrJRmRo1WUMiAIhAPZ6R+5Hyl5sGB4m8HYh
9mHEl+qVZauee8HGu9IWyKYq
-----END CERTIFICATE-----
)KEY";

const char* clientKey = R"KEY(
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIAb/hcl7cXX8gHH8gjlhXjcaj8pTonHP+MzqcS2rHY13oAoGCCqGSM49
AwEHoUQDQgAEmvEdmUuMBNnORlOjAKVjP7vRe/0KNQ0YUulT7K9s2tDk17jvQoTh
N7acbvBt/67MjOGz4/SOgwGTHmx1221/0w==
-----END EC PRIVATE KEY-----
)KEY";

void setup() {
  Serial.begin(115200);
  delay(2000);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  // Load CA certificate, client certificate, and client key
  wifiClient.setCACert(caCert);
  wifiClient.setCertificate(clientCert);
  wifiClient.setPrivateKey(clientKey);

  // Set MQTT server and port
  mqttClient.setServer(mqttBroker, mqttPort);

  // Set MQTT callback function
  mqttClient.setCallback(callback);

  // Connect to MQTT broker
  connectToMqttBroker();
}

void loop() {
  if (!mqttClient.connected()) {
    // Reconnect to MQTT broker if the connection is lost
    connectToMqttBroker();
  }
  mqttClient.loop();

  // Publish message to Event Grid
  publishEvent();

  // Delay before publishing the next event
  delay(5000);
}

void connectToMqttBroker() {
  while (!mqttClient.connected()) {
    Serial.println("Connecting to MQTT broker...");

    if (mqttClient.connect(username, deviceID,"")) {
      Serial.println("Connected to MQTT broker");
    } else {
      Serial.print("Failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" Retrying in 5 seconds...");
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  // Handle incoming MQTT messages here if needed
}

void publishEvent() {
  // Create the event message
  DynamicJsonDocument eventMessage(256);
  eventMessage["id"] = "1";
  eventMessage["subject"] = "Example Event";
  eventMessage["eventType"] = "example.event";
  JsonObject eventData = eventMessage.createNestedObject("data");
  eventData["key"] = "value";

  // Serialize the event message to a JSON string
  String jsonMessage;
  serializeJson(eventMessage, jsonMessage);

  // Publish the event message to Event Grid
  mqttClient.publish(eventGridTopic, jsonMessage.c_str());
}`

but always get problem like this :

Failed, rc=-2 Retrying in 5 seconds...

Connecting to MQTT broker...


Solution

  • The following is a working sample of the ESP32-S3 MQTT Client to publish a pressed button on the topic of the Azure Event Grid MQTT Broker. The publisher is written using the .NET nanoFramework.

    using Iot.Device.Button;
    using nanoFramework.M2Mqtt;
    using nanoFramework.M2Mqtt.Messages;
    using nanoFramework.Networking;
    using nanoFramework.Runtime.Native;
    using System;
    using System.Diagnostics;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Threading;
    
    namespace NFAppM5StampS3_MQTT_Broker
    {
        public class Program
        {
            static string ssid = "xxxxxx";
            static string password = "xxxxxx";
            //
            static string deviceId = "device2";
            static string username = "device2";
            static string brokerHostName = "xxxxxx.westeurope-1.ts.eventgrid.azure.net";
            static string pub_topic = "abc/test/button";
            //
            static MqttClient device = null;
            static int pinButton = 0;
            
    
            public static void Main()
            {
                int counter = 0;
                Debug.WriteLine("Hello from nanoFramework!");
                GpioButton buttonM5 = new GpioButton(buttonPin: pinButton);
    
                try
                {
                    #region Connect to WiFi
                    CancellationTokenSource cs = new(60000);
                    if (WifiNetworkHelper.ScanAndConnectDhcp(ssid, password, requiresDateTime: true, token: cs.Token))
                        Debug.WriteLine($"Wifi ready - {ssid}");
                    else
                        throw new Exception($"Wifi is not connected.");
                    #endregion
    
                    #region MQTT Connection
                    var clientCert = new X509Certificate2(client_cert, client_key, "");
                    device = new MqttClient(brokerHostName, 8883, true, null, clientCert, MqttSslProtocols.TLSv1_2);
                    device.ProtocolVersion = MqttProtocolVersion.Version_5;
                    device.Settings.ValidateServerCertificate = false;  //no CA signed server! 
                    var ret = device.Connect(deviceId, username, "");
                    if (ret != MqttReasonCode.Success)
                    {
                        Debug.WriteLine($"MQTT ERROR connecting: {ret}");
                        device.Disconnect();
                        throw new Exception("Device failed to connect it");
                    }
                    Debug.WriteLine(">>> Device is connected");
                    #endregion
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.InnerException?.Message ?? ex.Message);
                    Thread.Sleep(5000);
                    Power.RebootDevice();
                }
    
                #region ButtonPress          
                buttonM5.Press += (sender, e) =>
                {
                    Debug.WriteLine("The Button has been pressed");
                    string payload = $"{{\"counter\":{counter++}}}";
                    device.Publish(pub_topic, Encoding.UTF8.GetBytes(payload), "application/json; charset=utf-8", null);
                };
                #endregion
    
                Thread.Sleep(Timeout.Infinite);            
            }
    
            #region Certificates
            private const string client_cert = @"-----BEGIN CERTIFICATE-----
    .....
    -----END CERTIFICATE-----";
    
            private const string client_key = @"-----BEGIN EC PRIVATE KEY-----
    ....
    -----END EC PRIVATE KEY-----";
            #endregion
        }
    }
    

    The following screen snippet shows a subscriber MQTTx Client tool with receiving on the topic, where the button published a message:

    enter image description here

    and the following screen snippet shows the Event Grid messages received on this topic forwarded to the AEG Subscribers.

    enter image description here

    Note, that the telemetry data from the sensors is a straightforward work. It can be published to the AEG MQTT Broker based on the timer each minute.

    Update:

    The following is the packages.config file used in the above code:

    <?xml version="1.0" encoding="utf-8"?>
    <packages>
      <package id="nanoFramework.CoreLibrary" version="1.15.5" targetFramework="netnano1.0" />
      <package id="nanoFramework.Iot.Device.Button" version="1.2.536" targetFramework="netnano1.0" />
      <package id="nanoFramework.M2Mqtt" version="5.1.123" targetFramework="netnano1.0" />
      <package id="nanoFramework.Runtime.Events" version="1.11.15" targetFramework="netnano1.0" />
      <package id="nanoFramework.Runtime.Native" version="1.6.12" targetFramework="netnano1.0" />
      <package id="nanoFramework.System.Collections" version="1.5.31" targetFramework="netnano1.0" />
      <package id="nanoFramework.System.Device.Gpio" version="1.1.38" targetFramework="netnano1.0" />
      <package id="nanoFramework.System.Device.Wifi" version="1.5.81" targetFramework="netnano1.0" />
      <package id="nanoFramework.System.IO.Streams" version="1.1.59" targetFramework="netnano1.0" />
      <package id="nanoFramework.System.Net" version="1.10.77" targetFramework="netnano1.0" />
      <package id="nanoFramework.System.Text" version="1.2.54" targetFramework="netnano1.0" />
      <package id="nanoFramework.System.Threading" version="1.1.32" targetFramework="netnano1.0" />
    </packages>