簡體   English   中英

從BLE設備讀取數據

[英]Read data from BLE device

我正在嘗試從藍牙設備(BR-LE4.0-S2)讀取數據。 我能夠連接BLE設備,但無法從中讀取數據。我沒有關於BLE服務及其特性的任何規范。 這就是我的問題- (void)peripheral:didUpdateValueForCharacteristic:error:沒有被調用。 我按照教程“ https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/PerformingCommonCentralRoleTasks/PerformingCommonCentralRoleTasks.html#perapple_ref/doc/uid/TP40013257-CH3-SW2 ”。以下是我的碼。

我的要求是從BLE設備連續讀取數據。 任何幫助是極大的贊賞。

- (void)viewDidLoad
{
    self.myCentralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    self.peripheral = [[CBPeripheral alloc] init];
    self.peripheral.delegate = self;
    [super viewDidLoad];
}

- (void) centralManagerDidUpdateState:(CBCentralManager *)central {

    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
        [self.myCentralManager scanForPeripheralsWithServices:nil options:nil];
            break;
        default:
            NSLog(@"Central Manager did change state");
            break;
    }

}

- (void)centralManager:(CBCentralManager *)central
 didDiscoverPeripheral:(CBPeripheral *)peripheral
     advertisementData:(NSDictionary *)advertisementData
                  RSSI:(NSNumber *)RSSI {

    NSLog(@"Discovered %@", peripheral.name);
    [self.myCentralManager stopScan];
    NSLog(@"Scanning stopped");

    if (self.peripheral != peripheral) {
        self.peripheral = peripheral;
        NSLog(@"Connecting to peripheral %@", peripheral);
        // Connects to the discovered peripheral
    [self.myCentralManager connectPeripheral:peripheral options:nil];
    }
}

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

    NSLog(@"Peripheral connected");

    NSLog(@"Peripheral services : %@",peripheral.services );

    [self.peripheral setDelegate:self];

    [peripheral discoverServices:nil];

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

    if (error) {
        NSLog(@"Error discovering service: %@", [error localizedDescription]);
        return;
    }

    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:nil forService:nil];
    }
}

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

    int i = 0;
    for (CBCharacteristic *characteristic in service.characteristics) {

[peripheral setNotifyValue:YES forCharacteristic: characteristic];

    }
}

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

    NSData *data = characteristic.value;
    NSString *value = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];

    NSLog(@"Value %@",value);
    NSString *stringFromData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"Data ====== %@", stringFromData);
}


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

    if (error) {
        NSLog(@"Error changing notification state: %@",
              [error localizedDescription]);
    }
    NSString *value = [[NSString alloc] initWithData:self.interestingCharacteristic.value encoding:NSUTF8StringEncoding];

    NSLog(@"Value %@",value);

    NSLog(@"description: %@, descriptors: %@, properties: %d, service :%@, value:%@", characteristic.description, characteristic.descriptors, characteristic.properties, characteristic.service, characteristic.value);
    NSData *data = characteristic.value;

    if (characteristic.isNotifying) {
        NSString *stringFromData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [peripheral readValueForCharacteristic:characteristic];

        NSLog(@"Data ====== %@", @"ccdc");

    } else {
        [self.myCentralManager cancelPeripheralConnection:peripheral];

    }

}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"Peripheral Disconnected");
    self.peripheral = nil;

    // We're disconnected, so start scanning again
    NSDictionary *scanOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];

    [self.myCentralManager scanForPeripheralsWithServices:nil options:scanOptions];
}

