将数据写入多个BLE(蓝牙)设备

时间:2014-08-14 07:19:34

标签: ios bluetooth-lowenergy nsoperation

请检查以下情况:

ConnectDevices Class:

此方法用于连接BLE设备。我从ViewController调用此方法连接到BLE设备。

  -(void)connectToDevice:(CBPeripheral *)peripheral{

     [[AppDelegate app] cbCentral].delegate = self;
     [[[AppDelegate app] cbCentral] connectPeripheral:peripheral options:nil];

    }

此方法用于发现连接的BLE设备的服务。我从NSOperation子类

调用方法
 -(void)calldiscoverServicesForPeripheral:(CBPeripheral *)peripheral{

   [peripheral setDelegate:self];
   [peripheral discoverServices:@[[Utility SERVICE_UUID]]];

  }

此方法用于将数据写入BLE设备。我每隔一秒就从NSOperation班打电话。

 -(void)writeDataToPeripheral:(CBPeripheral *)peripheral Data:(NSData *)data{

        if (self.uartCharacteristic) {
            [peripheral writeValue:data forCharacteristic:self.uartCharacteristic type:CBCharacteristicWriteWithoutResponse];
        }

  }

CBCentralManager委托获取设备状态的方法

 - (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    printf("Status of CoreBluetooth central manager changed %d \r\n",central.state);
    // Determine the state of the peripheral
    if ([central state] == CBCentralManagerStatePoweredOff) {
        NSLog(@"CoreBluetooth BLE hardware is powered off");
    }
    else if ([central state] == CBCentralManagerStatePoweredOn) {
        NSLog(@"CoreBluetooth BLE hardware is powered on and ready");
    }
    else if ([central state] == CBCentralManagerStateUnauthorized) {
        NSLog(@"CoreBluetooth BLE state is unauthorized");
    }
    else if ([central state] == CBCentralManagerStateUnknown) {
        NSLog(@"CoreBluetooth BLE state is unknown");
    }
    else if ([central state] == CBCentralManagerStateUnsupported) {
        NSLog(@"CoreBluetooth BLE hardware is unsupported on this platform");
    }
    }

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral  *)peripheral {

    [delegate getConnectedPeripheral:peripheral];

   }

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {

    [delegate getConnectedPeripheral:peripheral];
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {

      NSLog(@"didFailToConnectPeripheral %@",peripheral);

 }

pragma mark - CBPeripheralDelegate

 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{

   // NSLog(@"Discovered servicea: %@", peripheral.services);

   for (CBService *service in peripheral.services) {

     if ([service.UUID isEqual: [Utility SERVICE_UUID]]){
        [peripheral discoverCharacteristics:@[[Utility UART_UUID]] forService:service];
     }
   }
 }



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

      for (CBCharacteristic *aChar in service.characteristics)
     {

        if ([aChar.UUID isEqual:[Utility UART_UUID]])
        {
        @synchronized(self.writeLock)
        {
            self.uartCharacteristic = aChar;
             //[peripheral readValueForCharacteristic:self.uartCharacteristic];

            [peripheral setNotifyValue:YES forCharacteristic:self.uartCharacteristic];

        }
    }    
  }
 }


- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{

    NSString *tempStr = [[NSString alloc] initWithData: characteristic.value encoding: NSWindowsCP1252StringEncoding];

    [delegate getDataFromPeripheral:peripheral Data:characteristic.value];

}

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
     if (error) {
         return;
    }
 }

我从NSOpeartion子类

调用上面的类
- (id)initWithConnectDevice:(ConnectDevice *)cDevice toPeripheral:(CBPeripheral *)peripheral{

      if (self = [super init]) {


    executing = NO;
    finished = NO;
    [[[AppDelegate app] connectDevices] setDelegate:self];
    self.connectedPeripheral = peripheral;

    deviceParticulars = [[DeviceParticulars alloc] init];

    dataArray = [[NSMutableArray alloc] init];
    dataString = [[NSMutableString alloc] init];
   }
   return self;

}

-(BOOL)isConcurrent{
     return YES;
}
- (BOOL)isExecuting {
     return executing;
}

- (BOOL)isFinished {
      return finished;
}

-(void) terminateOperation {

        [timer invalidate];

        [self willChangeValueForKey:@"isFinished"];
        [self willChangeValueForKey:@"isExecuting"];
        finished = YES;
        executing = NO;
        [self didChangeValueForKey:@"isExecuting"];
        [self didChangeValueForKey:@"isFinished"];

 }

- (void)start {

@autoreleasepool {

    if (self.isCancelled){
        [self willChangeValueForKey:@"isFinished"];
        finished = YES;
        [self didChangeValueForKey:@"isFinished"];
        return;
    }

    writableString = [[NSMutableString alloc] init];
    [self createFile:[connectedPeripheral.identifier UUIDString]];

    [[[AppDelegate app] connectDevices] calldiscoverServicesForPeripheral:connectedPeripheral];

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] run];
}
}

-(void)timerFired:(id)sender{

if (self.isCancelled){

    [self willChangeValueForKey:@"isFinished"];
    finished = YES;
    [self didChangeValueForKey:@"isFinished"];
    return;
}

for (CBPeripheral *peripheral in [[AppDelegate app] peripheralsArray]) {

    [[[AppDelegate app] connectDevices] writeDataToPeripheral:peripheral Data:[self dataFromText:@"#RAL$"]];
    NSLog(@"Reading Peripheral::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::%@",[[AppDelegate app] peripheralsArray]);

  }
  }

我在Appdelegate中分配ConnectDevices类实例。当连接BLE设备时,我从View Controller调用Nsoperation子类。

问题,当我将数据写入一个设备时,它工作正常。但我连接到其他设备并将数据写入第二设备我收到蓝牙警告"不是外围设备的有效特性。"

我认为我的代码存在问题。

你能帮我吗

请不要介意这一行很多代码。

非常感谢

1 个答案:

答案 0 :(得分:0)

为我的视图控制器创建一个单独的外围设备模型类和调用。这解决了我的问题。非常感谢Paul。