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创建服务与特征
-(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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。