介绍
手上有一块立创开发板,本着不吃灰的原则把它用起来,今天就来用它来连接上自己部署的MQTT服务器进行数据通信。
硬件:立创开发板
开发环境:Arduino IDE Win11
MQTT 平台:EMQX Platform
立创开发板介绍:
初出茅庐的小李博客之立创开发板初体验【Arduino IDE开发环境】:
地址:https://blog.csdn.net/weixin_43176183/article/details/139101412?spm=1001.2014.3001.5501
MQTT.fx客户端接入EMQX Platform
初出茅庐的小李博客之MQTT.fx客户端接入EMQX Platform
地址:https://blog.csdn.net/weixin_43176183/article/details/139190727?spm=1001.2014.3001.5501
参考文档:
https://docs.emqx.com/zh/cloud/latest/connect_to_deployments/esp32.html
过程记录:
安装MQTT依赖库
在 Arduino IDE 中完成以下安装。
先安装 ESP32 开发板。
点击工具 -> 开发板 -> 开发板管理。搜索 ESP32,点击安装 我已经安装过。
安装 PubSub client 库。
点击项目 -> 加载库 -> 管理库…。搜索 PubSubClient,安装 PubSubClient by Nick O’Leary。
通过 TCP 端口连接
写代码
- 引入对应的库
#include "WiFi.h"
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
- 定义用户自定义参数
// WiFi Credentials
const char *ssid = "AQST"; // Replace with your WiFi name
const char *password = "12345678"; // Replace with your WiFi password
// MQTT Broker Settings
const char *mqtt_broker = "xxxxxx.ala.cn-hangzhou.emqxsl.cn";//这里定义自己的连接地址
const char *mqtt_topic = "emqx/esp32";
const char *mqtt_username = "AQ";
const char *mqtt_password = "123456";
const int mqtt_port = 8883;
- 编写连接代码【准确的来说叫改写】
/连接Wifi热点函数
void ConnectToWiFi(void)
{
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
}
//连接MQTT代理函数
void ConnectToMQTT(void)
{
while (!mqtt_client.connected())
{
String client_id = "esp32-client-" + String(WiFi.macAddress());
Serial.printf("Connecting to MQTT Broker as %s...\n", client_id.c_str());
if(mqtt_client.connect(client_id.c_str(), mqtt_username, mqtt_password))
{
Serial.println("Connected to MQTT broker");
mqtt_client.subscribe(mqtt_topic);
mqtt_client.publish(mqtt_topic, "Hi EMQX I'm ESP32 by Arduino IED ^^"); // Publish message upon connection
}
else
{
Serial.print("Failed to connect to MQTT broker, rc=");
Serial.print(mqtt_client.state());
Serial.println(" Retrying in 5 seconds.");
delay(5000);
}
}
}
//MQTT 回调函数
void MqttCallback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message received on topic: ");
Serial.println(topic);
Serial.print("Message: ");
for (unsigned int i = 0; i < length; i++)
{
Serial.print((char) payload[i]);//打印有效载荷的信息
}
Serial.println("\n-----------------------");
}
- 函数调用
void setup(void)
{
Serial.begin(115200); //设置串口参数
ConnectToWiFi(); //连接Wifi热点
// Set Root CA certificate
espClient.setCACert(ca_cert); //设置CA证书
mqtt_client.setServer(mqtt_broker, mqtt_port);//指定代理 指定端口
mqtt_client.setKeepAlive(60); //保活时间
mqtt_client.setCallback(MqttCallback); //回调函数
ConnectToMQTT(); //连接MQTT 代理
}
void loop(void)
{
if (!mqtt_client.connected())
{
ConnectToMQTT();
}
mqtt_client.loop();
}
特别提示:这里的地址要写自己的地址 CA证书也要用自己的证书 否则连不上
官方原话:
添加服务端证书。如果您在使用公共 MQTT Broker、Serverless 部署或基础版部署的 TLS/SSL 端口连接,在此下载 CA 证书。 如您使用专业版 / BYOC 部署的 TLS/SSL 端口连接,请使用自己的服务端证书。
-
开启MQTT服务器
-
编译烧录代码
用MQTT.fx连接到MQTT服务器跟ESP32开发板进行通信
发布消息:
ESP32收到订阅消息
这里可以看到开发板收到了消息 但是客户端提示收到的消息不是标准json
改进一下发送的数据格式
{
"mag": "This is Json Data"
}
总结:
利用Arduino IED 进行MQTT通信 确实很方便,很容易就能实现两个设备的交互、但是使用库的缺点也很明显 有很多api不太懂它的意思,还需要进一步研究。
完整代码
#include "WiFi.h"
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
// WiFi Credentials
const char *ssid = "AQST"; // Replace with your WiFi name
const char *password = "12345678"; // Replace with your WiFi password
// MQTT Broker Settings
const char *mqtt_broker = "xxxxxxx.ala.cn-hangzhou.emqxsl.cn";//这里要改成自己的地址!!!!
const char *mqtt_topic = "emqx/esp32";
const char *mqtt_username = "AQ";
const char *mqtt_password = "123456";
const int mqtt_port = 8883;
WiFiClientSecure espClient;
PubSubClient mqtt_client(espClient);
void ConnectToWiFi(void);//函数声明
void ConnectToMQTT(void);//函数声明
void MqttCallback(char *mqtt_topic, byte *payload, unsigned int length);//函数声明
const char *ca_cert = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB
CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97
nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt
43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P
T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4
gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO
BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR
TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw
DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr
hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg
06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF
PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls
YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
-----END CERTIFICATE-----
)EOF";
void setup(void)
{
Serial.begin(115200); //设置串口参数
ConnectToWiFi(); //连接Wifi热点
// Set Root CA certificate
espClient.setCACert(ca_cert); //设置CA证书
mqtt_client.setServer(mqtt_broker, mqtt_port);//指定代理 指定端口
mqtt_client.setKeepAlive(60); //保活时间
mqtt_client.setCallback(MqttCallback); //回调函数
ConnectToMQTT(); //连接MQTT 代理
}
//连接Wifi热点函数
void ConnectToWiFi(void)
{
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
}
//连接MQTT代理函数
void ConnectToMQTT(void)
{
while (!mqtt_client.connected())
{
String client_id = "esp32-client-" + String(WiFi.macAddress());
Serial.printf("Connecting to MQTT Broker as %s...\n", client_id.c_str());
if(mqtt_client.connect(client_id.c_str(), mqtt_username, mqtt_password))
{
Serial.println("Connected to MQTT broker");
mqtt_client.subscribe(mqtt_topic);
mqtt_client.publish(mqtt_topic, "Hi EMQX I'm ESP32 by Arduino IED ^^"); // Publish message upon connection
}
else
{
Serial.print("Failed to connect to MQTT broker, rc=");
Serial.print(mqtt_client.state());
Serial.println(" Retrying in 5 seconds.");
delay(5000);
}
}
}
//MQTT 回调函数
void MqttCallback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message received on topic: ");
Serial.println(topic);
Serial.print("Message: ");
for (unsigned int i = 0; i < length; i++)
{
Serial.print((char) payload[i]);//打印有效载荷的信息
}
Serial.println("\n-----------------------");
}
void loop(void)
{
if (!mqtt_client.connected())
{
ConnectToMQTT();
}
mqtt_client.loop();
}
// WiFiClient espClient;
// PubSubClient mqtt_client(espClient);
// void setup(void)
// {
// Serial.begin(115200);
// ConnectToWiFi(); //连接指定热点
// //mqtt_client.setServer(mqtt_broker, mqtt_port);
// espClient.setCACert(ca_cert);
// mqtt_client.setKeepAlive(60);
// mqtt_client.setCallback(MqttCallback); // Corrected callback function name
// ConnectToMQTT();
// }
// void loop(void)
// {
// if (!mqtt_client.connected())
// {
// ConnectToMQTT();
// }
// mqtt_client.loop();
// }
//用户自定义函数
// void ConnectToWiFi(void)
// {
// WiFi.begin(ssid, password);
// Serial.print("Connecting to WiFi");
// while (WiFi.status() != WL_CONNECTED)
// {
// delay(500);
// Serial.print(".");
// }
// Serial.println("\nConnected to WiFi");
// }
// //用户自定义函数
// void ConnectToMQTT(void)
// {
// while (!mqtt_client.connected())
// {
// String client_id = "esp32-client-" + String(WiFi.macAddress());
// Serial.printf("Connecting to MQTT Broker as %s.....\n", client_id.c_str());
// if (mqtt_client.connect(client_id.c_str(), mqtt_username, mqtt_password))
// {
// Serial.println("Connected to MQTT broker");
// mqtt_client.subscribe(mqtt_topic);
// mqtt_client.publish(mqtt_topic, "Hi EMQX I'm ESP32 ^^"); // Publish message upon successful connection
// }
// else
// {
// Serial.print("Failed, rc=");
// Serial.print(mqtt_client.state());
// Serial.println(" try again in 5 seconds");
// delay(5000);
// }
// }
// }
//用户自定义回调函数
// void MqttCallback(char *mqtt_topic, byte *payload, unsigned int length)
// {
// Serial.print("Message received on mqtt_topic: ");
// Serial.println(mqtt_topic);
// Serial.print("Message: ");
// for (unsigned int i = 0; i < length; i++)
// {
// Serial.print((char) payload[i]);
// }
// Serial.println("\n-----------------------");
// }
视频:
https://www.bilibili.com/video/BV1gJ4m1A7bg/?pop_share=1