dotintent / react-native-ble-plx

React Native BLE library
Apache License 2.0
3.09k stars 516 forks source link

How to read characteristics #717

Closed Madhu02 closed 3 years ago

Madhu02 commented 4 years ago

Question

How to read BLE Peripheral Characteristics in react native using react-native-ble-plx

I'm developing an application which scans for BLE devices(Peripherals), then connect to them, read their services and characteristics. For now, I was able to connect to an iPhone which acting as a Peripheral device with certain characteristics and also was able to connect to Fitbit Versa Watch to read the heart sensor data. Although I was able to discover their services, I wasn't able to extract more information from the services like ServiceUUId and their characteristics.

Below is my code is written in react native.

scanAndConnect() {
console.log("Scanning Started");
this.manager.startDeviceScan(null, null, (error, device) => {
if (error) {
  // Handle error (scanning will be stopped automatically)
 console.log("Error in scanning devices:", error);
 return
 }
   // Check if it is a device you are looking for based on advertisement data
   // or other criteria.
  console.log("Detected Device Details:", device.id, device.name);
   // ||device.localName === 'BLEPeripheralApp') 
   if (device.name === 'Versa Lite'){ //
      // Stop scanning as it's not necessary if you are scanning for one device.
      console.log("Device Found, Stopping the Scan.");
      console.log("Connecting to:",device.name)
      this.manager.stopDeviceScan();
      device.connect()
      .then((device) => {
       // this.info("Discovering services and characteristics")
       console.log("Connected...Discovering services and characteristics");
     return device.discoverAllServicesAndCharacteristics()
   })
  .then((device) => {
    console.log('Services and characteristics discovered');
    //return this.testChar(device)
    const services = device.services()
    console.log(services);
    return device.readCharacteristicForService(services)
    // device.readCharacteristicForService("abbaff00-e56a-484c-b832-8b17cf6cbfe8")
    // this.info("Setting notifications")
    //return this.setupNotifications(device)
  })
  .then(() => {
    const characteristicsData =  device.readCharacteristicForService();
    console.log(characteristicsData);
    //this.info("Listening...")
  }, (error) => {
    console.warn(error.message);
    // this.error(error.message)
    })
   }
 });
}

How do I extract the serviceUUId from the Service method and also read the characteristics of that service? For my iPhone peripheral, I have two mutable characteristics that I should be able to read and write. How do I read them from service to characteristics to the real value?

Any help/suggestions are much appreciated.

Thanks.

dariuszseweryn commented 4 years ago

Do you face any issues?

Madhu02 commented 4 years ago

@dariuszseweryn Thank you for responding. I was able to get the services and characteristics now. Have modified the above code and seems working fine. But i have a question how do i read the data of characteristics of each service. I have Fitbit Versa Lite Watch trying to connect to it and read the heart rate. I was able to fetch the services and its characteristics, but not getting how do i read the characteristics value. We have read, write, writeWithOutResponse, writeWithResponse i'm confused with this. if i want to read the heart rate of a watch how exactly do i need to proceed once the services and characteristics has been discovered. Kindly Help. Thank you.

lnvtphu commented 4 years ago

I've got the same issue. I've read the GATT Services (https://www.bluetooth.com/specifications/gatt/services/). But I don't know how to get the specified service value like Heart Rate, Running Speed and Cadence, etc.

Madhu02 commented 4 years ago

@lnvtphu It all depends on the device which you are trying read the characteristics, some of the devices like (Samsung Gear, Fibit Versa Lite)doesn't expose their heart rate services and characteristics. I was able to read the characteristics, but couldn't find the one related to Heart Rate as they aren't exposing their services. But Make sure you have 0*180D in any of the services UUID.

Below code should help you getting the characteristics for the services.

    async readData(device) {
    const services = await device.services();
    console.log("Services:",services);
    const characteristics = await services[1].characteristics();
    console.log("Characteristics:",characteristics);
    characteristics[0].monitor((err, update) => {
      if (err) {
        console.log(`characteristic error: ${err}`);
        console.log(JSON.stringify(err));
      } else {
        console.log("Is Characteristics Readable:",update.isReadable);
        console.log("Heart Rate Data:",base64.decode(update.value));
        // const readCharacteristic = await device.readCharacteristicForService(userDataServiceUUID, 
         heightCharacteristicUUID); // assuming the device is already connected
        // var data = new Uint16Array(base64.decode(update.value));

        const heartRateData = Buffer.from(update.value, 'base64').readUInt16LE(0);
        console.log("Heart Beats:",heartRateData);
      }
    });
  }
lnvtphu commented 4 years ago

@Madhu02 many thanks. At the moment, I try to write the Native Module to integrate the Band SDK provide by customer.

FazilMuhammed commented 4 years ago

@Madhu02 Hello Brother.. if you have idea about to connect bluetooth printer and print the slip. i have issue with bluetooth printer i cannot write data.please help me to get print slip

stale[bot] commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

keerthi552 commented 2 years ago

iam retetrieving characteristics of a service in that characteristics object iam getting value property as null("value":null) how can i get the value

Tadejo9 commented 2 years ago

@keerthi552 Have you called discoverServicesAndCharacteristics?

keerthi552 commented 2 years ago

yes i have called discoverServicesAndCharacteristics i got the services and characteristics,but with the characteristics value as null

Tadejo9 commented 2 years ago

Which method did you use to read data from the characteristic?

keerthi552 commented 2 years ago

