ESP8266 is not able to connect to mosquitto broker. "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds" - arduino

I'm running a mosquitto broker and a node-red server in my PC , node-red is able to connect to mosquitto. The ESP8266 is able to connect to the WiFi but not to the broker a "Attempting MQTT connection...failed, rc=-2 try again in 5 seconds" message is displayed in the serial monitor. I'm also using MQTT explorer I don't know if it has something to do with it.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "Milagros";
const char* password = "18095381";
const char* mqtt_server = "192.168.1.133";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(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();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("data", "hello world");
// ... and resubscribe
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("data", msg);
}
}```

Related

Node mcu esp8266 disconnects from MQTT broker

I have two node mcu modules connected to the same network, running the same code and powered the same way. Both of them are subscribed to the topic Terma but one of them randomly disconnects and then reconnects to the MQTT broker meanwhile it stayed connected to the wifi uninterruptedly, the other module stays connected with no problem. I don't know if it is a network issue or if the node mcu is damaged.
here is the code:
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "Milagros";
const char* password = "18095381";
const char* mqtt_server = "192.168.1.133";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
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(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(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();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(14, LOW);
client.publish("estado","1");
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(14, HIGH);
client.publish("estado","0");
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("terma", "hello world 1");
// ... and resubscribe
client.subscribe("terma");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(14, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1884);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}

Arduino MQTT disconnect

I have a ESP32 board with 2 relays and a DHT22 sensor and the bellow code in Arduino running on the ESP32
MQTT Broker is running on Pi4 with mosquitto and node-red dashboard.
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTTYPE DHT22
const char* ssid = "MY SSID";
const char* password = "1234";
const char* mqtt_server = "192.168.1.118";
WiFiClient espClient;
PubSubClient client(espClient);
const int DHTPin = 14;
const int lamp = 25;
const int lamp1 = 26;
DHT dht(DHTPin, DHTTYPE);
long now = millis();
long lastMeasure = 0;
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);
delay(1000);
WiFi.disconnect();
delay(1000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
String message;
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
char c = (char)payload[i];
message += c;
}
Serial.println();
if ((char)payload[0] == '0' || message == "false") {
digitalWrite(lamp, HIGH);
delay(100);
digitalWrite(lamp1, LOW);
Serial.println("lamp, HIGH si lamp1, LOW");
} else if ((char)payload[0] == '1' || message == "true") {
digitalWrite(lamp1, HIGH);
delay(100);
digitalWrite(lamp, LOW);
Serial.println("lamp, LOW si lamp1, HIGH");
} else if ((char)payload[0] == '2') {
digitalWrite(lamp, HIGH);
digitalWrite(lamp1, HIGH);
Serial.println("lamp, LOW si lamp1, LOW > STOP");
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe or resubscribe to a topic
// You can subscribe to more topics (to control more LEDs in this example)
client.subscribe("room/lamp");
client.subscribe("room/lamp1");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(lamp, OUTPUT);
pinMode(lamp1, OUTPUT);
pinMode(LED,OUTPUT);
dht.begin();
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// 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())
client.connect("ESP8266Client");
now = millis();
// Publishes new temperature and humidity every 30 seconds
if (now - lastMeasure > 5000) {
lastMeasure = now;
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
// float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
//if (isnan(h) || isnan(t) || isnan(f))
if (isnan(h) || isnan(t)){
Serial.println("Failed to read from DHT sensor!");
return;
}
// Computes temperature values in Celsius
float hic = dht.computeHeatIndex(t, h, false);
static char temperatureTemp[7];
dtostrf(t, 6, 2, temperatureTemp);
static char test[7];
dtostrf(hic, 6, 2, test);
static char humidityTemp[7];
dtostrf(h, 6, 2, humidityTemp);
client.publish("room/temperature", temperatureTemp);
client.publish("room/humidity", humidityTemp);
client.publish("room/test", test);
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
//Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.println(" *C ");
delay(500);
digitalWrite(LED,HIGH);
delay(500);
digitalWrite(LED,LOW);
}
}
The 2 relays are controlling a window in my bathroom. If I plug the ESP32 to power all is working, and I can open/close the window and sensor readings are ok.
But after ~24hours I can still see realtime sensor readings but when I try to open/close the window nothing is happening. On the MQTT broker I can see the mqtt messages but nothing is happening.
room/lamp1 1
room/lamp1 1
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/lamp 0
room/temperature 24.00
room/humidity 29.10
room/test 23.22
room/lamp 0
room/lamp 0
room/lamp 2
room/lamp1 2
room/lamp 2
room/lamp1 2
room/lamp 2
room/lamp1 2
room/lamp 2
Any suggestions.

Feather Huzzah MQTT

I'm attempting to connect my Feather Huzzah to a local MQTT server but the program keeps blowing up and throwing a stack trace. When I attempt to decode the stack trace it's just empty, more frequently I only get part of the stack trace. Here's the code that I'm running, most of it is pretty similar to the pub/sub client example code for Arduino. I've tried erasing the flash on the device, that didn't seem to help.
Even stranger is that it worked once, but as soon as I tried it again adding the callback the code stopped working and blows up. If I try removing the callback nothing changes. I've tried stripping out a lot of the code just to see if I can get a consistent connection to MQTT, but that doesn't seem to be working either. The MQTT server is the latest Mosquitto from Ubuntu 18.04.
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
const char* ssid = "xxxxxxxx";
const char* password = "xxxxxxxxx";
const int hallPin = 14;
const int ledPin = 0;
const char* mqtt_server = "mosquitto.localdomain";
long lastMsg = 0;
char msg[100];
int value = 0;
int hallState = 0;
WiFiClient espClient;
PubSubClient client(espClient);
WiFiUDP ntpUDP;
// By default 'time.nist.gov' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP);
// Setup and connect to the wifi
void setup_wifi() {
delay(100);
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.println("Gateway: ");
Serial.println(WiFi.gatewayIP());
}
//Reconnect to the MQTT broker
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("/homeassistant/devices/doorbell", "hello world");
// ... and resubscribe
client.subscribe("/homeassistant/doorbell/receiver");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//Process messages incoming from the broker
void callback(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]);
}
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(hallPin, INPUT);
Serial.begin(115200);
setup_wifi();
timeClient.begin();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
setup_wifi();
}
if (!client.connected()) {
reconnect();
}
hallState = digitalRead(hallPin);
if (hallState == LOW) {
digitalWrite(ledPin, HIGH);
generateAndSendMessage();
delay(1000); //Add in a delay so it doesn't send messages extremely rapidly
} else {
digitalWrite(ledPin, LOW);
}
}
void generateAndSendMessage() {
timeClient.update();
StaticJsonBuffer<100> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["sensor"] = "doorbell";
root["time"] = timeClient.getEpochTime();
root["value"] = 1;
root.printTo(msg);
Serial.println(msg);
client.publish("/homeassistant/devices/doorbell", msg);
}
Looking at the generateAndSendMessage function, I believe you are having an issue due to the size of the MQTT buffer.
The MQTT buffer is by default set to 128 bytes. This includes the length of the channel name along with the message.
The length of you channel is 32 bytes, and the json buffer you used to make the message is 100 bytes long. So you might just be exceeding the 128 byte mark.
Just declare this before including the PubSubClient.h
#define MQTT_MAX_PACKET_SIZE 200
This macro defines the buffer size of the PubSubClient to 200. You can change it to whatever you believe is required.
I hope this helps.

MQTT code stops working after a couple of hours

Made some code for a NodeMCU in the Arduino IDE to push a button using MQTT. The code works perfectly fine for some time, but after a couple of hours it will not respond anymore.
The code is very frankenstein, since I am a mega rookie, and is as follows:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
const char* ssid = "ap_name"; //change
const char* password = "ap_pw"; //change
const char* mqttServer = "server_ip"; //change
const int mqttPort = 1883;
const char* mqttUser = "server_name"; //change
const char* mqttPassword = "server_pw"; //change
WiFiClient espClient;
PubSubClient client(espClient);
Servo servo;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
servo.attach(D4);
servo.write(70);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish("esp/test", "Hello from ESP8266");
client.subscribe("esp/test");
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
if(*payload == 49){
rotServo();
Serial.println();
Serial.print("Roterar servo");
delay(3000);
client.publish("esp/test", "0");
}
Serial.println();
Serial.println("-----------------------");
}
void rotServo(){
servo.attach(D4);
servo.write(70);
delay(1000);
servo.write(175);
delay(2000);
servo.write(70);
delay(3000);
servo.detach();
}
void loop() {
client.loop();
}
Anyone that would know what might be causing it to stop working?
It could be because, you never reconnect if your client ever gets disconnected.
See the example here for more details, but here is the reconnect function from the example and how it is called in the loop. You would need to tailor it to suite your application.
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
...
}
On another note, while I don't think it would cause your specific problem, in your callback, you just compare the contents of the payload to the number 49.
if(*payload == 49){
...
}
You should check that the topic is the actual topic you are interested in and that the length is also what you expect, before you start looking at the payload.

NodeMCU gets strange IP address

Today I got my NodeMCU and I instantly started with coding. I wanted to connect to my WiFi and to my MQTT server.
I used the PubSub example for this.
In the serial monitor I get the message that I connected successfully with the WiFi, but I get the IP 172.20.10.6. However we have a 192.168... network.
Then when I try to reach my MQTT server it doesn't find it. When I try to give the NodeMCU a static IP it also says connected successfully and shows up the static IP I gave it, but I still can't connect to my MQTT server.
I can't ping the NodeMCU and don't find it in my Smartphone app "Fing".
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "myssid";
const char* password = "mypw";
const char* mqtt_server = "192.168.42.131";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
pinMode(BUILTIN_LED, OUTPUT);
// Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
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.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(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();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(BUILTIN_LED, LOW);
// Turn the LED on (Note that LOW is the voltage level
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(BUILTIN_LED, HIGH);
// Turn the LED off by making the voltage HIGH
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe("mathistest");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, "hello world #%ld", value);
}
}
You are most likely having a DHCP failure.
A 172.20.x.x address is a non-routable IP address (see: https://www.lifewire.com/what-is-a-private-ip-address-2625970) and the DHCP code is (likely) using that address when the address assignment fails.
Stepping back, DHCP is most likely failing because you are failing to connect to the Wifi network with the correct SSID and password.

Resources