蓝牙

随着iOS项目开发  很多app需要通过蓝牙与设备连接

蓝牙开发注意:

先定义中心设备和外围设备以及遵守蓝牙协议

 

[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @interface ViewController()<CBCentralManagerDelegate,CBPeripheralDelegate>  
  2. @property (strong, nonatomic) CBCentralManager *manager;  
  3. @property (nonatomic, strong) CBPeripheral *peripheral;  
  4.   
  5. @property (nonatomic, weak)NSTimer * connentTimer;  
  6.   
  7. @end  


 

 

再实现delegate方法

  1. 判断蓝牙状态,如成功则扫描指定UUID设备(如不指定UUID,则无法后台持续连接)
  2. 当发现指定设备后,连接该设备
  3. 当连接指定外围设备成功,编写定时器,每秒读取1次RSSI
  4. 当监听到失去和外围设备连接,重新建立连接
  5. 当读取到RSSI值,打印出它的值
 
 
[objc] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. //蓝牙状态  
  2. - (void)centralManagerDidUpdateState:(CBCentralManager *)central  
  3. {  
  4.     NSString * state = nil;  
  5.     switch ([central state])  
  6.     {  
  7.         case CBCentralManagerStateUnsupported:  
  8.             state = @"The platform/hardware doesn't support Bluetooth Low Energy.";  
  9.             break;  
  10.          //应用程序没有被授权使用蓝牙  
  11.         case CBCentralManagerStateUnauthorized:  
  12.             state = @"The app is not authorized to use Bluetooth Low Energy.";  
  13.             break;  
  14.              //尚未打开蓝牙  
  15.         case CBCentralManagerStatePoweredOff:  
  16.             state = @"Bluetooth is currently powered off.";  
  17.             break;  
  18.              //连接成功  
  19.         case CBCentralManagerStatePoweredOn:  
  20.             [self.manager scanForPeripheralsWithServices:nil options:nil];  
  21.             state = @"work";  
  22.             break;  
  23.         case CBCentralManagerStateUnknown:  
  24.         default:  
  25.             ;  
  26.     }  
  27.       
  28.     NSLog(@"Central manager state: %@", state);  
  29. }  
  30. //查找设备  
  31. - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI  
  32. {  
  33.       //每个蓝牙设备有自己唯一的标识符,根据标识符确认自己要连接的设备  
  34.     if ([peripheral.identifier isEqual:self.peripheral.identifier])  
  35.     {  
  36.         self.peripheral = peripheral;  
  37.         //数据连接定时器  
  38.         self.connentTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(connentPeripheral) userInfo:@"timer" repeats:YES];  
  39.         [self.connentTimer fire];  
  40.     }  
  41. }  
  42.   
  43. - (void)connentPeripheral {  
  44.     //连接外设  
  45.     self.manager.delegate = self;  
  46.     [self.manager connectPeripheral:_peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];  
  47.   
  48. }  
  49.   
  50. //连接成功后调用  
  51. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral  
  52. {  
  53.     NSLog(@"Did connect to peripheral: %@,%@", peripheral,peripheral.name);  
  54.     [peripheral setDelegate:self];  //查找服务  
  55.     [peripheral discoverServices:nil];  
  56.     [self.connentTimer invalidate];  
  57.     //监测设备是否断开了  
  58. //    [self createWorkDataSourceWithTimeInterval:1];  
  59. }  
  60. //当监听到失去和外围设备连接,重新建立连接  
  61. //这个方法是必须实现的,因为蓝牙会中断连接,正好触发这个方法重建连接。重建连接可能造成数秒后才能读取到RSSI。  
  62.   
  63. - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error  
  64. {  
  65.     [self.manager connectPeripheral:peripheral options:nil];  
  66. }  
  67.   
  68. - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error  
  69. {  
  70.     NSLog(@"%@",error.description);  
  71. }  
  72.   
  73. //返回的蓝牙服务通知通过代理实现  
  74. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error  
  75. {  
  76.     if (error)  
  77.     {  
  78.         NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);  
  79.         return;  
  80.     }  
  81.     for (CBService *service in peripheral.services)  
  82.     {  
  83. //        NSLog(@"Service found with UUID: %@", service.UUID.UUIDString);  
  84.         //发现服务  
  85.         if ([service.UUID isEqual:[CBUUID UUIDWithString:@"180D"]])//heart rate  
  86.         {  
  87.             //在一个服务中寻找特征值  
  88.             [peripheral discoverCharacteristics:nil forService:service];  
  89.         }  
  90.     }  
  91. }  
  92.   
  93. //返回的蓝牙特征值通知通过代理实现  
  94. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error  
  95. {  
  96.     if (error)  
  97.     {  
  98.         NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);  
  99.         return;  
  100.     }  
  101.     for (CBCharacteristic * characteristic in service.characteristics)  
  102.     {  
  103.         NSLog(@"characteristic:%@",characteristic);  
  104.         if( [characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A37"]])  
  105.         {  
  106.               
  107.             [self notification:service.UUID characteristicUUID:characteristic.UUID peripheral:peripheral on:YES];  
  108. //            [self.peripheral setNotifyValue:YES forCharacteristic:characteristic];  
  109.         }  
  110.     }  
  111. }  
  112.   
  113. //处理蓝牙发过来的数据  
  114. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error  
  115. {  
  116.   
  117. }  
  118.   
  119. -(void) notification:(CBUUID *) serviceUUID characteristicUUID:(CBUUID *)characteristicUUID peripheral:(CBPeripheral *)p on:(BOOL)on  
  120. {  
  121.     CBService *service = [self getServiceFromUUID:serviceUUID p:p];  
  122.     if (!service)  
  123.     {  
  124.         //        if (p.UUID == NULL) return; // zach ios6 addedche  
  125.         //        NSLog(@"Could not find service with UUID on peripheral with UUID \n");  
  126.         return;  
  127.     }  
  128.     CBCharacteristic *characteristic = [self getCharacteristicFromUUID:characteristicUUID service:service];  
  129.     if (!characteristic)  
  130.     {  
  131.         //        if (p.UUID == NULL) return; // zach ios6 added  
  132.         //        NSLog(@"Could not find characteristic with UUID  on service with UUID  on peripheral with UUID\n");  
  133.         return;  
  134.     }  
  135.     [p setNotifyValue:on forCharacteristic:characteristic];  
  136.       
  137. }  
  138.   
  139. -(CBService *) getServiceFromUUID:(CBUUID *)UUID p:(CBPeripheral *)p  
  140. {  
  141.       
  142.     for (CBService* s in p.services)  
  143.     {  
  144.         if ([s.UUID isEqual:UUID]) return s;  
  145.     }  
  146.     return nil; //Service not found on this peripheral  
  147. }  
  148. -(CBCharacteristic *) getCharacteristicFromUUID:(CBUUID *)UUID service:(CBService*)service {  
  149.       
  150.     for (CBCharacteristic* c in service.characteristics)  
  151.     {  
  152.         if ([c.UUID isEqual:UUID]) return c;  
  153.     }  
  154.     return nil; //Characteristic not found on this service  
  155. }  
posted @ 2017-02-14 09:46  枫锅锅  阅读(352)  评论(0编辑  收藏  举报