我对蓝牙通信很陌生。我的第一个项目打算将数据从 iOS 设备传输到 BLEshield(小芯片)。
为了测试我的中心代码,我决定将 iPhone 设置为外围设备(一旦我拿到芯片,它将扮演的角色)和 iPad 作为中心。
我可以连接设备并将数据从外围设备发送到中央设备。不过这很容易:
- (void)startService {
_readChar = [[CBMutableCharacteristic alloc] initWithType:[CBUUID ...] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];
_writeChar = [[CBMutableCharacteristics alloc] initWithType:[CBUUID ...] properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsWriteable];
_service = [[CBMutableService alloc] initWithType:[CBUUID ...] primary:YES];
[_service setCharacteristics:@[_readChar, _writeChar]];
_peripheral = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
[_peripheral addService:_service];
[_peripheral startAdvertising:@{CBAdvertisementDataServiceUUIDKey: @[[CBUUID ...]], CBAdvertisementDataLocalNameKey: @"ServiceName"}];
}
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
[_peripheral updateValue:[@"HELLO WORLD" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:_readChar onSubscribedCentrals:nil];
}
但我无法让另一个方向起作用。要从中心端发送数据,我有以下代码:
[_activePeripheral writeValue:[@"PONG" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:_writeChar type:CBCharacteristicWriteWithoutResponse];
我假设应该在外围设备上调用这些方法之一:
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray *)requests
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
但实际上什么也没发生。不幸的是,我的硬件项目将使用只能在外围模式下工作的芯片,最后我将几乎完全写入外围设备,因为它是控制信号的发送器。
我希望有一个人可以帮助我!