张世豪
3 小时以前 d22349714c8d199c02f336f90fba841ef8f5cd39
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package chuankou;
 
import com.fazecast.jSerialComm.SerialPort;
import java.util.function.Consumer;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import publicway.SerialProtocolParser; // 添加导入
import xitongshezhi.SystemDebugDialog;
 
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;
 
    // 其他现有方法保持不变...
 
    /**
     * 获取串口接收的数据条数
     * 当条数超过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;
    }
 
    /**
     * 获取协议解析器实例
     */
    public SerialProtocolParser getProtocolParser() {
        return protocolParser;
    }
 
    /**
     * 重置数据条数计数器
     */
    public void resetReceivedDataCount() {
        receivedDataCount = 0;
    }
 
    // 以下为原有代码,保持不变...
    public InputStream getInputStream() {
        if (port != null && port.isOpen()) {
            return port.getInputStream();
        }
        return null;
    }
 
    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);
        }
    }
 
    /**
     * 设置协议解析器
     */
    public void setProtocolParser(SerialProtocolParser parser) {
        this.protocolParser = parser;
    }
 
    /**
     * 启用调试输出,将接收到的数据打印到控制台
     */
    public void enableDebugOutput() {
        //System.out.println("串口调试输出已启用 - 开始监听串口数据...");
    }
 
    /**
     * 获取当前调试状态
     */
    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 boolean open(String portName, int baud) {
        if (port != null && port.isOpen()) {
            return true;
        }
 
        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 void close() {
        stopCapture();
        if (port != null && port.isOpen()) {
            port.closePort();
        }
        port = null;
    }
 
    /**
     * 启动数据接收线程
     */
    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);
 
                    // 新增:将数据传递给协议解析器 - 确保始终执行
                    if (protocolParser != null) {
                        protocolParser.receiveData(data);
                    }
 
                    // 确保数据回调始终执行,不受暂停状态影响
                    if (dataReceivedCallback != null && !paused) {
                        dataReceivedCallback.accept(data);
                    }
                    if (responseConsumer != null && !paused) {
                        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);
 
                // 新增:将数据传递给协议解析器 - 确保始终执行
                if (protocolParser != null) {
                    protocolParser.receiveData(data);
                }
 
                // 确保数据回调始终执行,不受暂停状态影响
                if (dataReceivedCallback != null && !paused) {
                    dataReceivedCallback.accept(data);
                }
                if (responseConsumer != null && !paused) {
                    responseConsumer.accept(data);
                }
            }
        });
        readerThread.setDaemon(true);
        readerThread.start();
    }
    // 新增:设置暂停状态但不影响协议解析器
    public void setPaused(boolean paused) {
        this.paused = paused;
        // 注意:不停止协议解析器,只暂停UI回调
    }
 
    // 新增:单独停止数据捕获而不影响协议解析器
    public void stopDataCaptureOnly() {
        // 只停止数据回调,不影响协议解析器
        this.dataReceivedCallback = null;
        this.responseConsumer = null;
    }
    /**
     * 停止数据接收线程
     */
    public void stopCapture() {
        capturing = false;
        if (readerThread != null) {
            try { readerThread.join(500); } catch (InterruptedException ignore) {}
            readerThread = null;
        }
    }
 
 
    public boolean isPaused() {
        return paused;
    }
 
    public boolean isOpen() {
        return port != null && port.isOpen();
    }
    /**
     * 发送数据(优化版本)
     */
    public boolean send(byte[] data) {
        if (!isOpen()) {
            return false;
        }
 
        // 添加发送前的串口状态检查
        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;
    }
 
}