Skip to content

Instantly share code, notes, and snippets.

@adam-fowler
Last active November 24, 2020 16:13
Show Gist options
  • Save adam-fowler/c09c85b33f2ec5f36954d21eb130d7c6 to your computer and use it in GitHub Desktop.
Save adam-fowler/c09c85b33f2ec5f36954d21eb130d7c6 to your computer and use it in GitHub Desktop.

Using MQTTNIO to connect to a AWS IoT Broker with WebSockets

import SotoSignerV4

let host = "MY_AWS_IOT_ENDPOINT"
let port = 443
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):\(port)/mqtt")!, 
    method: .GET, 
    headers: headers, 
    body: .none, 
    expires: .minutes(30)
)
let requestURI = "/mqtt?\(signedURL.query!)"
let client = MQTTClient(
    host: host,
    port: port,
    identifier: "My Client",
    eventLoopGroupProvider: .createNew,
    configuration: .init(useSSL: true, useWebSockets: true, webSocketURLPath: requestUri)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment