peterhinch / micropython-mqtt

A 'resilient' asynchronous MQTT driver. Recovers from WiFi and broker outages.
MIT License
550 stars 117 forks source link

config.clean_init vs. config.clean #40

Closed tve closed 1 year ago

tve commented 4 years ago

This is not a bug report, just a little heads-up ;-)

I'm not sure I understand correctly what the intent of these two flags is, but I don't believe they function as intended. My understanding is that having two flags is intended to allow a mode (clean_init=true, clean=false) where the initial connection creates a clean state but then subsequent automatic reconnections continue with the previous state such that unacked packets queued at the broker get retransmitted. This seems to be what unclean.py demonstrates.

However, section 3.1.2.4 of the MQTT 3.1.1 spec states:

If CleanSession is set to 1, the Client and Server MUST discard any previous Session and start a new one. This Session lasts as long as the Network Connection. State data associated with this Session MUST NOT be reused in any subsequent Session.

Note the last sentence: when the initial clean connection ends, the state, including queued packets and subscriptions, must be deleted by the broker.

The unclean.py example sort-a works because it does not notice that unacked packets from the first connection are lost and because it resubscribes on each subsequent connection even though that is not necessary if the connection state were always retained.

peterhinch commented 2 years ago

Apologies for the ridiculous delay in responding to this :)

I agree with the points you raised and have pushed an update to address them. The unclean.py demo now subscribes once only. The approach where clean_init==True and clean==False is to connect using clean session to discard pending messages, then to disconnect and reconnect using a non-clean session. This seems a bit hacky but I can't see another way. Can you?

I added this section to the README to explain the reasoning behind the extra clean_init flag. It also aims to explain why .connect throws an OSError if WiFi or broker are down when power initially comes up, an issue which has caused confusion.

peterhinch commented 1 year ago

Closing as I believe this is now fixed. Thank you for the report.