静态设备正在连接,但动态设备在 Android 中没有响应

statically device is connecting but dynamically device is not responding in android

提问人:Hayjyo 提问时间:8/18/2023 最后编辑:Hayjyo 更新时间:8/18/2023 访问量:27

问:

嗨,在下面的代码中,如果我尝试在 sendCommands() 内部调用另一个方法 writeCommand(),静态值为 75%,它工作正常。

但是具有动态值的 writeCommand() 它没有发生。任何人都可以在这个问题上提供帮助。

 @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        Log.d("PesBleDevice", "onConnectionStateChange, status : " + status + ";newState : " + newState);
        Log.d("PesBleDevice", "No. of listeners : " + connectionStateChangeListenerQueue.size());

        if (newState == BluetoothProfile.STATE_CONNECTED) {
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }

          //  boolean serviceFound = gatt.discoverServices();
          //  Log.d("PesBleDevice", "onConnectionState Changed -> serviceFound : " + serviceFound);
            List<BluetoothGattService> gattServices = gatt.getServices();
            Log.e("PesBleDevice", "gattServices size is : " + gattServices.size());
            final BluetoothManager bluetoothManager = (BluetoothManager) activity.getSystemService(Context.BLUETOOTH_SERVICE);
            int gattStatus = bluetoothManager.getConnectionState(bleDevice, BluetoothProfile.GATT);
            Log.e("PesBleDevice", "Inside onConnectionStateChange, connection state should be 2 = " + gattStatus);
            gatt.requestMtu(256);

        }

        Iterator iterator = connectionStateChangeListenerQueue.iterator();

        while (iterator.hasNext()) {
            ENHOBleCallback cb = (ENHOBleCallback) iterator.next();
            //iterator.remove();
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // successfully connected to the GATT Server
                Log.d("PesBleDevice", "Connected to Pes GATT server");
                Timber.tag("PES").i("PesBleDevice-> Inside onConnectionStateChange method | Connected to Pes GATT server");
                PesManager.getInstance(webView).btStatusInOffline(1);

                try {
                    cb.onSuccess(newState);
                    Log.d("PesBleDevice", "Sending BLE connection status to PesManager after Wifi Provisioning | connected");
                    Timber.tag("PES").i("PesBleDevice-> Inside onConnectionStateChange method | Sending BLE connection status to PesManager after Wifi Provisioning | connected");
                    PesManager.getInstance(webView).sendReconnectBLEStatusSent(1); // 1 is for connected

                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        gatt.discoverServices();
                    }, 6000);
                } catch (ENHOBleCallbackException e) {
                    e.printStackTrace();
                    retryIfNoService(bleDevice, activity);
                }

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // disconnected from the GATT Server
                Log.d("PesBleDevice", "Disconnected from Pes GATT server");

                PesManager.getInstance(webView).btStatusInOffline(newState);
                Log.d("PesBleDevice", "Ble Active connection value = " + newState);
                PesManager.getInstance(webView).bleActiveConnectionThroughOutApp(newState);
                Timber.tag("PES").i("PesBleDevice-> Inside onConnectionStateChange method | Disconnected from Pes GATT server");
                Log.d("PesBleDevice", "Sending BLE connection status to PesManager after Wifi Provisioning | Disconnected");
                Timber.tag("PES").i("PesBleDevice-> Inside onConnectionStateChange method | Sending BLE connection status to PesManager after Wifi Provisioning | Disconnected");

                PesManager.getInstance(webView).sendReconnectBLEStatusSent(newState);


                if (bluetoothGatt != null) {
                    bluetoothGatt.close();
                    bluetoothGatt = null;
                }
                try {
                    cb.onFailure(newState);
                } catch (ENHOBleCallbackException e) {
                    e.printStackTrace();
                }
            }
        }
        //connectionStateChangeListenerQueue.clear();
    }

    @Override
    public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
        super.onMtuChanged(gatt, mtu, status);
        if (status == BluetoothGatt.GATT_SUCCESS) {
            gatt.discoverServices();
        }
        Log.i(TAG, "New MTU: " + mtu + " , Status: " + status + " , Succeed: " + (status == gatt.GATT_SUCCESS));
    }

Pesdevice的.java:

public  void sendCommands(BluetoothGatt gatt) throws JSONException {

        if (bluetoothGatt != null) {

            List<BluetoothGattService> gattServices = bluetoothGatt.getServices();

            if (2 == BluetoothProfile.STATE_CONNECTED) // BLE Is connected after provision as ghatt is connected.
            {
                if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                requestMtu(256);
                offline_gatt = gatt;
                jsonString = "{\"i\": 1, \"v\": 1, \"t\": 11, \"ts\": 1, \"m\": 75}";
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    writeCommand(offline_gatt,jsonString);
                }, 5000);
            }
        }
    }

write方法:

public static void writeCommand(BluetoothGatt gatt, String jsonString) {
        List<BluetoothGattService> gattServices = gatt.getServices();
        for (int i = 0; i < gattServices.size(); i++) {
            String serviceUUID = gattServices.get(i).getUuid().toString();
            if (serviceUUID.equalsIgnoreCase(SERVICE_GUID)) {
                List<BluetoothGattCharacteristic> gattCharacteristics = gattServices.get(i).getCharacteristics();
                for (BluetoothGattCharacteristic gattCharacteristic :
                        gattCharacteristics) {
                    final String uuid = gattCharacteristic.getUuid().toString();
                    if (uuid.equalsIgnoreCase(TX_CHAR_GUID)) {
                        byte[] payload = jsonString.getBytes();
                        gattCharacteristic.setValue(payload);
                        gattCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);

                        boolean writeStatus = gatt.writeCharacteristic(gattCharacteristic);
                    }
                }
            }
        }
    }

powersave命令: 这里的调用不是用相同的方法发生的。

public static void powerSaveCommand(int value,Activity context) {
        jsonString = "{\"i\": 1, \"v\": 1, \"t\": 5, \"ts\":  1, \"m\": " + value + "}";
        writeCommand(offline_gatt, jsonString);
}
Android 方法

评论


答:

0赞 Emil 8/18/2023 #1

在执行新的操作之前,必须始终等待上一个 GATT 操作完成。

例如,在发出新的 GATT 操作(如写入)之后,必须等待回调。每次写入后,必须等待相应的回调,然后才能发送新的 GATT 操作。requestMtuonMtuChangedonCharacteristicWrite

在您的代码中,我没有看到任何确保应用这些约束的内容。

如果你解释一下“它没有发生”的意思,可能会得到更好的答复。例如,变量中存储的结果是什么?writeStatus

评论

0赞 Hayjyo 8/18/2023
直接调用 writeStatus 值为 true,否则为 false
0赞 Hayjyo 8/18/2023
onMtuChanged 添加到我的代码中,请看一下,我什么时候可以添加等待 prvious 操作完成
0赞 Hayjyo 8/18/2023
更新了我的代码,请看