iOS开发(OC)——蓝牙(BLE)

iOS开发交流群:301058503

  • 导入头文件
#import <CoreBluetooth/CoreBluetooth.h>
  • 定义代理
CBCentralManagerDelegate,CBPeripheralDelegate
  • 定义全局变量
@property (nonatomic,strong)CBCentralManager *centralManager;
@property (nonatomic,strong)CBPeripheral *peripheral;
@property (nonatomic,strong)CBCharacteristic *writeCharacteristic;
@property (nonatomic,strong)CBCharacteristic *readCharacteristic;
  • 实例化
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
  • 当蓝牙状态发生变化时,会触发下面的代理
#pragma mark-CBCentralManagerDelegate
 - (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBCentralManagerStatePoweredOff:
        {
            //蓝牙关闭
        }
            break;
        case CBCentralManagerStatePoweredOn:
        {
            //蓝牙打开,开始扫描
            NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], CBCentralManagerScanOptionAllowDuplicatesKey, nil];//这个设置会使已经扫描到的设备继续被扫描。如果不需要吗,则设为nil
    [_centralManager scanForPeripheralsWithServices:nil options:options];
        }
            break;
        case CBCentralManagerStateResetting:
            break;
        case CBCentralManagerStateUnauthorized:
            break;
        case CBCentralManagerStateUnknown:
            break;
        case CBCentralManagerStateUnsupported:
            break;
        default:
            break;
    }
}
  • 扫描到设备,触发一下代理
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)args_peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{

NSLog(@"Did discover peripheral. peripheral: %@ rssi: %@, UUID: %@ advertisementData: %@ ", args_peripheral, RSSI, args_peripheral.identifier, advertisementData);
//args_peripheral.identifier:蓝牙设备标识
//RSSI:信号强度
//advertisementData:广播数据(iOS无法扫描出蓝牙Mac,所以需要把Mac放到广播里面)
if (){//选择某个设备进行连接
    _peripheral = args_peripheral;
    [_centralManager connectPeripheral:_peripheral options:nil];
}


}
  • 蓝牙连接回调
#pragma mark-CBPeripheralDelegate
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"Connecting Fail: %@",error);
}

//连接成功,扫描服务
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)args_peripheral{
    NSLog(@"连接成功");
    [_peripheral setDelegate:self];
    [_peripheral discoverServices:nil];//nil:查找所有服务
}
  • 查找服务回调
#pragma mark-找到服务
-(void)peripheral:(CBPeripheral *)args_peripheral didDiscoverServices:(NSError *)error{
    if (error) {
        NSLog(@"Error discover service: %@",[error localizedDescription]);
        return;
    }

    for(CBService *service in args_peripheral.services){
//        NSLog(@"Service found with UUID: %@",service.UUID);
        if([service.UUID isEqual:[CBUUID UUIDWithString:myPeripheral]]){//myPeripheral这个是服务的标识,如:@"FFFA"
            [_peripheral discoverCharacteristics:nil forService:service];//查找特征值
        }
    }

}
  • 找到特征值的回调
 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error{

    for(CBCharacteristic * characteristic in service.characteristics){
//        NSLog(@"Character found with UUID: %@",characteristic.UUID);
        if([characteristic.UUID isEqual:[CBUUID UUIDWithString:writeCharacter]]){//writeCharacter:写特征值,根据你的蓝牙协议而定
            _writeCharacteristic = characteristic;
        }else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:readCharacter]]){//readCharacter:读特征值,根据你的蓝牙协议而定
            _readCharacteristic = characteristic;
        }
    }
    //绑定
    //写数据:nsdata,绑定蓝牙的命令,根据你的蓝牙协议而定
    [_peripheral writeValue:nsdata forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];

    //读数据
    [_peripheral setNotifyValue:YES forCharacteristic:_readCharacteristic];
    [_peripheral readValueForCharacteristic:_readCharacteristic];
}
  • 特征值发生变化的回调
//写数据出错的原因
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
//    NSLog(@"write data error=%@",error);
}



//监听发生变化的特征
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{
//    NSLog(@"uuid:=%@",characteristic.UUID);
}

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

    unsigned char data[characteristic.value.length];
    [characteristic.value getBytes:&data length:characteristic.value.length];

for(int i=0;i<[characteristic.value length];i++){
 NSLog(@"char update! value%d = %d",i,data[i]);
 }


}

猜你喜欢

转载自blog.csdn.net/liumude123/article/details/80579152