问题
I am trying to establish MQTT communication with my local MQTT server on my pc (node.js, express, Mosca) and Esp8266.
esp8286 is not connecting with my server, the error is
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Can't connect to Broker.
Here is Node js code:
var moscaSettings = {
host: '0.0.0.0',
port: 1883,
http: {
port: 8002,
host: '0.0.0.0',
static: './mqtt/',
bundle: true,
},
};
var server = new mosca.Server(moscaSettings);
// var server = new mosca.Server({
// host: '192.168.1.75'
// });
server.on('clientConnected', function(client) {
console.log('client connected', client.id);
});
server.on('clientDisconnected', function(client) {
console.log('client disconnected', client.id);
});
server.on('published', function(packet, client) {
console.log(packet);
});
server.on('subscribed', function(topic, client) {
console.log('subscribed: ' + client.id);
});
server.on('unsubscribed', function(topic, client) {
console.log('unsubscribed: ' + client.id);
});
var ledCommand = '1';
setInterval(function() {
ledCommand = (ledCommand === '1') ? '1' : '0';
server.publish({topic: '1/1/1', payload: ledCommand});
}, 8000);
server.on('ready', function() {
console.log('Mosca server is up and running');
console.log("MQTT server is ready on port %s", moscaSettings.port);
console.log("HTTP Server is ready on pott %s", moscaSettings.http.port);
});
process.on('uncaughtException', function (err) {
console.error(err.stack);
console.log("Node NOT Exiting...");
});
and here is Esp8266 code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <EEPROM.h>
// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "AP1";
const char* password = "API@786_22#";
const char* mqtt_server = "192.168.1.75";
const char* clientname = "ESP-01-CLIENT1234";
//const int mqttPort = 3000;
WiFiClient espClient;
PubSubClient client(espClient);
// for data store intilization
int address = 10;
int s1=11;
int s2=12;
char arrayToStore1[10];
char arrayToStore2[10];
char arrayToStore[10];
// Connect an LED to each GPIO of your ESP8266
const int ledGPIO2 = D2;
const int ledGPIO3 = D3;
// Don't change the function below. This functions connects your ESP8266 to your router
void 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.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
// This functions is executed when some device publishes a message to a topic that your ESP8266 is subscribed to
// Change the function below to add logic to your program, so when a device publishes a message to a topic that
// your ESP8266 is subscribed you can actually do something
void callback(String topic, byte* message, unsigned int length) {
pinMode(ledGPIO3, OUTPUT);
pinMode(ledGPIO2, OUTPUT);
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// Feel free to add more if statements to control more GPIOs with MQTT
// If a message is received on the topic home/office/esp1/gpio2, you check if the message is either 1 or 0. Turns the ESP GPIO according to the message
if(topic=="1/1/1" || topic=="1/1"){
topic.toCharArray(arrayToStore, topic.length()+1);
EEPROM.begin(512);
EEPROM.put(address, arrayToStore);
EEPROM.commit();
Serial.println(arrayToStore);
Serial.print("Changing GPIO 4 for 1 ");
if(messageTemp == "1"){
digitalWrite(ledGPIO2, LOW);
messageTemp.toCharArray(arrayToStore1, messageTemp.length()+1);
EEPROM.put(s1, arrayToStore1);
EEPROM.commit();
Serial.print("On");
}
else if(messageTemp == "0"){
Serial.print("Changing GPIO 4 for 0 ");
digitalWrite(ledGPIO2, HIGH);
Serial.print("Off");
}
}
if(topic=="1/1/2" || topic=="1/1"){
Serial.print("Changing GPIO 5 to ");
if(messageTemp == "1"){
digitalWrite(ledGPIO3, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
digitalWrite(ledGPIO3, LOW);
Serial.print("Off");
}
}
Serial.println();
}
// This functions reconnects your ESP8266 to your MQTT broker
// Change the function below if you want to subscribe to more topics with your ESP8266
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(clientname,"usman.jamil","Code@123")) {
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("presence", "hello from mqtt");
client.subscribe("1/1/1");
client.subscribe("1/1");
client.subscribe("1/1/2");
// ... and resubscribe
//client.subscribe("tempfeed");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// The setup function sets your ESP GPIOs to Outputs, starts the serial communication at a baud rate of 115200
// Sets your mqtt broker and sets the callback function
// The callback function is what receives messages and actually controls the LEDs
void setup() {
// client.setCallback(callback);
// pinMode(ledGPIO2, OUTPUT);
Serial.begin(115200);
EEPROM.begin(512);
setup_wifi();
client.setServer(mqtt_server, 1883); //1883
client.setCallback(callback);
Serial.println("void setup runnning here ");
Serial.println("value saved in eeprom ");
EEPROM.get(s1, arrayToStore1);
Serial.println(arrayToStore1);
//if(arrayToStore=="1/1/1")
if (strcmp(arrayToStore1, "1") == 0)
{
Serial.println("value in eeprom ");
//digitalWrite(ledGPIO2, HIGH);
pinMode(ledGPIO2, OUTPUT);
}
else{
Serial.println("value not saved in eeprom ");
// digitalWrite(ledGPIO2, HIGH);
}
}
// For this project, you don't need to change anything in the loop function.
// Basically it ensures that you ESP is connected to your broker
void loop() {
if (!client.connected()) {
reconnect();
}
if(!client.loop())
/*
YOU NEED TO CHANGE THIS NEXT LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS
To change the ESP device ID, you will have to give a unique name to the ESP8266.
Here's how it looks like now:
client.connect("ESP8266Client");
If you want more devices connected to the MQTT broker, you can do it like this:
client.connect("ESPOffice");
Then, for the other ESP:
client.connect("ESPGarage");
That should solve your MQTT multiple connections problem
THE SECTION IN recionnect() function should match your device name
*/
client.connect(clientname);
}
来源:https://stackoverflow.com/questions/52399683/attempting-mqtt-connection-failed-rc-2-try-again-in-5-seconds