CoreBluetooth:baseK,中心模式,外设模式流程,iBeacon

baseK(相关基础知识)

蓝牙常见名称和缩写

  • BLE:(Bluetooth low energy)蓝牙4.0设备因为低耗电,也叫BLE
  • peripheral,central:外设和中心设备,发起链接的是central(一般是指手机),被链接的设备是peripheral(运动手环)
  • service and characteristic:(服务和特征)每个设备会提供服务和特征,类似于服务端的API,但是结构不同.每个设备会有很多服务,每个服务中包含很多字段,这些字段的权限一般分为读(read),写(write),通知(notify)几种,就是我们连接设备后具体需要操作的内容
  • Description:每个characteristic可以对应一个或者多个Description用于描述characteristic的信息或属性(eg.范围,计量单位)

蓝牙基础知识

  • CoreBluetooth框架的核心其实是俩东西:peripheral和central,对应他们分别有一组相关的API和类 


  • 这两组api粉笔对应不同的业务常见:左侧叫中心模式,就是以你的app作为中心,连接其他的外设的场景;而右侧称为外设模式,使用手机作为外设连接其他中心设备操作的场景

  • 服务和特征(service and characteristic)

    • 每个设备都会有1个or多个服务
    • 每个服务里都会有1个or多个特征
    • 特征就是具体键值对,提供数据的地方
    • 每个特征属性分为:读,写,通知等等
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
};
  • 外设,服务,特征的关系 

BLE中心模式流程

  • 1.建立中心角色
  • 2.扫描外设(Discover Peripheral)
  • 3.连接外设(Connect Peripheral)
  • 4.扫描外设中的服务和特征(Discover Services And Characteristics)
    • 4.1 获取外设的services
    • 4.2 获取外设的Characteristics,获取characteristics的值,,获取Characteristics的Descriptor和Descriptor的值
  • 5.利用特征与外设做数据交互(Explore And Interact)
  • 6.订阅Characteristic的通知
  • 7.断开连接(Disconnect)

BLE外设模式流程

  • 1.启动一个Peripheral管理对象
  • 2.本地peripheral设置服务,特征,描述,权限等等
  • 3.peripheral发送广告
  • 4.设置处理订阅,取消订阅,读characteristic,写characteristic的代理方法

蓝牙设备的状态

  • 1.待机状态(standby):设备没有传输和发送数据,并且没有连接到任何外设
  • 2.广播状态(Advertiser):周期性广播状态
  • 3.扫描状态(Scanner):主动搜索正在广播的设备
  • 4.发起链接状态(Initiator):主动向扫描设备发起连接
  • 5.主设备(Master):作为主设备连接到其它设备.
  • 6.从设备(Slave):作为从设备链接到其它设备

蓝牙设备的五种工作状态

  • 准备(Standby)
  • 广播(Advertising)
  • 监听扫描(Scanning)
  • 发起连接(Initiating)
  • 已连接(Connected)

蓝牙和版本使用限制

  • 蓝牙2.0:越狱设备
  • BLE:iOS6以上
  • MFI认证设备:无限制

