CoreBluetooth基本应用(一)

CoreBluetooth基本应用(一)_第1张图片

Part1 外设部分开发 CBPeripheralManager

1外设管理器

蓝牙外设管理中心,与手机的蓝牙硬件模板关联,可以获取到手机中蓝牙模块的一些状态等,但是管理的就是蓝牙外设。

1.1对外设管理器强引用
@property(nonatomic,strong)CBPeripheralManager *peripheralManager;
1.2初始化外设管理器
self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];  
//遵守协议  
@interface ViewController ()
1.3创建服务与特征
  • 服务:每个4.0蓝牙设备包含若干服务,包括 todo
  • 特征:每个服务包含若干特征
  • 特征与服务都有一个唯一标识的UUID,由设备厂商提供
 -(void)setupServiceAndCharacteristic{      
    //创建服务      
    CBUUID *serviceUUID = [CBUUID UUIDWithString:SERVICE_UUID];          
    CBMutableService *service = [[CBMutableService alloc] initWithType:serviceUUID primary:YES];     
   //创建特征      
    CBUUID *characteristicUUID = [CBUUID UUIDWithString:CHARATIC_UUID];
    CBMutableCharacteristic *characteristic = [[CBMutableCharacteristic  alloc] initWithType:characteristicUUID properties:CBCharacteristicPropertyRead|CBCharacteristicPropertyWrite value:nil permissions:CBAttributePermissionsReadable|CBAttributePermissionsWriteable ];      
    //将特征添加到服务中
    service.characteristics = @[characteristic];
    //添加服务到外设中 
    [self.peripheralManager addService:service];  }

2外设管理器代理

2.1当设备被更新时的回调
// 当设备状态被更新回调
-(void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral 
    // 判断设备状态
    if(peripheral.state == CBManagerStatePoweredOn) {
        // 创建服务(Service)和特征(Characteristics)
        [self setupServiceAndCharacteristic];
        // 开始广播
        [self.peripheralMgr startAdvertising:@{CBAdvertisementDataServiceUUIDsKey:@[[CBUUID UUIDWithString:SERVICE_UUID]]}];
    }
}
2.2 中心设备向外设请求读取数据
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request {
    // 把数据给请求对象->响应给中心设备
    request.value = [self.dataTextField.text dataUsingEncoding:NSUTF8StringEncoding];
    // 响应读取的操作
    [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
}
2.3 中心设备向外设写入数据
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests {
    CBATTRequest *req = [requests lastObject];
    self.dataTextField.text = [[NSString alloc] initWithData:req.value encoding:NSUTF8StringEncoding];
}
CoreBluetooth基本应用(一)_第2张图片
d0de2dc17c2be041612a0e8da10a8716.jpg

你可能感兴趣的:(CoreBluetooth基本应用(一))