Skip to content

Commit

Permalink
Swift 3.0 Support (#8)
Browse files Browse the repository at this point in the history
* Swift 3.0 Migration
* Update README documentation
* Refactor and update public interfaces
* Bump major version and update podspec
  • Loading branch information
Adolfo Martinelli committed Sep 16, 2016
1 parent 9ca83d4 commit 51973d4
Show file tree
Hide file tree
Showing 27 changed files with 529 additions and 566 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
language: objective-c
osx_image: xcode7.3
osx_image: xcode8
before_install:
- brew update
- brew install mosquitto
script:
- /usr/local/opt/mosquitto/sbin/mosquitto -d
- xcodebuild -project SwiftMQTT/SwiftMQTT.xcodeproj -scheme SwiftMQTT -sdk iphonesimulator test
- xcodebuild -project SwiftMQTT/SwiftMQTT.xcodeproj -scheme SwiftMQTT -sdk iphonesimulator -destination "name=iPhone 6s" test
48 changes: 25 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
# SwiftMQTT
MQTT Client in pure swift ❤️

Master:
MQTT Client in pure Swift ❤️️

[![Build Status](https://travis-ci.org/aciidb0mb3r/SwiftMQTT.svg)](https://travis-ci.org/aciidb0mb3r/SwiftMQTT)
[![Version](https://img.shields.io/cocoapods/v/SwiftMQTT.svg?style=flat)](http://cocoapods.org/pods/SwiftMQTT)
[![License](https://img.shields.io/cocoapods/l/SwiftMQTT.svg?style=flat)](http://cocoapods.org/pods/SwiftMQTT)

# Info
* Fully written in swift from ground up
* Closures everywhere :D
## Info
* Fully written in Swift from ground up
* Closures everywhere 😃
* Includes test cases and sample project
* Based on MQTT Version 3.1.1 (http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718043)

![Sample Project Screenshot](http://i.imgur.com/9lefVmVl.png)

# How to use
## How to use

## Create MQTTSession object:
### Create Session
```swift
mqttSession = MQTTSession(host: "localhost", port: 1883, clientID: "swift", cleanSession: true, keepAlive: 15, useSSL: false)
```

## Connect
### Connect
```swift
mqttSession.connect { (succeeded, error) -> Void in
if succeeded {
Expand All @@ -28,49 +30,49 @@ mqttSession.connect { (succeeded, error) -> Void in
}
```

## Subscribe
### Subscribe
```swift
mqttSession.subscribe("/hey/cool", qos: MQTTQoS.AtLeastOnce) { (succeeded, error) -> Void in
mqttSession.subscribe(to: "/hey/cool", delivering: .atLeastOnce) { (succeeded, error) -> Void in
if succeeded {
print("Subscribed!")
}
}
```

## Unsubscribe
### Unsubscribe
```swift
mqttSession.unSubscribe(["/ok/cool", "/no/ok"]) { (succeeded, error) -> Void in
mqttSession.unSubscribe(from: ["/ok/cool", "/no/ok"]) { (succeeded, error) -> Void in
if succeeded {
print("unSubscribed!")
}
}
```
## Publish

### Publish
```swift
let jsonDict = ["hey" : "sup"]
let data = try! NSJSONSerialization.dataWithJSONObject(jsonDict, options: NSJSONWritingOptions.PrettyPrinted)
let data = try! JSONSerialization.data(withJSONObject: jsonDict, options: .prettyPrinted)

mqttSession.publishData(data, onTopic: "/hey/wassap", withQoS: MQTTQoS.AtLeastOnce, shouldRetain: false) { (succeeded, error) -> Void in
mqttSession.publish(data, in: "/hey/wassap", delivering: .atLeastOnce, retain: false) { (succeeded, error) -> Void in
if succeeded {
print("Published!")
}
}
```

## Conform to `MQTTSessionDelegate` to receive messages
```
### Conform to `MQTTSessionDelegate` to receive messages
```swift
mqttSession.delegate = self
```
```swift
func mqttSession(session: MQTTSession, didReceiveMessage message: NSData, onTopic topic: String) {
let stringData = NSString(data: message, encoding: NSUTF8StringEncoding) as! String
print("data received on topic \(topic) message \(stringData)")
func mqttSession(session: MQTTSession, received message: Data, in topic: String) {
let string = String(data: message, encoding: .utf8)!
}
```

# Installation
## Installation

## CocoaPods
### CocoaPods

Install using [CocoaPods](http://cocoapods.org) by adding the following lines to your Podfile:

Expand All @@ -79,5 +81,5 @@ use_frameworks!
pod 'SwiftMQTT'
````

# License
## License
MIT
6 changes: 3 additions & 3 deletions SwiftMQTT.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
Pod::Spec.new do |s|

s.name = "SwiftMQTT"
s.version = "1.0.2"
s.summary = "MQTT Client in pure swift"
s.version = "2.0.0"
s.summary = "MQTT Client in pure Swift"
s.description = <<-DESC
MQTT Client in pure swift
MQTT Client in Swift 3.0 based on MQTT Version 3.1.1
DESC

s.homepage = "https://github.com/aciidb0mb3r/SwiftMQTT"
Expand Down
15 changes: 12 additions & 3 deletions SwiftMQTT/SwiftMQTT.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@
5471A8971BF228900079610F /* Products */,
);
sourceTree = "<group>";
usesTabs = 0;
};
5471A8971BF228900079610F /* Products */ = {
isa = PBXGroup;
Expand Down Expand Up @@ -202,11 +203,12 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0710;
LastUpgradeCheck = 0710;
LastUpgradeCheck = 0800;
ORGANIZATIONNAME = Ankit;
TargetAttributes = {
5471A8951BF228900079610F = {
CreatedOnToolsVersion = 7.1;
LastSwiftMigration = 0800;
};
5471A89F1BF228900079610F = {
CreatedOnToolsVersion = 7.1;
Expand Down Expand Up @@ -305,11 +307,12 @@
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = dwarf;
Expand Down Expand Up @@ -353,11 +356,12 @@
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
Expand All @@ -374,6 +378,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 9.1;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
Expand All @@ -397,6 +402,7 @@
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
};
name = Debug;
};
Expand All @@ -415,6 +421,7 @@
PRODUCT_BUNDLE_IDENTIFIER = im.ankit.SwiftMQTT;
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_VERSION = 3.0;
};
name = Release;
};
Expand All @@ -425,6 +432,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = im.ankit.SwiftMQTTTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 3.0;
};
name = Debug;
};
Expand All @@ -435,6 +443,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = im.ankit.SwiftMQTTTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 3.0;
};
name = Release;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0710"
LastUpgradeVersion = "0800"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
Expand Down
97 changes: 48 additions & 49 deletions SwiftMQTT/SwiftMQTT/MQTTExtensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,79 +8,78 @@

import Foundation

enum MQTTSessionError: ErrorType {
case None
case SocketError
enum MQTTSessionError: Error {
case none
case socketError
}

enum MQTTPacketType: UInt8 {
case Connect = 0x01
case Connack = 0x02
case Publish = 0x03
case PubAck = 0x04
case PubRec = 0x05
case PubRel = 0x06
case PubComp = 0x07
case Subscribe = 0x08
case SubAck = 0x09
case UnSubscribe = 0x0A
case UnSubAck = 0x0B
case PingReq = 0x0C
case PingResp = 0x0D
case Disconnect = 0x0E

case connect = 0x01
case connAck = 0x02
case publish = 0x03
case pubAck = 0x04
case pubRec = 0x05
case pubRel = 0x06
case pubComp = 0x07
case subscribe = 0x08
case subAck = 0x09
case unSubscribe = 0x0A
case unSubAck = 0x0B
case pingReq = 0x0C
case pingResp = 0x0D
case disconnect = 0x0E
}

public enum MQTTQoS: UInt8 {
case AtMostOnce = 0x0
case AtLeastOnce = 0x01
case ExactlyOnce = 0x02
case atMostOnce = 0x0
case atLeastOnce = 0x01
case exactlyOnce = 0x02
}

enum MQTTConnackResponse: UInt8, ErrorType {
case ConnectionAccepted = 0x00
case BadProtocol = 0x01
case ClientIDRejected = 0x02
case ServerUnavailable = 0x03
case BadUsernameOrPassword = 0x04
case NotAuthorized = 0x05
enum MQTTConnAckResponse: UInt8, Error {
case connectionAccepted = 0x00
case badProtocol = 0x01
case clientIDRejected = 0x02
case serverUnavailable = 0x03
case badUsernameOrPassword = 0x04
case notAuthorized = 0x05
}

extension NSMutableData {
extension Data {

func mqtt_encodeRemainingLength(length: Int) {
mutating func mqtt_encodeRemaining(length: Int) {
var lengthOfRemainingData = length
repeat {
var digit = UInt8(lengthOfRemainingData % 128);
lengthOfRemainingData /= 128;
if (lengthOfRemainingData > 0) {
digit |= 0x80;
var digit = UInt8(lengthOfRemainingData % 128)
lengthOfRemainingData /= 128
if lengthOfRemainingData > 0 {
digit |= 0x80
}
self.appendBytes(&digit, length: 1)
} while (lengthOfRemainingData > 0);
append(&digit, count: 1)
} while lengthOfRemainingData > 0
}

func mqtt_appendUInt8(data: UInt8) {
mutating func mqtt_append(_ data: UInt8) {
var varData = data
self.appendBytes(&varData, length: 1)
append(&varData, count: 1)
}

///Appends two bytes
///Big Endian
func mqtt_appendUInt16(data: UInt16) {
// Appends two bytes
// Big Endian
mutating func mqtt_append(_ data: UInt16) {
let byteOne = UInt8(data / 256)
let byteTwo = UInt8(data % 256)
self.mqtt_appendUInt8(byteOne)
self.mqtt_appendUInt8(byteTwo)
mqtt_append(byteOne)
mqtt_append(byteTwo)
}

func mqtt_appendData(data: NSData) {
self.mqtt_appendUInt16(UInt16(data.length))
self.appendData(data)
mutating func mqtt_append(_ data: Data) {
mqtt_append(UInt16(data.count))
append(data)
}

func mqtt_appendString(string: String) {
self.mqtt_appendUInt16(UInt16(string.characters.count))
self.appendData(string.dataUsingEncoding(NSUTF8StringEncoding)!)
mutating func mqtt_append(_ string: String) {
mqtt_append(UInt16(string.characters.count))
append(string.data(using: .utf8)!)
}
}
Loading

0 comments on commit 51973d4

Please sign in to comment.