Skip to content

Commit 29b5cec

Browse files
authored
README update (#125)
* README update * readme updates * bullet points * documentation update
1 parent 60676a7 commit 29b5cec

File tree

2 files changed

+18
-183
lines changed

2 files changed

+18
-183
lines changed

README.md

Lines changed: 10 additions & 181 deletions
Original file line numberDiff line numberDiff line change
@@ -1,190 +1,19 @@
11
# MQTT NIO
22

33
[![sswg:sandbox|94x20](https://img.shields.io/badge/sswg-sandbox-lightgrey.svg)](https://github.com/swift-server/sswg/blob/master/process/incubation.md#sandbox-level)
4-
[<img src="http://img.shields.io/badge/swift-5.5-brightgreen.svg" alt="Swift 5.5" />](https://swift.org)
4+
[<img src="http://img.shields.io/badge/swift-5.7-brightgreen.svg" alt="Swift 5.7" />](https://swift.org)
55
[<img src="https://github.com/adam-fowler/mqtt-nio/workflows/CI/badge.svg" />](https://github.com/adam-fowler/mqtt-nio/workflows/CI/badge.svg)
66

7-
A Swift NIO based MQTT v3.1.1 and v5.0 client supporting NIOTransportServices (required for iOS), WebSocket connections and TLS through both NIOSSL and NIOTransportServices.
7+
A Swift NIO based MQTT v3.1.1 and v5.0 client.
88

99
MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol that was developed by IBM and first released in 1999. It uses the pub/sub pattern and translates messages between devices, servers, and applications. It is commonly used in Internet of things (IoT) technologies.
1010

11-
## Usage
11+
MQTTNIO is a Swift NIO based implementation of a MQTT client. It supports
12+
- MQTT versions 3.1.1 and 5.0.
13+
- Unencrypted and encrypted (via TLS) connections
14+
- WebSocket connections
15+
- Posix sockets
16+
- Apple's Network framework via [NIOTransportServices](https://github.com/apple/swift-nio-transport-services) (required for iOS).
1217

13-
Create a client and connect to the MQTT broker.
14-
15-
```swift
16-
let client = MQTTClient(
17-
host: "mqtt.eclipse.org",
18-
port: 1883,
19-
identifier: "My Client",
20-
eventLoopGroupProvider: .createNew
21-
)
22-
client.connect().whenComplete { result in
23-
switch result {
24-
case .success:
25-
print("Succesfully connected")
26-
case .failure(let error):
27-
print("Error while connecting \(error)")
28-
}
29-
}
30-
```
31-
32-
Subscribe to a topic and add a publish listener to report publish messages sent from the server/broker.
33-
```swift
34-
let subscription = MQTTSubscribeInfo(topicFilter: "my-topics", qos: .atLeastOnce)
35-
client.subscribe(to: [subscription]).whenComplete { result in
36-
...
37-
}
38-
client.addPublishListener("My Listener") { result in
39-
switch result {
40-
case .success(let publish):
41-
var buffer = publish.payload
42-
let string = buffer.readString(length: buffer.readableBytes)
43-
print(string)
44-
case .failure(let error):
45-
print("Error while receiving PUBLISH event")
46-
}
47-
}
48-
```
49-
50-
Publish to a topic.
51-
```swift
52-
client.publish(
53-
to: "my-topics",
54-
payload: ByteBuffer(string: "This is the Test payload"),
55-
qos: .atLeastOnce
56-
).whenComplete { result in
57-
...
58-
}
59-
```
60-
Each MQTTClient function returns a Swift NIO `EventLoopFuture`. In the examples above I just use `whenComplete` to process the results, but you can use various methods to chain `EventLoopFuture` together. You can find out more about Swift NIO [here](https://apple.github.io/swift-nio/docs/current/NIO/Classes/EventLoopFuture.html).
61-
62-
## Swift Concurrency
63-
64-
Alongside the `EventLoopFuture` APIs MQTTNIO also includes async/await versions. So where with `EventLoopFutures` you would write
65-
```swift
66-
client.connect()
67-
.flatMap { _ -> EventLoopFuture<MQTTSuback> in
68-
let subscription = MQTTSubscribeInfo(topicFilter: "my-topics", qos: .atLeastOnce)
69-
return client.subscribe(to: [subscription])
70-
}
71-
.whenComplete { result in
72-
doStuff()
73-
}
74-
```
75-
you can now replace it with
76-
```swift
77-
try await client.connect()
78-
let subscription = MQTTSubscribeInfo(topicFilter: "my-topics", qos: .atLeastOnce)
79-
_ = try await client.subscribe(to: [subscription])
80-
doStuff()
81-
```
82-
83-
### PUBLISH listener AsyncSequence
84-
If you don't want to parse incoming PUBLISH packets via a callback the Swift concurrency support also includes an `AsyncSequence` for this purpose.
85-
```swift
86-
let listener = client.createPublishListener()
87-
for await result in listener {
88-
switch result {
89-
case .success(let publish):
90-
var buffer = publish.payload
91-
let string = buffer.readString(length: buffer.readableBytes)
92-
print(string)
93-
case .failure(let error):
94-
print("Error while receiving PUBLISH event")
95-
}
96-
}
97-
```
98-
99-
## TLS
100-
101-
MQTT NIO supports TLS connections. You can enable this through the `Configuration` provided at initialization. Set`Configuration.useSSL` to `true` and provide your SSL certificates via the `Configuration.tlsConfiguration` struct. For example to connect to the mosquitto test server `test.mosquitto.org` on port 8884 you need to provide their root certificate and your own certificate. They provide details on the website [https://test.mosquitto.org/](https://test.mosquitto.org/) on how to generate these.
102-
103-
```swift
104-
let rootCertificate = try NIOSSLCertificate.fromPEMBytes([UInt8](mosquittoCertificateText.utf8))
105-
let myCertificate = try NIOSSLCertificate.fromPEMBytes([UInt8](myCertificateText.utf8))
106-
let myPrivateKey = try NIOSSLPrivateKey(bytes: [UInt8](myPrivateKeyText.utf8), format: .pem)
107-
let tlsConfiguration: TLSConfiguration? = TLSConfiguration.forClient(
108-
trustRoots: .certificates(rootCertificate),
109-
certificateChain: myCertificate.map { .certificate($0) },
110-
privateKey: .privateKey(myPrivateKey)
111-
)
112-
let client = MQTTClient(
113-
host: "test.mosquitto.org",
114-
port: 8884,
115-
identifier: "MySSLClient",
116-
eventLoopGroupProvider: .createNew,
117-
configuration: .init(useSSL: true, tlsConfiguration: .niossl(tlsConfiguration)),
118-
)
119-
```
120-
121-
## WebSockets
122-
123-
MQTT also supports Web Socket connections. Set `Configuration.useWebSockets` to `true` and set the URL path in `Configuration.webSocketsURLPath` to enable these.
124-
125-
## NIO Transport Services
126-
127-
On macOS and iOS you can use the NIO Transport Services library (NIOTS) and Apple's `Network.framework` for communication with the MQTT broker. If you don't provide an `eventLoopGroup` or a `TLSConfigurationType` then this is the default for both platforms. If you do provide either of these then the library will base it's decision on whether to use NIOTS or NIOSSL on what you provide. Provide a `MultiThreadedEventLoopGroup` or `NIOSSL.TLSConfiguration` and the client will use NIOSSL. Provide a `NIOTSEventLoopGroup` or `TSTLSConfiguration` and the client will use NIOTS. If you provide a `MultiThreadedEventLoopGroup` and a `TSTLSConfiguration` then the client will throw an error. If you are running on iOS you should always choose NIOTS.
128-
129-
## AWS IoT
130-
131-
The MQTT client can be used to connect to AWS IoT brokers. You can use both a WebSocket connection authenticated using AWS Signature V4 and a standard connection using a X.509 client certificate. If you are using a X.509 certificate make sure you update the attached role to allow your client id to connect and which topics you can subscribe, publish to.
132-
133-
If you are using an AWS Signature V4 authenticated WebSocket connection you can use the V4 signer from [SotoCore](https://github.com/soto-project/soto) to sign your initial request as follows
134-
```swift
135-
import SotoSignerV4
136-
137-
let host = "MY_AWS_IOT_ENDPOINT.iot.eu-west-1.amazonaws.com"
138-
let headers = HTTPHeaders([("host", host)])
139-
let signer = AWSSigner(
140-
credentials: StaticCredential(accessKeyId: "MYACCESSKEY", secretAccessKey: "MYSECRETKEY"),
141-
name: "iotdata",
142-
region: "eu-west-1"
143-
)
144-
let signedURL = signer.signURL(
145-
url: URL(string: "https://\(host)/mqtt")!,
146-
method: .GET,
147-
headers: headers,
148-
body: .none,
149-
expires: .minutes(30)
150-
)
151-
let requestURI = "/mqtt?\(signedURL.query!)"
152-
let client = MQTTClient(
153-
host: host,
154-
identifier: "MyAWSClient",
155-
eventLoopGroupProvider: .createNew,
156-
configuration: .init(useSSL: true, useWebSockets: true, webSocketURLPath: requestUri)
157-
)
158-
```
159-
You can find out more about connecting to AWS brokers [here](https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html)
160-
161-
## MQTT Version 5.0
162-
163-
Version 2.0 of MQTTNIO added support for MQTT v5.0. To create a client that will connect to a v5 MQTT broker you need to set the version in the configuration as follows
164-
165-
```swift
166-
let client = MQTTClient(
167-
host: host,
168-
identifier: "MyAWSClient",
169-
eventLoopGroupProvider: .createNew,
170-
configuration: .init(version: .v5_0)
171-
)
172-
```
173-
174-
You can then use the same functions available to the v3.1.1 client but there are also v5.0 specific versions of `connect`, `publish`, `subscribe`, `unsubscribe` and `disconnect`. These can be accessed via the variable `MQTTClient.v5`. The v5.0 functions add support for MQTT properties in both function parameters and return types and the additional subscription parameters. For example here is a `publish` call adding the `contentType` property.
175-
176-
```swift
177-
let futureResponse = client.v5.publish(
178-
to: "JSONTest",
179-
payload: payload,
180-
qos: .atLeastOnce,
181-
properties: [.contentType("application/json")]
182-
)
183-
```
184-
185-
Whoever subscribes to the "JSONTest" topic with a v5.0 client will also receive the `.contentType` property along with the payload.
186-
187-
## Documentation
188-
189-
You can find reference documentation for MQTTNIO
190-
[here](https://swift-server-community.github.io/mqtt-nio/documentation/mqttnio/). There is also a sample demonstrating using MQTTNIO within an iOS app found [here](https://github.com/adam-fowler/EmCuTeeTee)
18+
You can find documentation for MQTTNIO
19+
[here](https://swift-server-community.github.io/mqtt-nio/documentation/mqttnio/). There is also a sample demonstrating the use MQTTNIO in an iOS app found [here](https://github.com/adam-fowler/EmCuTeeTee)

Sources/MQTTNIO/MQTTNIO.docc/mqttnio.md

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,16 @@
22

33
A Swift NIO based MQTT client
44

5-
MQTTNIO is a Swift NIO based MQTT v3.1.1 and v5.0 client supporting unencrypted, WebSocket connections and TLS through both NIOSSL and NIOTransportServices.
6-
75
MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol that was developed by IBM and first released in 1999. It uses the pub/sub pattern and translates messages between devices, servers, and applications. It is commonly used in Internet of things (IoT) technologies.
86

7+
MQTTNIO is a Swift NIO based implementation of a MQTT client. It supports
8+
9+
- MQTT versions 3.1.1 and 5.0.
10+
- Unencrypted and encrypted (via TLS) connections
11+
- WebSocket connections
12+
- Posix sockets
13+
- Apple's Network framework via [NIOTransportServices](https://github.com/apple/swift-nio-transport-services) (required for iOS).
14+
915
## Usage
1016

1117
Create a client and connect to the MQTT broker.

0 commit comments

Comments
 (0)