BLE测试

  • 两台BLE设备
  • 如何让iOS模拟器也能测试BLE?
    • 买一个CSR蓝牙4.0 USB适配器,插在Mac上
    • 在终端输入sudo nvram bluetoothHostControllerSwitchBehavior="never"
    • 重启Mac
    • 用Xcode4.6调试代码,将程序跑在iOS6.1模拟器上
    • 苹果把iOS7.0模拟器对BLE的支持移除了

    • BLE中心模式流程-coding

      BLE中心模式流程

      • 1.建立中心角色
      • 2.扫描外设(Discover Peripheral)
      • 3.连接外设(Connect Peripheral)
      • 4.扫描外设中的服务和特征(Discover Services And Characteristics)
        • 4.1 获取外设的services
        • 4.2 获取外设的Characteristics,获取characteristics的值,,获取Characteristics的Descriptor和Descriptor的值
      • 5.利用特征与外设做数据交互(Explore And Interact)
      • 6.订阅Characteristic的通知
      • 7.断开连接(Disconnect)

      准备环境

      • 1.Xcode7.0
      • 2.手机
      • 3.外设(手机+LightBlue)

      实现步骤

      1.导入CB头文件,建立主设备管理类,设置主设备代理

      #import <CoreBluetooth/CoreBluetooth.h>
      @interface XMGBLEController () <CBCentralManagerDelegate>
      @property (nonatomic, strong) CBCentralManager *cMgr; /**< 中心管理设备 */
      @end
      @implementation XMGBLEController
      #pragma mark - 懒加载
      // 1.建立中心管理者
      - (CBCentralManager *)cMgr
      {
          if (!_cMgr) {
              NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
              /*
               设置主设备的代理,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;//断开外设
               */
              _cMgr = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()]; // 线程不传默认是主线程
          }
          return _cMgr;
      }
      - (void)viewDidLoad {
          [super viewDidLoad];
          self.title = @"BLE";
          self.view.backgroundColor = [UIColor orangeColor];
          // 初始化
          [self cMgr];
          // 不能在此处扫描,因为状态还没变为打开
          //[self.cMgr scanForPeripheralsWithServices:nil options:nil];
      }
      

      2.扫描外设

      • 扫描的方法防治cMgr成功打开的代理方法中
      • 只有设备成功打开,才能开始扫描,否则会报错
      #pragma mark - CBCentralManagerDelegate
      // 中心管理者状态改变, 在初始化CBCentralManager的时候会打开设备,只有当设备正确打开后才能使用
      - (void)centralManagerDidUpdateState:(CBCentralManager *)central
      {
          NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
          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");
                  // 2.开始扫描周围的外设
                  /*
                   第一个参数nil就是扫描周围所有的外设,扫描到外设后会进入
                   - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
                   */
                  [self.cMgr scanForPeripheralsWithServices:nil options:nil];
      
                  break;
              default:
              break;
          }
      }
      // 扫描到设备会进入到此代理方法
      - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
      {
          NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);
          // 接下来连接设备
      }
      

      3.连接外设

      • 扫描手环,打印结果 

      • 根据打印结果
      // 扫描到设备会进入到此代理方法
      - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
      {
          NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);
      
          // 3.接下来可以连接设备
          //如果你没有设备,可以下载一个app叫lightbule的app去模拟一个设备
          //这里自己去设置下连接规则,我设置的是二维码扫描到的运动手环的设备号
          // 判断设备号是否扫描到
          if ([peripheral.name isEqualToString:@"OBand-75"]) {
              /*
               一个主设备最多能连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;//断开外设的委托
               */
              // 保存外设,否则方法结束就销毁
              self.per = peripheral;
              [self.cMgr connectPeripheral:self.per options:nil];
          }else
          {
              // 此处Alert提示未扫描到设备,重新扫描
      #warning noCode
              NSLog(@"没扫描到 >>>>>>>>  %s, line = %d", __FUNCTION__, __LINE__);
          }
      }
      // 外设连接成功
      - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
      {
          NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
          NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
      }
      // 外设连接失败
      - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
      {
          NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
      }
      // 断开连接(丢失连接)
      - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
      {
          NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
      }
      

      4.扫描外设中的服务和特征

        设备链接成功后,就可以扫描设备的服务(services)了,同样是通过代理,扫描到结果后会触发某代理方法.
        注意:此时CBCentralManagerDelegate已经不能满足需求,需要新的CBPeripheralDelegate来搞定.
        该协议中包含了central与peripheral的许多回调方法
        (eg.:获取services,获取characteristics,获取characteristics的值,获取characteristics的Descriptor以及Descriptor的值,写数据,读RSSI,用通知的方式订阅数据等等).
      
      • 4.1 获取外设的services
        • 首先设置外设的代理,并搜寻services
        • 然后在代理方法peripheral:didDiscoverServices:中遍历services
      // 外设连接成功
      - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
      {
          NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
          NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
          //设置的peripheral代理CBPeripheralDelegate
          //@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
          [peripheral setDelegate:self];
      
          //扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
          [peripheral discoverServices:nil];
          /*
           Discovers the specified services of the peripheral.
           An array of CBUUID objects that you are interested in. Here, each CBUUID object represents a UUID that identifies the type of service you want to discover.
           */
      }
      
      #pragma mark - CBPeripheralDelegate
      // 发现外设的service
      - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
      {
          if (error)
          {
              NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
              return;
          }
      
          for (CBService *service in peripheral.services) {
              NSLog(@"service.UUID = %@", service.UUID);
              //扫描每个service的Characteristics,扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
              [peripheral discoverCharacteristics:nil forService:service];
          }
      }
      
      • 4.2 获取外设的characteris,获取Characteristics的值,获取Characteristics的Descriptor以及Descriptor的值
      // 外设发现service的特征
      - (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);
          }
      
      #warning noCodeFor 优化,分开写是为了让大家看注释清晰,并不符合编码规范
          //获取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]; // 外设发现特征的描述
          }
      }
      
      // 获取characteristic的值
      - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
      {
          //打印出characteristic的UUID和值
          //!注意,value的类型是NSData,具体开发时,会根据外设协议制定的方式去解析数据
          NSLog(@"%s, line = %d, characteristic.UUID:%@  value:%@", __FUNCTION__, __LINE__, characteristic.UUID, characteristic.value);
      }
      // 获取Characteristics的 descriptor的值
      - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(nonnull CBDescriptor *)descriptor error:(nullable NSError *)error
      {
          //打印出DescriptorsUUID 和value
          //这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析
          NSLog(@"%s, line = %d, descriptor.UUID:%@ value:%@", __FUNCTION__, __LINE__, descriptor.UUID, descriptor.value);
      }
      // 发现特征Characteristics的描述Descriptor
      - (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
      {
          NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
          for (CBDescriptor *descriptor in characteristic.descriptors) {
              NSLog(@"descriptor.UUID:%@",descriptor.UUID);
          }
      }
      

      5.写数据到特征中

      // 5.将数据写入特征(自定义方法,为了看的更清楚,没别的意思)
      - (void)yf_peripheral:(CBPeripheral *)peripheral writeData:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic
      {
          /*
          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
          };
           打印出特征的权限(characteristic.properties),可以看到有很多种,这是一个NS_OPTIONS的枚举,可以是多个值
           常见的又read,write,noitfy,indicate.知道这几个基本够用了,前俩是读写权限,后俩都是通知,俩不同的通知方式
           */
          NSLog(@"%s, line = %d, characteristic.properties:%d", __FUNCTION__, __LINE__, characteristic.properties);
      
          // 只有特征的properties中有写的属性时候,才写
          if (characteristic.properties & CBCharacteristicPropertyWrite) {
              // 这句才是正宗的核心代码
              [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
          }
      }
      

      6.订阅特征的通知

      // 设置通知
      - (void)yf_peripheral:(CBPeripheral *)peripheral setNotifyForCharacteristic:(CBCharacteristic *)characteristic
      {
          // 设置通知, 数据会进入 peripheral:didUpdateValueForCharacteristic:error:方法
          [peripheral setNotifyValue:YES forCharacteristic:characteristic];
      }
      // 取消通知
      - (void)yf_peripheral:(CBPeripheral *)peripheral cancelNotifyForCharacteristic:(CBCharacteristic *)characteristic
      {
          [peripheral setNotifyValue:NO forCharacteristic:characteristic];
      }
      

      7.断开连接

      // 7.断开连接
      - (void)yf_cMgr:(CBCentralManager *)cMgr stopScanAndDisConnectWithPeripheral:(CBPeripheral *)peripheral
      {
          // 停止扫描
          [cMgr stopScan];
          // 断开连接
          [cMgr cancelPeripheralConnection:peripheral];
      }

      BLE-periphral外设模式流程

      之前在基础知识介绍过BLE应用的两种流程,如图:


      • central模式用的都是左边的类,而peripheral模式用的是右边的类

      peripheral模式的流程

      • 1.引入CoreBluetooth框架,初始化peripheralManager
      • 2.设置peripheralManager中的内容
      • 3.开启广播advertising
      • 4.对central的操作进行响应
        • 4.1 读characteristics请求
        • 4.2 写characteristics请求
        • 4.4 订阅和取消订阅characteristics

      准备环境

      • Xcode
      • 真机(4s以上)

      具体操作步骤

      1.引入CoreBluetooth框架,初始化peripheralManager

      #import <CoreBluetooth/CoreBluetooth.h>
      @interface XMGBLEPeripheralViewController () <CBPeripheralManagerDelegate>
      @property (nonatomic, strong) CBPeripheralManager *pMgr; /**< 外设管理者 */
      @end
      
      @implementation XMGBLEPeripheralViewController
      // 懒加载
      - (CBPeripheralManager *)pMgr
      {
          if (!_pMgr) {
              _pMgr = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
          }
          return _pMgr;
      }
      
      - (void)viewDidLoad {
          [super viewDidLoad];
          // 调用get方法初始化,初始化后CBPeripheralManager状态改变会调用代理方法peripheralManagerDidUpdateState:
          // 模拟器永远也不会是CBPeripheralManagerStatePoweredOn状态
          [self pMgr];
      }
      

      2.设置peripheralManager中的内容

      • 创建characteristics及其description,
      • 创建service,把characteristics添加到service中,
      • 再把service添加到peripheralManager中
      #pragma mark - CBPeripheralManagerDelegate
      // CBPeripheralManager初始化后会触发的方法
      - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
      {
          if (peripheral.state == CBPeripheralManagerStatePoweredOn) {
              // 提示设备成功打开
              [SVProgressHUD showSuccessWithStatus:@"xmg设备打开成功~"];
              // 配置各种服务入CBPeripheralManager
              [self yf_setupPMgr];
          }else
          {
              // 提示设备打开失败
              [SVProgressHUD showErrorWithStatus:@"失败!"];
          }
      }
      
      #pragma mark - 私有方法
      - (void)yf_setupPMgr
      {
          // 特征描述的UUID
          CBUUID *characteristicUserDescriptionUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];
          // 特征的通知UUID
          CBUUID *notifyCharacteristicUUID = [CBUUID UUIDWithString:notiyCharacteristicStrUUID];
          // 特征的读写UUID
          CBUUID *readwriteCharacteristicUUID = [CBUUID UUIDWithString:readwriteCharacteristicStrUUID];
          // 特征的只读UUID
          CBUUID *readCharacteristicUUID = [CBUUID UUIDWithString:readwriteCharacteristicStrUUID];
          CBUUID *ser1UUID = [CBUUID UUIDWithString:Service1StrUUID];
          CBUUID *ser2UUID = [CBUUID UUIDWithString:Service2StrUUID];
      
      
          // 初始化一个特征的描述
          CBMutableDescriptor *des1 = [[CBMutableDescriptor alloc] initWithType:characteristicUserDescriptionUUID value:@"xmgDes1"];
      
          // 可通知的特征
          CBMutableCharacteristic *notifyCharacteristic = [[CBMutableCharacteristic alloc] initWithType:notifyCharacteristicUUID // UUID
                                                                                             properties:CBCharacteristicPropertyNotify // 枚举:通知
                                                                                                  value:nil // 数据先不传
                                                                                            permissions:CBAttributePermissionsReadable]; // 枚举:可读
          // 可读写的特征
          CBMutableCharacteristic *readwriteChar = [[CBMutableCharacteristic alloc] initWithType:readwriteCharacteristicUUID
                                                                                      properties:CBCharacteristicPropertyRead | CBCharacteristicPropertyWrite
                                                                                           value:nil
                                                                                     permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
          [readwriteChar setDescriptors:@[des1]]; // 设置特征的描述
      
          // 只读特征
          CBMutableCharacteristic *readChar = [[CBMutableCharacteristic alloc] initWithType:readCharacteristicUUID
                                                                                 properties:CBCharacteristicPropertyRead
                                                                                      value:nil
                                                                                permissions:CBAttributePermissionsReadable];
      
          // 初始化服务1
          CBMutableService *ser1 = [[CBMutableService alloc] initWithType:ser1UUID primary:YES];
          // 为服务设置俩特征(通知, 带描述的读写)
          [ser1 setCharacteristics:@[notifyCharacteristic, readwriteChar]];
      
          // 初始化服务2,并且添加一个只读特征
          CBMutableService *ser2 = [[CBMutableService alloc] initWithType:ser2UUID primary:YES];
          ser2.characteristics = @[readChar];
      
          // 添加服务进外设管理者
          // 添加操作会触发代理方法peripheralManager:didAddService:error:
          [self.pMgr addService:ser1];
          [self.pMgr addService:ser2];
      }
      

      3.开启广播

      // 添加服务进CBPeripheralManager时会触发的方法
      - (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
      {
          // 由于添加了两次ser,所以方法会调用两次
          static int i = 0;
          if (!error) {
              i++;
          }
      
          // 当第二次进入方法时候,代表两个服务添加完毕,此时要用到2,由于没有扩展性,所以新增了可变数组,记录添加的服务数量
          if (i == self.servieces.count) {
              // 广播内容
              NSDictionary *advertDict = @{CBAdvertisementDataServiceUUIDsKey: [self.servieces valueForKeyPath:@"UUID"],
                                           CBAdvertisementDataLocalNameKey:LocalNameKey};
              // 发出广播,会触发peripheralManagerDidStartAdvertising:error:
              [peripheral startAdvertising:advertDict];
          }
      }
      // 开始广播触发的代理
      - (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
      {
      
      }
      
      >>>>>>>>分割线>>>>下面是修改的地方
      
      @property (nonatomic, strong) NSMutableArray *servieces; /**< 服务可变数组 */
      // 自定义服务
      - (NSMutableArray *)servieces
      {
          if (!_servieces) {
              _servieces = [NSMutableArray array];
          }
          return _servieces;
      }
      #pragma mark - 私有方法
      - (void)yf_setupPMgr
      {
          ...
      
          // 初始化服务1
          CBMutableService *ser1 = [[CBMutableService alloc] initWithType:ser1UUID primary:YES];
          // 为服务设置俩特征(通知, 带描述的读写)
          [ser1 setCharacteristics:@[notifyCharacteristic, readwriteChar]];
          [self.servieces addObject:ser1];
      
          // 初始化服务2,并且添加一个只读特征
          CBMutableService *ser2 = [[CBMutableService alloc] initWithType:ser2UUID primary:YES];
          ser2.characteristics = @[readChar];
          [self.servieces addObject:ser2];
      
          // 添加服务进外设管理者
          // 添加操作会触发代理方法peripheralManager:didAddService:error:
          if (self.servieces.count) {
              for (CBMutableService *ser in self.servieces) {
                  [self.pMgr addService:ser];
              }
          }
      }
      

      4.对central的操作做出响应

      • 4.1 读characteristics请求
      • 4.2 写characteristics请求
      • 4.3 订阅和取消订阅characteristics
      // 外设收到读的请求,然后读特征的值赋值给request
      - (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request
      {
          NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
          // 判断是否可读
          if (request.characteristic.properties & CBCharacteristicPropertyRead) {
              NSData *data = request.characteristic.value;
      
              request.value = data;
              // 对请求成功做出响应
              [self.pMgr respondToRequest:request withResult:CBATTErrorSuccess];
          }else
          {
              [self.pMgr respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
          }
      }
      // 外设收到写的请求,然后读request的值,写给特征
      - (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests
      {
          NSLog(@"%s, line = %d, requests = %@", __FUNCTION__, __LINE__, requests);
          CBATTRequest *request = requests.firstObject;
          if (request.characteristic.properties & CBCharacteristicPropertyWrite) {
              NSData *data = request.value;
              // 此处赋值要转类型,否则报错
              CBMutableCharacteristic *mChar = (CBMutableCharacteristic *)request.characteristic;
              mChar.value = data;
              // 对请求成功做出响应
              [self.pMgr respondToRequest:request withResult:CBATTErrorSuccess];
          }else
          {
              [self.pMgr respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
          }
      }
      
      
      // 与CBCentral的交互
      // 订阅特征
      - (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic
      {
          NSLog(@"%s, line = %d, 订阅了%@的数据", __FUNCTION__, __LINE__, characteristic.UUID);
          NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0
                                                            target:self
                                                          selector:@selector(yf_sendData:)
                                                          userInfo:characteristic
                                                           repeats:YES];
      
          self.timer = timer;
      
          /* 另一种方法 */
      //    NSTimer *testTimer = [NSTimer timerWithTimeInterval:2.0
      //                                                 target:self
      //                                               selector:@selector(yf_sendData:)
      //                                               userInfo:characteristic
      //                                                repeats:YES];
      //    [[NSRunLoop currentRunLoop] addTimer:testTimer forMode:NSDefaultRunLoopMode];
      
      }
      // 取消订阅特征
      - (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic
      {
          NSLog(@"%s, line = %d, 取消订阅了%@的数据", __FUNCTION__, __LINE__, characteristic.UUID);
          [self.timer invalidate];
          self.timer = nil;
      }
      
      - (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral
      {
          NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
      }
      
      // 计时器每隔两秒调用的方法
      - (BOOL)yf_sendData:(NSTimer *)timer
      {
          NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
          dateFormatter.dateFormat = @"yy:MM:dd:HH:mm:ss";
      
          NSString *now = [dateFormatter stringFromDate:[NSDate date]];
          NSLog(@"now = %@", now);
      
          // 执行回应central通知数据
          return  [self.pMgr updateValue:[now dataUsingEncoding:NSUTF8StringEncoding]
               forCharacteristic:timer.userInfo
            onSubscribedCentrals:nil];
      }

      iBeacon简介

      • iBeacon起源:苹果在WWDC2013上正式推出了iBeacon,并且在iOS7设备商配置了该功能
      • iBeacon应用:苹果期望将其作为一种技术标准,这个标准允许移动App(包括iOS和Android设备)监听来自于iBeacon设备上的信号并作出响应.
      • iBeacon设备:配备有BLE通信功能,并使用BLE向周围发送自己特有的ID,移动设备上的App在接收到该ID后可以作出相应的反应.比如,我们在店铺里设置iBeacon发射器,便可以让应用接收到信息并将这一信息通知给服务器,服务器向我们的App返回与该店铺相关的产品或折扣信息.
      • 本质上讲,iBeacon技术允许App了解他们在某个局部范围内的位置,并向用户分发基于位置的超文本上下文内容.

      简单开发流程

      • 1.初始化iBeacon的区域,以及区域管理者
      #import <CoreLocation/CoreLocation.h>
      
      @interface AppDelegate () <CLLocationManagerDelegate>
      
      @property (nonatomic, strong) CLBeaconRegion *beaconRegion; /**< beacon区域 */
      
      @property (nonatomic, strong) CLLocationManager *locMgr; /**< 位置管理者 */
      
      @end
      
      @implementation AppDelegate
      #pragma mark - lazy
      // 懒加载iBeacon区域
      - (CLBeaconRegion *)beaconRegion
      {
          if (!_beaconRegion) {
              NSUUID *proximityUUID = [[NSUUID alloc] initWithUUIDString:@"416C0120-5960-4280-A67C-A2A9BB166D0F"];
              _beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:proximityUUID
                                                                 identifier:@"brID"];
              /**
               *  一个App为了在特定商场提⾼高⽤用户体验,可⽤用使⽤用相同的proximity UUID来监听商场的所有商铺。当⽤用户进⼊入⼀一个商店时,App检测商铺的iBeacon设备并使⽤用major和 minor值来获取额外的信息,如⽤用户进⼊入哪家商店或⽤用户在商店的哪个区域(注意:虽然每个iBeacon都必须有⼀一个proximity UUID,但 major和minor的值是可选的)。
               */
          }
          return _beaconRegion;
      }
      
      // 懒加载创建地域管理者
      - (CLLocationManager *)locMgr
      {
          if (!_locMgr) {
              _locMgr = [[CLLocationManager alloc] init];
              _locMgr.delegate = self;
          }
          return _locMgr;
      }
      
      • 2.进入退出时候的操作
      #pragma mark - CLLocationManagerDelegate
      
      // 开始监听
      - (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region
      {
          NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
      }
      
      // 进入监控的region区域
      - (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
      {
          if ([region isEqual:self.beaconRegion]) {
              // Start calculating ranges for beacons in the specified region.
              // 开始计算beaconRegion区域内部的iBeacon设备数量,确定我们的设备与区域中的一个或多个iBeacon设备的相对距离,并在距离改变时被通知,触发代理 didRangeBeacons
              [self.locMgr startRangingBeaconsInRegion:self.beaconRegion];
      
              NSDictionary *info = [self.beaconRegion peripheralDataWithMeasuredPower:@0];
              // 通知外设开启广播
              [[NSNotificationCenter defaultCenter] postNotificationName:@"didEnterRegionNotification" object:nil userInfo:info];
          }
      
      }
      // 退出监控的region区域
      - (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
      {
          // 外设关闭广播
          // 通知外设开启广播
          [[NSNotificationCenter defaultCenter] postNotificationName:@"didExitRegionNotification" object:nil];
      }
      
      // 当指定Beacon区域的iBeacon设备进⼊入范围、离开范围或相对距离改变时,CLLocationManager对象调⽤用代理对象的 locationManager:didRangeBeacons:inRegion:
      - (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray<CLBeacon *> *)beacons inRegion:(CLBeaconRegion *)region
      {
          // beacons表⽰示当前设备范围内的iBeacon。
          // iBeacon的数组根据离设备的相对距离来排序,最近的在最前⾯面。
          // 我们可以使⽤用这些对象中的信息来确定⽤用户离每个iBeacon设备的距离。 CLBeacon对象(数组元素)的proximity属性给出了(手机)到⼀一个beacon的相对距离
          // 注意:iBeacon的排列依赖于检测到的BLE⽆无线信号的强度,以及这些信号受墙壁、门或其它物理实体的影响。当我们使⽤用iBeacon时需要考虑 这些影响因素。
          if (beacons.count) {
              for (NSInteger i = 0; i < beacons.count; i++) {
                  CLBeacon *beacon = beacons[i];
                  /**
                   *  typedef NS_ENUM(NSInteger, CLProximity) {
                   CLProximityUnknown,
                   CLProximityImmediate,
                   CLProximityNear,
                   CLProximityFar
                   } NS_ENUM_AVAILABLE_IOS(7_0) __WATCHOS_PROHIBITED;
                   */
                  if (beacon.proximity == CLProximityNear) {
                      NSLog(@"major = %@|| minor = %@", beacon.major, beacon.minor);
      
                      // 注意:当多个iBeacon设备广告了相同的proximityUUID, major和minor属性组合时,在locationManager:didRangeBeacons:inRegion:方法 中它们可能会有不同的距离与精度。建议每⼀一个beacon设备都是唯⼀一标识的。
                  }else
                  {
      
                  }
              }
          }
      
      }
      
      // 报错
      - (void)locationManager:(CLLocationManager *)manager rangingBeaconsDidFailForRegion:(CLBeaconRegion *)region withError:(NSError *)error
      {
          NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
      }
      
      • 3.外设模式给它广播
      #import <CoreBluetooth/CoreBluetooth.h>
      
      @interface ViewController () <CBPeripheralManagerDelegate>
      
      @property (nonatomic, strong) CBPeripheralManager *pMgr; /**< 外设管理模式 */
      
      @end
      
      @implementation ViewController
      
      // 懒加载创建
      - (CBPeripheralManager *)pMgr
      {
          if (!_pMgr) {
              //
              _pMgr = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
          }
          return _pMgr;
      }
      
      
      - (void)viewDidLoad {
          [super viewDidLoad];
          // Do any additional setup after loading the view, typically from a nib.
          // 先初始化外设管理者
          [self pMgr];
      
          [[NSNotificationCenter defaultCenter] addObserverForName:@"didEnterRegionNotification"
                                                            object:nil
                                                             queue:[NSOperationQueue mainQueue]
                                                        usingBlock:^(NSNotification * _Nonnull note) {
                                                            // 开始广播位置信息proximity UUID(及major或minor值)
                                                            if (self.pMgr.state == CBPeripheralManagerStatePoweredOn) {
                                                                //
                                                                [self.pMgr startAdvertising:note.userInfo];
                                                            }
                                                        }];
      
          [[NSNotificationCenter defaultCenter] addObserverForName:@"didExitRegionNotification"
                                                            object:nil
                                                             queue:[NSOperationQueue mainQueue]
                                                        usingBlock:^(NSNotification * _Nonnull note) {
                                                            if (self.pMgr.isAdvertising) {
                                                                [self.pMgr stopAdvertising];
                                                            }
                                                        }];
      }
      
      - (void)dealloc
      {
          // 实际上控制器中不写也不会出问题,此处只是为了 代码规范
          [[NSNotificationCenter defaultCenter] removeObserver:self];
      }
      
      #pragma mark - CBPeripheralManagerDelegate
      
      - (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
      {
          if (peripheral.state == CBPeripheralManagerStatePoweredOn) {
              //
          }
      }

      /**

       1.引入CoreBluetooth之后,初始化pMgr

       2.监听它的初始化状态,如果是On进行pMgr设置

       

       

       

       static NSString *const Service0StrUUID = @"FFF0";

       static NSString *const Service1StrUUID = @"FFE0";

       

       static NSString *const notiyCharacteristicStrUUID = @"FFF1";

       static NSString *const readwriteCharacteristicStrUUID = @"FFF2";

       static NSString *const readCharacteristicStrUUID = @"FFE1";

       

       static NSString *const LocalNameKey = @"XMGPeripheralDemo";

       

       #define XMGUUID(name) [CBUUID UUIDWithString:name]

       */

      import UIKit

      import CoreBluetooth


      let Service0StrUUID = "FFF0"

      let Service1StrUUID = "FFE0"


      let notiyCharacteristicStrUUID = "FFF1"

      let readwriteCharacteristicStrUUID = "FFF2"

      let readCharacteristicStrUUID = "FFE1"


      let LocalNameKey = "XMGpMgrDemo"



      class ViewController: UIViewController {

          

          @IBAction func startPeripheralMgr() {

              self.pMgr = CBPeripheralManager(delegate: self, queue: nil, options: nil)

          }

          var pMgr: CBPeripheralManager!


          var index = 0

          

          var timer: NSTimer?

          

          lazy var services: [CBMutableService] = {

              

              

              let descriptor = CBMutableDescriptor(type: CBUUID(string: CBUUIDCharacteristicUserDescriptionString), value: "xmg_descriptor")

              // swiftNS_Options枚举传多个值[,]

              let readWriteCharact = CBMutableCharacteristic(type: CBUUID(string: readwriteCharacteristicStrUUID),

                                                             properties: [.Read, .Write],

                                                             value: nil,

                                                             permissions: [.Readable, .Writeable])

              readWriteCharact.descriptors = [descriptor]

              

              // 根据UUID ,特征的属性,特征值, 特征值的权限属性

              let notifyCharact = CBMutableCharacteristic(type: CBUUID(string: notiyCharacteristicStrUUID),

                                                          properties: .Notify,

                                                          value: nil,

                                                          permissions: CBAttributePermissions.Readable)

              

              

              // 根据类型和是否是原生ser构造一个服务,需要注意的CBUUID的值不少随便确认是,是厂商提供的值,我们只需要用即可

              let ser0 = CBMutableService(type: CBUUID(string: Service0StrUUID), primary: true)

              ser0.characteristics = [notifyCharact, readWriteCharact]

              

              let readonlyData = "readonlyCharact".dataUsingEncoding(NSUTF8StringEncoding)

              let readonlyCharact = CBMutableCharacteristic(type: CBUUID(string: readCharacteristicStrUUID),

                                                            properties: .Read,

                                                            value: readonlyData,

                                                            permissions: .Readable)

              readonlyCharact.descriptors = [descriptor]

              

              let ser1 = CBMutableService(type: CBUUID(string: Service1StrUUID), primary: false)

              ser1.characteristics = [readonlyCharact]

              

              return [ser0, ser1]

          }()

          

          

          override func viewDidLoad() {

              super.viewDidLoad()

              // Do any additional setup after loading the view, typically from a nib.

          }

          

         


      }


      extension ViewController: CBPeripheralManagerDelegate

      {

          func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {

              switch peripheral.state {

              case .PoweredOff:

                  print("PoweredOff")

              case .PoweredOn:

                  print("PoweredOn")

                  // 3.设置外设

                  xmg_addServicesTopMgr(peripheral)

              case .Unsupported:

                  print("Unsupported")

                  

              default:

                  print("others")

              }

          }

          

          

          // 添加服务进外设管理者

          func xmg_addServicesTopMgr(peripheral: CBPeripheralManager) -> () {

              //

              

              //

              //peripheral.addService(<#T##service: CBMutableService##CBMutableService#>)

              for ser in self.services {

                  //

                  peripheral.addService(ser)

              }

          }

          

          // 当添加服务进pMgr的时候,会触发此回调

          func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) {

              //

              print("didAddService")

              guard error == nil else

              {

                  print("didAddService error: \(error)")

                  return;

              }

              guard index >= (self.services.count - 1) else

              {

                  index += 1

                  return

              }

              

              print("second in didAddService")

              // 开启广播

              let adv: [String: AnyObject] = [CBAdvertisementDataLocalNameKey: LocalNameKey, CBAdvertisementDataServiceUUIDsKey: self.services.map {$0.UUID}]

              peripheral.startAdvertising(adv)

          }

          

          // 当开始进行广告的时候,追踪广告的发送成败

          func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager, error: NSError?) {

              

              guard error == nil else {

                  

                  print("peripheralManagerDidStartAdvertising :\(error)")

                  return

              }

              

              print("start Adv")

          }

          

          /***>>>>>>>>4.与中心设备的交互>>>>>>>>>>**/

          // 4.1 当外设管理者接收到读取特征的请求的时候

          func peripheralManager(peripheral: CBPeripheralManager, didReceiveReadRequest request: CBATTRequest) {

              // 4.1.0 先判断特征属性是否可读,根据此做出响应

              if request.characteristic.properties.contains(.Read) {

                  // 4.1.1 如果特征可读,先拿到特征的值

                  let data = request.characteristic.value

                  // 4.1.2 将特征的值赋值给 响应

                  request.value = data

                  

                  // 4.1.3 将已经读取特征值的request返回

                  peripheral.respondToRequest(request, withResult: .Success)

              }else

              {

                  peripheral.respondToRequest(request, withResult: .ReadNotPermitted)

              }

          }

          

          // 4.2 当外设管理者收到写的请求时调用

          func peripheralManager(peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest]) {

          

              // 4.2.0 遍历收到的请求

              for request in requests {

                  // 4.2.1 根据请求特征的属性判断是否可写

                  if request.characteristic.properties.contains(.Write) {

                      // 4.2.2 拿到请求中的数据

                      let data = request.value

                      // 4.2.3 请此数据写入请求的特征中(需要注意特征类型转换)

                      let mchar = request.characteristic as! CBMutableCharacteristic

                      mchar.value = data

                      

                      // 4.2.4 发送修改后的请求和成功出去

                      peripheral.respondToRequest(request, withResult: .Success)

                  }else

                  {

                      peripheral.respondToRequest(request, withResult: .WriteNotPermitted)

                  }

              }

          }

          

          // 4.3.中心设备订阅外设管理者中的特征时候调用的方法

          func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) {

              // 4.3.1 既然被订阅,就要定时更新特征中的值

              self.timer = NSTimer.scheduledTimerWithTimeInterval(5.0,

                                                                  target: self,

                                                                  selector: #selector(ViewController.xmg_updateCharacteristic(_:)),

                                                                  userInfo: characteristic,

                                                                  repeats: true)

          }

          

          // 4.4 中心设备取消订阅某特征调用的方法

          func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFromCharacteristic characteristic: CBCharacteristic) {

              //

              print("didUnsubscribeFromCharacteristic")

              self.timer?.invalidate()

              self.timer = nil

          }

          

          // 按时更新特征(被订阅的特征)

          func xmg_updateCharacteristic(timer: NSTimer) {

              // 将数据随着时间进行更新

              let now = NSDate()

              let fomatter = NSDateFormatter()

              fomatter.dateFormat = "yy:MM:dd:HH:mm:ss"

              let nowStr = fomatter.stringFromDate(now)

              let nowData = nowStr.dataUsingEncoding(NSUTF8StringEncoding)

              

              // 发送一个更新的特征值给订阅了特征的中心设备

              let characteristic = timer.userInfo as! CBMutableCharacteristic

              pMgr.updateValue(nowData!,

                               forCharacteristic: characteristic,

                               onSubscribedCentrals: nil)

              

          }

      }


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

CoreBluetooth:baseK,中心模式,外设模式流程,iBeacon

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