Coder Social home page Coder Social logo

systembugtj / moscapsule Goto Github PK

View Code? Open in Web Editor NEW

This project forked from flightonary/moscapsule

0.0 1.0 0.0 263 KB

MQTT Client for iOS written in Swift

License: MIT License

Ruby 0.46% Objective-C 4.35% Swift 12.21% C 82.75% Shell 0.12% C++ 0.10%

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'

  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 returnCode == 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

Contributors

bjpetit avatar chrome-cgi avatar flightonary avatar hankbao avatar hvsw avatar iyuna avatar nickdomenicali avatar risalba avatar tefshuo avatar zzzkino avatar

Watchers

 avatar

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.