ESP8266 disconnected

Please tell me how to solve this problem.
Thank you.
Code:
#include <AsyncMqttClient.h>
#include <ESP8266WiFi.h>
#include <Ticker.h>

#define WIFI_SSID " ******** "
#define WIFI_PASSWORD " *********** "

// Raspberri Pi Mosquitto MQTT Broker
#define MQTT_HOST IPAddress(192, 168, 100, ***)
#define MQTT_PORT 1883

//Temperature MQTT Topics
#define MQTT_PUB_TEMP "mqtt/lm35"

const int LM35sensorPin = A0;
float LM35sensorValue;
float LM35voltageOut;
float LM35temperature;

// Temperature value
float temp;

AsyncMqttClient mqttClient;
Ticker mqttReconnectTimer;

WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
Ticker wifiReconnectTimer;

unsigned long previousMillis = 0; // Stores last time temperature was published
const long interval = 10000; // Interval at which to publish sensor readings

void connectToWifi() {
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

void onWifiConnect(const WiFiEventStationModeGotIP& event) {
Serial.println("Connected to Wi-Fi.");
connectToMqtt();
}

void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
Serial.println("Disconnected from Wi-Fi.");
mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
wifiReconnectTimer.once(2, connectToWifi);
}

void connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}

void onMqttConnect(bool sessionPresent) {
Serial.println("Connected to MQTT.");
Serial.print("Session present: ");
Serial.println(sessionPresent);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
Serial.println("Disconnected from MQTT.");

if (WiFi.isConnected()) {
mqttReconnectTimer.once(2, connectToMqtt);
}
}

void onMqttPublish(uint16_t packetId) {
Serial.print("Publish acknowledged.");
Serial.print(" packetId: ");
Serial.println(packetId);
}

void setup() {
pinMode(LM35sensorPin, INPUT);
Serial.begin(115200);
Serial.println();

wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);

mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
//mqttClient.onSubscribe(onMqttSubscribe);
//mqttClient.onUnsubscribe(onMqttUnsubscribe);
mqttClient.onPublish(onMqttPublish);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
// If your broker requires authentication (username and password), set them below
mqttClient.setCredentials("REPLACE_WITH_YOUR_USER", "REPLACE_WITH_YOUR_PASSWORD");

connectToWifi();
}

void loop() {
//LM35 SENSOR
LM35sensorValue = analogRead(LM35sensorPin);
LM35voltageOut = (LM35sensorValue * 3300) / 1024;

// calculate temperature for LM35 (LM35DZ)
LM35temperature = LM35voltageOut / 10;
//LM35temperatureF = (LM35temperatureC*1.8)+32;
unsigned long currentMillis = millis();
// Every X number of seconds (interval = 10 seconds)
// it publishes a new MQTT message
if (currentMillis - previousMillis >= interval) {
// Save the last time a new reading was published
previousMillis = currentMillis;
// Temperature in Celsius degrees
temp = LM35temperature;

// Publish an MQTT message on topic dev/test
uint16_t packetIdPub1 = mqttClient.publish(MQTT_PUB_TEMP, 1, true, String(temp).c_str());                            
Serial.printf("Publishing on topic %s at QoS 0, packetId: %i ", MQTT_PUB_TEMP, packetIdPub1);
Serial.printf("Message: %.2f \n", temp);

}
}

Hi @boyvip_123 What is the main problem? you could describe it.
I can see that your device closed the connection wifi, maybe could be for distance of router wifi.
I recommend use the "PubSubClient.h" library to MQTT communication with embedded systems.
What is your configuration on NodeRED?

I've used the "PubSubClient.h" library to MQTT communication, but the result is "Attempting MQTT connection... failed, rc=5 try again in 5 seconds"
This is code which test without lm35 sensor.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = " ****** ";
const char* password = " ******* ";
const char* mqtt_server = "192.168.x.x"; ///MQTT Broker
int MQTT_PORT = 1883;
WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
// Start the Serial Monitor
Serial.begin(115200);
//sensors.begin();
setup_wifi();
client.setServer(mqtt_server, MQTT_PORT);
}

void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
// Connecting to a WiFi network
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 reconnect() {
// Loop until we're reconnected
Serial.println("In reconnect...");
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}

void loop() {

client.publish("mqtt/lm35", "21.6");
if (!client.connected()) {
reconnect();
}
client.loop();
delay(1000);
}
image

And, is your MQTT Broker working?
You could first check if you can publish and subscribe to BROKER in NodeRED.

Captura de pantalla 2021-07-22 a la(s) 11.54.26 p. m.

so, when you inject:

Captura de pantalla 2021-07-22 a la(s) 11.55.04 p. m.

or you could use MQTT.fx or MQTT Explorer to check your MQTT connection to BROKER.

Yes. My MQTT Broker is working normally.

What broker are you using? And what's is version number?

Can you connect to your broker from another computer?

I use VNC without remote desktop and install MQTT on raspbian.

? What ?

What broker did you install on raspberry pi?

What version number is the broker software?

Can you connect MQTT explorer to the broker when MQTT explorer is running on a different computer?

Yes but, What name and version of broker MQTT?
maybe:
Mosquitto?
or Mosca?
or HiveMQ?
or Aedes? ...

Mosquitto

If you don't answer all the questions we can't help you

Mosquitto broker version 1.5.7.
I don't try to connect MQTT explorer to the broker.

Well how do you know if the broker is accessible from the esp?

It would be worth testing.

Install MQTT explorer on a different computer and try to connect to the broker on the pi. If you can do that, then the esp should be able to. If you can't, then the esp cannot.

Ok. I'll try it.
Thank you very much.

Have you put the actual IP address in there?

Yes. I put it in there.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.