RestoreSession Method

Restores session state data.

Syntax

int RestoreSession(const QString& qsStateData);

Remarks

This method restores previously-saved session state data and sets CleanSession to False. If the SessionStateFile configuration setting is set, the class will use the contents of that file to restore the session state data, ignoring the string passed to this method.

Depending on the elapsed time between connections the server may discard any previously saved session data on its side.

In MQTT 3.1.1, the time after which the server discards saved session data is not defined in the protocol specification and may vary between implementations. As a result, when re-connecting it may not be known if the server is capable of restoring a previous session.

To determine if a session can be restored on connection, set CleanSession to False, ClientId to the same value used in the initial connection, and call Connect.

When the Connected event fires, query the SessionPresent configuration setting. If SessionPresent is True the session should be restored by calling RestoreSession. If SessionPresent is False the session should not be restored so that the connection proceeds as a clean session.

Note: Not all servers support the use of SessionPresent.

Restore Session Example (Query SessionPresent)

mqtt1.CleanSession = false;
mqtt1.ClientId = clientId;
mqtt1.OnConnected += (s, e) => {
  if (mqtt1.Config("SessionPresent").ToLower() == "true")
    mqtt1.RestoreSession(sessionStr);
};
mqtt1.Connect(host,port);

If it is known that the server has not discarded the session state, for instance from familiarity with the server implementation and its behavior, then a simplified procedure can be performed. Simply set ClientId to the value used in the initial connection, call RestoreSession, and then call Connect.

Restore Session Example (Server Status Known)

mqtt1.ClientId = clientId;
mqtt1.RestoreSession(sessionStr);
mqtt1.Connect(host,port);

Refer to CleanSession and SaveSession for more information.

MQTT 5 Notes

In MQTT 5, the time after which the server discards saved session data is controlled by the SessionExpInterval. The server is required to store state data for the amount of time specified by this value, at which point it is required to delete it.

This feature allows the client to use its own time-based logic to determine whether it is necessary to call RestoreSession.

Error Handling

This method returns a result code; 0 indicates success, while a non-zero error code indicates that this method encountered an error during its execution. If an error occurs, the GetLastError() method can be called to retrieve the associated error message. (Note: This method's result code can also be obtained by calling the GetLastErrorCode() method after it returns.)

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks IoT 2020 Qt Edition - Version 20.0 [Build 8265]