adafruit / Adafruit_MQTT_Library

Arduino library for MQTT support
MIT License
566 stars 292 forks source link

connection closed: Error: read ECONNRESET #204

Open becks0815 opened 2 years ago

becks0815 commented 2 years ago

Issue:

Tried to upload data to a MQTT broker (local network; IObroker) but failed to update a value which was writeable in a first try. When using a different MQTT client (Windows based standalone program), I was able to change this value without issue. I also could see my ESP8266 client connecting to the brokar and - according to the feedback in the arduino program - update/broadcast the vaalue on the broker, which was/is false.

I monitored the logfile on the MQTT server side and always found the following log details whenever my ESP client tried to connect and change a value:

2021-12-30 18:19:52.967  - info: mqtt.0 (3366) Client [] connected with secret 1640884792963_6139
2021-12-30 18:20:55.447  - info: mqtt.0 (3366) Client [] reconnected. Old secret 1640884792963_6139. New secret 1640884855445_8033
2021-12-30 18:21:57.413  - info: mqtt.0 (3366) Client [] connection closed: Error: read ECONNRESET
2021-12-30 18:21:57.878  - info: mqtt.0 (3366) Client [] connected with secret 1640884917876_1207

Solution and possible explanation: To me it looks like the Adafruit library tries to keep the connection and stores some values in memory to achive this. However, my ESP8266 calls the function ESP.deepSleep() after submitting a value, is reset and then starts from scratch - and something happens here which I can't explain. Maybe the server also tries to keep the connection which is breaking up in an undesired way when the client goes into deep sleep mode.

The solution however is simple: Add mqtt.disconnect(); before calling deep sleep to close the connection in the correct way, which will not only result in the error in the log going away but also the value finally be published on the MQTT server

mqtt.disconnect();
ESP.deepSleep(120 * 1000000); // deep sleep for 120 secs

Maybe this problem and the solution could be added to the documentation as I am sure that a lot of people use MQTT on an ESP8266 to send data points to a server while keeping the ESP in deep sleep to conserver energy (and run them on battery).