MQTT reconnect help

Posted on
  • I'm testing against Every so often I get disconnected - which I imagine is from the server and is to be expected, as I think they regularly rollout the latest version.

    I have a disconnect event I can listen on, and currently I reissue mqtt.connect() in the events callback. My problem with this approach is that I'm losing memory. It might survive one reconnect, but not two. I have duplicated message listeners which I imagine is part of the memory problem.

    I considered another approach would be to save to memory and fire the reset() function, to bring the board and whole program back up?

    But is there any pattern/approach that I could use to recover without a restart?

    Edit: I've just considered that maybe I should unbind the listeners in the disconnect event callback too?

  • I think I need unsubscribe, to clean up, then reconnect

  • Could be... I wonder if you're keeping a reference to the MQTT connection somewhere? Any reference would mean that all the listeners and everything would be kept around, even after the disconnection?

    You could try trace() and see if you could figure out what was referencing your functions? It's a bit cryptic, but if you posted the results here I might be able to help.

  • @Gordon, very likely, and I think the way I've setup my code is not helping me clear and reinstantiate it. I'll have a look at that first before I waste any of your time here.

  • Yes. The way I was setup I could destroy the object but then I lost the listeners, so I've moved the whole thing including require, connect and the listener bindings into their own wrapper method which I recall on disconnect event. Appears to be working well with my triggering disconnect, so hopefully works when server triggers it. Thanks for the steer @Gordon

  • Almost 24 hours now. Best I had before was about 14, so I'm hoping I can ride out server disconnections now :)

  • hey @Ollie would you mind sharing the code how do you do it. I am haveing the same exact problem.


  • I think you've got the tinyMQTT module yes? That's the best code I have, although there's a bit of activity in the issues re "keep alive".

    I've had long running connections with the module, others have too, but I haven't used it a quite a while

  • @Ollie, thanks for fixing the double reconnect and activating the keepalive.

    Appreciate much!


  • @navas thanks, but wasn't me. A couple of pull requests have improved it - authors mentioned in the credits.

    Great to hear it's better though. Still fairly small at 1.45kb too :)

  • right, that's what making it special, so that I can run in ESP-01 (1MB) version

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview

MQTT reconnect help

Posted by Avatar for Ollie @Ollie