CoreBluetooth Central - >外围设备

时间:2013-11-17 18:20:52

标签: ios bluetooth-lowenergy core-bluetooth cbperipheral cbcentralmanager

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

但实际上没有任何反应。不幸的是,我的硬件项目将使用只能在外设模式下工作的芯片,最后我几乎只能写入外设,因为它是控制信号的发送器。

我希望有人可以帮助我!

2 个答案:

答案 0 :(得分:5)

以下属性:

  • _readChar应为CBCharacteristicPropertyRead
  • _writeChar应为CBCharacteristicPropertyWriteWithoutResponse

有关详细信息,请参阅hereCBCharacteristicPropertyNotify不允许该特性可写或可读,只能通知(订阅/取消订阅)。

答案 1 :(得分:-1)

只需使用https://github.com/LGBluetooth/LGBluetooth即可让生活更轻松