iOS蓝牙开发--CoreBluetooth

看了几天的关于iOS蓝牙的资料,总的来说,用起来挺麻烦的 XXD。。

      (CoreBluetooth框架用的 4.0  BLE协议--buletouch low energy​)

        CoreBluetooth框架的核心其实有两个东西,central(中心)和peripheral(外设)。分别对应两种模式:central模式是把你的app当成中心,连接其他外设如手环、蓝牙音响;peripheral模式是把你的app当成外设,去广播信号,连接别的中心。

        一般项目中,App都是用的central模式,蓝牙设备是peripheral,设备硬件写好4.0  BLE协议,你的App就可以通过蓝牙写命令进去了。(现在大多用4.0协议,用别的暂时没研究,估计大同小异,只不过就不是用CoreBluetooth这个框架了,如之前2.0的用的ExternalAccessory框架。)

       言归正传,如何通过蓝牙传递数据?一般的外设要创建一个以上服务​service,每个服务里面包括一个以上特征characteristic每个特征里面包括一个或多个描述Description。服务service相当于API接口, 特征characteristic就是我们传递数据的地方,描述Description是用来描述每个特征的信息或属性。

用法:

        #import ​    //先载入头文件

        @interface ViewController ()CBPeripheralDelegate>

   { 

      CBCentralManager *manager;  //主设备管理对象 

      NSMutableArray *peripherals;//用于保存被发现设备 

    }

   - (void)viewDidLoad { [super viewDidLoad]; 

    //初始化并设置委托和线程队列,线程的参数可以为nil,默认是main线程 

    manager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];

    ​​}

        //代理方法:centralManager成功打开,会触发这个方法

    -(void)centralManagerDidUpdateState:(CBCentralManager *)central{ 

     if(CBCentralManagerStatePoweredOn == central.state)

            {

                  //1⃣️开始扫描,第一个参数nil指定扫描所有外设。

                  [manager  scanForPeripheralsWithServices:nil  options:nil];

            }​

   }

    //扫描到设备会进入此方法

    -(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{ 

 // 一个主设备最多能连7个外设,每个外设最多只能给一个主设备连接 

//找到的设备必须(retained)持有它,否则CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的方法也不会被调用!!

  [peripherals addObject:peripheral]; //retained扫到的设备很重要

  [manager connectPeripheral:peripheral options:nil]; //2⃣️连接设备 

}

    //连接到Peripherals-成功 

    - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {

   NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name); 

   //设置peripheral的委托CBPeripheralDelegate 

   [peripheral setDelegate:self]; 

   //3⃣️扫描外设Services

   [peripheral discoverServices:nil];

 }

     //扫描到Services 

     -(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{ 

   // NSLog(@">>>扫描到服务:%@",peripheral.services); 

   for (CBService *service in peripheral.services) {

      NSLog(@"%@",service.UUID);

     //4⃣️扫描每个service的Characteristics

     [peripheral discoverCharacteristics:nil forService:service]; 

   }

}

     //扫描到Characteristics 

      -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{

      for (CBCharacteristic *characteristic in service.characteristics) {

      NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID); 

      } 

    //5⃣️获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:

    for (CBCharacteristic *characteristic in service.characteristics){ 

     [peripheral readValueForCharacteristic:characteristic]; 

  } 

    //7⃣️搜索Characteristic的Descriptors 

     for (CBCharacteristic *characteristic in service.characteristics){ 

    [peripheral discoverDescriptorsForCharacteristic: characteristic]; 

  }

}

   //6⃣️获取到characteristic的值

    -(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{ 

 //value的类型是NSData

    ​   NSLog(@"characteristic uuid:%@        value:%@",characteristic.UUID,characteristic.value); 

 } 

 //8⃣️搜索到Characteristic的Descriptors 

 -(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{ 

    for (CBDescriptor *d in characteristic.descriptors) {   

        NSLog(@"Descriptor uuid:%@",d.UUID);

    }

}

    //9⃣️获取到Descriptors的值 

    -(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error{ 

   //这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析 

    NSLog(@"characteristic uuid:%@ value:%@",[NSString stringWithFormat:@" %@ ",descriptor.UUID],descriptor.value); 

}

其他

//写数据到Characteristic中

[peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];

//设置通知,一有数据通知会进入:didUpdateValueForCharacteristic方法 [peripheral setNotifyValue:YES forCharacteristic:characteristic];

//停止扫描 

 [centralManager stopScan]; 

//断开连接 

 [centralManager cancelPeripheralConnection:peripheral];



参考资料:

   ​刘彦玮的博客


猜你喜欢

转载自blog.csdn.net/u011494083/article/details/51535691