我之前在esp8266上使用mosquito的测试mqtt代理(即test.mosquitto.org),并且使用了重新连接代码,即如果由于路由器重置而导致连接断开,则当互联网恢复连接时它将重新连接到代理。而且工作正常。我在Cloud Mqtt代理中使用了相同的代码,它也运行得很好。但是现在,当我像本教程MQTT broker on AWS EC2那样托管自己的mosquitto代理时,路由器重置后它停止了重新连接。以下是我在ESP8266上的代码:-
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* topic = "someTopic";
String clientId = "randomClientId";
const char* mqttServer = "xxxxxxxxxxxxxxx.compute.amazonaws.com";
const int mqttPort = 1883;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
lastReconnectAttempt = 0;
delay(500);
}
boolean reconnect() {
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
client.subscribe(topic);
}
return client.connected();
}
void loop() {
if (!client.connected())
{
long now = millis();
if (now - lastReconnectAttempt > 5000)
{
lastReconnectAttempt = now;
if (reconnect())
{
lastReconnectAttempt = 0;
}
}
} else
{
client.loop();
}
}
请让我知道是否有人知道原因。