You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android OTA Service结束字节返回错误129,写入时遇新问题求助

解决Android OTA写入结束字节(0x03)的问题

我之前已经搞定了Android OTA Service中结束字节返回错误129的问题,但现在在写入结束字节(对应OTAEND指令)时碰到了新状况。下面是相关的代码片段和我整理的排查方案:

触发写入结束字节的代码

case "OTAEND":
    Log.d("OTAEND", "Called");
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            writeOtaControl((byte) 0x03);
        }
    }, 500);
    break;

writeOtaControl方法(补全核心逻辑)

/**WRITES BYTE TO OTA CONTROL CHARACTERISTIC*****************************************/
public boolean writeOtaControl(byte ctrl) {
    Log.d("writeOtaControl", "Called");
    // 先检查Gatt连接状态
    if (bluetoothGatt == null || bluetoothGatt.getConnectionState() != BluetoothProfile.STATE_CONNECTED) {
        Log.e("writeOtaControl", "Gatt connection lost");
        return false;
    }
    
    if (bluetoothGatt.getService(ota_service) != null) {
        BluetoothGattCharacteristic otaControlChar = bluetoothGatt.getService(ota_service)
               .getCharacteristic(ota_control_char);
        if (otaControlChar != null) {
            otaControlChar.setValue(new byte[]{ctrl});
            // 注意:写入类型需要匹配设备端要求
            otaControlChar.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
            return bluetoothGatt.writeCharacteristic(otaControlChar);
        }
    }
    return false;
}

可能的问题排查与解决思路

  • 写入类型不匹配:很多OTA设备要求控制字节写入必须使用带响应的WRITE_TYPE_DEFAULT,而非无响应的WRITE_TYPE_NO_RESPONSE。如果设备期望收到响应但你用了无响应写入,大概率会忽略这个结束指令。
  • 固定延迟的不可靠性:用postDelayed(500)触发写入太依赖时间,固件传输的耗时可能波动,建议改成在固件传输完成的回调中触发写入,比如收到设备的“传输完成”通知后再发结束字节。
  • Gatt操作队列阻塞:BluetoothGatt的操作是串行队列,如果之前的固件分片写入还未完成,新的写入会直接失败。可以在onCharacteristicWrite回调中确认前一次操作成功后,再执行结束字节的写入。
  • Characteristic属性校验:确认ota_control_char的属性包含PROPERTY_WRITE或PROPERTY_WRITE_NO_RESPONSE,可以通过otaControlChar.getProperties()打印日志检查。
  • 设备端状态校验:有些OTA设备要求必须确认所有固件数据接收完整(比如校验CRC、字节数)才会处理结束字节,所以发送0x03前要确保固件传输的完整性。

优化后的回调触发示例

// 假设在收到设备的固件传输完成通知时调用
private void onFirmwareTransferConfirmed() {
    if (bluetoothGatt != null && bluetoothGatt.getConnectionState() == BluetoothProfile.STATE_CONNECTED) {
        writeOtaControl((byte) 0x03);
    }
}

// 重写Gatt回调,监控写入结果
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        if (characteristic.getUuid().equals(ota_control_char)) {
            Log.d("OTA", "End byte 0x03 written successfully");
            // 这里可以等待设备的OTA完成通知
        }
    } else {
        Log.e("OTA", "Write end byte failed, status: " + status);
        // 可根据需求添加重试逻辑
    }
}

内容的提问来源于stack exchange,提问作者trOnk12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:33:08