Reputation: 15
I used aREST to access to my NODEMCU but it says "Attempting MQTT connection...failed, rc=-4 try again in 5 seconds" on serial monitor
My code:
// Control ESP8266 anywhere
// Import required libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
#include <aREST.h>
// Clients
WiFiClient espClient;
PubSubClient client(espClient);
// Create aREST instance
aREST rest = aREST(client);
// Unique ID to identify the device for cloud.arest.io
char* device_id = "aliziveh79";
// WiFi parameters
const char* ssid = "Samsung J7";
const char* password = "Movahed12341234";
// Functions
void callback(char* topic, byte* payload, unsigned int length);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// Set callback
client.setCallback(callback);
// Give name and ID to device
rest.set_id(device_id);
rest.set_name("relay_anywhere");
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Set output topic
char* out_topic = rest.get_topic();
}
void loop() {
// Connect to the cloud
rest.loop(client);
}
// Handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {
rest.handle_callback(client, topic, payload, length);
}
I used aREST to access to my NODEMCU but it says Attempting MQTT connection...failed, rc=-4 try again in 5 seconds" on serial monitor
Upvotes: 1
Views: 8568
Reputation: 1203
When you connect the client, you have to change the name of the Device:
if (client.connect("CHANGE_THIS_IT_HAS_TO_BE_DIFFERENT_FOR_EACH_DEVICE"))
I use the MAC Address to change it dynamically
Upvotes: 0
Reputation: 59751
Return code -4 is a timeout trying to connect to the broker
// Possible values for client.state()
#define MQTT_CONNECTION_TIMEOUT -4
#define MQTT_CONNECTION_LOST -3
#define MQTT_CONNECT_FAILED -2
#define MQTT_DISCONNECTED -1
#define MQTT_CONNECTED 0
#define MQTT_CONNECT_BAD_PROTOCOL 1
#define MQTT_CONNECT_BAD_CLIENT_ID 2
#define MQTT_CONNECT_UNAVAILABLE 3
#define MQTT_CONNECT_BAD_CREDENTIALS 4
#define MQTT_CONNECT_UNAUTHORIZED 5
This most likely means the address for your broker is wrong (but I don't see where you are specifying that in the code you have provided)
Upvotes: 2