2

我的 BLE android 应用程序当前可以连接到我的 BLE 硬件并连接到 GATT 服务器。我还可以启用通知并读取特征。然而,所宣传的特征是 HEX 格式。在我的服务上,我尝试接收字符串或字节数组格式的数据,尝试了几个转换过程,但我仍然得到无意义的数据(即??x 等)

关于如何接收/转换十六进制数据的任何想法?服务:

private void broadcastUpdate(final String action,
        final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    if (UUID_BLE_SHIELD_RX.equals(characteristic.getUuid())) {

        //final byte[] rx = characteristic.getValue();

        final String rx=characteristic.getStringValue(0);
        //final     char rx=raw(char.value)


        intent.putExtra(EXTRA_DATA, rx);
    }

主要活动:

   private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (Service.ACTION_GATT_DISCONNECTED.equals(action)) {
        } else if (Service.ACTION_GATT_SERVICES_DISCOVERED
                .equals(action)) {
                getGattService(mBluetoothLeService.getSupportedGattService());
        } else if (Service.ACTION_DATA_AVAILABLE.equals(action)) {
           displayData(intent.getExtras().getString(Service.EXTRA_DATA));
        }

NRF 连接中看到的来自 BLE 模块的数据:(0x)04-01-19-00-BE

4

2 回答 2

0

对于特征属性,常用:

String yourHexData = theValueOfYourHexData;
yourHexData.getBytes();

这是我用来将十六进制字符串正确转换为的方法byte []

public static byte[] hexToByteData(String hex)
{
    byte[] convertedByteArray = new byte[hex.length()/2];
    int count  = 0;

    for( int i = 0; i < hex.length() -1; i += 2 )
    {
        String output;
        output = hex.substring(i, (i + 2));
        int decimal = (int)(Integer.parseInt(output, 16));
        convertedByteArray[count] =  (byte)(decimal & 0xFF);
        count ++;
    }
    return convertedByteArray;
}

我不知道你的意图,但字节数组也是“人类不可读的”。为此,有必要使用适当的十六进制到字符串的转换。但是,如果您需要十六进制到字节数组的转换,请尝试我的方法。

希望能帮助到你。

于 2020-02-06T12:45:27.570 回答
0

在您的 broadcastUpdate 函数中将其更改如下

if (UUID_BLE_SHIELD_RX.equals(characteristic.getUuid())) {
    final byte[] rx = characteristic.getValue();
    intent.putExtra(EXTRA_DATA, rx);
}

在 MainActivity

} else if (Service.ACTION_DATA_AVAILABLE.equals(action)) {
       displayData(intent.getByteArrayExtra(Service.EXTRA_DATA));
}

在 displayData 中调用函数将 byteArray 转换为 hexString

public String bytesToHex(byte[] bytes) {
    try {
        String hex="";
        for (byte b : bytes) {
            String st = String.format("%02X", b);
            hex+=st;
        }
        return hex;
    } catch (Exception ex) {
        // Handler for exception
    }
}
于 2020-04-04T04:12:10.420 回答