iOS - 蓝牙BLE4.0开发

打印 上一主题 下一主题

主题 866|帖子 866|积分 2598

1、蓝牙常见名称和缩写

   MFI :make for ipad ,iphone, itouch 专们为苹果装备制作的装备;
BLE: Bluetooth Low Energy,蓝牙4.0装备由于低耗电,所以也叫做BLE;
central:中心,发起连接的;
peripheral: 外设,被连接的装备;
service/characteristic:服务和特征 每个装备会提供服务和特征,雷同于服务端的api,但是机构不同。每个外设会有很多服务,每个服务中包含很多字段,这些字段的权限一样平常分为 读read,写write,关照notiy几种,就是我们连接装备后详细需要操纵的内容;
Description:每个characteristic可以对应一个或多个Description用户描述characteristic的信息或属性;
MFI:开发使用ExternalAccessory 框架;
BLE 4.0 :开发使用CoreBluetooth 框架;
  2、 蓝牙基础知识

CoreBluetooth框架的核心其实是两个东西:
外设和中心(peripheral and central):
可以明白成外设和中心。对应他们分别有一组干系的API和类。这两组api分别对应不同的业务场景,左侧叫做中心模式,就是以你的app作为中心,连接其他的外设的场景,而右侧称为外设模式,使用手机作为外设别其他中心装备操纵的场景。
服务和特征,特征的属性(service and characteristic):
每个装备都会有一些服务,每个服务里面都会有一些特征,特征就是详细键值对,提供数据的地方。每个特征属性分为这么几种:读,写,关照这么几种方式。
特征的界说罗列
  1. typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
  2.       CBCharacteristicPropertyBroadcast                                                                                                = 0x01,
  3.       CBCharacteristicPropertyRead                                                                                                        = 0x02,
  4.       CBCharacteristicPropertyWriteWithoutResponse                                                                        = 0x04,
  5.       CBCharacteristicPropertyWrite                                                                                                        = 0x08,
  6.       CBCharacteristicPropertyNotify                                                                                                        = 0x10,
  7.       CBCharacteristicPropertyIndicate                                                                                                = 0x20,
  8.       CBCharacteristicPropertyAuthenticatedSignedWrites                                                                = 0x40,
  9.       CBCharacteristicPropertyExtendedProperties                                                                                = 0x80,
  10.       CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)                = 0x100,
  11.       CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)        = 0x200
  12.   };
复制代码
2.1、蓝牙中心模式流程

   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)
  2.2、蓝牙外设模式流程 

   1. 启动一个Peripheral管理对象
2. 本地Peripheral设置服务,特性,描述,权限等等
3. Peripheral发送广告
4. 设置处理订阅、取消订阅、读characteristic、写characteristic的委托方法
   2.3、蓝牙装备状态

   1. 待机状态(standby):装备没有传输和发送数据,并且没有连接到任何设
2. 广播状态(Advertiser):周期性广播状态
3. 扫描状态(Scanner):主动寻找正在广播的装备
4. 发起链接状态(Initiator):主动向扫描装备发起连接。
5. 主装备(Master):作为主装备连接到其他装备。
6. 从装备(Slave):作为从装备连接到其他装备。
   2.4、蓝牙装备的五种工作状态

   准备(standby)
广播(advertising)
监听扫描(Scanning
发起连接(Initiating)
已连接(Connected)
  2.5、名词表明

   GAAT : Generic Attribute Profile , GATT设置文件是一个通用规范,用于在BLE链路上发送和吸收被称为“属性”的数据块。现在全部的BLE应用都基于GATT。 蓝牙SIG规定了很多低功耗装备的设置文件。设置文件是装备怎样在特定的应用步伐中工作的规格分析。注意一个装备可以实现多个设置文件。例如,一个装备可能包括心率监测仪和电量检测。
Characteristic 一个characteristic包括一个单一变量和0-n个用来描述characteristic变量的descriptor,characteristic可以被认为是一个类型,类 似于类。
Descriptor Descriptor用来描述characteristic变量的属性。例如,一个descriptor可以规定一个可读的描述,或者一个characteristic变量可接受的范围,或者一个characteristic变量特定的丈量单位。 Service service是characteristic的聚集。例如,你可能有一个叫“Heart Rate Monitor(心率监测仪)”的service,它包括了很多characteristics,如“heart rate measurement(心率丈量)”等。你可以在bluetooth.org 找到一个现在支持的基于GATT的设置文件和服务列表。
   3、实现步调

 1、导入CoreBluetooth头文件,建立主装备管理类,设置主装备委托;
  1. #import <CoreBluetooth/CoreBluetooth.h>
  2. @property (nonatomic,strong) CBCentralManager *manager;
  3. @property (nonatomic,strong) CBPeripheral *peripheral;
  4. @property (nonatomic,strong) CBCharacteristic *writeCharacteristic;
  5. @property (nonatomic,strong) NSDictionary *options;
  6. - (void)viewDidLoad
  7. {
  8.     [super viewDidLoad];
  9.    
  10.     self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
  11.     self.options = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithBool:YES], CBCentralManagerScanOptionAllowDuplicatesKey,nil];
  12. }
