我对蓝牙通信很陌生。我的第一个项目打算将数据从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

但实际上什么也没发生。不幸的是,我的硬件项目将使用一个只能在外围模式下工作的芯片,最终我将几乎完全写入外设,因为它是控制信号的发射器。

我希望有人能帮助我!

有帮助吗?

解决方案

的属性:

  • _readChar 应该是 CBCharacteristicPropertyRead
  • _writeChar 应该是 CBCharacteristicPropertyWriteWithoutResponse

这里 有关更多详情。 CBCharacteristicPropertyNotify 不允许特性是可写的或可读的,它只是可通知的(订阅/取消订阅)。

其他提示

只是使用 https://github.com/lgbluetooth/lgbluetooth 它将让生活更轻松

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top