iOS蓝牙框架CoreBluetooth应用

前一段时间做一个iPhone端通过蓝牙与血压计交互的软件,类似于天天血压这款软件的功能。在此带来了关于蓝牙的一些分享!

1、外设

外设就是一台向外发送信息的设备,它以广播的形势进行消息的发送,在手机和血压计中,血压计所扮演的角色就是外设。其它的一些例子,又比如智能手环、打印机、跑步用的计步器等等,这些设备都是属于外设。在CoreBluetooth 中是通过CBPeripheralManager来进行管理的。

2、中心

中心是我们所说的手机端,用来接收外设所发送的信息,比如血压计测量时所测量的值,测量的最终结果等信息,另外也可以通过中心端向外设写入一些值来使外设展示一些功能,比如通过手机端发送的一些指令使得血压计启动测量、关闭测量和关机功能。

二、实现手机端(中心)的代码逻辑

1、建立中心角色
2、扫描外设
3、连接外设
4、扫描外设中的服务和特征
    4.1 获取外设的services
    4.2 获取外设的Characteristics,获取Characteristics的值,获取Characteristics的Descriptor和Descriptor的值
5、与外设做数据交互
6、 订阅Characteristic的通知
7、断开连接

在此解释一下什么是服务(services),在硬件工程师开发一款蓝牙设备时,会在设备中定义好服务。在每一个服务中都有一个或多个特征,每个特征的属性有只读、只写、通知等等。


创建中心管理者

//导入框架
#import 
@interface XYViewController ()
//用于保存被发现设备
@property (strong, nonatomic) NSMutableArray* myPeripherals;
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    self.myCentralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:nil];
}

设置主设备的委托,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;//断开外设的委托

扫描到设备进行连接

//扫描到设备会进入方法
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{

 //接下连接测试设备,如果没有设备,可以下载一个叫lightbule的app去模拟一个设备 
//找到的设备必须持有它,否则CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的方法也不会被调用!!
 [myPeripherals addObject:peripheral];
 //连接设备
  [manager connectPeripheral:peripheral options:nil];
     
}

一个主设备最多能连7个外设,每个外设最多只能给一个主设备连接,连接成功、失败、断开都会进入到相应的代理

//连接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
 NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
 [peripheral setDelegate:self];
        //扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
        [peripheral discoverServices:nil];
}

//连接到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]);

}

扫描到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];
    }

    }

获取外设的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);
}

把数据写到Characteristic中,⚠️在写入的时候,必须要先写入与外设建立连接的值,只有建立了连接之后写入其他的值才能有反应(ps:我被坑过)

//写数据
-(void)writeCharacteristic:(CBPeripheral *)peripheral
            characteristic:(CBCharacteristic *)characteristic
                     value:(NSData *)value{

    //打印出 characteristic 的权限,可以看到有很多种,这是一个NS_OPTIONS,就是可以同时用于好几个值,
    //常见的有read,write,notify,indicate,知知道这几个基本就够用了,前连个是读写权限,后两个都是通知,两种不同的通知方式。
  /*
     CBCharacteristicPropertyBroadcast                                              
     CBCharacteristicPropertyRead                                                   
     CBCharacteristicPropertyWriteWithoutResponse                                   
     CBCharacteristicPropertyWrite                                                  
     CBCharacteristicPropertyNotify                                                 
     CBCharacteristicPropertyIndicate                                               
    CBCharacteristicPropertyAuthenticatedSignedWrites                               
     CBCharacteristicPropertyExtendedProperties                                     
     CBCharacteristicPropertyNotifyEncryptionRequired 
   CBCharacteristicPropertyIndicateEncryptionRequired 
  */
    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(@"该字段不可写!");
    }

}

订阅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];
}

断开连接

//停止扫描并断开连接
-(void)disconnectPeripheral:(CBCentralManager *)centralManager
                 peripheral:(CBPeripheral *)peripheral{
    //停止扫描
    [centralManager stopScan];
    //断开连接
    [centralManager cancelPeripheralConnection:peripheral];
}

如何计算写入的值?

一下为模拟数据,仅供参考,主要讲的是计算思路
蓝牙文档如图所示

iOS蓝牙框架CoreBluetooth应用_第1张图片
屏幕快照 2016-07-30 下午11.25.32.png
iOS蓝牙框架CoreBluetooth应用_第2张图片
屏幕快照 2016-07-30 下午11.32.45.png

按照文档流程所示可以算出每一项功能所对应的值以及手机端所接收到值对应的功能
在这些值中其中校验码的计算是需要自己计算一下的,计算的方法如下图所示,现将16进制转化为2进制,然后进行异或运算获得

iOS蓝牙框架CoreBluetooth应用_第3张图片
mmexport1469892606458.jpg

demo,在此

你可能感兴趣的:(iOS蓝牙框架CoreBluetooth应用)