Giter Club home page Giter Club logo

mqtt-nio's Introduction

MQTT NIO

sswg:sandbox|94x20 Swift 5.7

A Swift NIO based MQTT v3.1.1 and v5.0 client.

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.

MQTTNIO is a Swift NIO based implementation of a MQTT client. It supports

  • MQTT versions 3.1.1 and 5.0.
  • Unencrypted and encrypted (via TLS) connections
  • WebSocket connections
  • Posix sockets
  • Apple's Network framework via NIOTransportServices (required for iOS).
  • Unix domain sockets

You can find documentation for MQTTNIO here. There is also a sample demonstrating the use MQTTNIO in an iOS app found here

mqtt-nio's People

Contributors

adam-fowler avatar finestructure avatar jpgrayson avatar m-housh avatar michalsrutek avatar obriensp avatar x-0o0 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mqtt-nio's Issues

Keep alive messages not sent

Describe the bug
Starting with version 2.5 keepAliveMessages aren't sent anymore. Before version 2.5 we could see the keep alive messages being sent correctly through the web socket.

To Reproduce
We use the following configuration to initiate the client:

   let configuration = MQTTClient.Configuration(
        keepAliveInterval: .seconds(30),
        connectTimeout: .seconds(20),
        userName: "ips:ips-public",
        password: "password",
        useSSL: true,
        useWebSockets: true,
        webSocketURLPath: "/ws"
    )
   let client = MQTTClient(
        host: "host",
        port: 443,
        identifier: generateClientIdentifier(),
        eventLoopGroupProvider: .createNew,
        configuration: configuration
    )

Expected behavior
We expect the client to send keep alive messages every 30 seconds as it did with previous versions.

Context:

  • Platform iOS
  • Xcode Version: 13
  • Version 2.5

Auto-Reconnect

Hello, I connect my devices using MQTT, but rely on a cellular network that drops out occasionally causing a keep-alive failure or other type of disconnection. Currently I am using the following code to auto-reconnect. However, it often does not work. I wanted to see if you had any suggestions @adam-fowler as to the best way to cleanly shutdown and restart the MQTT client.

        client.addCloseListener(named: "close") { [unowned self] result in
            DispatchQueue.main.async { [unowned self] in
                switch result {
                case .success:
                    print("MQTT client \(self.clientIdentifier) closed without error")
                    try? self.stopClient()
                    self.client = try? self.createMQTTClient(jwtString: try self.createJWT())
                case .failure(let error):
                    print("MQTT client \(self.clientIdentifier) disconnected with error:")
                    dump(error)
                    try? self.stopClient()
                    self.client = try? self.createMQTTClient(jwtString: try self.createJWT())
                }
            }
        }

Ubuntu 18.04 Raspberry Pi 3 - Connection hangs and never succeeds or fails

Describe the bug
I implemented a simple MQTT Client to connect to Google Cloud IoT. When running on MacOS it works great. However, when using Ubuntu 18.04 on a Raspberry Pi 3, The try client.connect().wait() never returns.

To Reproduce
Steps to reproduce the behavior:

  1. Implement an MQTT Client
  2. Install on Raspberry Pi 3 running Ubuntu 18.04 (bionic)

Expected behavior
I would like it to succeed or fail with some specific error

Context (please complete the following information):

  • Platform: Linux Ubuntu 18.04
  • Swift/Xcode Version: 5.1.5 and 5.3
  • Version: main branch latest

Strange error on connect appeared yesterday

Used this lib all day before yesterday and mid day yesterday I started getting this error with MQTTNIO.
Does it with the other fork as well.
That class is private api it seems as there is nothing on google about it.

If u just use URLSession.shared to load a url I dont see this error.
It has completely broken my app.
Any ideas?

this is from client.connect().wait()

Ive enabled ats exceptions, tried non beta Xcode , everything I can think of.

