藍牙協版本體走過了 1.0 到 4.0 的演進。最新的 4.0 主打低功耗,因此一般也稱之為 BLE(Bluetooth Low Energy)。
iOS 上有兩個框架可以處理藍牙外設連線。一個是 External Accessory,從 iOS 3.0 就開始支援,在 iPhone 4S 問世之前是主流做法,但它的門檻在於——需要取得 Apple 的 MFi 認證。
另一個是本文主角 CoreBluetooth,從 iPhone 4S 起支援,專門用於與 BLE 裝置通訊(它的 API 本身就是依 BLE 設計的)。它不需要 MFi,加上現今多數藍牙裝置都支援 4.0,因此是目前 iOS 上比較推薦的開發方式。
CoreBluetooth 的核心概念其實就兩個:peripheral(外設)與 central(中心)。對應各自有一組 API 與類別。
你要開發的裝置扮演哪個角色,就用哪一組 API。本文的案例中,金融刷卡器是 peripheral,iPhone 是 central,所以主要使用 central 這組類別。反過來,如果你想用手機模擬一個外設(例如讓 iPad 與 iPhone 互通,iPad 當 central、iPhone 當 peripheral),那就得在 iPhone 端改用 peripheral 那組類別來開發。
有個概念必須先講清楚:什麼是服務與特徵?
每一個藍牙 4.0 裝置都是透過「服務」與「特徵」來暴露自己的。一個裝置必然包含一個或多個服務,每個服務底下又包含若干特徵,而特徵才是與外界互動的最小單位。舉例來說,某個 BLE 裝置可能用特徵 A 描述自己的出廠資訊,用特徵 B 來收發資料。
服務與特徵都以 UUID 唯一標識。國際藍牙組織為一些典型裝置(例如心跳、血壓測量裝置)制定了標準的 service UUID:
#define BLE_UUID_ALERT_NOTIFICATION_SERVICE 0x1811
#define BLE_UUID_BATTERY_SERVICE 0x180F
#define BLE_UUID_BLOOD_PRESSURE_SERVICE 0x1810
#define BLE_UUID_CURRENT_TIME_SERVICE 0x1805
#define BLE_UUID_CYCLING_SPEED_AND_CADENCE 0x1816
#define BLE_UUID_DEVICE_INFORMATION_SERVICE 0x180A
#define BLE_UUID_GLUCOSE_SERVICE 0x1808
#define BLE_UUID_HEALTH_THERMOMETER_SERVICE 0x1809
#define BLE_UUID_HEART_RATE_SERVICE 0x180D
#define BLE_UUID_HUMAN_INTERFACE_DEVICE_SERVICE 0x1812
#define BLE_UUID_IMMEDIATE_ALERT_SERVICE 0x1802
#define BLE_UUID_LINK_LOSS_SERVICE 0x1803
#define BLE_UUID_NEXT_DST_CHANGE_SERVICE 0x1807
#define BLE_UUID_PHONE_ALERT_STATUS_SERVICE 0x180E
#define BLE_UUID_REFERENCE_TIME_UPDATE_SERVICE 0x1806
#define BLE_UUID_RUNNING_SPEED_AND_CADENCE 0x1814
#define BLE_UUID_SCAN_PARAMETERS_SERVICE 0x1813
#define BLE_UUID_TX_POWER_SERVICE 0x1804
#define BLE_UUID_CGM_SERVICE 0x181A
當然,市面上大量裝置並不在這個標準清單裡,本文使用的金融刷卡器就是一例。這種情況下,硬體廠商通常會提供文件,說明裝置內各服務與特徵的功能:哪些可讀寫、哪些唯讀、哪些用來取模組資訊等等。
作為一個 central,要完成完整通訊,大致得走過這幾步:
建立中心角色 → 掃描外設(discover)→ 連線外設(connect)→ 掃描服務與特徵(discover)→ 資料互動(explore and interact)→ 斷線(disconnect)。
首先在自己的類別標頭檔引入 CoreBluetooth,並實作兩個 delegate 協定 <CBCentralManagerDelegate, CBPeripheralDelegate>:
#import <CoreBluetooth/CoreBluetooth.h>
CBCentralManager *manager;
manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
[manager scanForPeripheralsWithServices:nil options:options];
這個方法的第一個參數可以指定特定 peripheral 的 UUID 清單,理論上 central 只會回報符合的裝置。但我實測時發現,傳入特定 UUID 反而掃不到任何裝置:
NSArray *uuidArray = [NSArray arrayWithObjects:
[CBUUID UUIDWithString:@"1800"],
[CBUUID UUIDWithString:@"180A"],
[CBUUID UUIDWithString:@"1CB2D155-33A0-EC21-6011-CD4B50710777"],
[CBUUID UUIDWithString:@"6765D311-DD4C-9C14-74E1-A431BBFD0652"], nil];
[manager scanForPeripheralsWithServices:uuidArray options:options];
目前還不清楚原因,懷疑與裝置本身的廣播包(advertisement packet)內容有關。
掃到 4.0 裝置後,系統會透過回呼函式把裝置資訊交給我們,接著就能發起連線:
- (void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI {
if (![_dicoveredPeripherals containsObject:peripheral])
[_dicoveredPeripherals addObject:peripheral];
NSLog(@"dicoveredPeripherals:%@", _dicoveredPeripherals);
}
// 連線指定裝置
- (BOOL)connect:(CBPeripheral *)peripheral {
NSLog(@"connect start");
_testPeripheral = nil;
[manager connectPeripheral:peripheral
options:[NSDictionary dictionaryWithObject:
[NSNumber numberWithBool:YES]
forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
// 用計時器監控連線逾時
connectTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f
target:self
selector:@selector(connectTimeout:)
userInfo:peripheral
repeats:NO];
return YES;
}
連線成功後系統同樣會回呼通知,我們就在這個回呼裡去掃描裝置下所有服務與特徵:
- (void)centralManager:(CBCentralManager *)central
didConnectPeripheral:(CBPeripheral *)peripheral {
[connectTimer invalidate]; // 停止計時器
NSLog(@"Did connect to peripheral: %@", peripheral);
_testPeripheral = peripheral;
[peripheral setDelegate:self];
[peripheral discoverServices:nil];
}
一個裝置裡的服務與特徵往往很多,實務上我們通常只關心其中幾個,所以會在回呼中做比對篩選:
- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverServices:(NSError *)error {
NSLog(@"didDiscoverServices");
if (error) {
NSLog(@"Discovered services for %@ with error: %@",
peripheral.name, [error localizedDescription]);
if ([self.delegate respondsToSelector:
@selector(DidNotifyFailConnectService:withPeripheral:error:)])
[self.delegate DidNotifyFailConnectService:nil
withPeripheral:nil error:nil];
return;
}
for (CBService *service in peripheral.services) {
if ([service.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_PROPRIETARY_SERVICE]]) {
NSLog(@"Service found with UUID: %@", service.UUID);
[peripheral discoverCharacteristics:nil forService:service];
isVPOS3356 = YES;
break;
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverCharacteristicsForService:(CBService *)service
error:(NSError *)error {
if (error) {
NSLog(@"Discovered characteristics for %@ with error: %@",
service.UUID, [error localizedDescription]);
if ([self.delegate respondsToSelector:
@selector(DidNotifyFailConnectChar:withPeripheral:error:)])
[self.delegate DidNotifyFailConnectChar:nil withPeripheral:nil error:nil];
return;
}
// 找出可讀的特徵
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_TX]]) {
NSLog(@"Discovered read characteristics:%@ for service: %@",
characteristic.UUID, service.UUID);
_readCharacteristic = characteristic;
if ([self.delegate respondsToSelector:@selector(DidFoundReadChar:)])
[self.delegate DidFoundReadChar:characteristic];
break;
}
}
// 找出可寫的特徵
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_RX]]) {
NSLog(@"Discovered write characteristics:%@ for service: %@",
characteristic.UUID, service.UUID);
_writeCharacteristic = characteristic;
if ([self.delegate respondsToSelector:@selector(DidFoundWriteChar:)])
[self.delegate DidFoundWriteChar:characteristic];
break;
}
}
if ([self.delegate respondsToSelector:
@selector(DidFoundCharacteristic:withPeripheral:error:)])
[self.delegate DidFoundCharacteristic:nil withPeripheral:nil error:nil];
}
送出資料很簡單,封裝成一個函式即可:
// 寫資料
- (void)writeChar:(NSData *)data {
[_testPeripheral writeValue:data
forCharacteristic:_writeCharacteristic
type:CBCharacteristicWriteWithResponse];
}
其中 _testPeripheral 與 _writeCharacteristic 就是前面保存下來的裝置物件與可寫特徵。使用時先組好封包再呼叫,例如觸發刷卡:
- (void)msrRead {
unsigned char command[512] = {0};
unsigned char *pTmp;
int nSendLen = 0;
unsigned char ucCrc[3] = {0};
_commandType = COMMAND_MSR_READ;
pTmp = command;
*pTmp = 0x02; // start
pTmp++;
*pTmp = 0xc1; // main cmd
pTmp++;
*pTmp = 0x07; // sub cmd
pTmp++;
nSendLen = 2;
*pTmp = nSendLen / 256;
pTmp++;
*pTmp = nSendLen % 256;
pTmp++;
*pTmp = 0x00;
pTmp++;
*pTmp = 0x00;
pTmp++;
Crc16CCITT(command + 1, pTmp - command - 1, ucCrc);
memcpy(pTmp, ucCrc, 2);
NSData *data = [[NSData alloc] initWithBytes:&command length:9];
NSLog(@"send data:%@", data);
[g_BLEInstance.recvData setLength:0];
[g_BLEInstance writeChar:data];
}
接收資料這邊要留意特徵的 properties。例如本例中要互動的特徵 properties 值為 0x10,代表只能用訂閱方式收資料,於是啟動訂閱:
// 監聽裝置
- (void)startSubscribe {
[_testPeripheral setNotifyValue:YES forCharacteristic:_readCharacteristic];
}
裝置有資料回傳時,同樣透過系統回呼通知我們。這裡要注意 BLE 單次傳輸的封包長度有限,實務上要做緩衝與組包判斷:
- (void)peripheral:(CBPeripheral *)peripheral
didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic
error:(NSError *)error {
if (error) {
NSLog(@"Error updating value for characteristic %@ error: %@",
characteristic.UUID, [error localizedDescription]);
if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadError:)])
[_mainMenuDelegate DidNotifyReadError:error];
return;
}
[_recvData appendData:characteristic.value];
if ([_recvData length] >= 5) { // 已收到標頭
unsigned char *buffer = (unsigned char *)[_recvData bytes];
int nLen = buffer[3] * 256 + buffer[4];
// 完整封包長度 = 標頭 3 + 資料 nLen + 其他欄位
if ([_recvData length] == (nLen + 3 + 2 + 2)) {
if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadData)])
[_mainMenuDelegate DidNotifyReadData];
}
}
}
這一步最簡單,一個 API 就夠:
// 主動斷開裝置
- (void)disConnect {
if (_testPeripheral != nil) {
NSLog(@"disConnect start");
[manager cancelPeripheralConnection:_testPeripheral];
}
}
整條鏈路走下來你會發現,CoreBluetooth 的設計完全是回呼驅動:每一步動作都對應一個 delegate 方法,狀態流轉清清楚楚。真正需要花心思的反而不是 API 本身,而是封包格式解析、逾時與斷線重連機制,以及不同廠商裝置在廣播包與特徵行為上的差異。