尝试订阅 CBCharacteristic 时不允许写入错误

Writing is not permitted error when attempting to subscribe to CBCharacteristic

我正在开发一个与蓝牙 LE 设备通信的应用程序,因此我正在使用 CoreBluetooth 来执行此操作。

我用的外设暴露了1个服务,有两个特性一个串口FIFO特性,支持indication/notification/write/write无响应;以及支持写入的串口信用特性

根据我的阅读,我了解到我需要订阅的特征是 FIFO 特征,但是当我调用 [_connectedPeripheral setNotifyValue:YES forCharacteristic:characteristic]; 时,我得到一个 Writing is not permitted 错误。

我检查了特征的属性,它具有 ReadWriteWithoutResponseNotifyIndicate 属性。

这是我第一次使用 CoreBluetooth,我是一个蓝牙新手,所以我可能忽略了一些明显的东西,但我们将不胜感激。

编辑:这是代码:

#define SDL440S_SERVICE @"2456E1B9-26E2-8F83-E744-F34F01E9D701"
#define SDL440S_CHARACTERISTIC @"2456E1B9-26E2-8F83-E744-F34F01E9D703"

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"Did connect %@", peripheral.name);
    // _connectedPeripheral is a property...
    if (_connectedPeripheral != peripheral) {
        _connectedPeripheral = peripheral;
    }
    _connectedPeripheral.delegate = self;
    [_connectedPeripheral discoverServices:@[[CBUUID UUIDWithString:SDL440S_SERVICE]]];
}

#pragma mark - <CBPeripheralManager>

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (peripheral == _connectedPeripheral) {
        for (CBService *service in _connectedPeripheral.services) {
            if ([service.UUID.UUIDString isEqualToString:SDL440S_SERVICE]) {
                [_connectedPeripheral discoverCharacteristics:@[[CBUUID UUIDWithString:SDL440S_CHARACTERISTIC]] forService:service];
            }
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID.UUIDString isEqualToString:SDL440S_CHARACTERISTIC]) {
            // Subsribe to characteristic
            [_connectedPeripheral setNotifyValue:YES forCharacteristic:characteristic];
        }
    }
}

// Getting values

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    if (error) {
        NSLog(@"Error changing note state for char: %@.\nError: %@", characteristic, error.localizedDescription);
    }
}

如果有人遇到此问题,供日后参考,这是与设备的 credit 特性有关。

我感兴趣的服务公开了两个特征 credit 特征和 FIFO特性。 (我知道信用特征是标准问题。)问题是我必须先将我想接收的最大数据量写入信用特征,然后才能接收数据并将数据写入 FIFO 特征。

即:

unsigned char buf[1] = {/*relevant data here...*/};
NSData *data = [NSData dataWithBytes:buf length:1];
[peripheral writeValue:data forCharacteristic:creditCharacteristic type:CBCharacteristicWriteWithoutResponse];