wjc
2026-03-24 c4ae4589c6c001329ebb731589b209e8ddcbf7ca
app/src/main/java/com/hdl/photovoltaic/utils/BleWifiConfiguratorUtils.java
@@ -327,6 +327,7 @@
            bluetoothGatt.disconnect();  // 先断开连接
            bluetoothGatt.close();
            bluetoothGatt = null;
            Log.d(TAG, "Connecting to 先断开旧蓝牙连接");
        }
        BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
        // 自动连接 = false,避免系统缓存连接
@@ -369,9 +370,15 @@
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                isConnected = false;
//                if (bluetoothGatt != null) {
//                    bluetoothGatt.close();
//                    bluetoothGatt = null;
//                }
                if (connectListener != null) {
                    callbackHandler.post(() -> connectListener.onDisconnected());
                }
                Log.d(TAG, "Connected to GATT server, onDisconnected");
            }//
        }
@@ -387,6 +394,9 @@
                }
                characteristic = targetService.getCharacteristic(charUuid);
                notifyCharacteristic = targetService.getCharacteristic(notifyCharUuid);
                boolean mtuRequestResult = gatt.requestMtu(512); // 默认设置请求最大 MTU,有设备可能不支持
                Log.d(TAG, "requestMtu(512) 结果:" + mtuRequestResult);
                if (characteristic == null) {
                    Log.e(TAG, "Required characteristics not found");
                    notifyConnectionFailed("Characteristics not found");
@@ -419,7 +429,7 @@
                }
                return;
            }
            Log.d(TAG, "onCharacteristicWrite: 写入成功回复");
            if (characteristic.getUuid().equals(charUuid)) {
                //写入成功
                if (writeListener != null) {
@@ -431,6 +441,8 @@
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            Log.d(TAG, "onCharacteristicChanged: " + characteristic.getUuid());
            //收到蓝牙回复的数
            if (characteristic.getUuid().equals(notifyCharUuid) && writeListener != null) {
                byte[] value = characteristic.getValue();
                String response = new String(value, StandardCharsets.UTF_8);
@@ -440,16 +452,46 @@
        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            Log.d(TAG, "onDescriptorWrite: status=" + status +
                    ", descriptor=" + descriptor.getUuid());
            // 通知描述符写入完成,可以忽略
//            if (status == BluetoothGatt.GATT_SUCCESS) {
//                Log.d(TAG, "通知开启成功,可以接收设备响应了");
//            } else {
//                Log.e(TAG, "通知开启失败:" + status);
//                if (writeListener != null) {
//                    callbackHandler.post(() -> writeListener.onWriteFailed(status));
//                }
//            }
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "通知开启成功,可以接收设备响应了");
            } else {
                Log.e(TAG, "通知开启失败:" + status);
                if (writeListener != null) {
                    callbackHandler.post(() -> writeListener.onWriteFailed(status));
                }
            }
        }
        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            //todo 后面兼用mtc分包的,目前默认设置512字节
            if (status == BluetoothGatt.GATT_SUCCESS) {
//                currentMtu = mtu;
                Log.d(TAG, "✅ MTU 协商成功:当前 MTU = " + mtu + " 字节");
                Log.d(TAG, "   有效数据长度 = " + (mtu - 5) + " 字节");
//                // MTU 设置成功后,标记连接成功
//                isConnected = true;
//                if (connectListener != null) {
//                    callbackHandler.post(() -> {
//                        Log.d(TAG, "通知连接成功回调");
//                        connectListener.onConnected();
//                    });
//                }
            } else {
//                Log.w(TAG, "⚠️ MTU 协商失败,status: " + status + ",使用默认 MTU=23");
////                currentMtu = 23;
//                // 即使 MTU 失败,也认为连接成功(使用默认 MTU)
//                isConnected = true;
//                if (connectListener != null) {
//                    callbackHandler.post(() -> connectListener.onConnected());
//                }
            }
        }
    };
@@ -467,13 +509,26 @@
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                    UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
            if (descriptor != null) {
//                // 第 3 步:设置描述符的值
//                // 先检查特征属性,决定使用 NOTIFY 还是 INDICATE
//                int charProp = characteristic.getProperties();
//                if ((charProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
//                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
//                    Log.d(TAG, "使用 NOTIFICATION 模式");
//                } else if ((charProp & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
//                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
//                    Log.d(TAG, "使用 INDICATION 模式");
//                } else {
//                    Log.e(TAG, "该特征不支持通知/指示");
//                    return;
//                }
                // 第 3 步:设置描述符的值为 ENABLE_NOTIFICATION_VALUE,
                // ↑ 这个值是 byte[]{0x01, 0x00},告诉设备端"我要订阅通知"
                descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                // 第 4 步:写入描述符到设备
                //↑ 只有写入成功后,告诉设备端,设备才会开始发送通知,
                bluetoothGatt.writeDescriptor(descriptor);
                Log.e(TAG, "writeDescriptor success");
                Log.d(TAG, "writeDescriptor success");
            }
        }
    }
@@ -495,6 +550,7 @@
     */
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    public void writeCredentials(String data, WriteListener listener) {
        Log.d(TAG, "writeCredentials :准备写入");
        this.writeListener = listener;
        if (!isConnected || characteristic == null) {
            if (listener != null) {
@@ -508,6 +564,7 @@
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    private void writeCharacteristic(BluetoothGattCharacteristic characteristic, String value) {
        Log.d(TAG, "writeCharacteristic :开始写入");
        if (!this.getMissingPermissions().isEmpty()) {
            callbackHandler.post(() -> this.writeListener.onWriteFailed(-2)); // 没有权限
            return;
@@ -515,6 +572,7 @@
        characteristic.setValue(value.getBytes(StandardCharsets.UTF_8));
        characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
        bluetoothGatt.writeCharacteristic(characteristic);
        Log.d(TAG, "writeCharacteristic :开始完成");
    }
    // ==================== 工具方法 ====================