From 03b0fb0ba2de86bcfff277778826547c0e37a93f Mon Sep 17 00:00:00 2001
From: 张世豪 <979909237@qq.com>
Date: 星期四, 20 十一月 2025 23:52:51 +0800
Subject: [PATCH] 优化修改

---
 src/chuankou/SerialPortService.java |  439 ++++++++++++++++++++++++++++--------------------------
 1 files changed, 227 insertions(+), 212 deletions(-)

diff --git a/src/chuankou/SerialPortService.java b/src/chuankou/SerialPortService.java
index 5fe532c..7efeb68 100644
--- a/src/chuankou/SerialPortService.java
+++ b/src/chuankou/SerialPortService.java
@@ -10,234 +10,249 @@
 
 public class SerialPortService {
 
-    private SerialPort port;
-    private volatile boolean capturing = false;
-    private volatile boolean paused = true;
-    private Thread readerThread;
-    private Consumer<byte[]> responseConsumer;
-    
-    // 浼樺寲锛氶噸鐢ㄧ紦鍐插尯锛屽噺灏戝唴瀛樺垎閰�
-    private byte[] readBuffer = new byte[200];
-    private ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
-    private Consumer<byte[]> dataReceivedCallback;
-    
-    // 鏂板锛氬崗璁В鏋愬櫒寮曠敤
-    private SerialProtocolParser protocolParser = new SerialProtocolParser();
-    
-    // 鏂板锛氭暟鎹潯鏁拌鏁板櫒
-    public static  int receivedDataCount = 0;
+	private SerialPort port;
+	private volatile boolean capturing = false;
+	private volatile boolean paused = true;
+	private Thread readerThread;
+	private Consumer<byte[]> responseConsumer;
 
-    // 鍏朵粬鐜版湁鏂规硶淇濇寔涓嶅彉...
-    
-    /**
-     * 鑾峰彇涓插彛鎺ユ敹鐨勬暟鎹潯鏁�
-     * 褰撴潯鏁拌秴杩�1涓囨椂鑷姩浠�1寮�濮嬮噸鏂拌鏁�
-     * @return 鏁版嵁鏉℃暟瀛楃涓�
-     */
-    public static String getReceivedDataCount() {
-        receivedDataCount++;
-        if (receivedDataCount > 10000) {
-            receivedDataCount = 1;
-        }
-        return String.valueOf(receivedDataCount);
-    }
-    
-    public static void setReceivedDataCount(int receivedDataCount) {
-		SerialPortService.receivedDataCount = receivedDataCount;
-	}
-    
-    /**
-     * 鑾峰彇鍗忚瑙f瀽鍣ㄥ疄渚�
-     */
-    public SerialProtocolParser getProtocolParser() {
-        return protocolParser;
-    }
+	// 浼樺寲锛氶噸鐢ㄧ紦鍐插尯锛屽噺灏戝唴瀛樺垎閰�
+	private byte[] readBuffer = new byte[200];
+	private ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024);
+	private Consumer<byte[]> dataReceivedCallback;
+
+	// 鏂板锛氬崗璁В鏋愬櫒寮曠敤
+	private SerialProtocolParser protocolParser = new SerialProtocolParser();
+
+	// 鏂板锛氭暟鎹潯鏁拌鏁板櫒
+	public static  int receivedDataCount = 0;
+
+	// 鍏朵粬鐜版湁鏂规硶淇濇寔涓嶅彉...
 
 	/**
-     * 閲嶇疆鏁版嵁鏉℃暟璁℃暟鍣�
-     */
-    public void resetReceivedDataCount() {
-        receivedDataCount = 0;
-    }
+	 * 鑾峰彇涓插彛鎺ユ敹鐨勬暟鎹潯鏁�
+	 * 褰撴潯鏁拌秴杩�1涓囨椂鑷姩浠�1寮�濮嬮噸鏂拌鏁�
+	 * @return 鏁版嵁鏉℃暟瀛楃涓�
+	 */
+	public static String getReceivedDataCount() {
+		receivedDataCount++;
+		if (receivedDataCount > 10000) {
+			receivedDataCount = 1;
+		}
+		return String.valueOf(receivedDataCount);
+	}
 
