MQTTNIO - Non-blocking, event-driven Swift client for MQTT build on SwiftNIO

Related tags

Networking mqtt-nio
Overview

MQTTNIO

Non-blocking, event-driven Swift client for MQTT (5.0 and 3.1.1) build on SwiftNIO.

This library has support for WebSocket connections and TLS. It runs on all platforms Swift NIO runs on (e.g. macOS, iOS, Linux, etc.).

Tests Swift 5.4 Release

Installation

Use the SPM string to easily include the dependendency in your Package.swift file.

.package(url: "https://github.com/sroebert/mqtt-nio.git", from: "2.0.0")

Supported Platforms

MQTTNIO supports the following platforms:

  • Ubuntu 18.04+
  • macOS 10.9+, iOS 7+, tvOS 12+ or watchOS 6+

Dependencies

This package has four dependencies:

This package has no additional system dependencies.

Usage

Create Client and Connect

let client = MQTTClient(
    configuration: .init(
        target: .host("127.0.0.1", port: 1883)
    ),
    eventLoopGroupProvider: .createNew
)
client.connect()

The client automatically reconnects when failing to connect or when disconnected from the broker.

Connect to an MQTT 3.1.1 broker

let client = MQTTClient(
    configuration: .init(
        target: .host("127.0.0.1", port: 1883),
        protocolVersion: .version3_1_1
    ),
    eventLoopGroupProvider: .createNew
)
client.connect()

Subscribe

client.subscribe(to: "some/topic")

Unsubscribe

client.unsubscribe(from: "some/topic")

Publish

client.publish("Hello World!", to: "some/topic", qos: .exactlyOnce)
client.publish("Hello World!", "some/topic")
client.publish("Hello World!", to: "some/topic", retain: true)

Receive callbacks to know when the client connects/disconnects and receives messages.

client.whenConnected { response in
    print("Connected, is session present: \(response.isSessionPresent)")
}
client.whenDisconnected { reason in
    print("Disconnected: \(reason)")
}
client.whenMessage { message in
    print("Received: \(message)")
}

For platforms where the Combine framework is available, it is also possible to subscribe to publishers.

let cancellable = client.connectPublisher
    .sink { response in
        print("Connected, is session present: \(response.isSessionPresent)")
    }
let cancellable = client.disconnectPublisher
    .sink { reason in
        print("Disconnected: \(reason)")
    }
let cancellable1 = client.messagePublisher
    .sink { message in
        print("Received: \(message)")
    }
let cancellable2 = client.messagePublisher(forTopic: "some/topic")
    .sink { message in
        print("Received: \(message)")
    }

Unit Tests

To easily run the tests locally, simply run docker-compose to setup the needed MQTT broker containers.

