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

Flutter中flutter_libserialport写入超60字节失败的解决方法

解决Flutter串口写入超过60字节数据的问题

问题原因

flutter_libserialport的write方法返回的是实际写入串口缓冲区的字节数,并非全部数据的长度。当数据量超过串口单次可写入的缓冲区大小(此处为60字节)时,剩余数据需要分批写入。

修复方案

修改SerialPortManager中的write方法,通过循环逐步写入剩余数据,直到所有数据发送完成:

int write(Uint8List data) {
  try {
    if (!_serialPort.isOpen) {
      if (!open()) {
        return -1;
      }
    }
    
    int totalWritten = 0;
    int remaining = data.length;
    int offset = 0;
    
    while (remaining > 0) {
      int written = _serialPort.write(data.sublist(offset));
      if (written <= 0) {
        debugPrint("Write failed after $totalWritten bytes");
        logManager.addLog("Write failed after $totalWritten bytes");
        return totalWritten == 0 ? -1 : totalWritten;
      }
      totalWritten += written;
      offset += written;
      remaining -= written;
      
      // 可选:若设备串口处理速度慢,添加短暂延迟避免缓冲区溢出
      // await Future.delayed(const Duration(milliseconds: 1));
    }
    
    return totalWritten;
  } catch (e) {
    debugPrint("Error writing to port $portName: $e");
    logManager.addLog("Error writing to port $portName: $e");
    return -1;
  }
}

关键说明

  • 循环写入:每次调用write获取实际写入长度,更新偏移量和剩余数据量,直到全部发送完毕。
  • 错误处理:若某次写入返回<=0,记录已写入字节数并返回,避免数据丢失。
  • 可选延迟:根据设备串口处理能力,可添加短暂延迟防止缓冲区溢出。

验证修改

修改后重新测试,打印的length应等于120,说明120字节数据已完整写入串口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 12:30:03