-    // 浠ヤ笅涓哄師鏈変唬鐮侊紝淇濇寔涓嶅彉...
-    public InputStream getInputStream() {
-        if (port != null && port.isOpen()) {
-            return port.getInputStream();
-        }
-        return null;
-    }
+	public static void setReceivedDataCount(int receivedDataCount) {
+		SerialPortService.receivedDataCount = receivedDataCount;
+	}
 
-    public OutputStream getOutputStream() {
-        if (port != null && port.isOpen()) {
-            return port.getOutputStream();
-        }
-        return null;
-    }
-    
-    public void setComPortTimeouts(int timeoutMode, int readTimeout, int writeTimeout) {
-        if (port != null && port.isOpen()) {
-            port.setComPortTimeouts(timeoutMode, readTimeout, writeTimeout);
-        }
-    }
-    
-    /**
-     * 璁剧疆鍗忚瑙f瀽鍣�
-     */
-    public void setProtocolParser(SerialProtocolParser parser) {
-        this.protocolParser = parser;
-    }
-    
-    /**
-     * 鍚敤璋冭瘯杈撳嚭锛屽皢鎺ユ敹鍒扮殑鏁版嵁鎵撳嵃鍒版帶鍒跺彴
-     */
-    public void enableDebugOutput() {
-        System.out.println("涓插彛璋冭瘯杈撳嚭宸插惎鐢� - 寮�濮嬬洃鍚覆鍙f暟鎹�...");
-    }
+	/**
+	 * 鑾峰彇鍗忚瑙f瀽鍣ㄥ疄渚�
+	 */
+	public SerialProtocolParser getProtocolParser() {
+		return protocolParser;
+	}
 
-    /**
-     * 鑾峰彇褰撳墠璋冭瘯鐘舵��
-     */
-    public boolean isDebugEnabled() {
-        return capturing;
-    }
-    
-    public void startCapture() {
-        if (dataReceivedCallback != null) {
-            startCapture(dataReceivedCallback);
-        } else {
-            System.err.println("No data received callback set. Please call startCapture(Consumer<byte[]> onReceived) first.");
-        }
-   }
+	/**
+	 * 閲嶇疆鏁版嵁鏉℃暟璁℃暟鍣�
+	 */
+	public void resetReceivedDataCount() {
+		receivedDataCount = 0;
+	}
 
-    /**
-     * 鎵撳紑涓插彛
-     */
-    public boolean open(String portName, int baud) {
-        if (port != null && port.isOpen()) {
-            return true;
-        }
+	// 浠ヤ笅涓哄師鏈変唬鐮侊紝淇濇寔涓嶅彉...
+	public InputStream getInputStream() {
+		if (port != null && port.isOpen()) {
+			return port.getInputStream();
+		}
+		return null;
+	}
 
-        port = SerialPort.getCommPort(portName);
-        port.setComPortParameters(baud, 8, 1, SerialPort.NO_PARITY);
-        port.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 1, 0);
-        protocolParser.start();
-        return port.openPort();
-    }
-    
-    public void setResponseConsumer(Consumer<byte[]> consumer) {
-        this.responseConsumer = consumer;
-    }
+	public OutputStream getOutputStream() {
+		if (port != null && port.isOpen()) {
+			return port.getOutputStream();
+		}
+		return null;
+	}
 
-    /**
-     * 鍏抽棴涓插彛
-     */
-    public void close() {
-        stopCapture();
-        if (port != null && port.isOpen()) {
-            port.closePort();
-        }
-        port = null;
-    }
+	public void setComPortTimeouts(int timeoutMode, int readTimeout, int writeTimeout) {
+		if (port != null && port.isOpen()) {
+			port.setComPortTimeouts(timeoutMode, readTimeout, writeTimeout);
+		}
+	}
 
