您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 藍牙 4.0(BLE)開發完整指南:CoreBluetooth 實戰

編輯:iOS 開發綜合

一、專案背景

這次要串接的硬體是一台金融刷卡器,透過藍牙與 iPhone 通訊。App 端藉由發送不同的指令封包,控制刷卡器執行讀磁條卡、讀金融 IC 卡等動作。

二、iOS 上的兩套藍牙框架

藍牙協定演進到 4.0 時最大的賣點是低功耗,因此一般稱為 BLE(Bluetooth Low Energy)。iOS 支援藍牙的框架有兩個:

ExternalAccessory——自 iOS 3.0 起支援,在 iPhone 4s 之前是主流。缺點是硬體必須取得蘋果的 MFi 認證,門檻高、週期長。

CoreBluetooth——自 iPhone 4s 起支援,專門用於與 BLE 裝置通訊(API 全建構在 BLE 之上)。不需要 MFi 認證,加上現今多數藍牙裝置都支援 4.0,因此是目前 iOS 上最推薦的做法。

三、CoreBluetooth 的兩個角色

整個框架的核心就是兩個概念:Peripheral(外設)與 Central(中心),各自對應一組委派與類別。

你要開發的角色決定你該用哪一組 API。本範例中刷卡器是 peripheral、iPhone 是 central,因此主要使用 central 相關類別。反之,若要做「兩台 iOS 裝置互相通訊」,其中一端就得改用 peripheral 的 API。

四、服務與特徵(Service & Characteristic)

每個 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

不在標準清單中的裝置(例如本例的刷卡器),硬體廠商通常會另外提供文件,說明各服務與特徵的用途——哪些可讀寫、哪些唯讀。

五、實作流程

作為中心角色,完整通訊要經過六個階段:

建立中心角色 → 掃描外設 → 連接外設 → 掃描服務與特徵 → 資料互動 → 斷開連接

1. 建立中心角色

在自訂類別的 header 引入 CoreBluetooth,並實作兩個委派:

#import <CoreBluetooth/CoreBluetooth.h>

// 介面宣告需繼承 <CBCentralManagerDelegate, CBPeripheralDelegate>

CBCentralManager *manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

2. 掃描外設

[manager scanForPeripheralsWithServices:nil options:options];

這個方法可以傳入特定服務 UUID 以過濾裝置,但實測時若傳入特定 UUID,反而一台都掃不到——懷疑與裝置本身的廣播包內容有關。因此實務上常見的做法是傳 nil 掃全部,再自行過濾:

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];

3. 連接外設

掃到裝置後,系統會回呼:

- (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;
}

4. 掃描服務與特徵

- (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
{
    if (error) {
        NSLog(@"Discovered services for %@ with error: %@",
              peripheral.name, [error localizedDescription]);
        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];
            break;
        }
    }
}
- (void)peripheral:(CBPeripheral *)peripheral
didDiscoverCharacteristicsForService:(CBService *)service
             error:(NSError *)error
{
    if (error) {
        NSLog(@"Discovered characteristics for %@ with error: %@",
              service.UUID, [error localizedDescription]);
        return;
    }

    // 找出「讀」特徵
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_TX]]) {
            _readCharacteristic = characteristic;
            break;
        }
    }

    // 找出「寫」特徵
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_RX]]) {
            _writeCharacteristic = characteristic;
            break;
        }
    }
}

注意這些回呼都以 did 開頭——你不需要呼叫它們,條件達成時系統會自動觸發。

5. 資料互動

寫入很簡單,包成一個方法即可:

- (void)writeChar:(NSData *)data
{
    [_testPeripheral writeValue:data
              forCharacteristic:_writeCharacteristic
                           type:CBCharacteristicWriteWithResponse];
}

讀取有兩種模式:直接讀(read)與訂閱(notify)。要用哪一種,取決於特徵自身的 properties 欄位:

enum {
    CBCharacteristicPropertyBroadcast                  = 0x01,
    CBCharacteristicPropertyRead                       = 0x02,
    CBCharacteristicPropertyWriteWithoutResponse       = 0x04,
    CBCharacteristicPropertyWrite                      = 0x08,
    CBCharacteristicPropertyNotify                     = 0x10,
    CBCharacteristicPropertyIndicate                   = 0x20,
    CBCharacteristicPropertyAuthenticatedSignedWrites  = 0x40,
    CBCharacteristicPropertyExtendedProperties         = 0x80,
};

若某特徵的 properties 為 0x10,就代表它只能用訂閱方式收資料。啟動訂閱:

- (void)startSubscribe
{
    [_testPeripheral setNotifyValue:YES forCharacteristic:_readCharacteristic];
}

裝置有資料回傳時,同樣透過回呼通知,而且資料可能是分片送達,必須自行組包:

- (void)peripheral:(CBPeripheral *)peripheral
didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic
             error:(NSError *)error
{
    if (error) {
        NSLog(@"Error updating value for characteristic %@ error: %@",
              characteristic.UUID, [error localizedDescription]);
        return;
    }

    [_recvData appendData:characteristic.value];

    // 已收到長度欄位
    if ([_recvData length] >= 5) {
        unsigned char *buffer = (unsigned char *)[_recvData bytes];
        int nLen = buffer[3] * 256 + buffer[4];

        // 完整封包長度 = 資料本體 + 標頭3 + CRC2 + 結束2
        if ([_recvData length] == (nLen + 3 + 2 + 2)) {
            // 通知代理處理完整封包
        }
    }
}

組包時還要記得 CRC 校驗。以觸發刷卡為例:

-(void)msrRead
{
    unsigned char command[512] = {0};
    unsigned char *pTmp = command;
    unsigned char ucCrc[3] = {0};
    int nSendLen = 0;

    _commandType = COMMAND_MSR_READ;

    *pTmp++ = 0x02;   // 起始位元
    *pTmp++ = 0xc1;   // 主指令
    *pTmp++ = 0x07;   // 子指令

    nSendLen = 2;
    *pTmp++ = nSendLen / 256;
    *pTmp++ = nSendLen % 256;
    *pTmp++ = 0x00;
    *pTmp++ = 0x00;

    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];
}

6. 斷開連接

- (void)disConnect
{
    if (_testPeripheral != nil) {
        NSLog(@"disConnect start");
        [manager cancelPeripheralConnection:_testPeripheral];
    }
}

六、成果

最終完成了磁道資訊讀取、與金融 IC 卡的 APDU 互動等功能。

BLE 開發的幾個實務心得

一定要做逾時防護。BLE 的連接、掃描都可能無聲無息地卡住,沒有逾時機制,使用者只會看到一片空白。

收資料務必假設會分片。BLE 單次傳輸量很小,一個完整封包被拆成好幾次回呼是常態,必須用緩衝區累加後再判斷長度。

先把硬體文件讀熟。UUID、指令格式、CRC 演算法全都由廠商定義,猜不出來也不該猜。

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