要從BLE外圍設備讀取值,請執行以下步驟

  1. 掃描可用的設備

     NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBCentralManagerScanOptionAllowDuplicatesKey]; [self.myCentralManager scanForPeripheralsWithServices:nil options:options];` 
  2. 在檢測到設備時,將回撥“didDiscoverPeripheral”委托方法。 然后與檢測到的BLE設備建立連接

     -(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI { //Connect detected device.... if (!peripheral.isConnected) { peripheral.delegate = self; [bluetoothManager_ connectPeripheral:peripheral options:nil]; } } 
  3. 成功連接后,請求BLE設備中的所有可用服務

     - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{ NSLog(@"Peripheral Connected"); // Make sure we get the discovery callbacks peripheral.delegate = self; // Search only for services that match our UUID [peripheral discoverServices:nil]; } 
  4. 請求每項服務中可用的所有特征

     - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { if (error) { NSLog(@"Error discovering services: %@", [error localizedDescription]); return; } // Loop through the newly filled peripheral.services array, just in case there's more than one. for (CBService *service in peripheral.services) { [peripheral discoverCharacteristics:nil forService:service]; } } 
  5. 一旦我們獲得了所需的特性細節,我們需要訂閱它,這讓外圍設備知道我們想要它包含的數據

     - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{ // Deal with errors (if any) if (error) { NSLog(@"Error discovering characteristics: %@", [error localizedDescription]); return; } // Again, we loop through the array, just in case. for (CBCharacteristic *characteristic in service.characteristics) { if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:REQUIRED_CHARA_ID]]) { // If it is, subscribe to it [peripheral setNotifyValue:YES forCharacteristic:characteristic]; } } } 
  6. 完成所有這些步驟后,BLE設備將通過委托方法通知您通知狀態的變化

     - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{ if (error) { NSLog(@"Error changing notification state: %@", error.localizedDescription); } // Notification has started if (characteristic.isNotifying) { NSLog(@"Notification began on %@", characteristic); } } 

您將通過以下方法接收來自BLE設備的任何通知

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"Error reading characteristics: %@", [error localizedDescription]);
        return;
    }

    if (characteristic.value != nil) {
          //value here.        
    }
}

斯威夫特版本itZme的回答帶着些許的修改 ,由於didConnectToPeripheral不會被調用(你還需要不斷地為連接的強引用外設,如下所示):

掃描可用設備:

centralManager.scanForPeripheralsWithServices(nil, options: nil)

在檢測到設備時,將回撥“didDiscoverPeripheral”委托方法。 然后與檢測到的BLE設備建立連接。 但是首先要保留外圍設備的強大參考:

private var peripherals: [CBPeripheral] = []

func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {

  if peripheral.state != .connected {
    self.peripherals.append(peripheral)
    peripheral.delegate = self
    centralManager.connectPeripheral(peripheral , options: nil)
  }
}

剩下的應該是這樣的:

extension ViewController: CBPeripheralDelegate {

func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {

  if error != nil {
    print("Error connecting to peripheral: \(error?.localizedDescription)")
    return
  }
}

func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
print("Peripheral connected.")

  peripheral.delegate = self
  peripheral.discoverServices(nil)
}

func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {

  if error != nil {
    print("Error discovering services \(error?.localizedDescription)")
    return
  }

  for service: CBService in peripheral.services! {
    peripheral.discoverCharacteristics(nil, forService: service)
  }
}

func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {

  if error != nil {
    print("Error discovering characteristics \(error?.localizedDescription)")
    return
  }

  for characteristic: CBCharacteristic in service.characteristics! {
    if characteristic.UUID == CBUUID(string: YOUR_CHARACTERISTIC_UUID) {
      peripheral.readValueForCharacteristic(characteristic)
      // for some devices, you can skip readValue() and print the value here
    }
  }
}

func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {

   if characteristic.UUID == CBUUID(string: YOUR_CHARACTERISTIC_UUID) {
      print(characteristic.value)
    }       
}

}
  func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

    for newChar: CBCharacteristic in service.characteristics!{

        peripheral.readValue(for: newChar)

        if newChar.properties.rawValue == 0x10 || newChar.properties.rawValue == 0x8C{

            peripheral.setNotifyValue(true, for: newChar)
        }
        else if newChar.properties.rawValue == 0x12{

            peripheral.setNotifyValue(true, for: newChar)
        }
     }


 func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

    print(characteristic)
 }

首先你必須執行read()函數。如果執行read()函數,那么“didUpdateValueForCharesteristics”將會運行。你可以在這個函數中讀取字符串值。這很簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM