前言
1.了解如何接入的基本知识->4.3 MQTT设备云 2.看不懂没关系,稍微了解下即可.
?成功连接并接收到推送的消息?
21:58:22.594 -> Attempting MQTT connection...connected
21:58:22.692 -> Subscription to 'xxxxx' successful.
21:58:44.312 -> Message arrived [xxxxx] hello
22:00:22.725 -> Message arrived [xxxxx] 12
虽然是在esp32cam中使用,但其他esp版也可以尝试使用.如果可以可以邮我rorinliang076@gmail.com❥(^_-)
实操
1.打开Arduino下载PubSubClient库. 2.PubSubClient引入项目
#include <WiFi.h>
#include <PubSubClient.h>
3.声明配置项
const char* mqtt_server = "bemfa.com";
const int mqtt_server_port = 9501;
#define ID_MQTT "" //你的秘钥
String topic = ""; //你要订阅的主题
WiFiClient espClient;
PubSubClient client(espClient);
4.其他代码
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();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(ID_MQTT)) {
Serial.println("connected");
// 订阅主题 "example/topic"
if(client.subscribe(topic)) {
Serial.println("Subscription to '"+topic+"' successful.");
} else {
Serial.println("Subscription failed.");
}
} 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(){
//order code ...
client.setServer(mqtt_server,mqtt_server_port);
client.setCallback(callback);
if (client.connect(ID_MQTT)) {
Serial.println("Connected to MQTT server");
if(client.subscribe("camarados")) {
Serial.println("Subscription to 'camarados' successful.");
} else {
Serial.println("Subscription failed.");
}
} else {
Serial.println("MQTT connection failed");
}
//order code ...
}
void loop(){
if (!client.connected()) {
reconnect();
}
client.loop();
}
callback(): 这个回调函数将会在客户端收到订阅主题的消息时被调用,可以在这里做一些逻辑判断等操作.
reconnect(): 尝试连接到MQTT服务器.
在setup()函数中,通过setServer与setCallback初始化了mqtt链接.并判断是否连接成功,当连接成功时,使用
订阅主题; 同样的当需要reconnect()的时候,在reconnect()中也进行重新订阅,确保mqtt连接正常. client.subscribe