当前位置: 首页 > 工具软件 > CoreBlueTooth > 使用案例 >

CoreBluetooth基本应用(一)

边浩波
2023-12-01

1外设管理器

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

1.1对外设管理器强引用

@property(nonatomic,strong)CBPeripheralManager *peripheralManager;

1.2初始化外设管理器

self.peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];  

//遵守协议  
@interface ViewController ()<CBPeripheralManagerDelegate>

1.3创建服务与特征

  • 服务:每个4.0蓝牙设备包含若干服务,包括 <code>todo</code>
  • 特征:每个服务包含若干特征
  • 特征与服务都有一个唯一标识的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<CBATTRequest *> *)requests {
    CBATTRequest *req = [requests lastObject];
    self.dataTextField.text = [[NSString alloc] initWithData:req.value encoding:NSUTF8StringEncoding];
}



作者:小布衫
链接:https://www.jianshu.com/p/240bc7ce0aa0
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 类似资料: