### Run Linux Tests with Docker Compose Source: https://github.com/swift-server-community/mqtt-nio/blob/main/CONTRIBUTING.md Execute the project's tests on Linux using Docker Compose. Ensure Docker and Docker Compose are installed and configured. ```bash docker-compose run test ``` -------------------------------- ### MQTTClient Initialization Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.md Details on how to create and initialize an MQTTClient instance. ```APIDOC ## MQTTClient Initialization ### Description Initializes a new MQTTClient instance with specified host, port, identifier, event loop group provider, logger, and configuration. ### Method `init(host:port:identifier:eventLoopGroupProvider:logger:configuration:)` ### Parameters - **host** (String) - The MQTT broker host address. - **port** (Int) - The MQTT broker port. - **identifier** (String) - The unique client identifier. - **eventLoopGroupProvider** (EventLoopGroupProvider) - Provides the event loop group for network operations. - **logger** (Logger) - A logger instance for diagnostic output. - **configuration** (Configuration) - The client configuration settings. ### Related Structs - `Configuration-swift.struct` ``` -------------------------------- ### Initialize MQTTClient Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Create an MQTTClient instance using either basic parameters or a custom configuration object. ```swift import MQTTNIO import NIO // Basic client creation let client = MQTTClient( host: "mqtt.eclipse.org", port: 1883, identifier: "MyClient-\(UUID().uuidString)", eventLoopGroupProvider: .createNew ) // Client with custom configuration let configuredClient = MQTTClient( host: "broker.example.com", port: 8883, identifier: "SecureClient", eventLoopGroupProvider: .createNew, configuration: .init( version: .v3_1_1, keepAliveInterval: .seconds(60), connectTimeout: .seconds(15), userName: "myuser", password: "mypassword", useSSL: true ) ) ``` -------------------------------- ### Connect to an MQTT Broker Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/mqttnio.md Initializes an MQTTClient and establishes a connection to the specified host and port. ```swift let client = MQTTClient( host: "mqtt.eclipse.org", port: 1883, identifier: "My Client", eventLoopGroupProvider: .createNew ) do { try await client.connect() print("Succesfully connected") } catch { print("Error while connecting \(error)") } ``` -------------------------------- ### Create and Use MQTT v5.0 Client Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Configure the client for MQTT v5.0 using `.v5_0` and access enhanced methods via the `.v5` property. This includes connecting with v5.0 properties, publishing with extended options, and subscribing with v5-specific settings. ```swift let v5Client = MQTTClient( host: "mqtt5.example.com", port: 1883, identifier: "V5Client", eventLoopGroupProvider: .createNew, configuration: .init(version: .v5_0) ) ``` ```swift let connack = try await v5Client.v5.connect( cleanStart: true, properties: [ .sessionExpiryInterval(3600), .receiveMaximum(100) ] ) ``` ```swift var payload = ByteBufferAllocator().buffer(capacity: 100) payload.writeString("{\"value\": 42}") let ack = try await v5Client.v5.publish( to: "data/json", payload: payload, qos: .atLeastOnce, properties: [ .contentType("application/json"), .messageExpiry(3600), .userProperty("source", "sensor-1") ] ) ``` ```swift let v5Subscription = MQTTSubscribeInfoV5( topicFilter: "events/#", qos: .atLeastOnce, noLocal: true, retainAsPublished: true, retainHandling: .sendIfNew ) let subackV5 = try await v5Client.v5.subscribe( to: [v5Subscription], properties: [.subscriptionIdentifier(1)] ) ``` ```swift try await v5Client.v5.disconnect(properties: [.reasonString("Normal shutdown")]) try await v5Client.shutdown() ``` -------------------------------- ### Connecting to a Broker Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Shows how to establish a connection to an MQTT broker using both async/await and EventLoopFuture APIs, including options for Last Will messages. ```APIDOC ## Connecting to a Broker ### Description The `connect` method establishes a connection to the MQTT broker. The `cleanSession` parameter controls whether the server should resume previous session state or start fresh. ### Code Examples ```swift // Connect with async/await do { let sessionPresent = try await client.connect(cleanSession: true) print("Connected! Session present: \(sessionPresent)") } catch { print("Connection failed: \(error)") } // Connect with EventLoopFuture client.connect(cleanSession: true).whenComplete { result in switch result { case .success(let sessionPresent): print("Connected! Session present: \(sessionPresent)") case .failure(let error): print("Connection failed: \(error)") } } // Connect with Last Will message var willPayload = ByteBufferAllocator().buffer(capacity: 64) willPayload.writeString("Client disconnected unexpectedly") try await client.connect( cleanSession: true, will: ( topicName: "clients/status", payload: willPayload, qos: .atLeastOnce, retain: true ) ) ``` ``` -------------------------------- ### Connect to MQTT Broker Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Establish a connection using async/await or EventLoopFuture, optionally including a Last Will message. ```swift // Connect with async/await do { let sessionPresent = try await client.connect(cleanSession: true) print("Connected! Session present: \(sessionPresent)") } catch { print("Connection failed: \(error)") } // Connect with EventLoopFuture client.connect(cleanSession: true).whenComplete { result in switch result { case .success(let sessionPresent): print("Connected! Session present: \(sessionPresent)") case .failure(let error): print("Connection failed: \(error)") } } // Connect with Last Will message var willPayload = ByteBufferAllocator().buffer(capacity: 64) willPayload.writeString("Client disconnected unexpectedly") try await client.connect( cleanSession: true, will: ( topicName: "clients/status", payload: willPayload, qos: .atLeastOnce, retain: true ) ) ``` -------------------------------- ### Configure MQTT Client for v5.0 Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/mqttnio-v5.md Instantiate an MQTTClient with the configuration set to use MQTT v5.0 protocol. This is required for connecting to MQTT v5.0 brokers. ```swift let client = MQTTClient( host: host, identifier: "MyAWSClient", eventLoopGroupProvider: .createNew, configuration: .init(version: .v5_0) ) ``` -------------------------------- ### Publish with Quality of Service Levels Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Demonstrates publishing messages using QoS 0, 1, and 2 delivery guarantees. ```swift // QoS 0: At most once (fire and forget) // Message is sent once with no acknowledgment try await client.publish( to: "telemetry/fast", payload: ByteBuffer(string: "QoS 0 message"), qos: .atMostOnce ) // QoS 1: At least once // Message is retried until PUBACK is received try await client.publish( to: "commands/important", payload: ByteBuffer(string: "QoS 1 message"), qos: .atLeastOnce ) // QoS 2: Exactly once // Four-way handshake ensures single delivery try await client.publish( to: "transactions/critical", payload: ByteBuffer(string: "QoS 2 message"), qos: .exactlyOnce ) ``` -------------------------------- ### MQTTClient Instance Properties Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.md Overview of the properties available on an MQTTClient instance. ```APIDOC ## MQTTClient Instance Properties ### Description Provides access to various properties of an MQTTClient instance, including its configuration, identifier, connection details, and MQTT version specific properties. ### Properties - **configuration** (Configuration) - The client's configuration settings. - **identifier** (String) - The unique client identifier. - **host** (String) - The MQTT broker host address. - **port** (Int) - The MQTT broker port. - **eventLoopGroup** (EventLoopGroup) - The event loop group used by the client. - **logger** (Logger) - The logger instance for the client. - **v5** (V5) - Properties specific to MQTT version 5. - **V5** (V5) - Alias for MQTT version 5 properties. ``` -------------------------------- ### Configure TLS with NIOSSL Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Set up TLS connections for secure communication using NIOSSL. This involves loading certificates and keys, creating a TLS configuration, and initializing the MQTT client with SSL enabled. ```swift import NIOSSL let caCertificate = try NIOSSLCertificate.fromPEMFile("ca.pem") let clientCertificate = try NIOSSLCertificate.fromPEMFile("client.pem") let clientKey = try NIOSSLPrivateKey(file: "client.key", format: .pem) let tlsConfig = TLSConfiguration.forClient( trustRoots: .certificates(caCertificate), certificateChain: clientCertificate.map { .certificate($0) }, privateKey: .privateKey(clientKey) ) ``` ```swift let secureClient = MQTTClient( host: "secure.mqtt.example.com", port: 8883, identifier: "SecureClient", eventLoopGroupProvider: .createNew, configuration: .init( useSSL: true, tlsConfiguration: .niossl(tlsConfig), sniServerName: "secure.mqtt.example.com" ) ) ``` ```swift try await secureClient.connect() ``` -------------------------------- ### Connect via Unix Domain Sockets Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Establishes a local connection to an MQTT broker using a Unix domain socket path. ```swift let udsClient = MQTTClient( unixSocketPath: "/var/run/mosquitto/mosquitto.sock", identifier: "LocalClient", eventLoopGroupProvider: .createNew ) try await udsClient.connect() try await udsClient.publish( to: "local/messages", payload: ByteBuffer(string: "Local message"), qos: .atMostOnce ) ``` -------------------------------- ### Configure TLS Connection for MQTT NIO Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/mqttnio-connections.md Set up TLS certificates and configuration for a secure MQTT client connection. Ensure `useSSL` is true and provide valid certificate chains and private keys. ```swift let rootCertificate = try NIOSSLCertificate.fromPEMBytes([UInt8](mosquittoCertificateText.utf8)) let myCertificate = try NIOSSLCertificate.fromPEMBytes([UInt8](myCertificateText.utf8)) let myPrivateKey = try NIOSSLPrivateKey(bytes: [UInt8](myPrivateKeyText.utf8), format: .pem) let tlsConfiguration: TLSConfiguration? = TLSConfiguration.forClient( trustRoots: .certificates(rootCertificate), certificateChain: myCertificate.map { .certificate($0) }, privateKey: .privateKey(myPrivateKey) ) let client = MQTTClient( host: "test.mosquitto.org", port: 8884, identifier: "MySSLClient", eventLoopGroupProvider: .createNew, configuration: .init(useSSL: true, tlsConfiguration: .niossl(tlsConfiguration)) ) ``` -------------------------------- ### Establish WebSocket Connection Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Connect to MQTT brokers over WebSocket by configuring the client with WebSocket-specific settings, including URL path, maximum frame size, and initial request headers. ```swift let wsClient = MQTTClient( host: "ws.mqtt.example.com", port: 443, identifier: "WebSocketClient", eventLoopGroupProvider: .createNew, configuration: .init( useSSL: true, webSocketConfiguration: .init( urlPath: "/mqtt", maxFrameSize: 1 << 16, initialRequestHeaders: [ "Authorization": "Bearer my-token" ] ) ) ) ``` ```swift try await wsClient.connect() ``` -------------------------------- ### Subscribe to MQTT Topics Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Register interest in one or more topics using topic filters and Quality of Service (QoS) levels. Supports single topics, multiple topics, and wildcard subscriptions. ```swift let subscription = MQTTSubscribeInfo( topicFilter: "sensors/temperature", qos: .atLeastOnce ) let suback = try await client.subscribe(to: [subscription]) print("Subscription result: \(suback.returnCodes)") ``` ```swift let subscriptions = [ MQTTSubscribeInfo(topicFilter: "sensors/+/temperature", qos: .atLeastOnce), MQTTSubscribeInfo(topicFilter: "alerts/#", qos: .exactlyOnce), MQTTSubscribeInfo(topicFilter: "status/+", qos: .atMostOnce) ] let result = try await client.subscribe(to: subscriptions) for (index, code) in result.returnCodes.enumerated() { switch code { case .grantedQoS0, .grantedQoS1, .grantedQoS2: print("Subscribed to \(subscriptions[index].topicFilter)") case .failure: print("Failed to subscribe to \(subscriptions[index].topicFilter)") } } ``` -------------------------------- ### MQTTClient Subscription Management Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.md APIs for subscribing to and unsubscribing from topics. ```APIDOC ## MQTTClient Subscription Management ### Description Enables the client to subscribe to topics for receiving messages and unsubscribe from topics. ### Methods - **`subscribe(to:)`**: Subscribes to a topic. - **`subscribe(to:)-1y95e`**: Alternative method for subscribing to a topic. - **`unsubscribe(from:)`**: Unsubscribes from a topic. - **`unsubscribe(from:)-1wjnz`**: Alternative method for unsubscribing from a topic. ``` -------------------------------- ### Connect to AWS IoT Core Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Uses SotoSignerV4 to generate a signed URL for WebSocket connections to AWS IoT. ```swift import SotoSignerV4 let host = "your-endpoint.iot.us-east-1.amazonaws.com" let signer = AWSSigner( credentials: StaticCredential( accessKeyId: "YOUR_ACCESS_KEY", secretAccessKey: "YOUR_SECRET_KEY" ), name: "iotdata", region: "us-east-1" ) let signedURL = signer.signURL( url: URL(string: "https://\(host)/mqtt")!, method: .GET, headers: HTTPHeaders([("host", host)]), body: .none, expires: .minutes(30) ) let requestURI = "/mqtt?\(signedURL.query!)" let awsClient = MQTTClient( host: host, port: 443, identifier: "AWSIoTClient", eventLoopGroupProvider: .createNew, configuration: .init( useSSL: true, webSocketConfiguration: .init(urlPath: requestURI) ) ) try await awsClient.connect() ``` -------------------------------- ### Connect via Unix Domain Socket with MQTT NIO Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/mqttnio-connections.md Establish a connection to a local MQTT broker using a Unix Domain Socket. This bypasses traditional host and port networking. ```swift let client = MQTTClient( unixSocketPath: "/path/to/broker.socket", identifier: "UDSClient", eventLoopGroupProvider: .createNew ) ``` -------------------------------- ### MQTT Client Connection API Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.V5.md Methods for establishing and closing connections to an MQTT broker. ```APIDOC ## MQTT Client Connection API ### Description Methods for establishing and closing connections to an MQTT broker. ### Methods - `connect(cleanStart:properties:will:authWorkflow:)` - `disconnect(properties:)` ``` -------------------------------- ### MQTT Client Subscription API Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.V5.md Methods for subscribing to and unsubscribing from topics, and managing publish listeners. ```APIDOC ## MQTT Client Subscription API ### Description Methods for subscribing to and unsubscribing from topics, and managing publish listeners. ### Methods - `subscribe(to:properties:)` - `unsubscribe(from:properties:)` - `createPublishListener(subscriptionId:)` - `addPublishListener(named:subscriptionId:_:)` ``` -------------------------------- ### Publishing Messages Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Details on how to publish messages to topics with different Quality of Service (QoS) levels and retain options, using both async/await and EventLoopFuture. ```APIDOC ## Publishing Messages ### Description The `publish` method sends messages to a specific topic. Quality of Service (QoS) levels determine delivery guarantees: `.atMostOnce` (fire and forget), `.atLeastOnce` (acknowledged delivery), or `.exactlyOnce` (guaranteed single delivery). ### Code Examples ```swift // Publish with async/await var payload = ByteBufferAllocator().buffer(capacity: 256) payload.writeString("Hello, MQTT!") try await client.publish( to: "sensors/temperature", payload: payload, qos: .atLeastOnce, retain: false ) // Publish JSON data let jsonData = """{"temperature": 23.5, "humidity": 65, "timestamp": \"\(Date())\"}""" var jsonPayload = ByteBufferAllocator().buffer(capacity: jsonData.utf8.count) jsonPayload.writeString(jsonData) try await client.publish( to: "sensors/room1/data", payload: jsonPayload, qos: .exactlyOnce, retain: true ) // Publish with EventLoopFuture client.publish(to: "notifications", payload: payload, qos: .atMostOnce) .whenComplete { result in switch result { case .success: print("Message published") case .failure(let error): print("Publish failed: \(error)") } } ``` ``` -------------------------------- ### MQTT Client Authentication API Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.V5.md Methods for handling authentication with the MQTT broker. ```APIDOC ## MQTT Client Authentication API ### Description Methods for handling authentication with the MQTT broker. ### Methods - `auth(properties:authWorkflow:)` ``` -------------------------------- ### MQTTClient General Listeners Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.md Management of listeners for client lifecycle events like close and shutdown. ```APIDOC ## MQTTClient General Listeners ### Description Manages listeners for various client lifecycle events, including connection closure and shutdown. ### Methods - **`addCloseListener(named:_:)`**: Adds a named listener for connection close events. - **`addShutdownListener(named:_:)`**: Adds a named listener for client shutdown events. - **`removeCloseListener(named:)`**: Removes a named listener for connection close events. - **`removeShutdownListener(named:)`**: Removes a named listener for client shutdown events. ``` -------------------------------- ### MQTTClient Connection Management Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.md APIs for managing the connection state of the MQTTClient. ```APIDOC ## MQTTClient Connection Management ### Description Handles the connection and disconnection of the MQTTClient to the MQTT broker, and checks the connection status. ### Methods - **`connect(cleanSession:will:)`**: Establishes a connection to the MQTT broker. - **`connect(cleanSession:will:)-51e4w`**: Alternative method for establishing a connection. - **`isActive()`**: Checks if the client is currently connected. - **`disconnect()`**: Disconnects the client from the MQTT broker. - **`disconnect()-45iy6`**: Alternative method for disconnection. - **`ping()`**: Sends a PINGREQ message to the broker to keep the connection alive. - **`ping()-3m8i5`**: Alternative method for sending a PINGREQ. ``` -------------------------------- ### Publish with MQTT v5.0 Properties Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/mqttnio-v5.md Use the v5.0 specific publish function to send a message with additional MQTT properties, such as contentType. This function is accessed via `client.v5`. ```swift _ = try await client.v5.publish( to: "JSONTest", payload: payload, qos: .atLeastOnce, properties: [.contentType("application/json")] ) ``` -------------------------------- ### MQTTClient Shutdown Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.md Methods for gracefully shutting down the MQTTClient. ```APIDOC ## MQTTClient Shutdown ### Description Provides methods to shut down the MQTTClient, allowing for graceful disconnection and resource cleanup. ### Methods - **`shutdown(queue:)`**: Initiates an asynchronous shutdown process. - **`shutdown(queue:_:)`**: Initiates an asynchronous shutdown process with a completion handler. - **`syncShutdownGracefully()`**: Performs a synchronous graceful shutdown. ``` -------------------------------- ### Listen for MQTT Connection Events Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Register listeners to receive notifications for connection close and client shutdown events. Listeners can be named for easy removal. ```swift client.addCloseListener(named: "closeHandler") { result in switch result { case .success: print("Connection closed normally") case .failure(let error): print("Connection closed with error: \(error)") } } ``` ```swift client.addShutdownListener(named: "shutdownHandler") { result in switch result { case .success: print("Client shutdown complete") case .failure(let error): print("Shutdown error: \(error)") } } ``` ```swift client.removeCloseListener(named: "closeHandler") client.removeShutdownListener(named: "shutdownHandler") ``` -------------------------------- ### Sign AWS IoT WebSocket URL with SotoCore Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/mqttnio-aws.md Uses the AWSSigner from SotoCore to generate a signed URL for WebSocket connections to AWS IoT. Ensure the host, credentials, and region are correctly configured for your AWS environment. ```swift import SotoSignerV4 let host = "MY_AWS_IOT_ENDPOINT.iot.eu-west-1.amazonaws.com" let headers = HTTPHeaders([("host", host)]) let signer = AWSSigner( credentials: StaticCredential(accessKeyId: "MYACCESSKEY", secretAccessKey: "MYSECRETKEY"), name: "iotdata", region: "eu-west-1" ) let signedURL = signer.signURL( url: URL(string: "https://\(host)/mqtt")!, method: .GET, headers: headers, body: .none, expires: .minutes(30) ) let requestURI = "/mqtt?\(signedURL.query!)" let client = MQTTClient( host: host, identifier: "MyAWSClient", eventLoopGroupProvider: .createNew, configuration: .init(useSSL: true, webSocketConfiguration: .init(urlPath: requestUri)) ) ``` -------------------------------- ### MQTT Client Publish API Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.V5.md Methods for publishing messages to topics on the MQTT broker. ```APIDOC ## MQTT Client Publish API ### Description Methods for publishing messages to topics on the MQTT broker. ### Methods - `publish(to:payload:qos:retain:properties:)` ``` -------------------------------- ### Subscribe to Topics and Listen for Messages Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/mqttnio.md Subscribes to a topic filter and processes incoming publish events using an asynchronous listener. ```swift let subscription = MQTTSubscribeInfo(topicFilter: "my-topics", qos: .atLeastOnce) _ = try await client.subscribe(to: [subscription]) let listener = client.createPublishListener() for await result in listener { switch result { case .success(let publish): if publish.topicName == "my-topics" { var buffer = publish.payload let string = buffer.readString(length: buffer.readableBytes) print(string) } case .failure(let error): print("Error while receiving PUBLISH event") } } ``` -------------------------------- ### Configure TLS with NIO Transport Services (iOS/macOS) Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt For iOS and macOS, configure TLS using TSTLSConfiguration with Apple's Network framework. This requires loading certificates in DER format or PKCS#12 identity. ```swift #if canImport(Network) import Network let trustRoots = try TSTLSConfiguration.Certificates.der("ca.der") let clientIdentity = try TSTLSConfiguration.Identity.p12( filename: "client.p12", password: "certificate-password" ) let tsConfig = TSTLSConfiguration( minimumTLSVersion: .tlsV12, trustRoots: trustRoots, clientIdentity: clientIdentity, certificateVerification: .fullVerification ) ``` ```swift let iosClient = MQTTClient( host: "mqtt.example.com", port: 8883, identifier: "iOSClient", eventLoopGroupProvider: .createNew, configuration: .init( useSSL: true, tlsConfiguration: .ts(tsConfig) ) ) #endif ``` -------------------------------- ### Receive Published MQTT Messages Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Handle incoming messages using either an AsyncSequence for Swift concurrency or a callback-based listener. Ensure proper handling of payload data and potential errors. ```swift Task { let listener = client.createPublishListener() for await result in listener { switch result { case .success(let publish): var payloadCopy = publish.payload let message = payloadCopy.readString(length: payloadCopy.readableBytes) ?? "" print("Received on \(publish.topicName): \(message)") print("QoS: \(publish.qos), Retain: \(publish.retain)") case .failure(let error): print("Error receiving message: \(error)") } } } ``` ```swift client.addPublishListener(named: "myListener") { result in switch result { case .success(let publish): var payload = publish.payload if let message = payload.readString(length: payload.readableBytes) { print("[\(publish.topicName)] \(message)") } case .failure(let error): print("Listener error: \(error)") } } ``` ```swift client.removePublishListener(named: "myListener") ``` -------------------------------- ### MQTTClient Publish Listeners Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.md Management of listeners for incoming published messages. ```APIDOC ## MQTTClient Publish Listeners ### Description Allows for the creation and management of listeners that are triggered when messages are published to the client. ### Methods - **`createPublishListener()`**: Creates a new listener for published messages. - **`addPublishListener(named:_:)`**: Adds a named listener for published messages. - **`removePublishListener(named:)`**: Removes a named listener for published messages. ``` -------------------------------- ### Publish MQTT Messages Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Send payloads to specific topics using various QoS levels and API patterns. ```swift // Publish with async/await var payload = ByteBufferAllocator().buffer(capacity: 256) payload.writeString("Hello, MQTT!") try await client.publish( to: "sensors/temperature", payload: payload, qos: .atLeastOnce, retain: false ) // Publish JSON data let jsonData = """ {"temperature": 23.5, "humidity": 65, "timestamp": "\(Date())"} """ var jsonPayload = ByteBufferAllocator().buffer(capacity: jsonData.utf8.count) jsonPayload.writeString(jsonData) try await client.publish( to: "sensors/room1/data", payload: jsonPayload, qos: .exactlyOnce, retain: true ) // Publish with EventLoopFuture client.publish(to: "notifications", payload: payload, qos: .atMostOnce) .whenComplete { result in switch result { case .success: print("Message published") case .failure(let error): print("Publish failed: \(error)") } } ``` -------------------------------- ### Publish a Message to a Topic Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/mqttnio.md Sends a payload to a specific topic with a defined Quality of Service level. ```swift try await client.publish( to: "my-topics", payload: ByteBuffer(string: "This is the Test payload"), qos: .atLeastOnce ) ``` -------------------------------- ### Disconnect and Shutdown MQTT Client Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Properly disconnect from the broker and shut down the client to release resources. The shutdown method is required before deallocation. ```swift try await client.disconnect() ``` ```swift try await client.shutdown() ``` ```swift try client.syncShutdownGracefully() ``` ```swift let client = MQTTClient( host: "mqtt.example.com", port: 1883, identifier: "LifecycleClient", eventLoopGroupProvider: .createNew ) do { try await client.connect() // ... perform MQTT operations ... try await client.disconnect() } catch { print("Error: \(error)") } // Always shutdown, even if errors occurred try await client.shutdown() ``` -------------------------------- ### MQTTClient Publish Operations Source: https://github.com/swift-server-community/mqtt-nio/blob/main/Sources/MQTTNIO/MQTTNIO.docc/MQTTClient.md Methods for publishing messages using the MQTTClient. ```APIDOC ## MQTTClient Publish Operations ### Description Allows the client to publish messages to specified topics with various Quality of Service (QoS) levels and retain options. ### Methods - **`publish(to:payload:qos:retain:)`**: Publishes a message to a topic. - **`publish(to:payload:qos:retain:properties:)`**: Publishes a message with additional properties. ``` -------------------------------- ### Check Connection Status Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Uses the isActive method to verify the connection and trigger reconnection if necessary. ```swift if client.isActive() { print("Client is connected") try await client.publish(to: "status", payload: ByteBuffer(string: "online"), qos: .atMostOnce) } else { print("Client is not connected, attempting reconnection...") try await client.connect() } ``` -------------------------------- ### Filter MQTT v5.0 Messages by Subscription Identifier Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Use the v5-specific publish listener to filter incoming messages based on a subscription identifier. This allows for targeted message handling for specific subscriptions. ```swift let subscriptionId: UInt = 42 try await v5Client.v5.subscribe( to: [MQTTSubscribeInfoV5(topicFilter: "filtered/topic", qos: .atLeastOnce)], properties: [.subscriptionIdentifier(subscriptionId)] ) ``` ```swift let filteredListener = v5Client.v5.createPublishListener(subscriptionId: subscriptionId) for await publish in filteredListener { var payload = publish.payload let message = payload.readString(length: payload.readableBytes) ?? "" print("Received (subscription \(subscriptionId)): \(message)") } ``` -------------------------------- ### Perform Manual Ping Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Configures a client with automatic pings disabled to allow for manual ping requests. ```swift // Disable automatic ping in configuration let manualPingClient = MQTTClient( host: "mqtt.example.com", port: 1883, identifier: "ManualPingClient", eventLoopGroupProvider: .createNew, configuration: .init(disablePing: true, keepAliveInterval: .seconds(120)) ) // Manually ping the server try await manualPingClient.ping() print("Server responded to ping") ``` -------------------------------- ### Unsubscribe from MQTT Topics Source: https://context7.com/swift-server-community/mqtt-nio/llms.txt Remove subscriptions from specified topics. Supports both asynchronous and callback-based unsubscribe operations. ```swift try await client.unsubscribe(from: ["sensors/temperature", "alerts/#"]) ``` ```swift client.unsubscribe(from: ["status/+"]) .whenSuccess { print("Unsubscribed successfully") } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.