依赖:
<dependency>
<groupId>com.fazecast</groupId>
<artifactId>jSerialComm</artifactId>
<version>${jSerialComm}</version>
</dependency>
代码:
private ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();public static synchronized SerialPortUtils getInstance() {if (instance == null) {instance = new SerialPortUtils();}return instance;}public SerialPort openPort(String portName, int baudRate, int dataBits, int stopBits, int parity) {if (serialPort == null || !serialPort.isOpen()) {serialPort = SerialPort.getCommPort(portName);serialPort.setComPortParameters(baudRate, dataBits, stopBits, parity);serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);serialPort.openPort();}return serialPort;}@Overridepublic void executeOptimized(XXXPO xxxPO) {SerialPortUtils serialPortUtil = SerialPortUtils.getInstance();SerialPort comPort = null;try {comPort = serialPortUtil.openPort(xxxPO.串口, xxxPO。比特率, xxxPO.数据位, xxxPO.停止位,xxxPO.校验位);if (comPort == null || !comPort.isOpen()) {return;}comPort.addDataListener(new SerialPortDataListener() {@Overridepublic int getListeningEvents() {return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;}@Overridepublic void serialEvent(SerialPortEvent event) {if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {return;}byte[] newData = new byte[event.getSerialPort().bytesAvailable()];int numRead = event.getSerialPort().readBytes(newData, newData.length);if (numRead > 0) {byteArrayOutputStream.write(newData, 0, numRead); // 直接将读取到的数据写入ByteArrayOutputStream// 打印二进制数据, 确定结尾是不是 \r \n的进制结尾,测试没问题可以删除System.out.print("Received binary data: ");for (byte b : newData) {System.out.printf("%02X ", b); // %02X 表示以两位十六进制数打印,不足两位前面补0}System.out.println(); // 换行// 检查并处理完整的行processAccumulatedData();}}});} catch (Exception e) {e.printStackTrace();}}private void processAccumulatedData() {byte[] byteArray = byteArrayOutputStream.toByteArray();if(byteArray.length < 2){return;}// 确保数据以 \r\n 结尾,如果不是则认为是不完整的数据并直接返回if ( byteArray[byteArray.length - 2] != '\r' && byteArray[byteArray.length - 1] != '\n') {return;}String data = new String(byteArray, StandardCharsets.UTF_8);// 按照 \r\n 分割数据为多行String[] lines = data.split("\r\n");for (String line : lines) {// 处理每一行数据System.out.println("line: " + line);handler(line);}// 处理完数据后重置 byteArrayOutputStream 准备接受下一批数据byteArrayOutputStream.reset();}