上一篇文章介绍了蓝牙的技术知识,这儿咱们详细阐明一下中心形式的运用场景。
主设备(手机去扫描衔接外设,发现外设服务和特点,操作服务和特点的运用。
一般来说,外设(蓝牙设备,比如智能手环之类的东西), 会由硬件工程师开发好,并定义好设备提供的服务,每个服务关于的特征,每个特征的特点(只读,只写,告诉等等)
本文比如的事务场景,便是用一手机app去读写蓝牙设备。
iOS衔接外设的代码完成流程
1. 树立中心角色
2. 扫描外设(discover)
3. 衔接外设(connect)
4. 扫描外设中的服务和特征(discover)
- 4.1 获取外设的services
- 4.2 获取外设的Characteristics,获取Characteristics的值,获取Characteristics的Descriptor和Descriptor的值
5. 与外设做数据交互(explore and interact)
6. 订阅Characteristic的告诉
7. 断开衔接(disconnect)
预备环境
1 xcode
2 开发证书和手机(蓝牙程序需要运用运用真机调试,运用模拟器也能够调试,但是办法很蛋疼,我会放在最终说)
3 蓝牙外设
完成过程
1 导入CoreBluetooth头文件,树立主设备管理类,设置主设备托付
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController : UIViewController<CBCentralManagerDelegate>
@interface ViewController (){
//系统蓝牙设备管理目标,能够把他理解为主设备,通过他,能够去扫描和链接外设
CBCentralManager *manager;
//用于保存被发现设备
NSMutableArray *peripherals;
}
- (void)viewDidLoad {
[super viewDidLoad];
/*
设置主设备的托付,CBCentralManagerDelegate
有必要完成的:
- (void)centralManagerDidUpdateState:(CBCentralManager *)central;//主设备状态改变的托付,在初始化CBCentralManager的合适会翻开设备,只有当设备正确翻开后才干运用
其他挑选完成的托付中比较重要的:
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //找到外设的托付
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//衔接外设成功的托付
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设衔接失利的托付
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设的托付
*/
//初始化并设置托付和线程行列,最好一个线程的参数能够为nil,默认会就main线程
manager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];
2 扫描外设(discover),扫描外设的办法咱们放在centralManager成功翻开的托付中,因为只有设备成功翻开,才干开端扫描,不然会报错。
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
switch (central.state) {
case CBCentralManagerStateUnknown:
NSLog(@">>>CBCentralManagerStateUnknown");
break;
case CBCentralManagerStateResetting:
NSLog(@">>>CBCentralManagerStateResetting");
break;
case CBCentralManagerStateUnsupported:
NSLog(@">>>CBCentralManagerStateUnsupported");
break;
case CBCentralManagerStateUnauthorized:
NSLog(@">>>CBCentralManagerStateUnauthorized");
break;
case CBCentralManagerStatePoweredOff:
NSLog(@">>>CBCentralManagerStatePoweredOff");
break;
case CBCentralManagerStatePoweredOn:
NSLog(@">>>CBCentralManagerStatePoweredOn");
//开端扫描周围的外设
/*
第一个参数nil便是扫描周围一切的外设,扫描到外设后会进入
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
*/
[manager scanForPeripheralsWithServices:nil options:nil];
break;
default:
break;
}
}
//扫描到设备会进入办法
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
NSLog(@"当扫描到设备:%@",peripheral.name);
//接下来能够衔接设备
}
3 衔接外设(connect)
//扫描到设备会进入办法
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
//接下衔接咱们的测验设备,假如你没有设备,能够下载一个app叫lightbule的app去模拟一个设备
//这儿自己去设置下衔接规则,我设置的是P最初的设备
if ([peripheral.name hasPrefix:@"P"]){
/*
一个主设备最多能连7个外设,每个外设最多只能给一个主设备衔接,衔接成功,失利,断开会进入各自的托付
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//衔接外设成功的托付
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设衔接失利的托付
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设的托付
*/
//找到的设备有必要持有它,不然CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的办法也不会被调用!!
[peripherals addObject:peripheral];
//衔接设备
[manager connectPeripheral:peripheral options:nil];
}
}
//衔接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@">>>衔接到名称为(%@)的设备-成功",peripheral.name);
}
//衔接到Peripherals-失利
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
NSLog(@">>>衔接到名称为(%@)的设备-失利,原因:%@",[peripheral name],[error localizedDescription]);
}
//Peripherals断开衔接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
NSLog(@">>>外设衔接断开衔接 %@: %@\n", [peripheral name], [error localizedDescription]);
}
有一点十分简单犯错,我们请注意。在didDiscoverPeripheral
这个托付中有这一行
//找到的设备有必要持有它,不然CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的办法也不会被调用!!
[peripherals addObject:peripheral];
请特别注意,假如不保存,会影响到后面的办法执行,这个地方许多人犯错,在我的蓝牙交流群中每天简直都会因为这个问题导致无法衔接和对外设后续的操作。
我们也能够看一下这个托付在xcode中的阐明,重点看@discussion中的内容,里面特别指出了需要retained目标。
/*!
* @method centralManager:didDiscoverPeripheral:advertisementData:RSSI:
*
* @param central The central manager providing this update.
* @param peripheral A <code>CBPeripheral</code> object.
* @param advertisementData A dictionary containing any advertisement and scan response data.
* @param RSSI The current RSSI of <i>peripheral</i>, in dBm. A value of <code>127</code> is reserved and indicates the RSSI
* was not available.
*
* @discussion This method is invoked while scanning, upon the discovery of <i>peripheral</i> by <i>central</i>. A discovered peripheral must
* be retained in order to use it; otherwise, it is assumed to not be of interest and will be cleaned up by the central manager. For
* a list of <i>advertisementData</i> keys, see {@link CBAdvertisementDataLocalNameKey} and other similar constants.
*
* @seealso CBAdvertisementData.h
*
*/
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI;
4 扫描外设中的服务和特征(discover)
- 设备衔接成功后,就能够扫描设备的服务了,同样是通过托付形式,扫描到成果后会进入托付办法。
- 但是这个托付已经不再是主设备的托付(CBCentralManagerDelegate),而是外设的托付(CBPeripheralDelegate),这个托付包含了主设备与外设交互的许多 回叫办法,包含获取services,获取characteristics,获取characteristics的值,获取characteristics的Descriptor,和Descriptor的值,写数据,读rssi,用告诉的方法订阅数据等等。
4.1获取外设的services
//衔接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@">>>衔接到名称为(%@)的设备-成功",peripheral.name);
//设置的peripheral托付CBPeripheralDelegate
//@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
[peripheral setDelegate:self];
//扫描外设Services,成功后会进入办法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
[peripheral discoverServices:nil];
}
//扫描到Services
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
// NSLog(@">>>扫描到服务:%@",peripheral.services);
if (error)
{
NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
return;
}
for (CBService *service in peripheral.services) {
NSLog(@"%@",service.UUID);
//扫描每个service的Characteristics,扫描到后会进入办法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
[peripheral discoverCharacteristics:nil forService:service];
}
}
4.2获取外设的Characteristics,获取Characteristics的值,获取Characteristics的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的值,读到数据会进入办法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in service.characteristics){
{
[peripheral readValueForCharacteristic:characteristic];
}
}
//搜索Characteristic的Descriptors,读到数据会进入办法:-(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的类型是NSData,详细开发时,会依据外设协议拟定的方法去解析数据
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
//这个descriptor都是关于characteristic的描绘,一般都是字符串,所以这儿咱们转换成字符串去解析
NSLog(@"characteristic uuid:%@ value:%@",[NSString stringWithFormat:@"%@",descriptor.UUID],descriptor.value);
}
5 把数据写到Characteristic中
//写数据
-(void)writeCharacteristic:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic
value:(NSData *)value{
//打印出 characteristic 的权限,能够看到有许多种,这是一个NS_OPTIONS,便是能够一起用于好几个值,常见的有read,write,notify,indicate,知知道这几个基本就够用了,前连个是读写权限,后两个都是告诉,两种不同的告诉方法。
/*
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的权限才干够写
if(characteristic.properties & CBCharacteristicPropertyWrite){
/*
最好一个type参数能够为CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,区别是是否会有反馈
*/
[peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}else{
NSLog(@"该字段不可写!");
}
}
6 订阅Characteristic的告诉
//设置告诉
-(void)notifyCharacteristic:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic{
//设置告诉,数据告诉会进入:didUpdateValueForCharacteristic办法
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
//撤销告诉
-(void)cancelNotifyCharacteristic:(CBPeripheral *)peripheral
characteristic:(CBCharacteristic *)characteristic{
[peripheral setNotifyValue:NO forCharacteristic:characteristic];
}
7 断开衔接(disconnect)
//中止扫描并断开衔接
-(void)disconnectPeripheral:(CBCentralManager *)centralManager
peripheral:(CBPeripheral *)peripheral{
//中止扫描
[centralManager stopScan];
//断开衔接
[centralManager cancelPeripheralConnection:peripheral];
}
8 模拟器蓝牙调试,慎用,最好还是用真机去调试。
因为在iPhone 4s之后的iOS才支撑BLE,新一代的这些iOS设备又都不便宜,在做测验的时候,用iOS模拟器进行调试,能够节约一些开发本钱。
怎么在iOS模拟器上调试BLE,
苹果最初给出的阐明是,支撑BLE的mac机子上能够用模拟器进行调试,并给出了一份技术文档(传送门),恶心的是,后来苹果抽风,又把这份文档移除,
并且把iOS 7.0的模拟器上对BLE的支撑也移除掉了(莫非是想让我们多买设备测验?Apple sucks.)后面,网上搜了一下,解决办法如下:
1. 买一个CSR蓝牙4.0 USB适配器(某宝上大概30块钱),在机子上插入该物(你懂的)
2. 在Terminal下敲入sudo nvram bluetoothHostControllerSwitchBehavior="never" , 重启Mac。
3. 用XCode 4.6调试代码,在iOS 6.1的模拟器上跑程序(用XCode 5.0跑iOS 7.0模拟器会抛反常,原因上面详诉过了,Apple sucks,你懂的)
怎么下降模拟器的IOS版别呢?
XCode->Preferences->Downloads里面有许多simulators你能够下载
挑选个6.1的下载好了
代码下载:
我博客中大部分示例代码都上传到了github,地址是:https://github.com/coolnameismy/demo
点击跳转代码下载地址
本文代码寄存目录是BleDemo