micropython / micropython-lib

Core Python libraries ported to MicroPython
Other
2.43k stars 1k forks source link

umqtt.simple quirks in ESP32 #579

Open elvis-epx opened 1 year ago

elvis-epx commented 1 year ago

I detect disconnection by capturing exceptions in MQTTClient.check_msg(), and calling MQTTClient.connect() again on the same MQTTClient object. In the code I found the problem first, it runs in a busy loop (no sleeps) which calls check_msg() very often.

  1. At least in my environment, it disconnects every ~30 minutes, the first disconnection always happens at 29th or 30th minute. Adding time.sleep() or sleep_ms() to the busy loop delays this first disconnectio to minute 45 or 50.

No other change avoids this periodic disconnection (I have tried disconnecting WiFi and/or MQTT on purpose every 15 min, the involuntary disconnection still happens). Perhaps this is an esp-idf connection timeout?

  1. After a number of times it happens, it can't connect anymore.

It seems that socket objects are not being closed in time; adding a periodic gc.collect() seems to resolve this issue.

None of these happens in ESP8266 (does the garbage collection work differently in there?) so perhaps these differences should be documented. Another improvement could be explicit socket closure upon reconnection.

elvis-epx commented 1 year ago

This old PR is a reasonable solution. https://github.com/micropython/micropython-lib/pull/382