代码:
#include <WiFi.h>#include <PubSubClient.h>const char *id=\"wifi名称\";const char *psw=\"wifi密码\";char *serverip=\"服务器ip\";int port=1883;char *serveruser=\"admin\";char *serverpsw=\"pubilic\";WiFiClient espclient;PubSubClient client(espclient);void callback(char *topic,byte *payload,unsigned int length){Serial.print(\"来自主题:\");Serial.println(topic);Serial.print(\"内容:\");for(int i=0;i<length;i++){Serial.print((char)payload[i]);}Serial.println(\"\");Serial.println(\"------------------------------------\");}void setup() {Serial.begin(115200);while(WiFi.status()!=WL_CONNECTED){delay(2500);Serial.println(\"正在连接至wifi...\");WiFi.begin(id,psw);}Serial.println(\"已连接.\");client.setServer(serverip,port);client.setCallback(callback);while(!client.connected()){Serial.println(\"正连接至MQTT服务器...\");if(client.connect(\"测试\",serveruser,serverpsw)){Serial.println(\"登录成功...\");}else{Serial.println(\"登陆失败,重新连接...\");Serial.println(client.state());delay(2000);}}client.subscribe(\"ESP32\");client.publish(\"ESP32\",\"测试测试from ESP32\");Serial.println(\"已发送测试消息\");}void loop() {client.loop();}
几个关键函数:
client.subscribe(String):订阅XXX主题
client.setCallback:接收来自服务器的消息
相关定义
#if defined(ESP8266) || defined(ESP32)#include <functional>#define MQTT_CALLBACK_SIGNATURE std::function<void(char*, uint8_t*, unsigned int)> callback#else#define MQTT_CALLBACK_SIGNATURE void (*callback)(char*, uint8_t*, unsigned int)#endif
PubSubClient& setCallback(MQTT_CALLBACK_SIGNATURE);
PubSubClient& PubSubClient::setCallback(MQTT_CALLBACK_SIGNATURE) {this->callback = callback;return *this;}
结果:
参考文章:
ESP32入门Arduino开发(八)–MQTT subscribing
PubSubClient-GitHuB库