藍牙開發是 iOS 中一個既有趣又容易踩坑的領域。本文從常見縮寫、基礎知識講起,再帶你走一遍中心模式與外設模式的完整開發流程,並附上關鍵程式碼。
MFI:make for iPad/iPhone/iTouch,專門為蘋果設備製作的配件。
BLE:Bluetooth Low Energy,藍牙 4.0 設備因低耗電,也稱 BLE。
peripheral / central:外設與中心。發起連接的一方為 central,被連接的設備為 peripheral。
service and characteristic:服務與特徵。每個設備都會提供服務與特徵,類似服務端的 API,但結構不同。每個外設有很多服務,每個服務包含很多字段,這些字段的權限一般分为讀(read)、寫(write)、通知(notify)幾種,就是我們連接設備後具體要操作的內容。
Description:每個 characteristic 可對應一個或多個 Description,用於描述 characteristic 的資訊或屬性。
MFI 開發使用 ExternalAccessory 框架;4.0 BLE 開發使用 CoreBluetooth 框架。
CoreBluetooth 框架的核心其實就兩個東西:peripheral 與 central,可理解為外設與中心,各自對應一組相關的 API 與類。
這兩組 API 對應不同業務場景:左側是中心模式,以你的 App 為中心去連接其他外設;右側是外設模式,把手機當作外設供其他中心設備操作。
服務與特徵(service and characteristic):每個設備都有一些服務,每個服務裡面有一些特徵,特徵就是具體的鍵值對,是提供數據的地方。特徵的屬性分為讀、寫、通知幾種方式。
// objective-c 特徵的定義枚舉
typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
CBCharacteristicPropertyBroadcast = 0x01,
CBCharacteristicPropertyRead = 0x02,
CBCharacteristicPropertyWriteWithoutResponse = 0x04,
CBCharacteristicPropertyWrite = 0x08,
CBCharacteristicPropertyNotify = 0x10,
CBCharacteristicPropertyIndicate = 0x20,
CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,
CBCharacteristicPropertyExtendedProperties = 0x80,
CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x100,
CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x200
};
1. 建立中心角色 2. 掃描外設(discover) 3. 連接外設(connect) 4. 掃描外設中的服務和特徵(discover) 4.1 獲取外設的 services 4.2 獲取外設的 Characteristics,獲取 Characteristics 的值,獲取 Descriptor 及其值 5. 與外設做數據交互(explore and interact) 6. 訂閱 Characteristic 的通知 7. 斷開連接(disconnect)
1. 啟動一個 Peripheral 管理對象 2. 本地 Peripheral 設置服務、特徵、描述、權限等 3. Peripheral 發送廣告 4. 設置處理訂閱、取消訂閱、讀 characteristic、寫 characteristic 的委托方法
1. 待機狀態(standby):設備沒有傳輸和發送數據,並且沒有連接到任何設備 2. 廣播狀態(Advertiser):周期性廣播狀態 3. 掃描狀態(Scanner):主動尋找正在廣播的設備 4. 發起鏈接狀態(Initiator):主動向掃描設備發起連接 5. 主設備(Master):作為主設備連接到其他設備 6. 從設備(Slave):作為從設備連接到其他設備
1. 建立中心角色 2. 掃描外設(discover) 3. 連接外設(connect) 4. 掃描外設中的服務和特徵(discover) 4.1 獲取外設的 services 4.2 獲取外設的 Characteristics,獲取 Characteristic 的值、Descriptor 及其值 5. 與外設做數據交互(explore and interact) 6. 訂閱 Characteristic 的通知 7. 斷開連接(disconnect)
1. Xcode 2. 開發證書和手機(藍牙程式建議真機調試,模擬器雖也可調試但很麻煩) 3. 藍牙外設
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController : UIViewController <CBCentralManagerDelegate, CBPeripheralDelegate>
{
// 系統藍牙設備管理對象,可理解為主設備,透過它去掃描和連接外設
CBCentralManager *manager;
// 用於保存被發現的設備
NSMutableArray *peripherals;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化並設置委托和線程隊列,隊列參數可為 nil,預設使用 main 線程
manager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
@end
CBCentralManagerDelegate 必須實現的委托是 centralManagerDidUpdateState:(主設備狀態改變,只有設備正確打開後才能使用)。其他較重要的可選委托包括 didDiscoverPeripheral(找到外設)、didConnectPeripheral(連接成功)、didFailToConnectPeripheral(連接失敗)、didDisconnectPeripheral(斷開連接)。
掃描方法要放在 centralManager 成功打開的委托中,因為只有設備成功打開才能開始掃描,否則會報錯。
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
switch (central.state) {
case CBCentralManagerStateUnknown:
NSLog(">>>CBCentralManagerStateUnknown");
break;
case CBCentralManagerStateResetting:
NSLog(">>>CBCentralManagerStateResetting");
break;
case CBCentralManagerStateUnsupported:
NSLog(">>>CBCentralManagerStateUnsupported");
break;
case CBCentralManagerStateUnauthorized:
NSLog(">>>CBCentralManagerStateUnauthorized");
break;
case CBCentralManagerStatePoweredOff:
NSLog(">>>CBCentralManagerStatePoweredOff");
break;
case CBCentralManagerStatePoweredOn:
NSLog(">>>CBCentralManagerStatePoweredOn");
// 開始掃描周圍的外設,第一個參數 nil 表示掃描所有外設
[manager scanForPeripheralsWithServices:nil options:nil];
break;
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 {
// 連接我們的測試設備,沒有設備可下載 LightBlue 之類的 App 模擬
// 這裡自訂連接規則,我設置的是 P 開頭的設備
if ([peripheral.name hasPrefix:@"P"]){
// 找到設備必須持有它,否則 CBCentralManager 不會保存 peripheral,
// 那麼 CBPeripheralDelegate 中的方法也不會被調用!!
[peripherals addObject:peripheral];
// 連接設備
[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]);
}
有一點非常容易出錯,請務必注意:在 didDiscoverPeripheral 委托中,一定要 [peripherals addObject:peripheral] 保存設備。若不保存,會影響後續方法執行,這是許多人連接與操作失敗的根源。官方文檔的 @discussion 中也特別指出,發現的 peripheral 必須被 retain,否則會被清理。
設備連接成功後即可掃描服務,同樣透過委托形式。但這個委托不再是主設備的 CBCentralManagerDelegate,而是外設的 CBPeripheralDelegate,它包含了主設備與外設交互的許多回叫方法。
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(">>>連接到名稱為(%@)的設備-成功", peripheral.name);
// 設置 peripheral 委托 CBPeripheralDelegate
[peripheral setDelegate:self];
// 掃描外設 Services
[peripheral discoverServices:nil];
}
// 掃描到 Services
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
if (error) {
NSLog(">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
return;
}
for (CBService *service in peripheral.services) {
NSLog(@"%@", service.UUID);
// 掃描每個 service 的 Characteristics
[peripheral discoverCharacteristics:nil forService:service];
}
}
// 掃描到 Characteristics
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
return;
}
for (CBCharacteristic *characteristic in service.characteristics) {
NSLog(@"service:%@ 的 Characteristic: %@", service.UUID, characteristic.UUID);
}
// 獲取 Characteristic 的值
for (CBCharacteristic *characteristic in service.characteristics){
[peripheral readValueForCharacteristic:characteristic];
}
// 搜索 Characteristic 的 Descriptors
for (CBCharacteristic *characteristic in service.characteristics){
[peripheral discoverDescriptorsForCharacteristic:characteristic];
}
}
// 獲取到 characteristic 的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
// value 類型是 NSData,實際開發時會根據外設協議解析數據
NSLog(@"characteristic uuid:%@ value:%@", characteristic.UUID, characteristic.value);
}
// 搜索到 Characteristic 的 Descriptors
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
NSLog(@"characteristic uuid:%@", characteristic.UUID);
for (CBDescriptor *d in characteristic.descriptors) {
NSLog(@"Descriptor uuid:%@", d.UUID);
}
}
// 獲取到 Descriptors 的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {
// descriptor 一般為字符串,轉換成字符串解析
NSLog(@"characteristic uuid:%@ value:%@", [NSString stringWithFormat:@"%@", descriptor.UUID], descriptor.value);
}
- (void)writeCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic value:(NSData *)value {
// 只有 characteristic.properties 有 write 權限才可以寫
if (characteristic.properties & CBCharacteristicPropertyWrite) {
// type 可為 CBCharacteristicWriteWithResponse,區別在於是否有反饋
[peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
} else {
NSLog(@"該字段不可寫!");
}
}
// 設置通知,數據通知會進入 didUpdateValueForCharacteristic 方法
- (void)notifyCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic {
[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];
}
溫馨提示:若想即時掌握藍牙與外設的連接狀態,一定要實現 didDisconnectPeripheral 委托。如此一來,外設斷開後只要仍可連接,就能在這裡寫入「進入 App 自動重連可搜到的外設」的邏輯。以上皆為本人親測可行,有任何問題歡迎交流。