ios - CoreBluetooth 中央 --> 外设

标签 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

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

我希望有人能帮助我!

最佳答案

属性:

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

参见 here更多细节。 CBCharacteristicPropertyNotify 不允许特征可写或可读,它只能通知(订阅/取消订阅)。

关于ios - CoreBluetooth 中央 --> 外设,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20034433/

相关文章:

swift - TI SensorTag 加速度计服务不做广告

ios - CoreBluetooth 背景 - 如何重新实例化 appdelegate 中的中央管理器对象?

iphone - 为 iPhone 添加心率测量服务作为外设

ios - Swift - 枚举的子类(或类似的东西)

Android BLE - 确定特征的存储值类型

ios - 可以让 Intel Edison 充当 iOS 的 Remote

swift - 不断更新 RSSI 数 swift

iPhone 应用程序内存不断增长

ios - NSJSONSerialization.JSONObjectWithData 导致应用程序在 alamofire 迁移后崩溃

ios - 我们是否需要使用 NSURLSessionDataTask 和 NSMutableURLRequest 处理进程的连接超时