connecting...
2021-06-22 10:36:33.311011-0500 MQTTTesting[1010:152012] Cannot parse config agent (NSPPrivacyProxyDNSAgent). No data available
2021-06-22 10:36:33.637955-0500 MQTTTesting[1010:152012] Cannot parse config agent (NSPPrivacyProxyDNSAgent). No data available
2021-06-22 10:36:33.641094-0500 MQTTTesting[1010:152012] Cannot parse config agent (NSPPrivacyProxyDNSAgent). No data available
connectTimeout(NIO.TimeAmount(nanoseconds: 10000000000))

Failed to Compile; Includes inline assembly

Describe the bug
Hi Adam

Thanks for this code - it is one of few mqtt libraries that I have found that is able to run independently on WatchOS. (which I need)
Testing and working well on both iOS and WatchOS 7, stimulators and devices.. Yah!

Unfortunately when i upload to Testflight: I receive this error:

ITMS-90562: Invalid Bundle - Bitcode failed to compile for your watchOS binary because it includes assembly source code or inline assembly. To resolve this issue, rewrite the corresponding code in a higher-level language such as Objective-C or Swift and redeliver your app.

At a guess it relates to the CCoreMqtt code? -- although can't find anything obvious.
Any suggestions or thoughts?

(Should mention - no other libraries/pods/dependencies, other than those needed/include with mqtt-nio)

Thanks.

Crashes when subscribing to all topics on mosquitto test server

Describe the bug
Fatal error when subscribing to all topics on mosquito test server.

To Reproduce
Steps to reproduce the behavior:

  1. Setup a client as documented
  2. Subscribe to # on test.mosquitto.org
  3. After a second or so the library will crash

Expected behavior
A clear and concise description of what you expected to happen.

macOS Big Sur, M1 mini
Swift 5.3, Xcode 12.3

Additional context

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file MQTTNIO/MQTTSerializer.swift, line 160

image

Cannot connect to mqtt broker after upgrading to 1.2.2

Describe the bug

let client = MQTTClient(
            host: "mqtt.eclipse.org",
            port: 1883,
            identifier: "My Client",
            eventLoopGroupProvider: .createNew
        )
        do {
            try client.connect().wait()
        } catch {
            print(error)
        }

connectTimeout(NIO.TimeAmount(nanoseconds: 10000000000))

  • Platform ios 14
  • Swift/Xcode Version: 5.3 / 12.4

I’m not sure if it’s because of my problem, so I need someone’s help to determine this bug
Thank you.

Use 1.2.2 to report a connection timeout error

Use 1.2.2 to report a connection timeout error
Sorry, the issue I submitted yesterday was closed, so I had to resubmit a new one

I installed 1.2.2 through spm in a new application and connected to the mqtt server to report:
connectTimeout(NIO.TimeAmount(nanoseconds: 10000000000))

The local mqtt broker is working normally, and other clients can be connected normally

let client = MQTTClient(
         host: "192.168.1.10",
         port: 1883,
         identifier: "My Client test222",
         eventLoopGroupProvider: .createNew
     )
     do {
         try client.connect(cleanSession: false).wait()
     } catch {
         print(error)
     }

I have been confused about this problem for three days. I have tried many solutions but failed. I hope someone can help me, thank you!

Xcode:12.4
swift: 5.3.2

1619459245150

Allow zero byte client ids and extract server assigned id from connack

From spec: A Server MAY allow a Client to supply a ClientID that has a length of zero bytes, however if it does so the Server MUST treat this as a special case and assign a unique ClientID to that Client [MQTT-3.1.3-6]. It MUST then process the CONNECT packet as if the Client had provided that unique ClientID, and MUST return the Assigned Client Identifier in the CONNACK packet

Long payload will cause errors!

Thanks author
This is the only library I can find on github that can be used in swift 5.3.
Please fix this bug, thank you very much!

json payload:
{"from":1000000,"to":1234567,"type":1,"content":"I am a beginner in swift and I am studying hard!!测试\n\n test, message","timestamp":1607243024,"nonce":"pAx2EsUuXrVuiIU3GGOGHNbUjzRRdT5b","sign":"ff902e31a6a5f5343d70a3a93ac9f946adf1caccab539c6f3a6"}

