Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data over a Bluetooth Low Energy (BLE) link?

Tags:

I am able to discover, connect to bluetooth.

Source Code---

Connect via bluetooth to Remote Device:

//Get the device by its serial number  bdDevice = mBluetoothAdapter.getRemoteDevice(blackBox);   //for ble connection  bdDevice.connectGatt(getApplicationContext(), true, mGattCallback); 

Gatt CallBack for Status:

 private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {     @Override     public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {     //Connection established     if (status == BluetoothGatt.GATT_SUCCESS         && newState == BluetoothProfile.STATE_CONNECTED) {          //Discover services         gatt.discoverServices();      } else if (status == BluetoothGatt.GATT_SUCCESS         && newState == BluetoothProfile.STATE_DISCONNECTED) {          //Handle a disconnect event      }     }      @Override     public void onServicesDiscovered(BluetoothGatt gatt, int status) {      //Now we can start reading/writing characteristics      } }; 

Now I want to send commands to Remote BLE device but don't know how to do that.

Once the command is sent to the BLE device, the BLE device will respond by broadcasting data which my application can receive.

like image 376
My God Avatar asked Apr 30 '14 16:04

My God


1 Answers

You need to break this process into a few steps, when you connect to a BLE device and discover Services:

  1. Display available gattServices in onServicesDiscovered for your callback

  2. To check whether you can write a characteristic or not
    check for BluetoothGattCharacteristic PROPERTIES -I didn't realize that need to enable the PROPERTY_WRITE on the BLE hardware and that wasted a lot of time.

  3. When you write a characteristic, does the hardware perform any action to explicitly indicate the operation (in my case i was lighting an led)

Suppose mWriteCharacteristic is a BluetoothGattCharacteristic The part where to check the PROPERTY should be like:

if (((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) |      (charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) > 0) {  // writing characteristic functions  mWriteCharacteristic = characteristic;   } 

And, to write your characteristic:

// "str" is the string or character you want to write byte[] strBytes = str.getBytes(); byte[] bytes = activity.mWriteCharacteristic.getValue();   YourActivity.this.mWriteCharacteristic.setValue(bytes); YourActivity.this.writeCharacteristic(YourActivity.this.mWriteCharacteristic);   

Those are the useful parts of the code that you need to implement precisely.

Refer this github project for an implementation with just a basic demo.

like image 177
Pararth Avatar answered Oct 12 '22 19:10

Pararth