复制代码
2、扫描外设(discover),扫描外设的方法我们放在centralManager成功打开的委托中,由于只有装备成功打开,才气开始扫描。
  1. - (void)centralManagerDidUpdateState:(CBCentralManager *)central
  2. {
  3.     switch (central.state) {
  4.         case CBCentralManagerStateUnknown:
  5.             NSLog(@">>>CBCentralManagerStateUnknown");
  6.             break;
  7.         case CBCentralManagerStateResetting:
  8.             NSLog(@">>>CBCentralManagerStateResetting");
  9.             break;
  10.         case CBCentralManagerStateUnsupported:
  11.             NSLog(@">>>CBCentralManagerStateUnsupported");
  12.             break;
  13.         case CBCentralManagerStateUnauthorized:
  14.             NSLog(@">>>CBCentralManagerStateUnauthorized");
  15.             break;
  16.         case CBCentralManagerStatePoweredOff:
  17.             NSLog(@">>>CBCentralManagerStatePoweredOff");
  18.             break;
  19.         case CBCentralManagerStatePoweredOn:
  20.             NSLog(@">>>CBCentralManagerStatePoweredOn");
  21.             
  22.             //开始扫描周围的外设
  23.             /* 第一个参数nil就是扫描周围所有的外设,扫描到外设后会进入
  24.             - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; */
  25.             [self.manager scanForPeripheralsWithServices:nil options:nil];
  26.             break;
  27.         default:
  28.             break;
  29.          }
  30. }
  31. //扫描到设备会进入方法
  32. - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
  33. {
  34.     NSLog(@"当扫描到设备:%@",peripheral.name);
  35.     //接下来可以连接设备
  36. }
复制代码
3、连接外设(connect) 
  1. // 扫描到设备会进入方法
  2. - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
  3. {
  4.     if ([peripheral.name hasPrefix:@"xxxx"])
  5.     {
  6.         /*
  7.             一个主设备最多能连7个外设,每个外设最多只能给一个主设备连接,连接成功,失败,断开会进入各自的委托
  8.          - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功的委托
  9.          - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设连接失败的委托
  10.          - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设的委托
  11.          */
  12.         // 找到的设备必须持有它,否则CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的方法也不会被调用!!
  13.         [peripherals addObject:peripheral];
  14.         //连接设备
  15.         [manager connectPeripheral:peripheral options:nil];
  16.     }
  17. }
  18. // 连接到Peripherals-成功
  19. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
  20. {
  21.     NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
  22. }
  23. // 连接到Peripherals-失败
  24. - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
  25. {
  26.     NSLog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);
  27. }
  28. // Peripherals断开连接
  29. - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
  30. {
  31.     NSLog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizedDescription]);
  32. }
复制代码
有一点非常容易堕落,大家请注意。在didDiscoverPeripheral这个委托中有这一行
 
  1. //找到的设备必须持有它,否则CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的方法也不会被调用!!
  2. [peripherals addObject:peripheral];
复制代码
 4、扫描外设中的服务和特征(discover)
 装备连接成功后,就可以扫描装备的服务了,同样是通过委托形式,扫描到结果后会进入委托方法。但是这个委托已经不再是主装备的委托(CBCentralManagerDelegate),而是外设的委托(CBPeripheralDelegate),这个委托包含了主装备与外设交互的很多 回叫方法,包括获取services,获取characteristics,获取characteristics的值,获取characteristics的Descriptor,和Descriptor的值,写数据,读rssi,用关照的方式订阅数据等等。