client.addPublishListener(named: "My Listener") { result in
switch result {
case .success(let publish):
var buffer = publish.payload
print(buffer)
let string = buffer.readString(length: buffer.readableBytes)
print(string)
case .failure(let error):
print("Error while receiving PUBLISH event")
print(error)
}
}
Error while receiving PUBLISH event
MQTTError(status: MQTTNIO.MQTTStatus.MQTTBadResponse)
Error while receiving PUBLISH event
MQTTError(status: MQTTNIO.MQTTStatus.MQTTBadResponse)
Error while receiving PUBLISH event
MQTTError(status: MQTTNIO.MQTTStatus.MQTTBadResponse)

xcode: 12.3 beta, swift: 5.3

Xcode preview fails to build with errors

Describe the bug
Adding mqtt-nio dependency to iOS project breaks SwiftUI Previews

To Reproduce
Steps to reproduce the behavior:

  1. Create a new iOS app project in Xcode
  2. Add mqtt-nio dependency in Swift packages to the app project
  3. open ContentView.swift and refresh the Preview. This generates 11 errors :

Undefined symbol: nominal type descriptor for NIOSSL.NIOSSLCertificate
Undefined symbol: nominal type descriptor for NIOSSL.NIOSSLClientTLSProvider
Undefined symbol: NIOSSL.NIOSSLCertificate.toDERBytes() throws -> [Swift.UInt8]
Undefined symbol: static NIOSSL.NIOSSLCertificate.fromPEMFile(Swift.String) throws -> [NIOSSL.NIOSSLCertificate]
Undefined symbol: type metadata accessor for NIOSSL.NIOSSLContext
Undefined symbol: nominal type descriptor for NIOSSL.TLSConfiguration
Undefined symbol: protocol conformance descriptor for NIOSSL.NIOSSLClientTLSProvider : NIOCore.NIOClientTLSProvider in NIOSSL
Undefined symbol: type metadata accessor for NIOSSL.NIOSSLCertificate
Undefined symbol: NIOSSL.NIOSSLContext.__allocating_init(configuration: NIOSSL.TLSConfiguration) throws -> NIOSSL.NIOSSLContext
Undefined symbol: static NIOSSL.TLSConfiguration.makeClientConfiguration() -> NIOSSL.TLSConfiguration
Undefined symbol: NIOSSL.NIOSSLClientTLSProvider.init(context: NIOSSL.NIOSSLContext, serverHostname: Swift.String?, customVerificationCallback: (([NIOSSL.NIOSSLCertificate], NIOCore.EventLoopPromise<NIOSSL.NIOSSLVerificationResult>) -> ())?) throws -> NIOSSL.NIOSSLClientTLSProvider

Expected behavior
mqtt-nio builds and runs fine in the iOS simulator and on a real iOS device but breaks previews in Xcode...the preview simulator fails with errors on the build.

Context (please complete the following information):

  • Platform [e.g. iOS, macOS, Linux] iOS
  • Swift/Xcode Version: Xcode 13.2.1
  • Version [e.g. 1.2.0] mqtt-nio latest 2.5.2

Additional context
I am filing a feedback with Apple as well, as it's equally likely that it's their tool that's broken as the code in mqtt-nio builds and run fine outside of Xcode Preview.

MQTTClient do not ping

the func scheduleTask in class PingreqHandler execute before channel is active;

Maybe you should start it in channelActive in class MQTTMessageHandler;

Don't use topic alias greater than server topic alias maximum

From spec: This value indicates the highest value that the Server will accept as a Topic Alias sent by the Client. The Server uses this value to limit the number of Topic Aliases that it is willing to hold on this Connection. The Client MUST NOT send a Topic Alias in a PUBLISH packet to the Server greater than this value [MQTT-3.2.2-17]. A value of 0 indicates that the Server does not accept any Topic Aliases on this connection. If Topic Alias Maximum is absent or 0, the Client MUST NOT send any Topic Aliases on to the Server [MQTT-3.2.2-18].

A sender MUST NOT send a PUBLISH packet containing a Topic Alias which has the value 0

Remove resend messages and only resend on reconnection

