麻烦问一下,esp8266nodemcu在使用arduino.ide连接阿里云平台的时候,wifi配置正常但连接不上mqtt,显示报错如下:
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
以下附报错源代码:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// WiFi 配置
const char* ssid = "Flutter"; // 替换为你的热点SSID
const char* password = "87654321"; // 替换为你的热点密码
// 阿里云 IoT 配置
const char* productKey = ""; // 替换为你的产品密钥
const char* deviceName = ""; // 替换为你的设备名称
const char* deviceSecret = ""; // 替换为你的设备密钥
// MQTT 服务器配置
const char* mqttServer = "iot-as-mqtt.cn-shanghai.aliyuncs.com";
const int mqttPort = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqttServer, mqttPort);
client.setCallback(mqttCallback);
}
void setup_wifi() {
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
int attempts = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
attempts++;
if (attempts >= 20) {
Serial.println(" Failed to connect to WiFi.");
Serial.print("WiFi status: ");
Serial.println(WiFi.status());
return;
}
}
Serial.println(" WiFi connected");
}
void mqttCallback(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 connectMQTT() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = String(productKey) + "." + String(deviceName); // 客户端ID
if (client.connect(clientId.c_str(), deviceName, deviceSecret)) {
Serial.println("MQTT connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state()); // 打印错误代码
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
connectMQTT();
}
client.loop();
// 示例:发送数据到阿里云
String payload = "{\"id\":\"1\",\"data\":{\"temperature\":25}}"; // 示例数据
String topic = "/sys/" + String(productKey) + "/" + String(deviceName) + "/thing/event/property/post"; // 主题
if (client.publish(topic.c_str(), payload.c_str())) {
Serial.println("Data sent to Aliyun: " + payload);
} else {
Serial.println("Data failed to send to Aliyun");
}
delay(10000); // 每10秒发送一次数据
} |