代码之家  ›  专栏  ›  技术社区  ›  duck1970

BLE特性未保留

  •  1
  • duck1970  · 技术社区  · 11 年前

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

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

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

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

    1. BLE服务类-一旦连接,就会扫描特征并根据其类型进行适当设置。

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

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

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

    CBBLEServicesClass中的字符定义

    #import "BLEServicesClass.h"
    #import "BLEControlClass.h"
    
    NSString *srModeUUIDString = @"346D0003-12A9-11CF-1279-81F2B7A91332";
    
    @interface BLEServicesClass() <CBPeripheralDelegate> {
    
    @private
        CBPeripheral        *servicePeripheral;
        CBCharacteristic    *srModeCharacteristic;
    @end
    

    didDiscoveryCharacteristicForService

    - (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。

    有什么帮助吗?

    2 回复  |  直到 11 年前
        1
  •  0
  •   DrMickeyLauer    7 年前

    我建议始终解决这些问题 按需提供 即通过迭代并使用匹配的UUID获取第一个UUID。如果没有,则为服务发出相同的新扫描。

    这样,您的程序将很容易在重新连接后存活下来。

        2
  •  0
  •   Nex Mishra    10 年前

    像我在应用程序中所做的那样,创建一个BLE单例类。无论何时应用程序处于运行状态,它都会在整个应用程序生命周期中保持特性的价值。