IOS学习之蓝牙4.0
轉載請注明出處
作者:小馬
IOS學習也一段時間了,該上點干貨了。前段時間研究了一下IOS藍牙通訊相關的東西,把研究的一個成果給大家分享一下。
一 項目背景
簡單介紹一下做的東西,設備是一個金融刷卡器,通過藍牙與iphone手機通訊。手機端的app通過發送不同的指令(通過藍牙)控制刷卡器執行一些動作,比如讀磁條卡,讀金融ic卡等。上幾張圖容易理解一些:
?<喎�"http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PGJyPgo8L3A+CjxwPjxpbWcgc3JjPQ=="http://www.2cto.com/uploadfile/Collfiles/20140524/201405240909454.jpg" alt="\">??
看了上面幾張圖,你應該大概了解這是個什么東東了。
二 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比較多,這里就不列舉了),如下:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #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的頭文件,并繼承兩個協議,代碼如下:
?
| 1 2 3 | #import <corebluetooth corebluetooth.h=""> CBCentralManager *manager; manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];</corebluetooth> |
2掃描外設(discover)
代碼如下:
?
| 1 | [manager scanForPeripheralsWithServices:nil options:options]; |
這個參數應該也是可以指定特定的peripheral的UUID,那么理論上這個central只會discover這個特定的設備,但是我實際測試發現,如果用特定的UUID傳參根本找不到任何設備,我用的代碼如下:
?
| 1 2 3 4 | 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的設備后,系統會通過回調函數告訴我們設備的信息,然后我們就可以連接相應的設備,代碼如下:
?
| 1 2 3 4 5 6 7 8 | - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI { ????if(![_dicoveredPeripherals containsObject:peripheral]) ????????[_dicoveredPeripherals addObject:peripheral]; ????? ????NSLog(@"dicoveredPeripherals:%@", _dicoveredPeripherals); } |
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //連接指定的設備 -(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)
同樣的,當連接成功后,系統會通過回調函數告訴我們,然后我們就在這個回調里去掃描設備下所有的服務和特征,代碼如下:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 | - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { ????[connectTimer invalidate];//停止時鐘 ????? ????NSLog(@"Did connect to peripheral: %@", peripheral); ????_testPeripheral = peripheral; ????? ????[peripheral setDelegate:self]; ????[peripheral discoverServices:nil]; ????? ????? } |
一個設備里的服務和特征往往比較多,大部分情況下我們只是關心其中幾個,所以一般會在發現服務和特征的回調里去匹配我們關心那些,比如下面的代碼:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | - (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; ????????} ????????? ????????? ????} } |
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | - (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)
發送數據很簡單,我們可以封裝一個如下的函數:
?
| 1 2 3 4 5 | //寫數據 -(void)writeChar:(NSData *)data { ????[_testPeripheral writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse]; } |
_testPeripheral和_writeCharacteristic是前面我們保存的設備對象和可以讀寫的特征。
然后我們可以在外部調用它,比如當然我要觸發刷卡時,先組好數據包,然后調用發送函數:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | -(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),它是一個整型值,有如下幾個定義:
?
| 1 2 3 4 5 6 7 8 9 10 | enum { ?????CBCharacteristicPropertyBroadcast = 0x01, ?????CBCharacteristicPropertyRead = 0x02, ?????CBCharacteristicPropertyWriteWithoutResponse = 0x04, ?????CBCharacteristicPropertyWrite = 0x08, ?????CBCharacteristicPropertyNotify = 0x10, ?????CBCharacteristicPropertyIndicate = 0x20, ?????CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40, ?????CBCharacteristicPropertyExtendedProperties = 0x80, ?????}; |
比如說,你要交互的特征,它的properties的值是0x10,表示你只能用訂閱的方式來接收數據。我這里是用訂閱的方式,啟動訂閱的代碼如下:
?
| 1 2 3 4 5 | //監聽設備 -(void)startSubscribe { ????[_testPeripheral setNotifyValue:YES forCharacteristic:_readCharacteristic]; } |
當設備有數據返回時,同樣是通過一個系統回調通知我,如下所示:
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | - (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就行了,代碼如下:
?
| 1 2 3 4 5 6 7 8 9 10 11 | //主動斷開設備 -(void)disConnect { ????? ????if (_testPeripheral != nil) ????{ ????????NSLog(@"disConnect start"); ????????[manager cancelPeripheralConnection:_testPeripheral]; ????} } |
總結
以上是生活随笔為你收集整理的IOS学习之蓝牙4.0的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ios 耳机线控
- 下一篇: 如何使用iOS AddressBook