docker-compose up
Comments
  • No such module 'MQTTNIO' for watchos application

    No such module 'MQTTNIO' for watchos application

    Per the instructions I have added this package, but I can't seem to import the module. Seems to work fine for an ios application. I must be missing something obvious. Is there anything I can try?

    This is the relevant code in my swift code

    import MQTTNIO
    
    opened by arrow53 5
  • callback for subscribe message

    callback for subscribe message

    I'm using an MQTTClient. I want to subscribe and have a callback when I receive a message. I'm using version 2.0.0 (also tried with 2.6.0). This is for a watchOS app

    If I do this

        init() {
            client.connect()
            
            client.whenMessage { message in
                print("Received: \(message)")
            }
        }
    

    I get this Value of type 'MQTTClient' has no member 'whenMessage'

    opened by arrow53 4
  • ioOnClosedChannel error when connecting

    ioOnClosedChannel error when connecting

    I am trying to connect to a broker on a watch app (WatchOS: 8.3) but I receive this error: Error while connecting ioOnClosedChannel

    I have been looking trough the package to find something but I can't seem to find anything.

    This is the code I use (with correct values for username, password and url filled in):

        let credentials = MQTTConfiguration.Credentials.init(username: "username", password: "password")
        
        let client = MQTTClient(configuration: .init(url: URL(string: "url")!, credentials: credentials))
        //client.connect()
        client.connect().whenComplete { result in
            switch result {
            case .success:
                print("Succesfully connected")
            case .failure(let error):
                print("Error while connecting \(error)")
            }
        }
    

    Thanks in advance!

    opened by azzastudios 4
  • Reply to WebSocket ping frames

    Reply to WebSocket ping frames

    This fixes WebSocket connections to Mosquitto brokers disconnecting every 5 minutes due to the server not receiving any response to WebSocket ping frames. Mosquitto uses libwebsockets which defaults to sending a ping frame every 5 minutes with a 10 second timeout.

    opened by jasoncodes 3
  • App Store Connect - Invalid bundle: Bitcode failed to compile

    App Store Connect - Invalid bundle: Bitcode failed to compile

    Hi

    I am trying to upload my app to the app store connect using this package. But I'm getting this error when uploading:

    ITMS-90562: Invalid Bundle - Bitcode failed to compile for your watchOS binary because it includes assembly source code or inline assembly.

    I found that it is probably related to dependency on the Swift-NIO-SSL package. But haven't been able to work out a solution.

    Maybe you have a solution to this problem.

    Thanks in advance.

    opened by azzastudios 3
  • Not receiving IoT Messages when device is initially in disconnected mode and then connects again.

    Not receiving IoT Messages when device is initially in disconnected mode and then connects again.

    I have a below scenario where I don't receive old messages.

    1. Device is currently in disconnected state
    2. Send message A from Azure IoT Hub
    3. Connect device to IoTHub
    4. Not receiving old message A from step 2.

    The current time out is 1 hour on IoT Hub side. Is there any settings or anything I need to do to get old messages. Thanks.

    opened by amarthere 2
  • Unable to use client certificate chain

    Unable to use client certificate chain

    Hi, great project, thank you for your work! :)

    From version 4.6 we are unable to pass client certificate chain, because client certificate is passed by SecIdentity and SecIndetity is unable to hold certificate chain. I have created PR to your project solving this problem: https://github.com/sroebert/mqtt-nio/pull/10

    I asked Apple engineer about my solution and he confirmed that this is correct solution: https://developer.apple.com/forums/thread/715174

    All tests passed.

    opened by MuniekMg 2
  • Xcode is crashing during exctracting the IPA, with MQTT NIO

    Xcode is crashing during exctracting the IPA, with MQTT NIO

    Hey,

    I have integrated the MQTT NIO version 2.5.0 to my current watch OS target. Everything works fine I am able to access the API during my development. But I am facing an Xcode crash while exporting IPA from Archive.

    1. Running on the device and simulator --> No issues
    2. Archiving is successful.

    3) Exporting IPA from Archive --> Xcode is crashing. I have tested with other package dependencies, i am able to export IPA successfully.

    Please do the needful

    opened by muralivm 2
  • wss signed url: Disconnected while waiting for 'Connect Acknowledgment'

    wss signed url: Disconnected while waiting for 'Connect Acknowledgment'

    Hi,

    I've been testing MQTT libraries for Swift for the past two days and this repo appears to be the only Swift library which supports wss. Nice work!

    Issues: I received the log: "notice nl.roebert.MQTTNio : Disconnected while waiting for 'Connect Acknowledgement'"

    1. Is there a callback to alert the application when an error like this occurs?

    2. I'm not sure how to resolve the issue. The url is a pre-signed AWS url with query string. I have the same working on Android with Eclipse.Paho. Looking at the MQTTConfiguration.swift I don't believe the query string is being included, is this a correct assumption? If that is correct is there any way to add the query string?

    var client: MQTTClient! ..... //signed url url = wss://a2xxxxxxxx.iot.us-east-1.amazonaws.com/mqtt?X-Amz-Algori....... ... client = MQTTClient(configuration: .init(url: url, clientId: clientId)) client.connect() Thanks

    opened by JavierRefuerzo 1
  • Client connection hangs on Ubuntu 18.04

    Client connection hangs on Ubuntu 18.04

    I got an MQTT client running on macOS, but when running the same code on Linux (Ubuntu 18.04 on a Raspberry Pi 3) the client.connect().wait() never succeeds or fails - it just hangs. Any guidance would be very helpful. Thanks!

    opened by ksinghal 1
Releases(2.8.1)
Owner
Steven Roebert
Steven Roebert
A Swift Multiplatform Single-threaded Non-blocking Web and Networking Framework

Serverside non-blocking IO in Swift Ask questions in our Slack channel! Lightning (formerly Edge) Node Lightning is an HTTP Server and TCP Client/Serv

