IOS藍芽4.0與讀卡器通訊
IOS學習也一段時間了,該上點乾貨了。前段時間研究了一下IOS藍芽通訊相關的東西,把研究的一個成果給大家分享一下。
一 專案背景
簡單介紹一下做的東西,裝置是一個金融刷卡器,通過藍芽與iphone手機通訊。手機端的app通過傳送不同的指令(通過藍芽)控制刷卡器執行一些動作,比如讀磁條卡,讀金融ic卡等。上幾張圖容易理解一些:
看了上面幾張圖,你應該大概瞭解這是個什麼東東了。
二 IOS 藍芽介紹
藍芽協議本身經歷了從1.0到4.0的升級演變, 最新的4.0以其低功耗著稱,所以一般也叫BLE(Bluetoothlow energy)。
iOS 有兩個框架支援藍芽與外設連線。一個是 ExternalAccessory。從ios3.0就開始支援,也是在iphone4s出來之前用的比較多的一種模式,但是它有個不好的地方,External Accessory需要拿到蘋果公司的MFI認證。
另一個框架則是本文要介紹的CoreBluetooth,在iphone4s開始支援,專門用於與BLE裝置通訊(因為它的API都是基於BLE的)。這個不需要MFI,並且現在很多藍芽裝置都支援4.0,所以也是在IOS比較推薦的一種開發方法。
三 CoreBluetooth介紹
CoreBluetooth框架的核心其實是兩個東西,peripheral和central, 可以理解成外設和中心。對應他們分別有一組相關的API和類,如下圖所示:
如果你要程式設計的裝置是central那麼你大部分用到,反之亦然。在我們這個示例中,金融刷卡器是peripheral,我們的iphone手機是central,所以我將大部分使用上圖中左邊部分的類。使用peripheral程式設計的例子也有很多,比如像用一個ipad和一個iphone通訊,ipad可以認為是central,iphone端是peripheral,這種情況下在iphone端就要使用上圖右邊部分的類來開發了。
四 服務和特徵
有個概念有必要先說明一下。什麼是服務和特徵呢(service and characteristic)?
每個藍芽4.0的裝置都是通過服務和特徵來展示自己的,一個裝置必然包含一個或多個服務,每個服務下面又包含若干個特徵。特徵是與外界互動的最小單位。比如說,一臺藍芽4.0裝置,用特徵A來描述自己的出廠資訊,用特徵B來與收發資料等。
服務和特徵都是用UUID來唯一標識的,UUID的概念如果不清楚請自行google,國際藍芽組織為一些很典型的裝置(比如測量心跳和血壓的裝置)規定了標準的service UUID(特徵的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
當然還有很多裝置並不在這個標準列表裡,比如我用的這個金融刷卡器。藍芽裝置硬體廠商通常都會提供他們的裝置裡面各個服務(service)和特徵(characteristics)的功能,比如哪些是用來互動(讀寫),哪些可獲取模組資訊(只讀)等。
五 實現細節
作為一箇中心要實現完整的通訊,一般要經過這樣幾個步驟:
建立中心角色—掃描外設(discover)—連線外設(connect)—掃描外設中的服務和特徵(discover)—與外設做資料互動(explore and interact)—斷開連線(disconnect)。
1建立中心角色
首先在我自己類的標頭檔案中要包含CoreBluetooth的標頭檔案,並繼承兩個協議<CBCentralManagerDelegate,CBPeripheralDelegate>,程式碼如下:
#import <CoreBluetooth/CoreBluetooth.h>
CBCentralManager *manager;
manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
2掃描外設(discover)
程式碼如下:
[manager scanForPeripheralsWithServices:nil options:options];
這個引數應該也是可以指定特定的peripheral的UUID,那麼理論上這個central只會discover這個特定的裝置,但是我實際測試發現,如果用特定的UUID傳參根本找不到任何裝置,我用的程式碼如下:
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連線外設(connect)
當掃描到4.0的裝置後,系統會通過回撥函式告訴我們裝置的資訊,然後我們就可以連線相應的裝置,程式碼如下:
- (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掃描外設中的服務和特徵(discover)
同樣的,當連線成功後,系統會通過回撥函式告訴我們,然後我們就在這個回撥裡去掃描裝置下所有的服務和特徵,程式碼如下:
- (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
{
NSLog(@"didDiscoverServices");
if (error)
{
NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
if ([self.delegate respondsToSelector:@selector(DidNotifyFailConnectService:withPeripheral:error:)])
[self.delegate DidNotifyFailConnectService:nil withPeripheral:nil error:nil];
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];
isVPOS3356 = YES;
break;
}
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (error)
{
NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
if ([self.delegate respondsToSelector:@selector(DidNotifyFailConnectChar:withPeripheral:error:)])
[self.delegate DidNotifyFailConnectChar:nil withPeripheral:nil error:nil];
return;
}
for (CBCharacteristic *characteristic in service.characteristics)
{
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_TX]])
{
NSLog(@"Discovered read characteristics:%@ for service: %@", characteristic.UUID, service.UUID);
_readCharacteristic = characteristic;//儲存讀的特徵
if ([self.delegate respondsToSelector:@selector(DidFoundReadChar:)])
[self.delegate DidFoundReadChar:characteristic];
break;
}
}
for (CBCharacteristic * characteristic in service.characteristics)
{
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_RX]])
{
NSLog(@"Discovered write characteristics:%@ for service: %@", characteristic.UUID, service.UUID);
_writeCharacteristic = characteristic;//儲存寫的特徵
if ([self.delegate respondsToSelector:@selector(DidFoundWriteChar:)])
[self.delegate DidFoundWriteChar:characteristic];
break;
}
}
if ([self.delegate respondsToSelector:@selector(DidFoundCharacteristic:withPeripheral:error:)])
[self.delegate DidFoundCharacteristic:nil withPeripheral:nil error:nil];
}
相信你應該已經注意到了,回撥函式都是以"did"開頭的,這些函式不用你呼叫,達到條件後系統後自動呼叫。
5與外設做資料互動(explore and interact)
傳送資料很簡單,我們可以封裝一個如下的函式:
//寫資料
-(void)writeChar:(NSData *)data
{
[_testPeripheral writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];
}
_testPeripheral和_writeCharacteristic是前面我們儲存的裝置物件和可以讀寫的特徵。
然後我們可以在外部呼叫它,比如當然我要觸發刷卡時,先組好資料包,然後呼叫傳送函式:
-(void)msrRead
{
unsigned char command[512] = {0};
unsigned char *pTmp;
int nSendLen = 0;
unsigned char ucCrc[3] = {0};
_commandType = COMMAND_MSR_READ;
pTmp = command;
*pTmp = 0x02;//start
pTmp++;
*pTmp = 0xc1;//main cmd
pTmp++;
*pTmp = 0x07;//sub cmd
pTmp++;
nSendLen = 2;
*pTmp = nSendLen/256;
pTmp++;
*pTmp = nSendLen%256;
pTmp++;
*pTmp = 0x00;//sub cmd
pTmp++;
*pTmp = 0x00;//sub cmd
pTmp++;
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];
}
資料的讀分為兩種,一種是直接讀(reading directly),另外一種是訂閱(subscribe)。從名字也能基本理解兩者的不同。實際使用中具體用一種要看具體的應用場景以及特徵本身的屬性。前一個好理解,特徵本身的屬性是指什麼呢?特徵有個properties欄位(characteristic.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]);
if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadError:)])
[_mainMenuDelegate DidNotifyReadError:error];
return;
}
[_recvData appendData:characteristic.value];
if ([_recvData length] >= 5)//已收到長度
{
unsigned char *buffer = (unsigned char *)[_recvData bytes];
int nLen = buffer[3]*256 + buffer[4];
if ([_recvData length] == (nLen+3+2+2))
{
//接收完畢,通知代理做事
if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadData)])
[_mainMenuDelegate DidNotifyReadData];
}
}
}
6 斷開連線(disconnect)
這個比較簡單,只需要一個API就行了,程式碼如下:
//主動斷開裝置
-(void)disConnect
{
if (_testPeripheral != nil)
{
NSLog(@"disConnect start");
[manager cancelPeripheralConnection:_testPeripheral];
}
}
六 成果展示
上幾張效果圖,UI沒怎麼修飾,主要關注功能,實現了讀取磁軌資訊,與金融ic卡進行APDU互動等功能。