
上一篇介紹了藍牙基礎知識,這裡具體說明中心模式(central)的應用場景:手機去掃描並連接外設,發現外設提供的服務與特徵,進而讀寫數據。外設(比如智能手環)通常由硬件工程師實現,並約定好服務、特徵及每個特徵的屬性(只讀、只寫、通知等)。本文的業務場景就是:用一個 App 去讀寫藍牙設備。
建立中心角色
掃描外設(discover)
連接外設(connect)
掃描外設的服務與特徵(discover):獲取 services;獲取 Characteristics 及其值、Descriptor 及其值
與外設做數據交互(explore and interact)
訂閱 Characteristic 的通知
斷開連接(disconnect)
模擬器調試(慎用,建議真機)
Xcode
開發證書與真機(模擬器也能調,但過程折騰)
一個藍牙外設
#import [CoreBluetooth/CoreBluetooth.h](因識別問題,此處將尖括號改為方括號)
@interface ViewController ()
// 系統藍牙管理對象,即主設備,通過它掃描與連接外設
CBCentralManager *manager;
@end
- (void)viewDidLoad {
[super viewDidLoad];
/* 必須實現的委托:
- centralManagerDidUpdateState: 主設備狀態變化,設備正確打開後才能使用
其他重要委托:
- didDiscoverPeripheral: 找到外設
- didConnectPeripheral: 連接成功
- didFailToConnectPeripheral: 連接失敗
- didDisconnectPeripheral: 斷開連接 */
manager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}掃描必須放在設備成功打開的回調裡,否則會報錯:
-(void)centralManagerDidUpdateState:(CBCentralManager *)central {
switch (central.state) {
case CBCentralManagerStatePoweredOn:
// 第一個參數傳 nil 表示掃描周圍所有外設
[manager scanForPeripheralsWithServices:nil options:nil];
break;
// Unknown / Resetting / Unsupported / Unauthorized / PoweredOff 等狀態按需處理
default:
break;
}
}
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
NSLog(@"當掃描到設備:%@", peripheral.name);
}實戰中通常要按名稱規則篩選目標設備,避免誤連:
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
// 這裡以 P 開頭作為連接規則;沒有真實設備時可用 LightBlue 之類的 App 模擬
if ([peripheral.name hasPrefix:@"P"]) {
// 一個主設備最多連接 7 個外設,一個外設同時只能被一個主設備連接
[manager connectPeripheral:peripheral options:nil];
}
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@">>>連接到名稱為(%@)的設備-成功", peripheral.name);
}
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(@">>>連接到名稱為(%@)的設備-失敗,原因:%@", [peripheral name], [error localizedDescription]);
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(@">>>外設連接斷開連接 %@: %@\n", [peripheral name], [error localizedDescription]);
}連接成功後,代理要從 CBCentralManagerDelegate 切換到 CBPeripheralDelegate——後者才是與外設交互的回調集合,涵蓋獲取 services、characteristics、值、descriptor,以及寫數據、讀 RSSI、通知訂閱等。
// 4.1 獲取 services
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
[peripheral setDelegate:self];
[peripheral discoverServices:nil];
}
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
if (error) { return; }
for (CBService *service in peripheral.services) {
NSLog(@"%@", service.UUID);
[peripheral discoverCharacteristics:nil forService:service];
}
}
// 4.2 獲取 characteristics、值與 descriptor
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
for (CBCharacteristic *characteristic in service.characteristics) {
NSLog(@"service:%@ 的 Characteristic: %@", service.UUID, characteristic.UUID);
[peripheral readValueForCharacteristic:characteristic];
[peripheral discoverDescriptorsForCharacteristic:characteristic];
}
}
// 注意:value 類型是 NSData,實際開發需按外設協議解析
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
NSLog(@"characteristic uuid:%@ value:%@", characteristic.UUID, characteristic.value);
}
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
for (CBDescriptor *d in characteristic.descriptors) {
NSLog(@"Descriptor uuid:%@", d.UUID);
}
}寫之前務必檢查權限位。CBCharacteristicProperties 是 NS_OPTIONS,常見的有 read、write、notify、indicate,前兩個是讀寫權限,後兩個是兩種不同的通知方式:
-(void)writeCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic value:(NSData *)value {
NSLog(@"%lu", (unsigned long)characteristic.properties);
if (characteristic.properties & CBCharacteristicPropertyWrite) {
// type 可選 CBCharacteristicWriteWithResponse 或 WithoutResponse,區別在於是否有反饋
[peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
} else {
NSLog(@"該字段不可寫!");
}
}-(void)notifyCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic {
// 開啟後數據會持續進入 didUpdateValueForCharacteristic
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
-(void)cancelNotifyCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic {
[peripheral setNotifyValue:NO forCharacteristic:characteristic];
}-(void)disconnectPeripheral:(CBCentralManager *)centralManager peripheral:(CBPeripheral *)peripheral {
[centralManager stopScan];
[centralManager cancelPeripheralConnection:peripheral];
}BLE 從 iPhone 4S 之後的機型才支持,而這些設備都不便宜,因此早期很多人會想著用模擬器省成本。蘋果最初說明支持 BLE 的 Mac 上可以模擬器調試並提供了技術文檔,後來卻移除了文檔,同時也移除了 iOS 7.0 模擬器對 BLE 的支持。當時網上的變通方案大致是:外接一個 CSR 藍牙 4.0 USB 適配器;在終端執行 sudo nvram bluetoothHostControllerSwitchBehavior="never" 後重啟;再用 Xcode 4.6 配合 iOS 6.1 模擬器運行(iOS 7.0 模擬器會拋異常)。模擬器版本可在 Xcode → Preferences → Downloads 中下載。
坦白說,如今完全沒有必要折騰這些,直接真機調試最省事。
代碼下載:https://github.com/coolnameismy/demo,本文代碼位於 BleDemo 目錄。