MQTT code stops working after a couple of hours - arduino

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.

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();
}

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

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);
}
}```

ESP8266 stopped receiving data from firebase

I am trying to receive data from firebase to my ESP8266 so that I can send a mail using received data on button press. But the ESP stops receiving data after a couple of minutes. Can anyone tell the reason behind it?
Here's the code.
#include <ESP8266WiFi.h>
#include "Gsender.h"
#include <FirebaseArduino.h>
#define FIREBASE_HOST "iotapp11.firebaseio.com"
int button = 0;
const char* ssid = "Redmi 3s";
const char* password = "alohomora";
void setup()
{
pinMode(button,INPUT);
Serial.begin(115200);
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");}
Serial.println(" connected");
Serial.println(WiFi.localIP());
Firebase.begin(FIREBASE_HOST);
}
void loop(){
Firebase.get(FIREBASE_HOST); //Tried putting it in void setup and even removed it but nothing worked.
int but_val = digitalRead(button);
Gsender *gsender = Gsender::Instance();
String emailid =Firebase.getString("Email");
String subject =Firebase.getString("Subject");
String content =Firebase.getString("Content");
Serial.println(emailid);
Serial.println(subject);
Serial.println(content);
if ( but_val == LOW){
Serial.println("Button pressed");
delay(1000);
gsender->Subject(subject)->Send(emailid, content) ;
Serial.println("Message sent.");
delay(1000);
} else {
Serial.println("Button Not pressed");
delay(1000);
}
}

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.

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