如何通过蓝牙低功耗(BLE)链路发送数据?

My *_*God 20 android bluetooth-lowenergy android-bluetooth gatt

我能够发现,连接到蓝牙.

源代码 - -

通过蓝牙连接到远程设备:

//Get the device by its serial number
 bdDevice = mBluetoothAdapter.getRemoteDevice(blackBox);

 //for ble connection
 bdDevice.connectGatt(getApplicationContext(), true, mGattCallback);
Run Code Online (Sandbox Code Playgroud)

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

    }
};
Run Code Online (Sandbox Code Playgroud)

现在我想向远程BLE设备发送命令,但不知道如何做到这一点.

一旦命令被发送到BLE设备,BLE设备将通过广播我的应用程序可以接收的数据来响应.

Par*_*rth 15

当您连接到BLE设备并发现服务时,您需要将此过程分解为几个步骤:

  1. 显示适用gattServicesonServicesDiscovered您的callback

  2. 要检查是否可以写入特性或不
    检查BluetoothGattCharacteristic PROPERTIES - 我没有意识到需要在BLE硬件上启用PROPERTY_WRITE并浪费了大量时间.

  3. 当您编写特征时,硬件是否执行任何操作以明确指示操作(在我的情况下,我正在点亮LED)

假设mWriteCharacteristicBluetoothGattCharacteristic 检查PROPERTY的部分应该是:

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

并且,写下你的特点:

// "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);  
Run Code Online (Sandbox Code Playgroud)

这些是您需要精确实现的代码的有用部分.

只需一个基本演示,就可以参考这个github项目进行实现.

  • 这段代码对`strBytes`没有任何作用. (9认同)

Mar*_*fer 5

一个使Android与LED灯互动的友好指南。

步骤1.获得一个工具来扫描您的BLE设备。我在Win10上使用了“蓝牙LE Lab”,但这也可以做到:https//play.google.com/store/apps/details? id = com.macdom.ble.blescanner

步骤2.通过输入数据来分析BLE设备的行为,建议输入十六进制值。

第3步。获取Android文档样本。https://github.com/googlesamples/android-BluetoothLeGatt

步骤4.修改您在其中找到的UUID SampleGattAttributes

我的配置:

    public static String CUSTOM_SERVICE = "0000ffe5-0000-1000-8000-00805f9b34fb";
    public static String CLIENT_CHARACTERISTIC_CONFIG = "0000ffe9-0000-1000-8000-00805f9b34fb";

    private static HashMap<String, String> attributes = new HashMap();

    static {
        attributes.put(CUSTOM_SERVICE, CLIENT_CHARACTERISTIC_CONFIG);
        attributes.put(CLIENT_CHARACTERISTIC_CONFIG, "LED");
    }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

步骤5.在BluetoothService.java中,修改onServicesDiscovered

@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {

        for (BluetoothGattService gattService : gatt.getServices()) {
            Log.i(TAG, "onServicesDiscovered: ---------------------");
            Log.i(TAG, "onServicesDiscovered: service=" + gattService.getUuid());
            for (BluetoothGattCharacteristic characteristic : gattService.getCharacteristics()) {
                Log.i(TAG, "onServicesDiscovered: characteristic=" + characteristic.getUuid());

                if (characteristic.getUuid().toString().equals("0000ffe9-0000-1000-8000-00805f9b34fb")) {

                    Log.w(TAG, "onServicesDiscovered: found LED");

                    String originalString = "560D0F0600F0AA";

                    byte[] b = hexStringToByteArray(originalString);

                    characteristic.setValue(b); // call this BEFORE(!) you 'write' any stuff to the server
                    mBluetoothGatt.writeCharacteristic(characteristic);

                    Log.i(TAG, "onServicesDiscovered: , write bytes?! " + Utils.byteToHexStr(b));
                }
            }
        }

        broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
    } else {
        Log.w(TAG, "onServicesDiscovered received: " + status);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用以下函数转换字节字符串:

public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
    data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
            + Character.digit(s.charAt(i + 1), 16));
}
return data;
}
Run Code Online (Sandbox Code Playgroud)

PS:上面的代码距离生产还很遥远,但我希望它对BLE新手有所帮助。