Coder Social home page Coder Social logo

moscapsule's Introduction

Moscapsule

MQTT Client for iOS written in Swift.
This framework is implemented as a wrapper of Mosquitto library and covers almost all mosquitto features.
It uses Mosquitto version 1.4.8.

Mosquitto

Mosquitto is an open source message broker that implements the MQ Telemetry Transport protocol versions 3.1 and 3.1.1. MQTT provides a lightweight method of carrying out messaging using a publish/subscribe model. Mosquitto is written in C language.

Installation

CocoaPods

CocoaPods is a Cocoa project manager. It is a easy way for to install framework, so I recommend to using it.
Create your project on Xcode and specify it in your podfile;

target 'MyApp' do
  use_frameworks!

  project 'MyApp.xcodeproj'
  platform :ios, '9.0'

  pod 'Moscapsule', :git => 'https://github.com/flightonary/Moscapsule.git'
  pod 'OpenSSL-Universal'

  target 'MyAppTests' do
    inherit! :search_paths
  end

  target 'MyAppUITests' do
    inherit! :search_paths
  end
end

and then run;

$ pod install

Also you can specify old swift version in the podfile, such as the following;

pod 'Moscapsule', :git => 'https://github.com/flightonary/Moscapsule.git', :branch => 'swift2'

In order to import the framework in tests, you should select configuration files.
a) Select your project and info.
b) Change configuration files from none to Pods.debug/release.
Configuration File

Manual Installation

If you don't want to use CocoaPods, you can install manually.

a) Check out Moscapsule.

$ git clone https://github.com/flightonary/Moscapsule.git

b) The framework depends on OpenSSL. Before building it, you must checkout the submodule.

$ git submodule update --init

c) Create a Xcode project and Workspace if you don't have these.
d) Open workspace and drag & drop your project and Moscapsule.xcodeproj into Navigation.
e) Drag & drop Moscapsule.xcodeproj under your project tree in Navitaion.
f) Select your project and Build Phases.
g) Add Moscapsule in Target Dependencies and Link Binary With Libraries using + button.

Moscapsule Manual Installation

Quick Start

Here is a basic sample.

import Moscapsule

// set MQTT Client Configuration
let mqttConfig = MQTTConfig(clientId: "cid", host: "test.mosquitto.org", port: 1883, keepAlive: 60)
mqttConfig.onConnectCallback = { returnCode in
    NSLog("Return Code is \(returnCode.description)")
}
mqttConfig.onMessageCallback = { mqttMessage in
    NSLog("MQTT Message received: payload=\(mqttMessage.payloadString)")
}

// create new MQTT Connection
let mqttClient = MQTT.newConnection(mqttConfig)

// publish and subscribe
mqttClient.publishString("message", topic: "publish/topic", qos: 2, retain: false)
mqttClient.subscribe("subscribe/topic", qos: 2)

// disconnect
mqttClient.disconnect()

The framework supports TLS_PSK, Server and/or Client certification.
Here is a sample for server certificate.

import Moscapsule

// Note that you must initialize framework only once after launch application
// in case that it uses SSL/TLS functions.
moscapsule_init()

let mqttConfig = MQTTConfig(clientId: "server_cert_test", host: "test.mosquitto.org", port: 8883, keepAlive: 60)

let bundlePath = NSBundle(forClass: self.dynamicType).bundlePath.stringByAppendingPathComponent("cert.bundle")
let certFile = bundlePath.stringByAppendingPathComponent("mosquitto.org.crt")

mqttConfig.mqttServerCert = MQTTServerCert(cafile: certFile, capath: nil)

let mqttClient = MQTT.newConnection(mqttConfig)

Reference

Controlling Connections

Create new connection;

// create MQTT Client Configuration with mandatory prameters
let mqttConfig = MQTTConfig(clientId: "cid", host: "test.mosquitto.org", port: 1883, keepAlive: 60)
// create new MQTT Connection
let mqttClient = MQTT.newConnection(mqttConfig)

As soon as MQTTClient instance is created client attempt to connect to the host. It can be delayed by setting connectImmediately to false.

let mqttClient = MQTT.newConnection(mqttConfig, connectImmediately = false)
mqttClient.connectTo(host: "test.mosquitto.org", port: 1883, keepAlive: 60)

Diconnect the connection;

mqttClient.disconnect()

Reconnect to the same host;

mqttClient.reconnect()

Messaging

Publish a string to MQTT broker;

