Skip to content

v3: MQTTSession #215

@adam-fowler

Description

@adam-fowler

It is possible for an MQTT session to last between connections. Because of this it is worthwhile making the session a first class object. MQTTSession will store a client id, inflight publish packets and any subscriptions that have been made. It should be possible to call subscribe on MQTTSession and the subscription will be valid across multiple MQTT connections.

MQTTConnection.withConnection will get a new optional parameter session. This session will be stored in the connection. If no session is supplied then a new session is created. If you supply a session then the connection will be made asking for a session from the server (cleanSession/cleanStart = false). If the server's CONNACK indicates there is no session, then the MQTTSession contents are cleared and any subscription streams are ended. Otherwise the connection will continue with the session data it has got and any inflight packets will be resent.

Because you can call subscribe on MQTTSession outside of the MQTTConnection.withConnection this function cannot return as soon as its closure is done. It can only exit if all subscriptions are ended, an error is thrown or the connection is closed by the server.

let session = MQTTSession(name: "TestSession")
try await withThrowingTaskGroup { group in
    group.addTask {
        // this subscribe won't activate until a connection is made 
        try await session.subscribe(to: [.init(topicFilter: "testMQTTPublishRetain", qos: .atLeastOnce)]) { sub in
            for try await publish in sub {
                ...
            }
        }
    group.addTask {
        // does not exit until either all subscriptions are ended or there is an error
        try await MQTTConnection.withConnection(
            address: .hostname(Self.hostname, port: 8080),
            session: session
        ) { connection in
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions