MQTTv5 Clean Start (Clean Sessions) and Session Expiry

In MQTT v3.1.1 we have the concept of clean sessions or non persistent/persistent connections.

On connect the client indicates to the server using the clean session flag if the session state should be kept by the server when the client disconnects.

Session state includes any client subscriptions and also messages depending on the QOS used and is covered in detail in the Understanding clean sessions tutorial , I recommend you read before proceeding if you are unfamiliar with clean sessions.



MQTTv5 Clean Start

In MQTTv5 clean sessions is now known as clean start, and is used in conjunction with a new feature called the session expiry interval.

Setting clean start to True is the same as setting clean sessions to True and Setting clean sessions to False is the same as setting clean sessions to False.

However when clean sessions is False you can also set a session expiry interval. After this interval the server will expire the client and clear the session state.

This overcomes the problem in 3.1.1 were the session state would be stored indefinitely if the client didn’t reconnect and clear it.

The clean session interval is a 4 byte integer and setting it to 0xFFFFFFFF means the session doesn’t expire.

If the session expiry interval is not defined a value of 0 is used which means that the session expires when the client disconnects.

Summary

Set clean start to False and a session expiry interval to store the session state. This is equivalent to clean session False but with a timeout.

Set clean start to True and the session expiry interval to 0 to not store the session state. This is equivalent to clean session True.

Python Code Demo

The following screen shot show the code running. It starts by setting the session expiry interval to 30 seconds and disconnecting. Messages are then published and should be queued on the broker.

If the client reconnects within 30 seconds it receives the messages if it connects after 30 seconds it doesn’t receive the messages as the broker has timed out the session.

session-expire-demo

 

Demo Script

download

Related Tutorials and Resources

Please rate? And use Comments to let me know more
[Total: 0   Average: 0/5]

Leave a Reply

Your email address will not be published. Required fields are marked *