24

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

源代码 - -

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

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

 //for ble connection
 bdDevice.connectGatt(getApplicationContext(), true, mGattCallback);

Gatt 回调状态:

 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

    }
};

现在我想向远程 BLE 设备发送命令,但不知道该怎么做。

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

4

2 回答 2

15

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

  1. 显示可供您gattServices使用onServicesDiscoveredcallback

  2. 要检查您是否可以编写特征,
    请检查BluetoothGattCharacteristic PROPERTIES - 我没有意识到需要在 BLE 硬件上启用 PROPERTY_WRITE,这浪费了很多时间。

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

假设mWriteCharacteristic是一个BluetoothGattCharacteristic 检查属性的部分应该是这样的:

if (((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) |
     (charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) > 0) {
 // writing characteristic functions
 mWriteCharacteristic = 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);  

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

请参阅此 github 项目以获取仅包含基本演示的实现。

于 2014-05-01T09:53:10.520 回答
10

一个让 Android 与 LED 灯交互的友好指南。

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

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

步骤 3. 获取 Android 文档的示例。https://github.com/googlesamples/android-BluetoothLeGatt

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

我的配置:

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

在此处输入图像描述

步骤 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);
    }
}

使用此函数转换字节字符串:

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

PS:上面的代码离生产还很远,但我希望它对那些刚接触BLE的人有所帮助。

于 2017-11-03T01:41:40.137 回答