藍牙協議本身經歷了從1.0到4.0的升級演化, 最新的4.0以其低功耗著稱,所以1般也叫BLE(Bluetoothlow energy)。
iOS 有兩個框架支持藍牙與外設連接。1個是 ExternalAccessory。從ios3.0就開始支持,也是在iphone4s出來之前用的比較多的1種模式,但是它有個不好的地方,External Accessory需要拿到蘋果公司的MFI認證。
另外一個框架則是本文要介紹的CoreBluetooth,在iphone4s開始支持,專門用于與BLE裝備通訊(由于它的API都是基于BLE的)。這個不需要MFI,并且現在很多藍牙裝備都支持4.0,所以也是在IOS比較推薦的1種開發方法。
CoreBluetooth介紹
CoreBluetooth框架的核心實際上是兩個東西,peripheral和central, 可以理解成外設和中心。對應他們分別有1組相干的API和類,以下圖所示:
如果你要編程的裝備是central那末你大部份用到,反之亦然。在我們這個示例中,金融刷卡器是peripheral,我們的iphone手機是central,所以我將大部份使用上圖中左側部份的類。使用peripheral編程的例子也有很多,比如像用1個ipad和1個iphone通訊,ipad可以認為是central,iphone端是peripheral,這類情況下在iphone端就要使用上圖右側部份的類來開發了。
服務和特點
有個概念有必要先說明1下。甚么是服務和特點呢(service and characteristic)?
每一個藍牙4.0的裝備都是通過服務和特點來展現自己的,1個裝備必定包括1個或多個服務,每一個服務下面又包括若干個特點。特點是與外界交互的最小單位。比如說,1臺藍牙4.0裝備,用特點A來描寫自己的出廠信息,用特點B來與收發數據等。
服務和特點都是用UUID來唯1標識的,UUID的概念如果不清楚請自行google,國際藍牙組織為1些很典型的裝備(比如丈量心跳和血壓的裝備)規定了標準的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)的功能,比如哪些是用來交互(讀寫),哪些可獲得模塊信息(只讀)等.
實現細節
作為1個中心要實現完全的通訊,1般要經過這樣幾個步驟:
建立中心角色—掃描外設(discover)—連接外設(connect)—掃描外設中的服務和特點(discover)—與外設做數據交互(explore and interact)—斷開連接(disconnect)。
1建立中心角色
首先在我自己類的頭文件中要包括CoreBluetooth的頭文件,并繼承兩個協議<CBCentralManagerDelegate,CBPeripheralDelegate>,代碼以下:
[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片
#import <CoreBluetooth/CoreBluetooth.h>
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⑶3A0-EC21⑹011-CD4B50710777"],[CBUUID UUIDWithString:@"6765D311-DD4C⑼C14⑺4E1-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]];
//開1個定時器監控連接超時的情況
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];
}
1個裝備里的服務和特點常常比較多,大部份情況下我們只是關心其中幾個,所以1般會在發現服務和特點的回調里去匹配我們關心那些,比以下面的代碼:
[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)
發送數據很簡單,我們可以封裝1個以下的函數:
[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];
}
當裝備有數據返回時,一樣是通過1個系統回調通知我,以下所示:
[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)
這個比較簡單,只需要1個API就好了,代碼以下:
[objc] view plain copy 在CODE上查看代碼片派生到我的代碼片
//主動斷開裝備
-(void)disConnect
{
if (_testPeripheral != nil)
{
NSLog(@"disConnect start");
[manager cancelPeripheralConnection:_testPeripheral];
}
}
效果圖就不上傳了,你可以找裝備試試,嘗試操作1下,原理就是這些,如有不好地方,還望給予斧正,不勝感激!!!謝謝!!!