不保留 BLE 特性

BLE Characteristic not retained

我正在编写一个与多个(5 到 10 个)相同 BLE 设备通信的应用程序。每个 BLE 设备都有多个特性,有些是静态的,有些是更新的,有些是可以写入的。

该应用程序在导航控制器中嵌入了多个 ViewController,适用于 IOS 设备(特别是 IOS 8+ 和 iPhone 6)。

为了使程序高效并与 CoreBluetooth 一起工作,我创建了 classes 来管理 BLE 交互:

  1. BLE 控制 Class - 扫描并连接正确的 BLE 设备。

  1. BLE 服务 Class - 连接后扫描特征并根据其类型适当设置它们。

由外围设备发送并由管理器接收的具有已知连接特性的数据然后存储在后端 SQLite 数据库中。

我面临的问题是回写连接的外围设备特征。我已经在 CBCharacteristic 中收集了特性,但是当我尝试向它写入 CBCharacteristic 的值为 NULL 时,它不会在 class 中持续存在。

以下是我使用过的代码的摘要:

BLE 服务中的 CBCharacteristic 定义Class

#import "BLEServicesClass.h"
#import "BLEControlClass.h"

NSString *srModeUUIDString = @"346D0003-12A9-11CF-1279-81F2B7A91332";

@interface BLEServicesClass() <CBPeripheralDelegate> {

@private
    CBPeripheral        *servicePeripheral;
    CBCharacteristic    *srModeCharacteristic;
@end

didDiscoverCharacteristicForService

- (void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error;
{

    NSArray     *characteristics    = [service characteristics];
    CBCharacteristic *characteristic;

        if ([[characteristic UUID] isEqual:srModeUUID]) {
            NSLog(@"didDiscoverServices - Mode Characteristic");
            srModeCharacteristic = characteristic;
        }

写入特征

-(void)writeCharacteristic:(CBCharacteristic *)whichCharacteristic data:(NSData*)data device:(NSString *)device
{

    NSArray   *devices;
    devices = [[BLEControlClass sharedInstance] connectedPeripherals];

    int i;
    for (i = 0; i < [[[BLEControlClass sharedInstance] connectedPeripherals] count]; i++) {
        CBPeripheral *peripheral=[[[BLEControlClass sharedInstance] connectedPeripherals] objectAtIndex:i];
        peripheral.delegate=self;
        NSString *tesfordevice = peripheral.name;

        if (tesfordevice == device) {
            [whichCharacteristic.service.peripheral writeValue:data forCharacteristic:whichCharacteristic type:CBCharacteristicWriteWithResponse];
        }
    }
}

调用者:

-(void)writeModeCharacteristic:(NSData*)data :(NSString *)device
{
    [self writeCharacteristic:srModeCharacteristic data:data device:device];
}

我的问题是 srModeCharacteristic 在被发现时最初设置正确,但后来为 NULL。

有什么帮助吗?

制作一个 BLE 单例 class 正如我在我的应用程序中所做的那样。每当应用程序处于 运行 状态时,它会在整个应用程序生命周期中保留特征值。

我建议始终根据需要 解析特征 ,即通过迭代并使用匹配的 UUID 获取第一个。如果有 none,请发出新的扫描 - 对于服务也是如此。

这样你的程序就可以很容易地重新连接。