我一直在尝试通过 MQTT 将我的 ESP32 板连接到我的笔记本电脑。我已经在我的笔记本电脑上安装了 Mosquitto MQTT 代理,但我每次都无法连接我的 ESP32。这是我用来检查 MQTT 连接的测试代码。
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "......"; //WiFi Name
const char* password = "......"; //WiFi Password
const char* server= "xxx.xxx.xx.xx"; //RPi or Machine IP on which the broker is
WiFiClient espClient;
PubSubClient client(espClient);
int setup_WiFi(){
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("Attempting MQTT connection...");
client.connect("esp32");
if (client.connect("esp32")){
Serial.println("connected");
}
else {
Serial.print("failed, rc=");
Serial.println(client.state());
}
return 0;
}
int reconnect() {
unsigned long startAttemptTime = millis();
while (!client.connected())
{
Serial.println("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("esp32")){
Serial.println("connected");
}
else {
Serial.print("failed, rc=");
Serial.println(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
return 0;
}
int send_mqtt(){
setup_WiFi();
char sss[15]="Hello World";
if (!client.connected()){
reconnect();
}
client.publish("esp32/test", sss); //send message
WiFi.disconnect(true);
Serial.println("Sent");
return 0;
}
void setup() {
Serial.begin(115200);
client.setServer(server, 1883); //mqtt server details
setup_WiFi();
reconnect();
}
void loop() {
send_mqtt();
delay(10000); //Wait 10 secs before next transmission
}
但每次我得到错误
失败,rc=-2
在过去的两个月左右的时间里,我一直在尝试做同样的事情,但没有成功。同时,我广泛搜索了互联网,看看我做错了什么。我确保两个设备都在同一个局域网上。