with tutorial studio para org how example desarrollo con beacons beacon apps app ios objective-c core-bluetooth

ios - tutorial - Leer datos del dispositivo BLE



how to use beacons with android studio (4)

En primer lugar, debe ejecutar la función de lectura (). Si ejecuta la función de lectura (), se ejecutará "didUpdateValueForCharesteristics". Puede leer el valor de la cadena en esta función. Esto es simple.

Estoy intentando leer datos de un dispositivo Bluetooth (BR-LE4.0-S2). Pude conectar un dispositivo BLE, pero no pude leer datos de él. No tengo ninguna especificación sobre los servicios BLE y sus características. Aquí, cuál es mi problema - (void)peripheral:didUpdateValueForCharacteristic:error: no se llama. Seguí el tutorial " https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/PerformingCommonCentralRazucationConc.Cap.ConconCentralColeRoleTasks.html. código.

Lo que mi requisito es leer datos continuamente desde el dispositivo BLE. Cualquier ayuda es muy apreciada.

- (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]; }


Para leer un valor de un dispositivo periférico BLE, siga estos pasos

  1. Escanear en busca de dispositivos disponibles

    NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBCentralManagerScanOptionAllowDuplicatesKey]; [self.myCentralManager scanForPeripheralsWithServices:nil options:options];`

  2. Al detectar un dispositivo, recibirá una llamada al método delegado "didDiscoverPeripheral". Luego establecer una conexión con el dispositivo BLE detectado

    -(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. En una conexión exitosa, solicite todos los servicios disponibles en el dispositivo 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. Solicitar todas las características disponibles en cada servicio.

    - (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. Una vez que obtenemos los detalles de las características requeridas, debemos suscribirnos, lo que le permite al periférico saber que deseamos los datos que contiene.

    - (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. Al completar todos estos pasos, el dispositivo BLE le permitirá conocer el cambio del estado de la notificación a través del método de delegado

    - (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); } }

Recibirá cualquier notificación del dispositivo BLE en el siguiente método

- (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. } }


Versión Swift de la respuesta de itZme con una pequeña modificación debido a que didConnectToPeripheral no fue llamado (también necesita mantener una referencia fuerte a los periféricos para poder conectarse, de la siguiente manera):

Buscar dispositivos disponibles:

centralManager.scanForPeripheralsWithServices(nil, options: nil)

Al detectar un dispositivo, recibirá una llamada al método delegado "didDiscoverPeripheral". Luego establezca una conexión con el dispositivo BLE detectado. Pero también mantén una fuerte referencia de los periféricos primero:

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) } }

Y el resto debería ser así:

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) }