let msg = "message"
mqttClient.publish(string: msg, topic: topic, qos: 2, retain: false)

Publish a data to MQTT broker;

let data = Data(bytes: [0x00, 0x01, 0x00, 0x00])
mqttClient.publish(data, topic: topic, qos: 2, retain: false)

Subscribe a topic on MQTT broker;

mqttClient.subscribe("/path/to/topic", qos: 2)

Messages on subscribed topic can be received in callback as mentioned below.

Unsubscribe a topic;

mqttClient.unsubscribe("/path/to/topic")

Callbacks

Callback for result of attempting to connect;

mqttConfig.onConnectCallback = { returnCode in
  if returnCode == ReturnCode.success {
    // something to do in case of successful connection
  }
  else {
    // error handling for connection failure
  }
}

Callback which is called when a client disconnected;

mqttConfig.onDisconnectCallback = { reasonCode in
  if reasonCode == ReasonCode.disconnect_requested {
    // successful disconnection you requested
  } else if ... {
    // other cases such as unexpected disconnection.
  }
}

Callback which is called when a client published successfuly;

mqttConfig.onPublishCallback = { messageId in
  // successful publish
}

Callback which is called when a client received message successfuly;

mqttConfig.onMessageCallback = { mqttMessage in
  if mqttMessage.topic == "/path/to/subscribed/topic" {
    NSLog("MQTT Message received: payload=\(mqttMessage.payloadString)")
  } else if ... {
    // something to do in case of other topics
  }
}

Callback which is called when a client subscrived topic successfuly;

mqttConfig.onSubscribeCallback = { (messageId, grantedQos) in
  NSLog("subscribed (mid=\(messageId),grantedQos=\(grantedQos))")
}

Callback which is called when a client unsubscrived topic successfuly;

mqttConfig.onSubscribeCallback = { messageId in
  NSLog("unsubscribed (mid=\(messageId)")
}

Connection Options

T.B.D.

License

Moscapsule: The MIT License (MIT)
Mosquitto: EPL/EDL license

Author

tonary <[email protected]>

moscapsule's People

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

moscapsule's Issues

Is it possible to work with timeouts?

I'm trying to create some NSTimer for dealing with timeout in connection and message receiving but the timer is never called. I presume that's because some thread issues but I'm not sure.

I saw the mosquitto_loop_ and MQTTReconnOpts stuff but not sure how and if it is possible to change those data to get some timeout functionality.

Bellow same sample code:

@objc private func createConnection() {
    timeout = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(timeout(_:)), userInfo: ["foo":"bar"], repeats: false)
    mqttClient = MQTT.newConnection(mqttConfig)
    timeout?.invalidate()
}

How to import?

What is the best way to import this in an existing project? Could you add instructions to the read me please?

Example project

Please create an example project demonstrating the functionality of the library.

Why do you not use another queue for library?

You have serialQueue in the your code and method addRequestToQueue. But serialQueue isn't used anywhere and method addRequestToQueue calls closure in the current queue and doesn't use serialQueue. Why? I have a lot of issues because it. Did you do it because some special issue or not? If not, I can create pull request with this

How to receive mqttMessage in mqttConfig.onMessageCallback

My program can do PUBLISH, PUBRIC, PUBERL, PUBCOMP now
The message print in Log is show below

MyProgram[5194:1180483] [MOSQUITTO] DEBUG Client cid received PUBLISH (d0, q2, r0, m8, 'Test/6', ... (145 bytes))
2016-04-22 09:42:55.109 MyProgram[5194:1180483] [MOSQUITTO] DEBUG Client cid sending PUBREC (Mid: 8)
2016-04-22 09:42:55.117 MyProgram[5194:1180483] [MOSQUITTO] DEBUG Client cid received PUBREL (Mid: 8)
2016-04-22 09:42:55.117 MyProgram[5194:1180483] [MOSQUITTO] DEBUG Client cid sending PUBCOMP (Mid: 8)
2016-04-22 09:43:25.627

But my program never do this block
self.mqttConfig.onMessageCallback = { mqttMessage in
NSLog(“MQTT Message received: payload=(mqttMessage.payloadString)")
}
So I can’t get the mqttMessage.

How to receive mqttMessage?

Thank you!

ps. Sorry for my poor English. If you have any question, please tell me.

My question is similar to this website.
http://stackoverflow.com/questions/36289214/how-to-receive-message-of-subscribed-topic-with-moscapsule

Could Not Connect with tcp Url

Hello everyone,

We are developing an application which needs to consume AWS IoT service based on a MQTT protocol deviation. We are currently facing issues to get connected with MQTT broker provided by AWS IoT cloud server.

Following is the environment:

iOS Version: 11.4
Programming language: Swift 4
Library for MQTT: Moscapsule
Steps followed:
1.Set initial config clientid, host, port
2.Set User Authentication.
using the above step my code works fine , when I Connect mqttClient with WEB Socket . I get response from
1 . On Connection CallBack .
2. On Publish CallBack .
3. On Subscribe CallBack.
4. On Message CallBack.
Problems faced:
When trying to Connect with TCP Socket , I didn't get any response .
Any help in this context is highly appreciable.

Thanks in advance.

Continuous disconnection - MOSQ_CONN_LOST

I keep getting a continuous MOSQ_CONN_LOST and it reconnects but I feel I will lose messages at this rate as it disconnects almost every second. Testing with Xcode 7.3.1 and ios 9.3
screen shot 2016-09-20 at 7 22 47 pm

Sometimes I stop getting messages from topics I'm subscribed with no visible errors/disconnects.

After SUBSCRIBING to topic connection getting disconnect

Hi I'm trying to connect Connect to my MQTT server with SSL Certificate authentication it worked fine. After I subcribed the Topic the connection getting disconnected. This is my code
moscapsule_init()
**let mqttConfig = MQTTConfig(clientId: "shantha", host: "aws.amazonaws.com", port:poer, keepAlive: 60)
let path = Bundle.main.path(forResource: "ca", ofType: "pem")
let path1 = Bundle.main.path(forResource: "client", ofType: "crt")
let key = Bundle.main.path(forResource: "client", ofType: "key")

    mqttConfig.mqttServerCert = MQTTServerCert(cafile: path, capath: nil)
    mqttConfig.mqttClientCert = MQTTClientCert(certfile: path1!, keyfile: key!, keyfile_passwd: nil)
    mqttConfig.mqttTlsOpts = MQTTTlsOpts(tls_insecure: false, cert_reqs: CertReqs.ssl_verify_peer, tls_version: "tlsv1", ciphers: nil)
   
    mqttConfig.onConnectCallback = { returnCode in
        if returnCode == ReturnCode.success {
            print("connected")
            // something to do in case of successful connection
        }
        else {
            // error handling for connection failure
        }
    }
    
            mqttConfig.onMessageCallback = { mqttMessage in
                if mqttMessage.topic == "topic" {
                    NSLog("MQTT Message received: payload=\(mqttMessage.payloadString)")
                } else  {
                    // something to do in case of other topics
                }
            }
    
    let mqttClient = MQTT.newConnection(mqttConfig)
   
    mqttClient.connectTo(host: "aws.amazonaws.com", port: 7926, keepAlive: 60)
            let deadlineTime = DispatchTime.now() + .seconds(20)
            DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: {
               mqttClient.subscribe("topic", qos: 2, requestCompletion: nil)
            })**

Im geting connection keep disconnecting can please help me with this issue.

Thanks,

Can not receive messages

var mqttClient: MQTTClient? = nil
let mqttConfig = MQTTConfig(clientId: "Sasa", host: "192.168.0.11", port: 1883, keepAlive: 60)
override func viewDidLoad() {
super.viewDidLoad()
mqttClient = MQTT.newConnection(mqttConfig)

    print( "\(mqttClient?.isConnected)")
    mqttClient?.subscribe("ios/test", qos: 0)
    DispatchQueue.main.async {
        self.mqttConfig.onMessageCallback = { msg in
            print("asdasda \(msg.payloadString!)")
            sleep(1)
        
        }
        self.mqttConfig.onConnectCallback = { rtrn in
            print(rtrn)
        }
    }

}

it does not go in onMessageCallback...

Please fix warnings when using in iOS 9.2

I am seeing 400+ warnings when using this with Xcode 7.2 and iOS 9.2,
"/Pods/Moscapsule/mosquitto/lib/logging_mosq.c:36:21: Implicit conversion loses integer precision: 'unsigned long' to 'int'"

  • /Pods/Moscapsule/mosquitto/lib/net_mosq.c:664:34: Implicit conversion loses integer precision: 'size_t' (aka 'unsigned long') to 'int'
    (null): Object file (/Pods/OpenSSL-Universal/lib-ios/libcrypto.a(asn1_lib.o)) was built for newer iOS version (9.2) than being linked (8.0)

Carthage support

Please consider Carthage support for easy implementation.

Keep up the good work.

Definition of Queue Name

Hello, so I realize if i set the client Id to a certain value, it is used within the queue name on the broker such as

Queue mqtt-subscription-{name here}qos1

Where does this get set within the code? Id like to be able to define my own queue names.

Autoreconnect stall

Autoreconnect stops when I

  1. enable airplane mode
  2. onDisconnectCallback (KeepAlive_Timeout)
  3. onDisconnectCallback (Disconnect_Requested)
  4. disable airplane mode

Or sometimes it just stops after disconnection with MOSQ_ERRNO.

Then I set mqttReconnOpts=nil and call reconnect() in onDisConnectCallback,
but connection is never made after Disconnect_Requested, so I changed it to disconnect() and reconnect(), this is power consumptive so I changed it to trigger disconnect()/reconnect() with a watchdog timer instead of in onDisConnectCallback. This works in most of time but once or twice a day, I get infinite Disconnect_Requested.

Finally, renew MQTTClient instance in onDisConnectCallback and watchdog timer emulate reconnection, but the session is of course lost.

I'm using
pod 'Moscapsule', :git => 'https://github.com/flightonary/Moscapsule.git'
pod 'OpenSSL-Universal', '~> 1.0.1.18'
on iOS 10.

Any suggestion?

Publish Podspec

Why isn't the podspec for this product officially published in the Cocoapods Trunk?

Reconnection delay

Hi, I have a question regarding auto reconnection. What if I don't need this feature? I tried to set new MQTTReconnOpts instance with max parameters, but this struct doesn't contain initializers.

So, how I can change reconnection settings?

Compiler Error: 'openssl/ssl.h' file not found

Running Xcode 8.2.1 and getting following compiler error:
IOS/MyApp/Moscapsule/mosquitto/lib/mosquitto_internal.h:27:12: 'openssl/ssl.h' file not found when I try to build the Mocapsule error

Any ideas why? I don't see the file ssl.h.

Swift3

If you can create a swift3 branch, I can pr

git submodule for openssl not working

I've tried to init and update the git submodule but unfortunately the console says:

Please make sure you have the correct access rights
and the repository exists.
Clone of '[email protected]:krzyzanowskim/OpenSSL.git' into submodule path 'submodules/OpenSSL' failed

My fault. Problems with SSH Key.

Open SSL.h not found Error

We have install the pod successfully as shown in document part. But it always give the error that open ssl.h file not found.So i would request you to please resolve the issue .

Problems with pthread_join

I'm actively using this library and I often use "disconnect" and "connect" and creating new instances of moscapsule. Very often I get zombie thread, because of pthread_join has UB and thread freezes. How can I debug and fix this problem?
For reproducing don't need to make any special things, just connect to broker, send disconnect, create another one moscapsule entity, repeat steps and so on.
screen shot 2017-01-20 at 4 16 15 pm

Receive string message

Good evening,

For the needs of my application, I would need to receive messages in the format string, only I do not find how to retrieve a message after a subscribe, could someone explain to me how to do?

I thank you in advance.

cordially

Iphone 6 usege

Moscapsule library use OpenSSL. I look this library and library page says

Architectures

iOS with architectures: armv7, armv7s, arm64 + simulator (i386, x86_64)
OSX with architectures: i386, x86_64

Iphone 6 and other some iphone models use Apple A8 processor and this processor architecture is ARMv8-A. So when i use Moscapsule i have any problem about iphone models ?

Username/Password

Hello,

Is there any possibility to use this library with username password login?

Thanks,
Markus

ipv6 network

this library doesn't work with tls connection through ipv6 network.

it happens because this library has the next code:

/*#ifdef WITH_TLS
    if(mosq->tls_cafile || mosq->tls_capath || mosq->tls_psk){
        hints.ai_family = PF_INET;
    }else
#endif
    {
        hints.ai_family = PF_UNSPEC;
    }

But PF_INET allows ipv4 only, can we use PF_UNSPEC for all connections? Because PF_UNSPEC allows both ipv4 and ipv6.

Currently, if you want to use tls connection in ipv6 only network, then getaddrinfo will return error. But if you change ai_family to PF_INET6, PF_UNSPEC or you will not setup it, then connection will work properly.

P.S. you will get reject from apple team if you use this library for connections with tls until this issue solved

Swift 2.0 - Xcode 7 support

There are some issues about unavailable methods. Specificially:
"'advance' is unavailable: call the 'advancedBy(n)' method on the index"
in the Moscapsule.swift file

Use this library to connect with AWS IoT broker

Hello everyone,

We are developing an application which needs to consume AWS IoT service based on a MQTT protocol deviation. We are currently facing issues to get connected with MQTT broker provided by AWS IoT cloud server.

Following is the environment:

  1. iOS Version: 8.0 / 9.0
  2. Programming language: Swift
  3. Library for MQTT: Moscapsule

Steps followed:
1.Set initial config clientid, host, port
2.Set client certificate with private key, providing .pem file path (e.g. cert.pem, privateKey.pem)
3.Set server certificate which is root certificate .pem file path (e.g. rootCA.pem)
4.Set tls opts with tsl_insecure: false, cert_reqs: SSL_VERIFY_PEER, tls version: tlsv1.2, ciphers: nil

Problems faced:
1.When trying to connect to server/broker gives error “unable to create TLS_Context”.
2.With setting tls cert_reqs: SSL_VERIFY_NONE, gives connection status success with subcribe and publish sucess, but doesn’t reflect on server or broker.

Any help in this context is highly appreciable.

Thanks in advance.

how to receive message from broker?

Hi, I have simple code with example from README.
I try to get any message from broker after subscribe, when I click on button. But instead of receive any data I have subscribe and DISCONNECT, could you please help with this issue ?
Bellow code from xCode and console log after button click

 import UIKit
 import Moscapsule

    @IBAction func goButtonPresed(sender: AnyObject) {
           self.sendMQTT()
      }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func sendMQTT ()  {
         let topic = "dallas/led"
         let message = "1"

        // set MQTT Client Configuration
        let mqttConfig = MQTTConfig(clientId: "esp2", host: "m12.cloudmqtt.com", port: 10661, keepAlive: 60)
        mqttConfig.mqttAuthOpts = MQTTAuthOpts(username: "USERNAME", password: "PASSWORD")

        mqttConfig.onPublishCallback = { messageId in
            NSLog("published (mid=\(messageId))")
        }
        mqttConfig.onMessageCallback = { mqttMessage in
            NSLog("MQTT Message received: payload=\(mqttMessage.payloadString!)")
        }

        // create new MQTT Connection
        let mqttClient = MQTT.newConnection(mqttConfig)

        // publish and subscribe
        mqttClient.publishString(message, topic: topic, qos: 1, retain: true)
        mqttClient.subscribe("dallas/temp", qos: 1)
    }
    }


and below console log after button click:

2016-05-07 00:42:01.359 mqtt2[58997:1526453] [MOSQUITTO] DEBUG Client esp2 sending CONNECT
2016-05-07 00:42:01.360 mqtt2[58997:1526453] [MOSQUITTO] DEBUG Client esp2 sending PUBLISH (d0, q1, r1, m1, 'dallas/led', ... (1 bytes))
2016-05-07 00:42:01.360 mqtt2[58997:1526453] [MOSQUITTO] DEBUG Client esp2 sending SUBSCRIBE (Mid: 2, Topic: dallas/temp, QoS: 1)
2016-05-07 00:42:01.361 mqtt2[58997:1526453] [MOSQUITTO] DEBUG Client esp2 sending DISCONNECT

As I understand disconnect was called after deinit(), but how I can setup stable connect via button click without self disconnect and receive massage from broker until I will call disconnect() func via click on another button for example ?

A lot of thanks for any help.

About onMessageCallback

I want subscribe some message by mqtt
but the program didn’t do this block

mqttConfig.onMessageCallback = { mqttMessage in
// write received message to log
NSLog("MQTT Message received: payload=(mqttMessage.payloadString)")
}

until I add dispatch_main() after mqttClient.publishString , it can work.
But it let the program only do onMessageCallback , how to stop it?
——————————————————————————
If I didn’t add dispatch_main()
the message is show above

2016-04-13 09:23:07.381 myprogram[26583:2388414] [MOSQUITTO] DEBUG Client cid sending CONNECT
false
2016-04-13 09:23:07.382 myprogram[26583:2388414] [MOSQUITTO] DEBUG Client cid sending SUBSCRIBE (Mid: 1, Topic: #, QoS: 0)
2016-04-13 09:23:07.382 myprogram[26583:2388414] [MOSQUITTO] DEBUG Client cid sending PUBLISH (d0, q0, r1, m2, 'topic123', ... (7 bytes))
2016-04-13 09:23:07.382 myprogram[26583:2388414] [MOSQUITTO] DEBUG Client cid sending DISCONNECT

It didn’t print any callback message.
What is the problem?
ps. I didn't write mqttClient.disconnect() in my code.

Does it have any example?
ps. sorry for my poor English, if you have any question, please tell me, thanks!

The question is similar to this website http://social.gseosem.com/stackoverflow/how-to-create-a-persistent-mqtt-connection-to-mosquitto-with-moscapsule/

How do I subscribe to wildcard topics?

I've successfully established the connection and I can simulate a chat sending messages back and forth on a specific topic (e.g. chat/room/1) between my iOS Simulator and Web Service.

However, I now want my iOS to subscribe using a wild card to chat/room/*, but it doesn't work as a wild card.

My code:

mqttClient.subscribe("chat/room/*", qos: 2)

To be clear, after my iOS Simulator subscribed to chat/room/*:

  • I CANNOT receive messages that are published to chat/room/1 or chat/room/2
  • but I CAN receive messages that are published explicitly to chat/room/*

Moscapsule-Swift.h not found

'Moscapsule-Swift.h' this file is not found. I'm running on lastest xcode, and also there are 14 issues in the framework, does it matter to the project running?

XCode check: integer overflow while running for iOS 9.3 (iPad2)

File: mosquitto.c
Row: 73

Message:
Signed integer overflow: 1521456818 * 1000 cannot be represented in type 'long'

Code:
srand((unsigned int)(tv.tv_sec*1000 + tv.tv_usec/1000));

Xcode pause execution on every start if running on iPad2 device or simulator (iOS 9.3).
No warnings if running on 64bit device or simulator.

Not able to Publish with CA Server Certificate

I have a CA server certificate, using the same certificate i am able to PUBLISH the message in android using paho lib, I am not able to receive the message PUBLISHED by my iOS app using the moscapsule lib. the log shows "mosq_success", but i am not able to receive the message on the other end. The code is below -

`
func initMQTTByMoscapsule() -> Void {

    mosquitto_lib_cleanup()
    
    moscapsule_init()
    
    let mqttConfig = MQTTConfig(clientId: clientID + String(ProcessInfo().processIdentifier), host: host, port: 8883, keepAlive: 60)

    let mqttAuth = MQTTAuthOpts.init(username: userName, password: password)
    mqttConfig.mqttAuthOpts = mqttAuth
    
    let resourcePath = Bundle.main.url(forResource: "authoritycert", withExtension: "crt");
    mqttConfig.mqttServerCert = MQTTServerCert(cafile: nil, capath: resourcePath?.absoluteString)
    
    let mqttClient1 = MQTT.newConnection(mqttConfig)
    
    
    mqttClient1.connectTo(host: host, port: 8883, keepAlive: 60) { (MosqResult) in
    print("\n\n\n Return Code is \(MosqResult)")
                
    if mqttClient1.isConnected {
        print("\n\n\n Dude its is connected \n\n")
    }
                
    mqttClient1.publish(string: "test-blind-10", topic: topicToSub, qos: 0, retain: false, requestCompletion: { (resultMessage, resultcode) in
                    print("\n\n\n The PUBLISH result - \(resultMessage) \n\n")
        })
    }
    
    mqttConfig.onPublishCallback = { messageID in
        print("\n\n\n Return Code is \(messageID.description) on publish")
    }
    //mqttClient.subscribe("subscribe/topic", qos: 2)
    
    mqttConfig.onConnectCallback = { returnCode in
        print("\n\n\n Return Code is \(returnCode.description) (on Connect)")
    }
    
    `

and the resulting log is below

`[38695:1102928] [MOSQUITTO] DEBUG Client Smart***&Client38695 sending CONNECT
2018-10-24 10:27:34.845393+0530 CC[38695:1104304] [MOSQUITTO] DEBUG Client Smart***&Client38695 sending CONNECT

Return Code is mosq_success

2018-10-24 10:27:36.975967+0530 CC[38695:1102928] [MOSQUITTO] DEBUG Client Smart***&Client38695 sending PUBLISH (d0, q0, r0, m1, 'a**&-r**&-topic', ... (13 bytes))

The PUBLISH result - mosq_success

2018-10-24 10:27:38.375126+0530 CC[38695:1104304] [MOSQUITTO] DEBUG Client Smart***&Client38695 sending DISCONNECT`

still i am not receiving the message in the other end.

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.