使用felHR85/UsbSerial向Galileosky终端发送响应失败求助
问题排查与解决方案
核心问题根源
RS-485为半双工通信,多数USB转RS-485模块依赖RTS引脚切换收发模式,现有代码未配置该控制;同时sendMessage方法未等待写入完成就标记传输结束,且响应数据的编码格式可能不符合Galileosky终端的协议要求。
具体修改代码
1. 配置RS-485收发控制(关键步骤)
在setupUsbConnection方法中添加RTS引脚控制及写入完成回调,确保发送时切换到发送模式,完成后切回接收模式:
public void setupUsbConnection() { if (device != null) { UsbDeviceConnection connection = usbManager.openDevice(device); serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection); if (serialPort != null) { serialPort.open(); serialPort.setBaudRate(19200); serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8); serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1); serialPort.setParity(UsbSerialInterface.PARITY_NONE); // 初始设置为接收模式 serialPort.setRTS(false); // 设置写入完成回调,传输结束后切回接收模式 serialPort.setUsbWriteCallback(new UsbSerialInterface.UsbWriteCallback() { @Override public void onWriteFinished(int bytesWritten) { isTransmitting = false; serialPort.setRTS(false); } }); } } else { System.err.println("Device not found"); } }
2. 修复sendMessage方法
修改为直接接收字节数组(避免字符串编码错误),发送前切换到发送模式:
public void sendMessage(byte[] responseBytes) { if (serialPort != null && responseBytes != null) { isTransmitting = true; // 发送前切换到发送模式 serialPort.setRTS(true); serialPort.write(responseBytes); } else { System.err.println("Serial port is not initialized or response data is null"); } } // 新增工具方法:十六进制字符串转字节数组,用于构造符合终端协议的响应 public static byte[] hexStringToByteArray(String hexStr) { int len = hexStr.length(); byte[] result = new byte[len / 2]; for (int i = 0; i < len; i += 2) { result[i / 2] = (byte) ((Character.digit(hexStr.charAt(i), 16) << 4) + Character.digit(hexStr.charAt(i+1), 16)); } return result; }
3. 在onReceivedData中实现响应逻辑
根据Galileosky终端的协议要求构造响应帧,示例为返回ACK(需根据实际协议调整):
public final UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { @Override public void onReceivedData(byte[] data) { String receivedDataHex = bytesToHex(data); if (callbackFunction != null) { callbackFunction.onReceived(receivedDataHex); } // 构造响应:示例为在原数据后添加06作为ACK(需替换为终端要求的响应格式) byte[] response = hexStringToByteArray(receivedDataHex + "06"); sendMessage(response); } };
额外注意事项
- 严格匹配Galileosky终端的响应协议:包括帧结构、校验位、ACK字节等,必须与终端文档一致。
- 检查硬件接线:确保USB转RS-485模块的A/B线与终端对应连接,部分模块需通过硬件跳帽启用RTS控制。
- 确认串口参数:波特率、数据位、停止位、奇偶校验必须和终端配置完全一致,当前代码为19200/8N1。
内容的提问来源于stack exchange,提问作者Like Channel
相关产品推荐
相关产品推荐

