
上一篇講完了藍牙的基礎知識,這次來談中心(Central)模式的實際落地。所謂中心模式,就是手機去掃描並連接外設、發現外設提供的服務與特徵、再對它們進行讀寫。一般來說,外設(藍牙裝置,例如智慧手環)由硬體工程師開發並定義好:它提供哪些服務、每個服務有哪些特徵、每個特徵的權限(唯讀、唯寫、通知等)。本文的場景就是一支手機 App 去讀寫藍牙裝置。
整體流程
環境準備
實作步驟
1. 引入 CoreBluetooth,建立中心管理者並設定 delegate
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController : UIViewController <CBCentralManagerDelegate, CBPeripheralDelegate>
// 系統藍牙裝置管理物件,可理解為「主設備」,掃描與連接外設都靠它
@property (nonatomic, strong) CBCentralManager *manager;
@end
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化並設定 delegate 與 queue,queue 傳 nil 時預設使用 main queue
self.manager = [[CBCentralManager alloc] initWithDelegate:self
queue:dispatch_get_main_queue()];
}需要留意的幾個 delegate:
2. 掃描外設
掃描動作要放在 manager 狀態確認可用的 delegate 裡,否則會直接報錯。
- (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 代表掃描周遭所有外設
[self.manager scanForPeripheralsWithServices:nil options:nil];
break;
default:
break;
}
}
// 掃到裝置時會進入這裡
- (void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI {
NSLog(@"掃到裝置:%@", peripheral.name);
}3. 連接外設
一個中心設備最多同時連 7 個外設,而每個外設同時只能被一個中心連接。連接的結果會分別進入成功、失敗、中斷三個 delegate。
- (void)centralManager:(CBCentralManager *)central
didDiscoverPeripheral:(CBPeripheral *)peripheral
advertisementData:(NSDictionary *)advertisementData
RSSI:(NSNumber *)RSSI {
// 這裡自行定義篩選規則,範例挑名稱以 P 開頭的裝置
// 若手上沒有實機,可用 LightBlue 這類 App 模擬一個外設
if ([peripheral.name hasPrefix:@"P"]) {
[self.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(@">>> %@ 已斷線:%@", peripheral.name, error.localizedDescription);
}4. 掃描服務與特徵
連上之後就可以掃服務了。注意這裡換成 CBPeripheralDelegate——它才是承載主從互動各種回呼的地方,包含取得 services、characteristics、特徵值、Descriptor 及其值、寫入資料、讀 RSSI、以通知方式訂閱資料等等。
4.1 取得 services:
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@">>> 已連上 %@", peripheral.name);
// 設定外設的 delegate
peripheral.delegate = self;
// 掃描服務,結果進入 peripheral:didDiscoverServices:
[peripheral discoverServices:nil];
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
if (error) {
NSLog(@">>> 掃描 %@ 的服務失敗:%@", peripheral.name, error.localizedDescription);
return;
}
for (CBService *service in peripheral.services) {
NSLog(@"%@", service.UUID);
// 針對每個 service 掃它的特徵
[peripheral discoverCharacteristics:nil forService:service];
}
}4.2 取得特徵、特徵值、Descriptor 及其值:
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"掃描 %@ 的特徵失敗:%@", service.UUID, error.localizedDescription);
return;
}
for (CBCharacteristic *c in service.characteristics) {
NSLog(@"service: %@ 的 Characteristic: %@", service.UUID, c.UUID);
}
// 讀取特徵值,結果進入 didUpdateValueForCharacteristic:
for (CBCharacteristic *c in service.characteristics) {
[peripheral readValueForCharacteristic:c];
}
// 掃描特徵的 Descriptor,結果進入 didDiscoverDescriptorsForCharacteristic:
for (CBCharacteristic *c in service.characteristics) {
[peripheral discoverDescriptorsForCharacteristic:c];
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
// value 是 NSData,實際開發時要依硬體協議自行解析
NSLog(@"characteristic uuid: %@ value: %@", characteristic.UUID, characteristic.value);
}
- (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);
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {
// Descriptor 內容通常是字串,這裡轉成字串方便閱讀
NSLog(@"descriptor uuid: %@ value: %@",
descriptor.UUID,
[NSString stringWithFormat:@"%@", descriptor.value]);
}5. 寫入資料到特徵
寫入之前務必先確認權限。CBCharacteristicProperties 是一個 NS_OPTIONS,可以同時包含多個值,常見的有 read、write、notify、indicate,前兩個是讀寫權限,後兩者是兩種不同的通知方式:
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
};- (void)writeCharacteristic:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic
value:(NSData *)value {
NSLog(@"%lu", (unsigned long)characteristic.properties);
// 具備 write 權限才能寫入
if (characteristic.properties & CBCharacteristicPropertyWrite) {
// type 可為 CBCharacteristicWriteWithResponse 或 WithoutResponse,
// 差別在於是否需要對方回應
[peripheral writeValue:value forCharacteristic:characteristic
type:CBCharacteristicWriteWithResponse];
} else {
NSLog(@"該特徵不可寫!");
}
}6. 訂閱與取消訂閱通知
// 開啟通知後,資料會從 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];
}7. 中斷連線
- (void)disconnectPeripheral:(CBCentralManager *)central
peripheral:(CBPeripheral *)peripheral {
[central stopScan]; // 停止掃描
[central cancelPeripheralConnection:peripheral]; // 斷開連線
}8. 關於用模擬器除錯
坦白說不建議。BLE 從 iPhone 4s 之後的機型才支援,而這些新機型都不便宜,測試時想省成本才會想用模擬器。Apple 一開始說明過:在支援 BLE 的 Mac 上可以用模擬器除錯,並提供過一份技術文件;但後來把文件下架,也把 iOS 7.0 模擬器對 BLE 的支援移除了。
網路上找到的變通做法是:
範例程式碼
我部落格上的範例大多放在 GitHub:https://github.com/coolnameismy/demo,本文對應的目錄是 BleDemo。