您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 藍牙開發(二):用 CoreBluetooth 讀寫 BLE 外設的完整流程

編輯:iOS 相關資訊

上一篇講完了藍牙的基礎知識,這次來談中心(Central)模式的實際落地。所謂中心模式,就是手機去掃描並連接外設、發現外設提供的服務與特徵、再對它們進行讀寫。一般來說,外設(藍牙裝置,例如智慧手環)由硬體工程師開發並定義好:它提供哪些服務、每個服務有哪些特徵、每個特徵的權限(唯讀、唯寫、通知等)。本文的場景就是一支手機 App 去讀寫藍牙裝置。

整體流程

  1. 建立中心角色
  2. 掃描外設(discover)
  3. 連接外設(connect)
  4. 掃描服務與特徵(discover)
    • 取得外設的 services
    • 取得 services 的 Characteristics,並讀取特徵值、特徵的 Descriptor 及其值
  5. 與外設進行資料交互(explore and interact)
  6. 訂閱 Characteristic 的通知
  7. 中斷連線(disconnect)

環境準備

  • Xcode
  • 開發憑證與真機(藍牙功能需要真機除錯;模擬器理論上也能跑,但過程相當折騰,最後再說)
  • 一個 BLE 外設

實作步驟

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:

  • centralManagerDidUpdateState: 為必實作,藍牙開啟後才會進入可用狀態,只有狀態正確才能開始掃描。
  • didDiscoverPeripheral:advertisementData:RSSI: 掃描到外設時呼叫。
  • didConnectPeripheral: 連接成功。
  • didFailToConnectPeripheral:error: 連接失敗。
  • didDisconnectPeripheral:error: 連線中斷。

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 的支援移除了。

網路上找到的變通做法是:

  1. 買一個 CSR 藍牙 4.0 USB 適配器插上 Mac。
  2. 在終端機執行 sudo nvram bluetoothHostControllerSwitchBehavior="never",然後重開機。
  3. 用 Xcode 4.6 搭配 iOS 6.1 模擬器執行(用 Xcode 5.0 跑 iOS 7.0 模擬器會拋異常)。模擬器版本可在 Xcode → Preferences → Downloads 中下載。

範例程式碼

我部落格上的範例大多放在 GitHub:https://github.com/coolnameismy/demo,本文對應的目錄是 BleDemo。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved