上一篇文章介紹了藍(lán)牙的基本知識(shí)面褐,這里我們具體說(shuō)下,中心模式的應(yīng)用場(chǎng)景取胎。主設(shè)備(手機(jī)去掃描連接外設(shè))發(fā)現(xiàn)外設(shè)服務(wù)和屬性展哭,操作服務(wù)和屬性的應(yīng)用。一般來(lái)說(shuō)闻蛀,外設(shè)(藍(lán)牙設(shè)備匪傍。比如智能手環(huán)之類(lèi)的東西),會(huì)有硬件工程師開(kāi)發(fā)好觉痛,并定義好設(shè)備提供的服務(wù)役衡,每個(gè)服務(wù)對(duì)應(yīng)的特征,每個(gè)特征的屬性(只讀薪棒、只寫(xiě)手蝎、通知等等),本文例子的業(yè)務(wù)場(chǎng)景俐芯,就是用一手機(jī)APP去讀寫(xiě)藍(lán)牙設(shè)備棵介。
一、iOS連接外設(shè)的代碼實(shí)現(xiàn)流程
- 建立中心角色
- 掃描外設(shè)(discover)
- 連接外設(shè)(connect)
- 掃描外設(shè)中的服務(wù)和特征(discover)
- 4.1 獲取外設(shè)的services
- 4.2 獲取外設(shè)的Characteristics,獲取Characteristics的值泼各,獲取Characteristics的Descriptor和Descriptor的值
- 與外設(shè)做數(shù)據(jù)交互(explore and interact)
- 訂閱Characteristic的通知
- 斷開(kāi)連接(disconnect)
二鞍时、準(zhǔn)備環(huán)境
- xcode
- 開(kāi)發(fā)證書(shū)和手機(jī)
3.藍(lán)牙外設(shè)
三、實(shí)現(xiàn)步驟
1.導(dǎo)入CoreBluetooth頭文件扣蜻,建立主設(shè)備管理類(lèi)逆巍,設(shè)置主設(shè)備代理
#import <CoreBluetooth/CoreBluetooth.h>
@interface BeCentralVewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
@interface BeCentralVewController (){
//系統(tǒng)藍(lán)牙設(shè)備管理對(duì)象,可以把他理解為主設(shè)備莽使,通過(guò)他锐极,可以去掃描和鏈接外設(shè)
CBCentralManager *manager;
//用于保存被發(fā)現(xiàn)設(shè)備
NSMutableArray *discoverPeripherals;
}
一些代理的信息
/*
設(shè)置主設(shè)備的委托,CBCentralManagerDelegate
必須實(shí)現(xiàn)的:
- (void)centralManagerDidUpdateState:(CBCentralManager *)central;//主設(shè)備狀態(tài)改變的委托,在初始化CBCentralManager的適合會(huì)打開(kāi)設(shè)備芳肌,只有當(dāng)設(shè)備正確打開(kāi)后才能使用
其他選擇實(shí)現(xiàn)的委托中比較重要的:
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //找到外設(shè)的委托
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//連接外設(shè)成功的委托
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外設(shè)連接失敗的委托
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral
*/
- 掃描外設(shè)(discover)
掃描外設(shè)的方法我們放在centralManagerDidUpdateState,只有設(shè)備成功打開(kāi)灵再,才能開(kāi)始掃描,否則會(huì)報(bào)錯(cuò)亿笤。
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
switch (central.state) {
case CBCentralManagerStateUnknown:
NSLog(@">>>CBCentralManagerStateUnknown");//初始的時(shí)候是未知的(剛剛創(chuàng)建的時(shí)候)
break;
case CBCentralManagerStateResetting:
NSLog(@">>>CBCentralManagerStateResetting");//正在充值的狀態(tài)
break;
case CBCentralManagerStateUnsupported:
NSLog(@">>>CBCentralManagerStateUnsupported");//設(shè)備不支持的狀態(tài)
break;
case CBCentralManagerStateUnauthorized:
NSLog(@">>>CBCentralManagerStateUnauthorized");//設(shè)備未授權(quán)的狀態(tài)
break;
case CBCentralManagerStatePoweredOff:
NSLog(@">>>CBCentralManagerStatePoweredOff");//設(shè)備關(guān)閉的狀態(tài)
break;
case CBCentralManagerStatePoweredOn:
NSLog(@">>>CBCentralManagerStatePoweredOn");
//開(kāi)始掃描周?chē)耐庠O(shè)
/*
第一個(gè)參數(shù)nil就是掃描周?chē)械耐庠O(shè)翎迁,掃描到外設(shè)后會(huì)進(jìn)入
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
*/
[central scanForPeripheralsWithServices:nil options:nil];
break;
default:
break;
}
}
掃描到設(shè)備后會(huì)進(jìn)入下面方法
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
NSLog(@"當(dāng)掃描到設(shè)備:%@",peripheral.name);
//接下來(lái)可以連接設(shè)備
}
3.連接設(shè)備(connect)
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
NSLog(@"當(dāng)掃描到設(shè)備:%@",peripheral.name);
//接下連接我們的測(cè)試設(shè)備,如果你沒(méi)有設(shè)備净薛,可以下載一個(gè)app叫l(wèi)ightbule的app去模擬一個(gè)設(shè)備
//這里自己去設(shè)置下連接規(guī)則汪榔,我設(shè)置的是P開(kāi)頭的設(shè)備
// if ([peripheral.name hasPrefix:@"P"]){
/*
一個(gè)主設(shè)備最多能連7個(gè)外設(shè),每個(gè)外設(shè)最多只能給一個(gè)主設(shè)備連接,連接成功肃拜,失敗痴腌,斷開(kāi)會(huì)進(jìn)入各自的委托
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//連接外設(shè)成功的委托
- (void)centra`lManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外設(shè)連接失敗的委托
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//斷開(kāi)外設(shè)的委托
*/
//找到的設(shè)備必須持有它雌团,否則CBCentralManager中也不會(huì)保存peripheral,那么CBPeripheralDelegate中的方法也不會(huì)被調(diào)用J看稀锦援!
[discoverPeripherals addObject:peripheral];
[central connectPeripheral:peripheral options:nil];
// }
}
//連接到Peripherals-失敗
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@">>>連接到名稱(chēng)為(%@)的設(shè)備-失敗,原因:%@",[peripheral name],[error localizedDescription]);
}
//Peripherals斷開(kāi)連接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
NSLog(@">>>外設(shè)連接斷開(kāi)連接 %@: %@\n", [peripheral name], [error localizedDescription]);
}
//連接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@">>>連接到名稱(chēng)為(%@)的設(shè)備-成功",peripheral.name);
//設(shè)置的peripheral委托CBPeripheralDelegate
//@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
[peripheral setDelegate:self];
//掃描外設(shè)Services,成功后會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
[peripheral discoverServices:nil];
}
**
有一個(gè)點(diǎn)非常容易出錯(cuò)剥悟,大家請(qǐng)注意灵寺,在didDiscoverPeripheral這個(gè)代理中有一行,
/找到的設(shè)備必須持有它懦胞,否則CBCentralManager中也不會(huì)保存peripheral替久,那么CBPeripheralDelegate中的方法也不會(huì)被調(diào)用!躏尉!
[discoverPeripherals addObject:peripheral];
請(qǐng)?zhí)貏e注意,如果不保存后众,會(huì)影響到后面的方法執(zhí)行胀糜,這個(gè)地方最容易出錯(cuò),大家也可以看下蒂誉,在xcode中的說(shuō)明教藻,重點(diǎn)看@discussion中的內(nèi)容,里面特別指出了重要的retained對(duì)象右锨。
4.掃描外設(shè)中的服務(wù)和特征(discover)
設(shè)備連接成功后括堤,就可以掃描設(shè)備中的服務(wù)了,同樣是通過(guò)代理的形式绍移,掃描到結(jié)果后會(huì)進(jìn)入委托方法悄窃。但這個(gè)委托已經(jīng)不再是主設(shè)備的委托(CBCentralManagerDelegate),而是外設(shè)的委托(CBPeripheralDelegate),這個(gè)委托包含了主設(shè)備與外設(shè)交互的許多回調(diào)方法,包括獲取services,獲取characteristics,獲取characteristics的值蹂窖,獲取characteristics的Descriptor,和Descriptor的值轧抗,寫(xiě)數(shù)據(jù),讀rssi,用通知的方式訂閱數(shù)據(jù)等等瞬测。
4.1獲取外設(shè)的services
//掃描到Services
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
// NSLog(@">>>掃描到服務(wù):%@",peripheral.services);
if (error)
{
NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
return;
}
for (CBService *service in peripheral.services) {
NSLog(@"%@",service.UUID);
//掃描每個(gè)service的Characteristics横媚,掃描到后會(huì)進(jìn)入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
[peripheral discoverCharacteristics:nil forService:service];
}
}
4.2獲取外設(shè)的Chatacteristics,獲取Chatacteristics的值,獲取Chatacteristics的Descriptor和Descriptor的值
//掃描到Characteristics
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
if (error)
{
NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
return;
}
for (CBCharacteristic *characteristic in service.characteristics)
{
NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);
}
//獲取Characteristic的值月趟,讀到數(shù)據(jù)會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in service.characteristics){
{
[peripheral readValueForCharacteristic:characteristic];
}
}
//搜索Characteristic的Descriptors灯蝴,讀到數(shù)據(jù)會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in service.characteristics){
[peripheral discoverDescriptorsForCharacteristic:characteristic];
}
}
//獲取的charateristic的值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
//打印出characteristic的UUID和值
//!注意,value的類(lèi)型是NSData孝宗,具體開(kāi)發(fā)時(shí)穷躁,會(huì)根據(jù)外設(shè)協(xié)議制定的方式去解析數(shù)據(jù)
NSLog(@"characteristic uuid:%@ value:%@",characteristic.UUID,characteristic.value);
}
//搜索到Characteristic的Descriptors
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
//打印出Characteristic和他的Descriptors
NSLog(@"characteristic uuid:%@",characteristic.UUID);
for (CBDescriptor *d in characteristic.descriptors) {
NSLog(@"Descriptor uuid:%@",d.UUID);
}
}
//獲取到Descriptors的值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error{
//打印出DescriptorsUUID 和value
//這個(gè)descriptor都是對(duì)于characteristic的描述,一般都是字符串碳褒,所以這里我們轉(zhuǎn)換成字符串去解析
NSLog(@"characteristic uuid:%@ value:%@",[NSString stringWithFormat:@"%@",descriptor.UUID],descriptor.value);
}
5.把數(shù)據(jù)寫(xiě)到Characteristic中
//寫(xiě)數(shù)據(jù)
-(void)writeCharacteristic:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic
value:(NSData *)value{
//打印出 characteristic 的權(quán)限折砸,可以看到有很多種看疗,這是一個(gè)NS_OPTIONS,就是可以同時(shí)用于好幾個(gè)值睦授,常見(jiàn)的有read两芳,write,notify去枷,indicate怖辆,知知道這幾個(gè)基本就夠用了,前連個(gè)是讀寫(xiě)權(quán)限删顶,后兩個(gè)都是通知竖螃,兩種不同的通知方式。
/*
typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
CBCharacteristicPropertyBroadcast = 0x01,
CBCharacteristicPropertyRead = 0x02,
CBCharacteristicPropertyWriteWithoutResponse = 0x04,
CBCharacteristicPropertyWrite = 0x08,
CBCharacteristicPropertyNotify = 0x10,
CBCharacteristicPropertyIndicate = 0x20,
CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,
CBCharacteristicPropertyExtendedProperties = 0x80,
CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x100,
CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x200
};
*/
NSLog(@"%lu", (unsigned long)characteristic.properties);
//只有 characteristic.properties 有write的權(quán)限才可以寫(xiě)
if(characteristic.properties & CBCharacteristicPropertyWrite){
/*
最好一個(gè)type參數(shù)可以為CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,區(qū)別是是否會(huì)有反饋
*/
[peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}else{
NSLog(@"該字段不可寫(xiě)逗余!");
}
}
6.訂閱Characteristic的通知
//設(shè)置通知
-(void)notifyCharacteristic:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic{
//設(shè)置通知特咆,數(shù)據(jù)通知會(huì)進(jìn)入:didUpdateValueForCharacteristic方法
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
//取消通知
-(void)cancelNotifyCharacteristic:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic{
[peripheral setNotifyValue:NO forCharacteristic:characteristic];
}
7.斷開(kāi)連接(disconnect)
//停止掃描并斷開(kāi)連接
-(void)disconnectPeripheral:(CBCentralManager *)centralManager
peripheral:(CBPeripheral *)peripheral{
//停止掃描
[centralManager stopScan];
//斷開(kāi)連接
[centralManager cancelPeripheralConnection:peripheral];
}
8 模擬器藍(lán)牙調(diào)試,慎用录粱,最好還是用真機(jī)去調(diào)試
由于在iPhone 4s之后的iOS才支持BLE腻格,新一代的這些iOS設(shè)備又都不便宜,在做測(cè)試的時(shí)候啥繁,用iOS模擬器進(jìn)行調(diào)試菜职,可以節(jié)約一些開(kāi)發(fā)成本。怎么在iOS模擬器上調(diào)試BLE旗闽,
蘋(píng)果最初給出的說(shuō)明是酬核,支持BLE的mac機(jī)子上可以用模擬器進(jìn)行調(diào)試,并給出了一份技術(shù)文檔(傳送門(mén))适室,惡心的是嫡意,后來(lái)蘋(píng)果抽風(fēng),又把這份文檔移除亭病,
并且把iOS 7.0的模擬器上對(duì)BLE的支持也移除掉了(難道是想讓大家多買(mǎi)設(shè)備測(cè)試鹅很?Apple sucks.)后面,網(wǎng)上搜了一下罪帖,解決辦法如下:
1. 買(mǎi)一個(gè)CSR藍(lán)牙4.0 USB適配器(某寶上大概30塊錢(qián))促煮,在機(jī)子上插入該物(你懂的)
2. 在Terminal下敲入sudo nvram bluetoothHostControllerSwitchBehavior="never" , 重啟Mac整袁。
3. 用XCode 4.6調(diào)試代碼菠齿,在iOS 6.1的模擬器上跑程序(用XCode 5.0跑iOS 7.0模擬器會(huì)拋異常,原因上面詳訴過(guò)了坐昙,Apple sucks绳匀,你懂的)
如何降低模擬器的IOS版本呢?
XCode->Preferences->Downloads里面有很多simulators你可以下載
選擇個(gè)6.1的下載好了