-    /**
-     * 鍚姩鏁版嵁鎺ユ敹绾跨▼
-     */
-    public void startCapture(Consumer<byte[]> onReceived) {
-        this.dataReceivedCallback = onReceived;
-        if (capturing || port == null || !port.isOpen()) return;
-        capturing = true;
-        paused = false;
+	/**
+	 * 璁剧疆鍗忚瑙f瀽鍣�
+	 */
+	public void setProtocolParser(SerialProtocolParser parser) {
+		this.protocolParser = parser;
+	}
 
-        readerThread = new Thread(() -> {
-            buffer.reset();
-            long lastReceivedTime = 0;
-            
-            while (capturing && port.isOpen()) {
-                long currentTime = System.currentTimeMillis();
-                
-                if (buffer.size() > 0 && (currentTime - lastReceivedTime) >= 20) {
-                    byte[] data = buffer.toByteArray();
-                    SystemDebugDialog.appendHexData(data);
-                    
-                    // 鏂板锛氬皢鏁版嵁浼犻�掔粰鍗忚瑙f瀽鍣�
-                    if (protocolParser != null) {
-                        protocolParser.receiveData(data);
-                    }
-                    
-                    if (!paused) {
-                        onReceived.accept(data);
-                        if (responseConsumer != null) {
-                            responseConsumer.accept(data);
-                        }
-                    }
-                    buffer.reset();
-                }
+	/**
+	 * 鍚敤璋冭瘯杈撳嚭锛屽皢鎺ユ敹鍒扮殑鏁版嵁鎵撳嵃鍒版帶鍒跺彴
+	 */
+	public void enableDebugOutput() {
+		//System.out.println("涓插彛璋冭瘯杈撳嚭宸插惎鐢� - 寮�濮嬬洃鍚覆鍙f暟鎹�...");
+	}
 
-                int len = port.readBytes(readBuffer, readBuffer.length);
-                currentTime = System.currentTimeMillis();
+	/**
+	 * 鑾峰彇褰撳墠璋冭瘯鐘舵��
+	 */
+	public boolean isDebugEnabled() {
+		return capturing;
+	}
 
-                if (len > 0) {
-                    buffer.write(readBuffer, 0, len);
-                    lastReceivedTime = currentTime;
-                }
-                
-                if (len <= 0 && buffer.size() == 0) {
-                    try { Thread.sleep(1); } catch (InterruptedException ignore) {}
-                }
-            }
-            
-            if (buffer.size() > 0) {
-                byte[] data = buffer.toByteArray();              
-                SystemDebugDialog.appendHexData(data);
-                
-                // 鏂板锛氬皢鏁版嵁浼犻�掔粰鍗忚瑙f瀽鍣�
-                if (protocolParser != null) {
-                    protocolParser.receiveData(data);
-                }
-                
-                if (!paused) {
-                    onReceived.accept(data);
-                    if (responseConsumer != null) {
-                        responseConsumer.accept(data);
-                    }
-                }
-            }
-        });
-        readerThread.setDaemon(true);
-        readerThread.start();
-    }
+	public void startCapture() {
+		if (dataReceivedCallback != null) {
+			startCapture(dataReceivedCallback);
+		} else {
+			System.err.println("No data received callback set. Please call startCapture(Consumer<byte[]> onReceived) first.");
+		}
+	}
 
-    /**
-     * 鍋滄鏁版嵁鎺ユ敹绾跨▼
-     */
-    public void stopCapture() {
-        capturing = false;
-        if (readerThread != null) {
-            try { readerThread.join(500); } catch (InterruptedException ignore) {}
-            readerThread = null;
-        }
-    }
+	/**
+	 * 鎵撳紑涓插彛
+	 */
+	public boolean open(String portName, int baud) {
+		if (port != null && port.isOpen()) {
+			return true;
+		}
 
-    public void setPaused(boolean paused) {
-        this.paused = paused;
-    }
+		port = SerialPort.getCommPort(portName);
+		port.setComPortParameters(baud, 8, 1, SerialPort.NO_PARITY);
+		port.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 1, 0);
+		protocolParser.start();
+		return port.openPort();
+	}
 
-    public boolean isPaused() {
-        return paused;
-    }
+	public void setResponseConsumer(Consumer<byte[]> consumer) {
+		this.responseConsumer = consumer;
+	}
 
