2016年3月22日 星期二

一個好用的iOS BLE開源第三方framework

https://github.com/HarveyHu/BLEHelper

BLEHelper

一個可以優雅支援一對多BLE裝置(Bluetooth Low Energy)操作的開源框架。(swift 2.2)

安裝(Installation)

CocoaPods

如下設定你的Podfile:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'BLEHelper', '~> 1.0'
設定好後就執行這個指令:
$ pod install

Carthage

使用Carthage安裝,把下面這行加入你的Cartfile中:
github "HarveyHu/BLEHelper" ~> 1.0.0
設定好後就執行這個指令:
$ carthage update --platform iOS
Xcode的設定請參考Carthage的官方網頁。

用法(Usage)

先在你的檔案導入BLEHelper框架:
import BLEHelper
然後把它作為一個已經初始化的property:
let bleHelper = BLECentralHelper()

掃瞄(Scan)

掃瞄附近的BLE裝置:
bleHelper.scan(1.0, serviceUUID: nil) { (devices) -> (Void) in
            //TODO: show your devices
        }

Connect

用已存在的device物件來連線:
bleHelper.connect(yourPeripheral) { (peripheral, error) -> (Void) in
            //TODO: do something when connected
        }
用 deviceUUID (peripheral.identifier) 的陣列 來一次連線多顆裝置:
self.bleHelper.retrieve(deviceUUIDs: [deviceUUIDString], completion: {(peripheral, error) -> (Void) in
            if error != nil {
                prettyLog("error: \(error?.description)")
                completion?(success: false)
                return
            }
            prettyLog("connect with \(peripheral)")
        })

操作(Operation)

讀取(read):
bleHelper.readValue("yourDeviceUUID", serviceUUID: "yourServiceUUID", characteristicUUID: "youCharacteristicUUID") { (success) -> (Void) in
            prettyLog("is read success: \(success)")
    }
設定是否開啟通知(enable notification):
bleHelper.enableNotification(true, deviceUUID: "yourDeviceUUID", serviceUUID: "yourServiceUUID", characteristicUUID: "youCharacteristicUUID") { (success) -> (Void) in
        prettyLog("set notify success: \(success)")
    }
寫入(write):
let command = "yourCommand"
if let data = command.dataUsingEncoding(NSUTF8StringEncoding) {
        bleHelper.writeValue(data, deviceUUID: "yourDeviceUUID", serviceUUID: "yourServiceUUID", characteristicUUID: "youCharacteristicUUID", withResponse: true) { (success) -> (Void) in
            prettyLog("is write success: \(success)")
        }
    }

委派(Delegate)

首先要先在你的Class開頭宣告符合BLECentralHelperDelegate。
這個委派包含兩個Callback方法:
一個是在裝置斷線時callback:
func bleDidDisconnectFromPeripheral(peripheral: CBPeripheral) {
    //TODO: do something...
}
另一個是用來接收裝置所回傳的資料:
func bleCentralDidReceiveData(data: NSData?, peripheral: CBPeripheral, characteristic: CBCharacteristic) {
    //TODO: do something...
}

範例(Example)

用Xcode打開 BLEHelper.xcworkspace , 把 Scheme 設為 "BLEHelperExample." 後就可以在你的iPhone或iPad上面執行啦!

License

MIT License

沒有留言:

張貼留言