BleManager.characteristicsForDevice(device id,service uuid)

the result is [{"_manager": {"_activePromises": [Object], "_activeSubscriptions": [Object], "_errorCodesToMessagesMapping": [Object], "_eventEmitter": [NativeEventEmitter], "_scanEventSubscription": null, "_uniqueId": 12}, "deviceID": device id, "id": 4, "isIndicatable": true, "isNotifiable": true, "isNotifying": false, "isReadable": false, "isWritableWithResponse": true, "isWritableWithoutResponse": false, "serviceID": 3, "serviceUUID": serviceId, "uuid": uuid, "value": null}]

Tadejo9 commented 2 years ago

https://dotintent.github.io/react-native-ble-plx/


characteristicsForDevice(deviceIdentifier, serviceUUID)
List of discovered Characteristics for given Device and Service.

Promise<Array<Characteristic>>: Promise which emits array of Characteristic objects which are discovered for a Device in specified Service .
readCharacteristicForService(serviceUUID, characteristicUUID, transactionId)
Promise<Characteristic>: Promise which emits first Characteristic object matching specified UUID paths. Latest value of Characteristic will be stored inside returned object.
keerthi552 commented 2 years ago

readCharacteristicForService is not working actually, instead i used characteristicsForService this returned object same as the one that returned by the method characteristicsForDevice,

if we want a device information like minPressure,maxPressure,ramp......, then, is these will we available in characteristics by id or it will be with a property name as these minPressure,maxPressure,ramp......

and if for every property(minPressure,maxPressure,ramp......) if it is obtained by characteristic id then iam not getting array of characteristics iam getting only one characteristic object

if we get the characteristic uuids can we decode it to a characteristic name

Madhu02 commented 2 years ago

Hi @keerthi552 Could you please elaborate what are you trying to achieve. I have working code of reading and writing data to and from characteristics to the device using this library. Which device are you trying to connect ?

keerthi552 commented 2 years ago

Hi @keerthi552 Could you please elaborate what are you trying to achieve. I have working code of reading and writing data to and from characteristics to the device using this library. Which device are you trying to connect ?

1)i want data like min Pressure,max Pressure,ramp,ramp time from a device,by refering some codes i understood that these data (Pressure,max Pressure,ramp,ramp) cannot be obtained directly instead we get the service uuid's,characeristic uuid's based on these uuid's how can we know that the characteristic uuid belongs to some pressure's or something else so,let me know if there is any way to convert characteristic uuid to meaning full characteristic string

2)even though i got an characteristic object iam getting the value property in characteristic object as null

Madhu02 commented 2 years ago

Hi @keerthi552 Could you please elaborate what are you trying to achieve. I have working code of reading and writing data to and from characteristics to the device using this library. Which device are you trying to connect ?

1)i want data like min Pressure,max Pressure,ramp,ramp time from a device,by refering some codes i understood that these data (Pressure,max Pressure,ramp,ramp) cannot be obtained directly instead we get the service uuid's,characeristic uuid's based on these uuid's how can we know that the characteristic uuid belongs to some pressure's or something else so,let me know if there is any way to convert characteristic uuid to meaning full characteristic string

2)even though i got an characteristic object iam getting the value property in characteristic object as null

First of all which device you are trying to connect? What is the device BLE Profile ? Does your BLE device has its own ble identifiers or does it follow Bluetooth standard specifications as per this link https://www.bluetooth.com/specifications/assigned-numbers/ Without knowing what your BLE peripheral device details and their identifiers, you cannot just connect and read those values. Does your BLE device has min Pressure,max Pressure,ramp,ramp time attributes in their profile ? For more information on BLE, go through the below links and see if your device brand or manufacture has certain assigned number for the attributes or values you are looking for. https://www.bluetooth.com/specifications/assigned-numbers/ https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers/ https://www.bluetooth.com/specifications/specs/

keerthi552 commented 2 years ago

Hi @keerthi552 Could you please elaborate what are you trying to achieve. I have working code of reading and writing data to and from characteristics to the device using this library. Which device are you trying to connect ?

1)i want data like min Pressure,max Pressure,ramp,ramp time from a device,by refering some codes i understood that these data (Pressure,max Pressure,ramp,ramp) cannot be obtained directly instead we get the service uuid's,characeristic uuid's based on these uuid's how can we know that the characteristic uuid belongs to some pressure's or something else so,let me know if there is any way to convert characteristic uuid to meaning full characteristic string 2)even though i got an characteristic object iam getting the value property in characteristic object as null

First of all which device you are trying to connect? What is the device BLE Profile ? Does your BLE device has its own ble identifiers or does it follow Bluetooth standard specifications as per this link https://www.bluetooth.com/specifications/assigned-numbers/ Without knowing what your BLE peripheral device details and their identifiers, you cannot just connect and read those values. Does your BLE device has min Pressure,max Pressure,ramp,ramp time attributes in their profile ? For more information on BLE, go through the below links and see if your device brand or manufacture has certain assigned number for the attributes or values you are looking for. https://www.bluetooth.com/specifications/assigned-numbers/ https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers/ https://www.bluetooth.com/specifications/specs/

iam using PHILIPS CPAP device,i got 2 services,is there any way to decode the ble service uuid's to know which service they are providing

Madhu02 commented 2 years ago

You will be able to get the service and their related UUID's in the service object. But certain manufacturers won't advertise their private data considering it as a secure. I suggest you first check the device documentation.