如何在 ESP32 上使用事件网格命名空间 MQTT 主机名或像 WOKWI 一样在线使用 ESP32 使用 DHT22 传感器发送温度或湿度等数据

问题描述 投票:0回答:1

我正在像 WOKWI 一样使用 ESP32 或 ESP32 在线进行实验,使用 DHT22 传感器将温度和湿度等数据发送到 MQTT 接收器(例如 MQTTx)。

现在我正在使用事件网格进行实验,特别是使用 MQTT Broker 支持的事件网格命名空间。启用代理并设置为公共连接后,我可以像 WOKWI 一样使用 MQTT 主机名连接到我的 ESP32 或 ESP32 ONLINE 吗?

我只想要一个带有 dht22 传感器的简单 esp32,将温度和湿度等数据发送到 MQTT 客户端(例如 MQTTx)

为此,我需要使用 Azure 中的其他资源吗?或者只是使用天蓝色事件网格命名空间?

我已经尝试过类似的文档:

`#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());
}`

但总是遇到这样的问题:

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

正在连接到 MQTT 代理...

cloud mqtt iot esp32 azure-eventgrid
1个回答
0
投票

以下是 ESP32-S3 MQTT 客户端的工作示例,用于发布关于 Azure Event Grid MQTT Broker 主题的按下按钮。发布器是使用 .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
    }
}

以下屏幕片段显示了订阅者 MQTTx 客户端工具,该工具正在接收主题,其中按钮发布了一条消息:

以下屏幕片段显示了转发到 AEG 订阅者的有关此主题的事件网格消息。

请注意,来自传感器的遥测数据是一项简单的工作。可以根据每分钟的计时器发布到 AEG MQTT Broker。

© www.soinside.com 2019 - 2024. All rights reserved.