藍牙協議本身經歷了從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的頭文件,並繼承兩個協議,代碼如下: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 #import CBCentralManager *manager; manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
2掃描外設(discover) 代碼如下: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 [manager scanForPeripheralsWithServices:nil options:options];
這個參數應該也是可以指定特定的peripheral的UUID,那麼理論上這個central只會discover這個特定的設備,但是我實際測試發現,如果用特定的UUID傳參根本找不到任何設備,我用的代碼如下: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 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的設備後,系統會通過回調函數告訴我們設備的信息,然後我們就可以連接相應的設備,代碼如下: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 - (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) 同樣的,當連接成功後,系統會通過回調函數告訴我們,然後我們就在這個回調裡去掃描設備下所有的服務和特征,代碼如下: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { [connectTimer invalidate];//停止時鐘 NSLog(@"Did connect to peripheral: %@", peripheral); _testPeripheral = peripheral; [peripheral setDelegate:self]; [peripheral discoverServices:nil]; }
一個設備裡的服務和特征往往比較多,大部分情況下我們只是關心其中幾個,所以一般會在發現服務和特征的回調裡去匹配我們關心那些,比如下面的代碼: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 - (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]; }
5與外設做數據交互(explore and interact) 發送數據很簡單,我們可以封裝一個如下的函數: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 //寫數據 -(void)writeChar:(NSData *)data { [_testPeripheral writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse]; }
_testPeripheral和_writeCharacteristic是前面我們保存的設備對象和可以讀寫的特征。 然後我們可以在外部調用它,比如當然我要觸發刷卡時,先組好數據包,然後調用發送函數: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 -(void)msrRead { unsigned char command[512] = {0}; unsigned charchar *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]; }
比如說,你要交互的特征,它的properties的值是0x10,表示你只能用訂閱的方式來接收數據。我這裡是用訂閱的方式,啟動訂閱的代碼如下: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 //監聽設備 -(void)startSubscribe { [_testPeripheral setNotifyValue:YES forCharacteristic:_readCharacteristic]; }
當設備有數據返回時,同樣是通過一個系統回調通知我,如下所示: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 - (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 charchar *buffer = (unsigned charchar *)[_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就行了,代碼如下: [objc] view plain copy 在CODE上查看代碼片派生到我的代碼片 //主動斷開設備 -(void)disConnect { if (_testPeripheral != nil) { NSLog(@"disConnect start"); [manager cancelPeripheralConnection:_testPeripheral]; } }