-    public boolean isOpen() {
-        return port != null && port.isOpen();
-    }
+	/**
+	 * 鍏抽棴涓插彛
+	 */
+	public void close() {
+		stopCapture();
+		if (port != null && port.isOpen()) {
+			port.closePort();
+		}
+		port = null;
+	}
 
-    /**
-     * 鍙戦�佹暟鎹�
-     */
-    public boolean send(byte[] data) {
-        if (!isOpen()) {
-            return false;
-        }
-        return port != null && port.isOpen() && port.writeBytes(data, data.length) > 0;
-    }
+	/**
+	 * 鍚姩鏁版嵁鎺ユ敹绾跨▼
+	 */
+	public void startCapture(Consumer<byte[]> onReceived) {
+		this.dataReceivedCallback = onReceived;
+		if (capturing || port == null || !port.isOpen()) return;
+		capturing = true;
+		paused = false;
+
+		readerThread = new Thread(() -> {
+			buffer.reset();
+			long lastReceivedTime = 0;
+
+			while (capturing && port.isOpen()) {
+				long currentTime = System.currentTimeMillis();
+
+				if (buffer.size() > 0 && (currentTime - lastReceivedTime) >= 20) {
+					byte[] data = buffer.toByteArray();
+					SystemDebugDialog.appendHexData(data);
+
+					// 鏂板锛氬皢鏁版嵁浼犻�掔粰鍗忚瑙f瀽鍣�
+					if (protocolParser != null) {
+						protocolParser.receiveData(data);
+					}
+
+					if (!paused) {
+						onReceived.accept(data);
+						if (responseConsumer != null) {
+							responseConsumer.accept(data);
+						}
+					}
+					buffer.reset();
+				}
+
+				int len = port.readBytes(readBuffer, readBuffer.length);
+				currentTime = System.currentTimeMillis();
+
+				if (len > 0) {
+					buffer.write(readBuffer, 0, len);
+					lastReceivedTime = currentTime;
+				}
+
+				if (len <= 0 && buffer.size() == 0) {
+					try { Thread.sleep(1); } catch (InterruptedException ignore) {}
+				}
+			}
+
+			if (buffer.size() > 0) {
+				byte[] data = buffer.toByteArray();              
+				SystemDebugDialog.appendHexData(data);
+
+				// 鏂板锛氬皢鏁版嵁浼犻�掔粰鍗忚瑙f瀽鍣�
+				if (protocolParser != null) {
+					protocolParser.receiveData(data);
+				}
+
+				if (!paused) {
+					onReceived.accept(data);
+					if (responseConsumer != null) {
+						responseConsumer.accept(data);
+					}
+				}
+			}
+		});
+		readerThread.setDaemon(true);
+		readerThread.start();
+	}
+
+	/**
+	 * 鍋滄鏁版嵁鎺ユ敹绾跨▼
+	 */
+	public void stopCapture() {
+		capturing = false;
+		if (readerThread != null) {
+			try { readerThread.join(500); } catch (InterruptedException ignore) {}
+			readerThread = null;
+		}
+	}
+
+	public void setPaused(boolean paused) {
+		this.paused = paused;
+	}
+
+	public boolean isPaused() {
+		return paused;
+	}
+
+	public boolean isOpen() {
+		return port != null && port.isOpen();
+	}
+	/**
+	 * 鍙戦�佹暟鎹紙浼樺寲鐗堟湰锛�
+	 */
+	public boolean send(byte[] data) {
+		if (!isOpen()) {
+			return false;
+		}
+
+		// 娣诲姞鍙戦�佸墠鐨勪覆鍙g姸鎬佹鏌�
+		if (port == null || !port.isOpen()) {
+			return false;
+		}
+
+		try {
+			// 娣诲姞灏忓欢杩燂紝閬垮厤杩炵画鍙戦��
+			Thread.sleep(2);
+		} catch (InterruptedException e) {
+			Thread.currentThread().interrupt();
+			return false;
+		}
+
+		int result = port.writeBytes(data, data.length);
+		return result > 0;
+	}
+
 }
\ No newline at end of file

--
Gitblit v1.9.3