4.1. 获取外设的services
  1. // 连接到Peripherals-成功
  2. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
  3. {
  4.     NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
  5.     //设置的peripheral委托CBPeripheralDelegate
  6.     //@interface ViewController : UIViewController
  7.     [peripheral setDelegate:self];
  8.     //扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
  9.     [peripheral discoverServices:nil];
  10. }
  11.         
  12. // 扫描到Services
  13. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
  14. {
  15.     //  NSLog(@">>>扫描到服务:%@",peripheral.services);
  16.     if (error) {
  17.         NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
  18.         return;
  19.     }
  20.     for (CBService *service in peripheral.services) {
  21.         NSLog(@"%@",service.UUID);
  22.         //扫描每个service的Characteristics,扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
  23.       
  24.         [peripheral discoverCharacteristics:nil forService:service];
  25.     }
  26. }
复制代码
 4.2、获取外设的Characteristics,获取Characteristics的值,获取Characteristics的Descriptor和Descriptor的值
  1. // 扫描到Characteristics
  2. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
  3. {
  4.     if (error) {
  5.         NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
  6.         return;
  7.     }
  8.     for (CBCharacteristic *characteristic in service.characteristics) {
  9.         NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);
  10.     }
  11.     //获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  12.     for (CBCharacteristic *characteristic in service.characteristics) {
  13.         [peripheral readValueForCharacteristic:characteristic];
  14.     }
  15.     //搜索Characteristic的Descriptors,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  16.     for (CBCharacteristic *characteristic in service.characteristics) {
  17.         [peripheral discoverDescriptorsForCharacteristic:characteristic];
  18.     }
  19. }
  20. // 获取的charateristic的值
  21. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  22. {
  23.     //打印出characteristic的UUID和值
  24.     //!注意,value的类型是NSData,具体开发时,会根据外设协议制定的方式去解析数据
  25.     NSLog(@"characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);
  26. }
  27. // 搜索到Characteristic的Descriptors
  28. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
  29. {
  30.     // 打印出Characteristic和他的Descriptors
  31.     NSLog(@"characteristic uuid:%@",characteristic.UUID);
  32.     for (CBDescriptor *d in characteristic.descriptors) {
  33.         NSLog(@"Descriptor uuid:%@",d.UUID);
  34.     }
  35. }
  36. // 获取到Descriptors的值
  37. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
  38. {
  39.     // 打印出DescriptorsUUID 和value
  40.     // 这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析
  41.     NSLog(@"characteristic uuid:%@  value:%@",[NSString stringWithFormat:@"%@",descriptor.UUID],descriptor.value);
  42. }
复制代码
5、把数据写到Characteristic中
  1. //写数据
  2. - (void)writeCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic value:(NSData *)value
  3. {
  4.     NSLog(@"%lu", (unsigned long)characteristic.properties);
  5.     // 只有 characteristic.properties 有write的权限才可以写
  6.     if(characteristic.properties & CBCharacteristicPropertyWrite) {
  7.         [peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
  8.     } else {
  9.         NSLog(@"该字段不可写!");
  10.     }
  11. }
复制代码
6、订阅Characteristic的关照 
  1. // 设置通知
  2. - (void)notifyCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic
  3. {
  4.     // 设置通知,数据通知会进入:didUpdateValueForCharacteristic方法
  5.     [peripheral setNotifyValue:YES forCharacteristic:characteristic];
  6. }
  7. // 取消通知
  8. - (void)cancelNotifyCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic
  9. {
  10.     [peripheral setNotifyValue:NO forCharacteristic:characteristic];
  11. }
复制代码
 7、断开连接(disconnect)
  1. // 停止扫描并断开连接
  2. -(void)disconnectPeripheral:(CBCentralManager *)centralManager peripheral:(CBPeripheral *)peripheral
  3. {
  4.     //停止扫描
  5.     [centralManager stopScan];
  6.     //断开连接
  7.     [centralManager cancelPeripheralConnection:peripheral];
  8. }
复制代码
8、代码下载: 
 示例代码都上传到了github,地点是:https://github.com/coolnameismy/demo​​​​​​​
注:本文为转载,详细转载于哪位老师,时间太久不记得了,请通过GitHub地点,找寻作者。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

飞不高

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表