From spec: When a Client reconnects with Clean Start set to 0 and a session is present, both the Client and Server MUST resend any unacknowledged PUBLISH packets (where QoS > 0) and PUBREL packets using their original Packet Identifiers. This is the only circumstance where a Client or Server is REQUIRED to resend messages. Clients and Servers MUST NOT resend messages at any other time

Notifying the subscription topic of a message notification

Hi Adam,

I am using your great component on a project that uses your library in two different forms, I have clients that will suscribe to a specific topic, lets say "topic/subtopic" and in a more general way let say "topic/"

My issue is that, when a publish notification arrives, the framework do not state for wich subscription topic happened, but just the topic of the message, so I cannot dispatch to the addecuate client. I would suggest to extend the MQTTPublishInfo to add either the topic of the subscription or eventually a copy of the MQTTSubscribeInfo. On that way I could map the subscriptions to my consumers.

Thanks for your support
Juan Solsona.

Watch OS 9 Beta: Couldn't establish connection to MQTT server, getting connection timeout error

Describe the bug
Getting Connection timeout error when try to establish the connection to MQTT server in Apple watch. but its working fine in WatchOS simulator. I am using WatchOS 9 beta 5.
I tried with 30 sec of connection timeout, still no use.

MQTTClient(host: url.host ?? "",
    port: url.port,
    identifier: clientId,
    eventLoopGroupProvider: .createNew,
    configuration: .init(version: .v3_1_1,
    keepAliveInterval: .seconds(10),
    connectTimeout: .seconds(30),
    useSSL: true,
    useWebSockets: true,
    tlsConfiguration: .ts(.init(certificateVerification: .fullVerification)),
    webSocketURLPath: "\(url.path)?\(url.query ?? "")"))

Seeing this below error in the log
connection error connectTimeout(NIOCore.TimeAmount(nanoseconds: 10000000000))

Expected behavior
Connection establish should happen between client and MQTT server in Watch OS 9 beta in a real watch.

Context (please complete the following information):

  • Platform : WatchOS
  • Swift/Xcode Version: Xcode 14 beta 5
  • Version : WatchOS 9 beta 5

MQTTNIO has moved

MQTTNIO has moved to the swift server community organisation. Please replace your Package.swift package dependency with

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

Build errors with Xcode 13.2

Describe the bug
Just a heads up, as Xcode 13.2 is still in beta, but we were trying to build an iOS project with mqtt-nio as SPM dependency, which fails when using Xcode 13.2. It throws the following build errors:

TSTLSConfiguration.swift:11:11: 'tls_protocol_version_t' is only available in iOS 13.0 or newer
TSTLSConfiguration.swift:45:35: 'tls_protocol_version_t' is only available in iOS 13.0 or newer
TSTLSConfiguration.swift:48:35: 'tls_protocol_version_t' is only available in iOS 13.0 or newer
TSTLSConfiguration.swift:65:28: 'tls_protocol_version_t' is only available in iOS 13.0 or newer
TSTLSConfiguration.swift:66:28: 'tls_protocol_version_t' is only available in iOS 13.0 or newer
TSTLSConfiguration.swift:65:54: 'TLSv10' is only available in iOS 13.0 or newer

Apple's docs on tls_protocol_version_t also list that it is available starting from iOS 13, so my guess is that this happens due to the Package.swift defining iOS 12 as platform: https://github.com/adam-fowler/mqtt-nio/blob/main/Package.swift#L7

To Reproduce
Steps to reproduce the behavior:

  1. Integrated mqtt-nio into an iOS project via SPM
  2. Build the project using Xcode 13.2

Expected behavior
The build should succeed.

Context (please complete the following information):

  • Platform: iOS
  • Swift/Xcode Version: Xcode 13.2.0 (13C5066c)
  • Version: 2.1.1

Add Tasks by writing to channel

Require MQTTTaskHandler to have OutboundIn type as MQTTTask. Can ensure tasks are removed and added on same EventLoop. Tidies up pushing tasks onto Channel, don't need to go via MQTTConnection all the time

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.