SkyLab 316 Oct 6, 2022
MQTT for iOS and macOS written with Swift

CocoaMQTT MQTT v3.1.1 client library for iOS/macOS/tvOS written with Swift 5 Build Build with Xcode 11.1 / Swift 5.1 Installation CocoaPods Install us

EMQ X MQTT Broker 1.4k Jan 1, 2023
An open-source Swift framework for building event-driven, zero-config Multipeer Connectivity apps

PeerKit An open-source Swift framework for building event-driven, zero-config Multipeer Connectivity apps Usage // Automatically detect and attach to

JP Simard 861 Dec 23, 2022
Passepartout is a non-official, user-friendly OpenVPN® client for iOS and macOS.

Passepartout Passepartout is a non-official, user-friendly OpenVPN® client for iOS and macOS. Overview All profiles in one place Passepartout lets you

Passepartout 523 Dec 27, 2022
Twitter-Client - A twitter client that allow users to view tweets on their iphone

Project 3 - Twitter Client Name of your app is a basic twitter app to read your

null 0 Feb 7, 2022
A computer-vision-driven app for detecting and mapping smog in public roads. Crowdsourcing is rewarded with NFTs. Uber Global Hackathon.

Smogify Detecting smog using ML and rewarding users with NFTs About The Project app in action: https://youtu.be/awJrP-sHb_I Under the growing uncertai

ASOFI 3 Aug 18, 2022
Swift-multipart-formdata - MultipartFormData: Build multipart/form-data type-safe in Swift

MultipartFormData Build multipart/form-data type-safe in Swift. A result builder

Felix Herrmann 21 Dec 29, 2022
A tool to build projects on MacOS and a remote linux server with one command

DualBuild DualBuild is a command line tool for building projects on MacOS and a remote Linux server. ##Setup Install the repository git clone https://

Operator Foundation 0 Dec 26, 2021
A barebones Swift HTTP client with automatic JSON response parsing.

HTTP Client A barebones Swift HTTP client with automatic JSON response parsing. Installation Add HTTP Client as a dependency through Xcode or directly

Joe Masilotti 30 Oct 11, 2022
A simple GCD based HTTP client and server, written in 'pure' Swift

SwiftyHTTP Note: I'm probably not going to update this any further - If you need a Swift networking toolset for the server side, consider: Macro.swift

Always Right Institute 116 Aug 6, 2022
📱  A strongly-typed, caching GraphQL client for iOS, written in Swift.

Apollo iOS is a strongly-typed, caching GraphQL client, written in Swift. It allows you to execute queries and mutations against a GraphQL server, and

Apollo GraphQL 3.6k Jan 7, 2023
An unofficial supported Swift client library for accessing News API.

An unofficial supported Swift client library for accessing News API.

Fumiya Yamanaka 9 Oct 1, 2022
A swift client for interacting with NATS servers

SwiftyNats A maintained swift client for interacting with a nats server based on NIO2. Tested with Swift 5.4 on and Swift Version Compatibility: Platf

aus der Technik - Simon & Simon GbR 25 Dec 15, 2022
Language Server Protocol (LSP) client for Swift

LanguageClient This is a Swift library for abstracting and interacting with language servers that implement the Language Server Protocol. It is built

Chime 35 Jan 1, 2023
A web API client in Swift built using Async/Await

Get A modern web API client in Swift built using Async/Await and Actors. let cli

Alexander Grebenyuk 745 Jan 3, 2023
SoundCloud client written on Swift

SoundCloud client written on Swift to integrate it easily with your apps. Features Fluent interface based on Models Reactive API with ReactiveCocoa 4.

Pedro Piñera Buendía 564 Mar 24, 2022
HTTPClient - HTTP Client With Swift

HTTPClient Ex. Search Repository import HTTPClient let url: URL = .init(string:

zunda 1 Jul 20, 2022
Open source Reddit client for iOS built entirely in Swift

Area51 Area51 is an open source Reddit client for iOS built entirely in Swift! Get the public beta on TestFlight Join the public Slack channel to coll

Kris 141 Dec 26, 2022
Restofire is a protocol oriented networking client for Alamofire

Restofire is a protocol oriented networking client for Alamofire. Features Requirements Installation Usage License Features Global Configuration for h

Restofire 381 Sep 29, 2022