@tuanjie/mcp_serial 0.0.0-stage → 2.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/README.md +256 -3
- package/README_CN.md +256 -0
- package/build/cli/command-line-parser.js +99 -0
- package/build/config/server.js +7 -0
- package/build/core/mcp-server.js +191 -0
- package/build/index.js +52 -0
- package/build/models/types.js +1 -0
- package/build/services/history-service.js +383 -0
- package/build/services/serial-connection-manager.js +936 -0
- package/build/tools/connect.js +69 -0
- package/build/tools/connection-status.js +27 -0
- package/build/tools/disconnect.js +46 -0
- package/build/tools/export-log.js +81 -0
- package/build/tools/index.js +21 -0
- package/build/tools/log-between.js +71 -0
- package/build/tools/realtime-speed.js +24 -0
- package/build/tools/send-command.js +114 -0
- package/build/tools/serial-detect.js +30 -0
- package/build/utils/logger.js +84 -0
- package/build/utils/serial-collect.js +22 -0
- package/build/utils/serial-line-split.js +47 -0
- package/build/utils/time-format.js +142 -0
- package/package.json +46 -6
|
@@ -0,0 +1,936 @@
|
|
|
1
|
+
import { Logger } from "../utils/logger.js";
|
|
2
|
+
import { splitSerialBuffer, sanitizeSerialLogLine } from "../utils/serial-line-split.js";
|
|
3
|
+
import { detectInteractiveAction, SERIAL_IDLE_MS } from "../utils/serial-collect.js";
|
|
4
|
+
import { HistoryService } from "./history-service.js";
|
|
5
|
+
import fs from "fs";
|
|
6
|
+
import path from "path";
|
|
7
|
+
import { SerialPort } from "serialport";
|
|
8
|
+
/**
|
|
9
|
+
* Serial Port Connection Manager
|
|
10
|
+
* 使用 serialport 原生库,不依赖 picocom 等外部命令
|
|
11
|
+
*/
|
|
12
|
+
export class SerialConnectionManager {
|
|
13
|
+
static instance;
|
|
14
|
+
configs = {};
|
|
15
|
+
defaultName = "default";
|
|
16
|
+
/** 已打开的串口实例 */
|
|
17
|
+
serialPorts = new Map();
|
|
18
|
+
statusCache = new Map();
|
|
19
|
+
connected = new Map();
|
|
20
|
+
outputBuffers = new Map();
|
|
21
|
+
readBaselines = new Map();
|
|
22
|
+
bytesRead = new Map();
|
|
23
|
+
bytesWritten = new Map();
|
|
24
|
+
lastReadTime = new Map();
|
|
25
|
+
lastWriteTime = new Map();
|
|
26
|
+
/** 接收字节事件队列,用于实时速率统计(保留最近 60 秒) */
|
|
27
|
+
byteEvents = new Map();
|
|
28
|
+
/** 被动接收行缓冲(按行写入带时间戳日志) */
|
|
29
|
+
receiveLineBuffers = new Map();
|
|
30
|
+
/** 保活周期定时器:启动后每 10s 发送回车 */
|
|
31
|
+
keepAliveTimers = new Map();
|
|
32
|
+
/** 保活延迟定时器:末次用户命令后等待一段时间再启动保活 */
|
|
33
|
+
keepAliveDelayTimers = new Map();
|
|
34
|
+
/** 字符统计定时器:每 3s 统计最近 3s 接收字符数并写入文件 */
|
|
35
|
+
charCountTimers = new Map();
|
|
36
|
+
static SPEED_RETENTION_MS = 60_000;
|
|
37
|
+
static DEFAULT_SPEED_WINDOWS = [1, 5, 10, 30];
|
|
38
|
+
static KEEP_ALIVE_INTERVAL_MS = 10_000;
|
|
39
|
+
/** 末次用户命令后多久启动保活(避免打断 boot/登录) */
|
|
40
|
+
static KEEP_ALIVE_DELAY_AFTER_COMMAND_MS = 120_000;
|
|
41
|
+
/** 字符统计间隔与统计窗口(秒) */
|
|
42
|
+
static CHAR_COUNT_INTERVAL_MS = 3_000;
|
|
43
|
+
static CHAR_COUNT_WINDOW_SECONDS = 3;
|
|
44
|
+
constructor() {
|
|
45
|
+
// Initialize
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Get singleton instance
|
|
49
|
+
*/
|
|
50
|
+
static getInstance() {
|
|
51
|
+
if (!SerialConnectionManager.instance) {
|
|
52
|
+
SerialConnectionManager.instance = new SerialConnectionManager();
|
|
53
|
+
}
|
|
54
|
+
return SerialConnectionManager.instance;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Batch set serial port configurations
|
|
58
|
+
*/
|
|
59
|
+
setConfig(configs, defaultName) {
|
|
60
|
+
this.configs = configs;
|
|
61
|
+
if (defaultName && configs[defaultName]) {
|
|
62
|
+
this.defaultName = defaultName;
|
|
63
|
+
}
|
|
64
|
+
else if (Object.keys(configs).length > 0) {
|
|
65
|
+
this.defaultName = Object.keys(configs)[0];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Add a new serial port connection configuration
|
|
70
|
+
*/
|
|
71
|
+
addConnection(name, config) {
|
|
72
|
+
if (this.configs[name]) {
|
|
73
|
+
throw new Error(`Serial connection '${name}' already exists`);
|
|
74
|
+
}
|
|
75
|
+
this.configs[name] = { ...config, name };
|
|
76
|
+
if (!this.defaultName) {
|
|
77
|
+
this.defaultName = name;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* 设置或更新单串口连接配置(单串口监控模式)
|
|
82
|
+
*/
|
|
83
|
+
setConnectionConfig(name, config) {
|
|
84
|
+
this.configs[name] = { ...config, name };
|
|
85
|
+
this.defaultName = name;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* 判断两条连接配置是否等价(用于 connect 幂等判断)
|
|
89
|
+
*/
|
|
90
|
+
isSameConfig(a, b) {
|
|
91
|
+
return (a.path === b.path &&
|
|
92
|
+
(a.baudRate || 9600) === (b.baudRate || 9600) &&
|
|
93
|
+
(a.dataBits || 8) === (b.dataBits || 8) &&
|
|
94
|
+
(a.stopBits || 1) === (b.stopBits || 1) &&
|
|
95
|
+
(a.parity || "none") === (b.parity || "none") &&
|
|
96
|
+
!!a.rtscts === !!b.rtscts &&
|
|
97
|
+
!!a.xon === !!b.xon &&
|
|
98
|
+
!!a.xoff === !!b.xoff &&
|
|
99
|
+
!!a.xany === !!b.xany);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* 配置并打开串口(单串口监控入口)
|
|
103
|
+
* 若已连接且配置相同则幂等返回;配置变化则先关闭再重连
|
|
104
|
+
*/
|
|
105
|
+
async connect(name, config) {
|
|
106
|
+
const key = name || this.defaultName;
|
|
107
|
+
const nextConfig = { ...config, name: key };
|
|
108
|
+
const existing = this.configs[key];
|
|
109
|
+
if (existing && this.isOpen(key) && this.isSameConfig(existing, nextConfig)) {
|
|
110
|
+
Logger.log(`Serial port [${key}] already connected with same config`, "info");
|
|
111
|
+
return this.getStatus(key);
|
|
112
|
+
}
|
|
113
|
+
if (this.isOpen(key)) {
|
|
114
|
+
await this.close(key);
|
|
115
|
+
}
|
|
116
|
+
this.setConnectionConfig(key, nextConfig);
|
|
117
|
+
await this.open(key);
|
|
118
|
+
const status = this.getStatus(key);
|
|
119
|
+
if (!status) {
|
|
120
|
+
throw new Error(`Failed to get status after connecting [${key}]`);
|
|
121
|
+
}
|
|
122
|
+
return status;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* 判断预连接是否应跳过(无有效串口路径)
|
|
126
|
+
*/
|
|
127
|
+
shouldSkipPreConnect(name, config) {
|
|
128
|
+
if (!config.path) {
|
|
129
|
+
Logger.log(`Skipping pre-connect for [${name}]: no serial path configured`, "info");
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* 启动时批量连接全部已配置串口
|
|
136
|
+
* 单条失败不中断其余连接
|
|
137
|
+
*/
|
|
138
|
+
async connectAll() {
|
|
139
|
+
const failures = [];
|
|
140
|
+
for (const name of Object.keys(this.configs)) {
|
|
141
|
+
const config = this.configs[name];
|
|
142
|
+
if (this.shouldSkipPreConnect(name, config)) {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
await this.connect(name, config);
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
const message = `[${name}]: ${error.message}`;
|
|
150
|
+
failures.push(message);
|
|
151
|
+
Logger.log(`Pre-connect failed for ${message}`, "error");
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (failures.length > 0) {
|
|
155
|
+
throw new Error(`Pre-connect incomplete: ${failures.join("; ")}`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Get specified connection configuration
|
|
160
|
+
*/
|
|
161
|
+
getConfig(name) {
|
|
162
|
+
const key = name || this.defaultName;
|
|
163
|
+
if (!this.configs[key]) {
|
|
164
|
+
throw new Error(`Serial configuration for '${key}' not set`);
|
|
165
|
+
}
|
|
166
|
+
return this.configs[key];
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* 构建 serialport 打开参数
|
|
170
|
+
*/
|
|
171
|
+
buildOpenOptions(config) {
|
|
172
|
+
return {
|
|
173
|
+
path: config.path,
|
|
174
|
+
baudRate: config.baudRate ?? 9600,
|
|
175
|
+
dataBits: config.dataBits ?? 8,
|
|
176
|
+
stopBits: config.stopBits ?? 1,
|
|
177
|
+
parity: (config.parity ?? "none"),
|
|
178
|
+
rtscts: config.rtscts ?? false,
|
|
179
|
+
xon: config.xon ?? false,
|
|
180
|
+
xoff: config.xoff ?? false,
|
|
181
|
+
xany: config.xany ?? false,
|
|
182
|
+
autoOpen: false,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* 清理连接运行时状态
|
|
187
|
+
*/
|
|
188
|
+
cleanupConnectionState(key, path) {
|
|
189
|
+
this.stopKeepAlive(key);
|
|
190
|
+
this.stopCharCountRecorder(key);
|
|
191
|
+
this.flushReceiveLineBuffer(key);
|
|
192
|
+
this.serialPorts.delete(key);
|
|
193
|
+
this.outputBuffers.delete(key);
|
|
194
|
+
this.readBaselines.delete(key);
|
|
195
|
+
this.byteEvents.delete(key);
|
|
196
|
+
this.connected.set(key, false);
|
|
197
|
+
if (path) {
|
|
198
|
+
this.statusCache.set(key, { path, isOpen: false });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* 处理串口接收数据
|
|
203
|
+
*/
|
|
204
|
+
handleIncomingData(key, text) {
|
|
205
|
+
const totalBytes = (this.bytesRead.get(key) || 0) + text.length;
|
|
206
|
+
this.bytesRead.set(key, totalBytes);
|
|
207
|
+
const now = Date.now();
|
|
208
|
+
this.lastReadTime.set(key, now);
|
|
209
|
+
this.recordByteEvent(key, text.length, now);
|
|
210
|
+
this.appendReceiveLineLog(key, text);
|
|
211
|
+
Logger.log(`[${key}] DATA RECEIVED (${text.length} bytes, total: ${totalBytes} bytes): ${this.formatDataForLog(text, 200)}`, "debug");
|
|
212
|
+
const buffers = this.outputBuffers.get(key);
|
|
213
|
+
if (!buffers)
|
|
214
|
+
return;
|
|
215
|
+
const globalBuffer = buffers.get("__GLOBAL__") || "";
|
|
216
|
+
buffers.set("__GLOBAL__", globalBuffer + text);
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* 串口关闭事件处理
|
|
220
|
+
*/
|
|
221
|
+
handlePortClose(key, error) {
|
|
222
|
+
const config = this.configs[key];
|
|
223
|
+
Logger.log(`Serial port [${key}] closed${error ? `: ${error.message}` : ""}`, error ? "error" : "info");
|
|
224
|
+
this.cleanupConnectionState(key, config?.path);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* 发送保活回车(不写入串口文本日志,仅 debug 记录)
|
|
228
|
+
*/
|
|
229
|
+
sendKeepAlive(key) {
|
|
230
|
+
const port = this.serialPorts.get(key);
|
|
231
|
+
if (!port?.isOpen || this.connected.get(key) !== true) {
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
port.write("\r", (error) => {
|
|
235
|
+
if (error) {
|
|
236
|
+
Logger.log(`[${key}] keep-alive failed: ${error.message}`, "debug");
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
this.bytesWritten.set(key, (this.bytesWritten.get(key) || 0) + 1);
|
|
240
|
+
this.lastWriteTime.set(key, Date.now());
|
|
241
|
+
this.updateStatus(key);
|
|
242
|
+
Logger.log(`[${key}] keep-alive sent \\r`, "debug");
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* 安排保活:末次用户命令 2 分钟后才启动周期保活;新命令会重置等待
|
|
247
|
+
*/
|
|
248
|
+
scheduleKeepAlive(key) {
|
|
249
|
+
this.stopKeepAlive(key);
|
|
250
|
+
this.clearKeepAliveDelay(key);
|
|
251
|
+
const delayTimer = setTimeout(() => {
|
|
252
|
+
this.keepAliveDelayTimers.delete(key);
|
|
253
|
+
this.startKeepAliveInterval(key);
|
|
254
|
+
}, SerialConnectionManager.KEEP_ALIVE_DELAY_AFTER_COMMAND_MS);
|
|
255
|
+
this.keepAliveDelayTimers.set(key, delayTimer);
|
|
256
|
+
Logger.log(`[${key}] keep-alive scheduled (${SerialConnectionManager.KEEP_ALIVE_DELAY_AFTER_COMMAND_MS / 1000}s after last command)`, "info");
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* 启动保活周期:每 10s 发送一次回车
|
|
260
|
+
*/
|
|
261
|
+
startKeepAliveInterval(key) {
|
|
262
|
+
const existing = this.keepAliveTimers.get(key);
|
|
263
|
+
if (existing) {
|
|
264
|
+
clearInterval(existing);
|
|
265
|
+
}
|
|
266
|
+
const timer = setInterval(() => {
|
|
267
|
+
this.sendKeepAlive(key);
|
|
268
|
+
}, SerialConnectionManager.KEEP_ALIVE_INTERVAL_MS);
|
|
269
|
+
this.keepAliveTimers.set(key, timer);
|
|
270
|
+
Logger.log(`[${key}] keep-alive started (every ${SerialConnectionManager.KEEP_ALIVE_INTERVAL_MS / 1000}s)`, "info");
|
|
271
|
+
}
|
|
272
|
+
clearKeepAliveDelay(key) {
|
|
273
|
+
const timer = this.keepAliveDelayTimers.get(key);
|
|
274
|
+
if (timer) {
|
|
275
|
+
clearTimeout(timer);
|
|
276
|
+
this.keepAliveDelayTimers.delete(key);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* 停止保活(含延迟等待与周期发送)
|
|
281
|
+
*/
|
|
282
|
+
stopKeepAlive(key) {
|
|
283
|
+
this.clearKeepAliveDelay(key);
|
|
284
|
+
const timer = this.keepAliveTimers.get(key);
|
|
285
|
+
if (timer) {
|
|
286
|
+
clearInterval(timer);
|
|
287
|
+
this.keepAliveTimers.delete(key);
|
|
288
|
+
Logger.log(`[${key}] keep-alive stopped`, "debug");
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* 记录当前 3 秒窗口内的接收字符数到文件
|
|
293
|
+
*/
|
|
294
|
+
recordCharCountSnapshot(key) {
|
|
295
|
+
const config = this.configs[key];
|
|
296
|
+
if (!config?.path) {
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
const now = Date.now();
|
|
300
|
+
const events = this.byteEvents.get(key) || [];
|
|
301
|
+
const stats = this.calcWindowSpeed(events, SerialConnectionManager.CHAR_COUNT_WINDOW_SECONDS, now);
|
|
302
|
+
HistoryService.getInstance().appendCharCountEntry(config.path, now, stats.bytes);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* 启动字符统计:每 3s 统计最近 3s 接收字符数,写入 .chars.log
|
|
306
|
+
*/
|
|
307
|
+
startCharCountRecorder(key) {
|
|
308
|
+
this.stopCharCountRecorder(key);
|
|
309
|
+
const timer = setInterval(() => {
|
|
310
|
+
this.recordCharCountSnapshot(key);
|
|
311
|
+
}, SerialConnectionManager.CHAR_COUNT_INTERVAL_MS);
|
|
312
|
+
this.charCountTimers.set(key, timer);
|
|
313
|
+
Logger.log(`[${key}] char-count recorder started (every ${SerialConnectionManager.CHAR_COUNT_INTERVAL_MS / 1000}s, window ${SerialConnectionManager.CHAR_COUNT_WINDOW_SECONDS}s)`, "info");
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* 停止字符统计定时器,并刷写未满一行的缓冲
|
|
317
|
+
*/
|
|
318
|
+
stopCharCountRecorder(key) {
|
|
319
|
+
const timer = this.charCountTimers.get(key);
|
|
320
|
+
if (timer) {
|
|
321
|
+
clearInterval(timer);
|
|
322
|
+
this.charCountTimers.delete(key);
|
|
323
|
+
Logger.log(`[${key}] char-count recorder stopped`, "debug");
|
|
324
|
+
}
|
|
325
|
+
const config = this.configs[key];
|
|
326
|
+
if (config?.path) {
|
|
327
|
+
HistoryService.getInstance().flushCharCountBuffer(config.path);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Format data for logging (escape special characters)
|
|
332
|
+
*/
|
|
333
|
+
formatDataForLog(data, maxLength = 500) {
|
|
334
|
+
if (data.length <= maxLength) {
|
|
335
|
+
return data
|
|
336
|
+
.replace(/\r/g, "\\r")
|
|
337
|
+
.replace(/\n/g, "\\n")
|
|
338
|
+
.replace(/\t/g, "\\t")
|
|
339
|
+
.replace(/\0/g, "\\0");
|
|
340
|
+
}
|
|
341
|
+
const truncated = data.substring(0, maxLength);
|
|
342
|
+
return (truncated
|
|
343
|
+
.replace(/\r/g, "\\r")
|
|
344
|
+
.replace(/\n/g, "\\n")
|
|
345
|
+
.replace(/\t/g, "\\t")
|
|
346
|
+
.replace(/\0/g, "\\0") + `... (truncated, total ${data.length} bytes)`);
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* 打开串口连接(serialport 原生实现)
|
|
350
|
+
*/
|
|
351
|
+
async open(name) {
|
|
352
|
+
const key = name || this.defaultName;
|
|
353
|
+
const config = this.getConfig(key);
|
|
354
|
+
const existing = this.serialPorts.get(key);
|
|
355
|
+
if (existing?.isOpen) {
|
|
356
|
+
Logger.log(`Serial port [${key}] ${config.path} is already open`, "info");
|
|
357
|
+
if (!this.charCountTimers.has(key)) {
|
|
358
|
+
this.startCharCountRecorder(key);
|
|
359
|
+
}
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
Logger.log(`Opening serial port [${key}] ${config.path} at ${config.baudRate || 9600} baud (serialport)`, "info");
|
|
363
|
+
try {
|
|
364
|
+
const port = new SerialPort(this.buildOpenOptions(config));
|
|
365
|
+
await new Promise((resolve, reject) => {
|
|
366
|
+
port.open((err) => (err ? reject(err) : resolve()));
|
|
367
|
+
});
|
|
368
|
+
this.bytesRead.set(key, 0);
|
|
369
|
+
this.bytesWritten.set(key, 0);
|
|
370
|
+
this.byteEvents.set(key, []);
|
|
371
|
+
this.outputBuffers.set(key, new Map());
|
|
372
|
+
port.on("data", (data) => {
|
|
373
|
+
this.handleIncomingData(key, data.toString());
|
|
374
|
+
});
|
|
375
|
+
port.on("close", () => {
|
|
376
|
+
this.handlePortClose(key);
|
|
377
|
+
});
|
|
378
|
+
port.on("error", (error) => {
|
|
379
|
+
Logger.log(`[${key}] serial port error: ${error.message}`, "error");
|
|
380
|
+
this.handlePortClose(key, error);
|
|
381
|
+
});
|
|
382
|
+
this.serialPorts.set(key, port);
|
|
383
|
+
this.connected.set(key, true);
|
|
384
|
+
Logger.log(`[${key}] PORT OPENED: ${config.path} (baudRate: ${config.baudRate || 9600}, dataBits: ${config.dataBits || 8}, stopBits: ${config.stopBits || 1}, parity: ${config.parity || "none"})`, "info");
|
|
385
|
+
this.statusCache.set(key, {
|
|
386
|
+
path: config.path,
|
|
387
|
+
isOpen: true,
|
|
388
|
+
baudRate: config.baudRate || 9600,
|
|
389
|
+
bytesRead: 0,
|
|
390
|
+
bytesWritten: 0,
|
|
391
|
+
});
|
|
392
|
+
this.startCharCountRecorder(key);
|
|
393
|
+
}
|
|
394
|
+
catch (error) {
|
|
395
|
+
this.connected.set(key, false);
|
|
396
|
+
throw new Error(`Failed to open serial port [${key}]: ${error.message}`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Check if connection is open
|
|
401
|
+
*/
|
|
402
|
+
isOpen(name) {
|
|
403
|
+
const key = name || this.defaultName;
|
|
404
|
+
const port = this.serialPorts.get(key);
|
|
405
|
+
return port !== undefined && port.isOpen && this.connected.get(key) === true;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Clear buffer for a connection (mark current position as new baseline)
|
|
409
|
+
* This ensures the next read operation only returns new data
|
|
410
|
+
*/
|
|
411
|
+
clearBuffer(name) {
|
|
412
|
+
const key = name || this.defaultName;
|
|
413
|
+
const buffers = this.outputBuffers.get(key);
|
|
414
|
+
if (buffers) {
|
|
415
|
+
const currentBuffer = buffers.get("__GLOBAL__") || "";
|
|
416
|
+
// Set current buffer length as the new baseline
|
|
417
|
+
this.readBaselines.set(key, currentBuffer.length);
|
|
418
|
+
Logger.log(`[${key}] Buffer baseline set to ${currentBuffer.length} bytes`, "debug");
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Read data from serial port
|
|
423
|
+
* Read data from serial port(异步缓冲轮询)
|
|
424
|
+
*/
|
|
425
|
+
async read(name, options = {}) {
|
|
426
|
+
const key = name || this.defaultName;
|
|
427
|
+
const timeout = options.timeout || 5000;
|
|
428
|
+
const maxBytes = options.maxBytes;
|
|
429
|
+
const waitFor = options.waitFor;
|
|
430
|
+
if (!this.isOpen(key)) {
|
|
431
|
+
throw new Error(`Serial port [${key}] is not open`);
|
|
432
|
+
}
|
|
433
|
+
const startTime = Date.now();
|
|
434
|
+
// Get baseline - either from clearBuffer() call or current buffer length
|
|
435
|
+
const baseline = this.readBaselines.get(key);
|
|
436
|
+
const currentGlobalBuffer = this.outputBuffers.get(key)?.get("__GLOBAL__") || "";
|
|
437
|
+
const initialBufferLength = baseline !== undefined ? baseline : currentGlobalBuffer.length;
|
|
438
|
+
// Update baseline to current position if not set
|
|
439
|
+
if (baseline === undefined) {
|
|
440
|
+
this.readBaselines.set(key, currentGlobalBuffer.length);
|
|
441
|
+
}
|
|
442
|
+
// Log read request
|
|
443
|
+
const readOptions = [];
|
|
444
|
+
if (timeout)
|
|
445
|
+
readOptions.push(`timeout=${timeout}ms`);
|
|
446
|
+
if (maxBytes)
|
|
447
|
+
readOptions.push(`maxBytes=${maxBytes}`);
|
|
448
|
+
if (waitFor)
|
|
449
|
+
readOptions.push(`waitFor="${waitFor}"`);
|
|
450
|
+
Logger.log(`[${key}] <<< READ REQUEST${readOptions.length > 0 ? ` (${readOptions.join(", ")})` : ""}`, "info");
|
|
451
|
+
return new Promise((resolveOriginal, rejectOriginal) => {
|
|
452
|
+
let isResolved = false;
|
|
453
|
+
const timeoutId = setTimeout(() => {
|
|
454
|
+
if (isResolved)
|
|
455
|
+
return;
|
|
456
|
+
isResolved = true;
|
|
457
|
+
const currentBuffer = this.outputBuffers.get(key)?.get("__GLOBAL__") || "";
|
|
458
|
+
const newData = currentBuffer.substring(initialBufferLength);
|
|
459
|
+
if (newData.length > 0) {
|
|
460
|
+
const duration = Date.now() - startTime;
|
|
461
|
+
Logger.log(`[${key}] <<< READ (${duration}ms, timeout with data, ${newData.length} bytes):\n${this.formatDataForLog(newData)}`, "info");
|
|
462
|
+
// Update baseline to mark this data as consumed
|
|
463
|
+
this.readBaselines.set(key, initialBufferLength + newData.length);
|
|
464
|
+
resolveOriginal(newData);
|
|
465
|
+
}
|
|
466
|
+
else {
|
|
467
|
+
Logger.log(`[${key}] <<< READ TIMEOUT (${Date.now() - startTime}ms): No data received`, "error");
|
|
468
|
+
rejectOriginal(new Error(`Read timeout after ${timeout}ms`));
|
|
469
|
+
}
|
|
470
|
+
}, timeout);
|
|
471
|
+
// Poll for new data
|
|
472
|
+
let lastDataLength = 0;
|
|
473
|
+
let silenceStartTime = Date.now();
|
|
474
|
+
const SILENCE_THRESHOLD = 200; // 200ms of silence before resolving
|
|
475
|
+
const checkData = () => {
|
|
476
|
+
if (isResolved)
|
|
477
|
+
return;
|
|
478
|
+
const currentBuffer = this.outputBuffers.get(key)?.get("__GLOBAL__") || "";
|
|
479
|
+
const newData = currentBuffer.substring(initialBufferLength);
|
|
480
|
+
// Check if new data arrived
|
|
481
|
+
if (newData.length > lastDataLength) {
|
|
482
|
+
lastDataLength = newData.length;
|
|
483
|
+
silenceStartTime = Date.now(); // Reset silence timer
|
|
484
|
+
}
|
|
485
|
+
if (newData.length === 0) {
|
|
486
|
+
// No new data yet, check again after a short delay
|
|
487
|
+
if (Date.now() - startTime < timeout) {
|
|
488
|
+
setTimeout(checkData, 20); // Check every 20ms (faster polling)
|
|
489
|
+
}
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
// Check conditions
|
|
493
|
+
let shouldResolve = false;
|
|
494
|
+
let result = newData;
|
|
495
|
+
if (waitFor) {
|
|
496
|
+
// Generic prompt matching: detect prompt completion
|
|
497
|
+
// Look for prompt at end of lines (most reliable indicator of command completion)
|
|
498
|
+
const lines = newData.split(/\r?\n/);
|
|
499
|
+
// Check last few lines for prompt (check more lines for reliability)
|
|
500
|
+
let promptFoundAtEnd = false;
|
|
501
|
+
let promptLineIndex = -1;
|
|
502
|
+
for (let i = lines.length - 1; i >= Math.max(0, lines.length - 5); i--) {
|
|
503
|
+
const line = lines[i]?.trim() || "";
|
|
504
|
+
// Check if line ends with prompt or is exactly the prompt
|
|
505
|
+
if (line.endsWith(waitFor) || line === waitFor) {
|
|
506
|
+
promptFoundAtEnd = true;
|
|
507
|
+
promptLineIndex = i;
|
|
508
|
+
break;
|
|
509
|
+
}
|
|
510
|
+
// Also check if prompt appears in the line (for cases like "ZXAN#")
|
|
511
|
+
if (line.includes(waitFor) && (line.endsWith(waitFor) || line.match(new RegExp(waitFor.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*$')))) {
|
|
512
|
+
promptFoundAtEnd = true;
|
|
513
|
+
promptLineIndex = i;
|
|
514
|
+
break;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
// Also check if prompt appears at end of data stream
|
|
518
|
+
const trimmedData = newData.trim();
|
|
519
|
+
const promptAtDataEnd = trimmedData.endsWith(waitFor) ||
|
|
520
|
+
newData.endsWith(waitFor + "\r\n") ||
|
|
521
|
+
newData.endsWith(waitFor + "\n") ||
|
|
522
|
+
newData.endsWith(waitFor + "\r");
|
|
523
|
+
if (promptFoundAtEnd || promptAtDataEnd) {
|
|
524
|
+
// Prompt found at end - command likely completed
|
|
525
|
+
// Wait a short period to ensure no more data is coming
|
|
526
|
+
const timeSinceLastData = Date.now() - silenceStartTime;
|
|
527
|
+
// If prompt is in the last line or second-to-last line, we're confident
|
|
528
|
+
const isRecentPrompt = promptLineIndex >= lines.length - 2;
|
|
529
|
+
if (isRecentPrompt && timeSinceLastData >= 30) {
|
|
530
|
+
// Recent prompt with short silence - resolve quickly
|
|
531
|
+
shouldResolve = true;
|
|
532
|
+
Logger.log(`[${key}] <<< READ (${Date.now() - startTime}ms, prompt "${waitFor}" detected at line ${promptLineIndex + 1}/${lines.length}, ${newData.length} bytes):\n${this.formatDataForLog(newData)}`, "info");
|
|
533
|
+
}
|
|
534
|
+
else if (timeSinceLastData >= 50) {
|
|
535
|
+
// Older prompt but with sufficient silence
|
|
536
|
+
shouldResolve = true;
|
|
537
|
+
Logger.log(`[${key}] <<< READ (${Date.now() - startTime}ms, prompt "${waitFor}" detected (${timeSinceLastData}ms silence), ${newData.length} bytes):\n${this.formatDataForLog(newData)}`, "info");
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
else if (newData.includes(waitFor)) {
|
|
541
|
+
// Prompt found but not at end - might be in progress
|
|
542
|
+
// Wait for data to stabilize
|
|
543
|
+
const timeSinceLastData = Date.now() - silenceStartTime;
|
|
544
|
+
if (timeSinceLastData >= 150) {
|
|
545
|
+
shouldResolve = true;
|
|
546
|
+
Logger.log(`[${key}] <<< READ (${Date.now() - startTime}ms, prompt "${waitFor}" found in data (${timeSinceLastData}ms silence), ${newData.length} bytes):\n${this.formatDataForLog(newData)}`, "info");
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
if (!shouldResolve && maxBytes && newData.length >= maxBytes) {
|
|
551
|
+
shouldResolve = true;
|
|
552
|
+
result = newData.substring(0, maxBytes);
|
|
553
|
+
Logger.log(`[${key}] <<< READ (${Date.now() - startTime}ms, reached maxBytes=${maxBytes}, ${result.length} bytes):\n${this.formatDataForLog(result)}`, "info");
|
|
554
|
+
}
|
|
555
|
+
else if (!shouldResolve && !waitFor && !maxBytes) {
|
|
556
|
+
// Default mode: wait for data to stabilize (silence period)
|
|
557
|
+
// This indicates command execution is likely complete
|
|
558
|
+
const timeSinceLastData = Date.now() - silenceStartTime;
|
|
559
|
+
if (timeSinceLastData >= SILENCE_THRESHOLD && newData.length > 0) {
|
|
560
|
+
shouldResolve = true;
|
|
561
|
+
Logger.log(`[${key}] <<< READ (${Date.now() - startTime}ms, data stabilized (${timeSinceLastData}ms silence), ${newData.length} bytes):\n${this.formatDataForLog(newData)}`, "info");
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
if (shouldResolve && !isResolved) {
|
|
565
|
+
isResolved = true;
|
|
566
|
+
clearTimeout(timeoutId);
|
|
567
|
+
// Update baseline to mark this data as consumed
|
|
568
|
+
const finalBuffer = this.outputBuffers.get(key)?.get("__GLOBAL__") || "";
|
|
569
|
+
this.readBaselines.set(key, initialBufferLength + result.length);
|
|
570
|
+
resolveOriginal(result);
|
|
571
|
+
}
|
|
572
|
+
else if (!isResolved) {
|
|
573
|
+
// Continue checking with faster polling
|
|
574
|
+
setTimeout(checkData, 20);
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
// Start checking immediately
|
|
578
|
+
checkData();
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* 在指定时长内收集串口新数据(到期即返回,无数据也返回空字符串)
|
|
583
|
+
*/
|
|
584
|
+
async readForDuration(name, durationMs = 5000) {
|
|
585
|
+
const key = name || this.defaultName;
|
|
586
|
+
if (!this.isOpen(key)) {
|
|
587
|
+
throw new Error(`Serial port [${key}] is not open`);
|
|
588
|
+
}
|
|
589
|
+
const baseline = this.readBaselines.get(key);
|
|
590
|
+
const currentGlobalBuffer = this.outputBuffers.get(key)?.get("__GLOBAL__") || "";
|
|
591
|
+
const initialBufferLength = baseline !== undefined ? baseline : currentGlobalBuffer.length;
|
|
592
|
+
if (baseline === undefined) {
|
|
593
|
+
this.readBaselines.set(key, currentGlobalBuffer.length);
|
|
594
|
+
}
|
|
595
|
+
const startTime = Date.now();
|
|
596
|
+
Logger.log(`[${key}] <<< READ FOR ${durationMs}ms`, "info");
|
|
597
|
+
while (Date.now() - startTime < durationMs) {
|
|
598
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
599
|
+
}
|
|
600
|
+
const currentBuffer = this.outputBuffers.get(key)?.get("__GLOBAL__") || "";
|
|
601
|
+
const newData = currentBuffer.substring(initialBufferLength);
|
|
602
|
+
this.readBaselines.set(key, initialBufferLength + newData.length);
|
|
603
|
+
Logger.log(`[${key}] <<< READ DONE (${Date.now() - startTime}ms, ${newData.length} bytes):\n${this.formatDataForLog(newData)}`, "info");
|
|
604
|
+
return newData;
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* 静默收包:持续读取直至无新数据 idleMs,或达到 hardTimeoutMs。
|
|
608
|
+
* 遇 More / `{ <cr>…}:` 自动续键(对齐 mcp_telnet)。
|
|
609
|
+
*/
|
|
610
|
+
async readUntilIdle(name, options = {}) {
|
|
611
|
+
const key = name || this.defaultName;
|
|
612
|
+
const idleMs = options.idleMs ?? SERIAL_IDLE_MS;
|
|
613
|
+
const hardTimeoutMs = options.hardTimeoutMs ?? 5000;
|
|
614
|
+
if (!this.isOpen(key)) {
|
|
615
|
+
throw new Error(`Serial port [${key}] is not open`);
|
|
616
|
+
}
|
|
617
|
+
const baseline = this.readBaselines.get(key);
|
|
618
|
+
const currentGlobalBuffer = this.outputBuffers.get(key)?.get("__GLOBAL__") || "";
|
|
619
|
+
const initialBufferLength = baseline !== undefined ? baseline : currentGlobalBuffer.length;
|
|
620
|
+
if (baseline === undefined) {
|
|
621
|
+
this.readBaselines.set(key, currentGlobalBuffer.length);
|
|
622
|
+
}
|
|
623
|
+
const startTime = Date.now();
|
|
624
|
+
let lastLen = 0;
|
|
625
|
+
let silenceStart = Date.now();
|
|
626
|
+
let awaitingDevice = false;
|
|
627
|
+
let sawData = false;
|
|
628
|
+
Logger.log(`[${key}] <<< READ UNTIL IDLE (idle=${idleMs}ms, hard=${hardTimeoutMs}ms)`, "info");
|
|
629
|
+
while (Date.now() - startTime < hardTimeoutMs) {
|
|
630
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
631
|
+
const currentBuffer = this.outputBuffers.get(key)?.get("__GLOBAL__") || "";
|
|
632
|
+
const newData = currentBuffer.substring(initialBufferLength);
|
|
633
|
+
if (newData.length > lastLen) {
|
|
634
|
+
lastLen = newData.length;
|
|
635
|
+
silenceStart = Date.now();
|
|
636
|
+
awaitingDevice = false;
|
|
637
|
+
sawData = true;
|
|
638
|
+
const action = detectInteractiveAction(newData);
|
|
639
|
+
if (action && !awaitingDevice) {
|
|
640
|
+
awaitingDevice = true;
|
|
641
|
+
const keyStroke = action === "cr" ? "\r" : " ";
|
|
642
|
+
try {
|
|
643
|
+
await this.write(keyStroke, key);
|
|
644
|
+
}
|
|
645
|
+
catch (e) {
|
|
646
|
+
Logger.log(`[${key}] auto-key failed: ${e.message}`, "debug");
|
|
647
|
+
}
|
|
648
|
+
silenceStart = Date.now();
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
else if (sawData && Date.now() - silenceStart >= idleMs) {
|
|
652
|
+
if (awaitingDevice) {
|
|
653
|
+
// 续键后仍无新数据:结束
|
|
654
|
+
awaitingDevice = false;
|
|
655
|
+
}
|
|
656
|
+
else {
|
|
657
|
+
const action = detectInteractiveAction(newData);
|
|
658
|
+
if (action) {
|
|
659
|
+
awaitingDevice = true;
|
|
660
|
+
try {
|
|
661
|
+
await this.write(action === "cr" ? "\r" : " ", key);
|
|
662
|
+
}
|
|
663
|
+
catch {
|
|
664
|
+
// ignore
|
|
665
|
+
}
|
|
666
|
+
silenceStart = Date.now();
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
this.readBaselines.set(key, initialBufferLength + newData.length);
|
|
671
|
+
Logger.log(`[${key}] <<< READ IDLE DONE (${Date.now() - startTime}ms, ${newData.length} bytes):\n${this.formatDataForLog(newData)}`, "info");
|
|
672
|
+
return newData;
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
const currentBuffer = this.outputBuffers.get(key)?.get("__GLOBAL__") || "";
|
|
676
|
+
const newData = currentBuffer.substring(initialBufferLength);
|
|
677
|
+
this.readBaselines.set(key, initialBufferLength + newData.length);
|
|
678
|
+
Logger.log(`[${key}] <<< READ HARD TIMEOUT (${Date.now() - startTime}ms, ${newData.length} bytes)`, "info");
|
|
679
|
+
return newData;
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* Write data to serial port
|
|
683
|
+
*/
|
|
684
|
+
async write(data, name) {
|
|
685
|
+
const key = name || this.defaultName;
|
|
686
|
+
const port = this.serialPorts.get(key);
|
|
687
|
+
if (!port || !port.isOpen || !this.isOpen(key)) {
|
|
688
|
+
throw new Error(`Serial port [${key}] is not open`);
|
|
689
|
+
}
|
|
690
|
+
const startTime = Date.now();
|
|
691
|
+
Logger.log(`[${key}] >>> WRITE (${data.length} bytes):\n${this.formatDataForLog(data)}`, "info");
|
|
692
|
+
return new Promise((resolve, reject) => {
|
|
693
|
+
port.write(data, (error) => {
|
|
694
|
+
const duration = Date.now() - startTime;
|
|
695
|
+
if (error) {
|
|
696
|
+
Logger.log(`[${key}] <<< WRITE ERROR (${duration}ms): ${error.message}`, "error");
|
|
697
|
+
reject(error);
|
|
698
|
+
}
|
|
699
|
+
else {
|
|
700
|
+
this.bytesWritten.set(key, (this.bytesWritten.get(key) || 0) + data.length);
|
|
701
|
+
this.lastWriteTime.set(key, Date.now());
|
|
702
|
+
this.updateStatus(key);
|
|
703
|
+
try {
|
|
704
|
+
const config = this.getConfig(key);
|
|
705
|
+
HistoryService.getInstance().appendSerialContent(config.path, data, "tx");
|
|
706
|
+
}
|
|
707
|
+
catch {
|
|
708
|
+
// 配置缺失时不写串口文本日志
|
|
709
|
+
}
|
|
710
|
+
this.scheduleKeepAlive(key);
|
|
711
|
+
Logger.log(`[${key}] <<< WRITE SUCCESS (${duration}ms, ${data.length} bytes written)`, "info");
|
|
712
|
+
resolve();
|
|
713
|
+
}
|
|
714
|
+
});
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Update status cache for a connection
|
|
719
|
+
*/
|
|
720
|
+
updateStatus(key) {
|
|
721
|
+
const port = this.serialPorts.get(key);
|
|
722
|
+
const config = this.getConfig(key);
|
|
723
|
+
if (port) {
|
|
724
|
+
this.statusCache.set(key, {
|
|
725
|
+
path: config.path,
|
|
726
|
+
isOpen: this.isOpen(key),
|
|
727
|
+
baudRate: config.baudRate || 9600,
|
|
728
|
+
bytesRead: this.bytesRead.get(key) || 0,
|
|
729
|
+
bytesWritten: this.bytesWritten.get(key) || 0,
|
|
730
|
+
lastReadTime: this.lastReadTime.get(key)
|
|
731
|
+
? new Date(this.lastReadTime.get(key)).toISOString()
|
|
732
|
+
: undefined,
|
|
733
|
+
lastWriteTime: this.lastWriteTime.get(key)
|
|
734
|
+
? new Date(this.lastWriteTime.get(key)).toISOString()
|
|
735
|
+
: undefined,
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* Close serial port connection
|
|
741
|
+
*/
|
|
742
|
+
async close(name) {
|
|
743
|
+
const key = name || this.defaultName;
|
|
744
|
+
const port = this.serialPorts.get(key);
|
|
745
|
+
if (!port) {
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
Logger.log(`Closing serial port connection [${key}]`, "info");
|
|
749
|
+
try {
|
|
750
|
+
await new Promise((resolve, reject) => {
|
|
751
|
+
port.close((err) => (err ? reject(err) : resolve()));
|
|
752
|
+
});
|
|
753
|
+
this.cleanupConnectionState(key, this.getConfig(key).path);
|
|
754
|
+
Logger.log(`Serial port [${key}] closed successfully`, "info");
|
|
755
|
+
}
|
|
756
|
+
catch (error) {
|
|
757
|
+
Logger.log(`Error closing serial port [${key}]: ${error.message}`, "error");
|
|
758
|
+
throw error;
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Close all connections
|
|
763
|
+
*/
|
|
764
|
+
async closeAll() {
|
|
765
|
+
const keys = Array.from(this.serialPorts.keys());
|
|
766
|
+
for (const key of keys) {
|
|
767
|
+
await this.close(key);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Get status of a connection
|
|
772
|
+
*/
|
|
773
|
+
getStatus(name) {
|
|
774
|
+
const key = name || this.defaultName;
|
|
775
|
+
this.updateStatus(key);
|
|
776
|
+
return this.statusCache.get(key);
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* 将被动接收数据按行写入历史日志(每行独立时间戳)
|
|
780
|
+
* 支持 \r\n / \n / \r 换行,写入前清洗控制字符
|
|
781
|
+
*/
|
|
782
|
+
appendReceiveLineLog(key, text) {
|
|
783
|
+
let buffer = this.receiveLineBuffers.get(key) || "";
|
|
784
|
+
buffer += text;
|
|
785
|
+
const { lines, remainder } = splitSerialBuffer(buffer);
|
|
786
|
+
this.receiveLineBuffers.set(key, remainder);
|
|
787
|
+
const historyService = HistoryService.getInstance();
|
|
788
|
+
const config = this.configs[key];
|
|
789
|
+
if (!config?.path)
|
|
790
|
+
return;
|
|
791
|
+
for (const line of lines) {
|
|
792
|
+
historyService.appendSerialContent(config.path, line, "rx", Date.now());
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
/**
|
|
796
|
+
* 断开前刷写未以换行结束的接收缓冲,保证带时间戳落盘
|
|
797
|
+
*/
|
|
798
|
+
flushReceiveLineBuffer(key) {
|
|
799
|
+
const buffer = this.receiveLineBuffers.get(key);
|
|
800
|
+
if (!buffer) {
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
const sanitized = sanitizeSerialLogLine(buffer);
|
|
804
|
+
const config = this.configs[key];
|
|
805
|
+
if (sanitized.length > 0 && config?.path) {
|
|
806
|
+
HistoryService.getInstance().appendSerialContent(config.path, sanitized, "rx", Date.now());
|
|
807
|
+
}
|
|
808
|
+
this.receiveLineBuffers.delete(key);
|
|
809
|
+
}
|
|
810
|
+
/**
|
|
811
|
+
* 记录接收字节事件(供实时速率统计)
|
|
812
|
+
*/
|
|
813
|
+
recordByteEvent(key, bytes, timestamp) {
|
|
814
|
+
const events = this.byteEvents.get(key) || [];
|
|
815
|
+
events.push({ timestamp, bytes });
|
|
816
|
+
const cutoff = timestamp - SerialConnectionManager.SPEED_RETENTION_MS;
|
|
817
|
+
while (events.length > 0 && events[0].timestamp < cutoff) {
|
|
818
|
+
events.shift();
|
|
819
|
+
}
|
|
820
|
+
this.byteEvents.set(key, events);
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* 计算指定时间窗口内的字符速率(字节/秒)
|
|
824
|
+
*/
|
|
825
|
+
calcWindowSpeed(events, windowSeconds, now) {
|
|
826
|
+
const cutoff = now - windowSeconds * 1000;
|
|
827
|
+
let bytes = 0;
|
|
828
|
+
for (const event of events) {
|
|
829
|
+
if (event.timestamp >= cutoff) {
|
|
830
|
+
bytes += event.bytes;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
const charsPerSecond = windowSeconds > 0 ? bytes / windowSeconds : 0;
|
|
834
|
+
return {
|
|
835
|
+
windowSeconds,
|
|
836
|
+
bytes,
|
|
837
|
+
charsPerSecond: Math.round(charsPerSecond * 100) / 100,
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* 获取实时字符速率统计
|
|
842
|
+
*/
|
|
843
|
+
getRealtimeSpeed(name, windows = SerialConnectionManager.DEFAULT_SPEED_WINDOWS) {
|
|
844
|
+
const key = name || this.defaultName;
|
|
845
|
+
const now = Date.now();
|
|
846
|
+
const events = this.byteEvents.get(key) || [];
|
|
847
|
+
const windowStats = windows.map((w) => this.calcWindowSpeed(events, w, now));
|
|
848
|
+
return {
|
|
849
|
+
connected: this.isOpen(key),
|
|
850
|
+
totalBytesRead: this.bytesRead.get(key) || 0,
|
|
851
|
+
totalBytesWritten: this.bytesWritten.get(key) || 0,
|
|
852
|
+
lastReadTime: this.lastReadTime.get(key)
|
|
853
|
+
? new Date(this.lastReadTime.get(key)).toISOString()
|
|
854
|
+
: undefined,
|
|
855
|
+
lastWriteTime: this.lastWriteTime.get(key)
|
|
856
|
+
? new Date(this.lastWriteTime.get(key)).toISOString()
|
|
857
|
+
: undefined,
|
|
858
|
+
windows: windowStats,
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* 获取当前连接完整状态(单串口监控)
|
|
863
|
+
*/
|
|
864
|
+
getConnectionStatus(name) {
|
|
865
|
+
const key = name || this.defaultName;
|
|
866
|
+
const config = this.configs[key];
|
|
867
|
+
if (!config) {
|
|
868
|
+
return { configured: false, connected: false };
|
|
869
|
+
}
|
|
870
|
+
return {
|
|
871
|
+
configured: true,
|
|
872
|
+
connected: this.isOpen(key),
|
|
873
|
+
config,
|
|
874
|
+
status: this.getStatus(key),
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* 枚举可用串口(serialport.list + /dev 扫描,无外部命令)
|
|
879
|
+
*/
|
|
880
|
+
static async listPorts() {
|
|
881
|
+
try {
|
|
882
|
+
const byPath = new Map();
|
|
883
|
+
const listed = await SerialPort.list();
|
|
884
|
+
for (const p of listed) {
|
|
885
|
+
byPath.set(p.path, {
|
|
886
|
+
path: p.path,
|
|
887
|
+
manufacturer: p.manufacturer,
|
|
888
|
+
serialNumber: p.serialNumber,
|
|
889
|
+
pnpId: p.pnpId,
|
|
890
|
+
locationId: p.locationId,
|
|
891
|
+
vendorId: p.vendorId,
|
|
892
|
+
productId: p.productId,
|
|
893
|
+
});
|
|
894
|
+
}
|
|
895
|
+
// 兜底扫描:Linux 扫 ttyUSB/ttyACM/ttyS;macOS 扫 tty.*/cu.*;Windows 无 /dev,跳过
|
|
896
|
+
if (process.platform === "linux" || process.platform === "darwin") {
|
|
897
|
+
try {
|
|
898
|
+
const devDir = "/dev";
|
|
899
|
+
const deviceNamePattern = process.platform === "linux"
|
|
900
|
+
? /^(ttyUSB\d+|ttyACM\d+|ttyS\d+)$/
|
|
901
|
+
: /^(tty\..+|cu\..+)$/;
|
|
902
|
+
for (const name of fs.readdirSync(devDir)) {
|
|
903
|
+
if (deviceNamePattern.test(name)) {
|
|
904
|
+
const fullPath = path.join(devDir, name);
|
|
905
|
+
if (!byPath.has(fullPath)) {
|
|
906
|
+
byPath.set(fullPath, { path: fullPath });
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
catch {
|
|
912
|
+
// /dev 不可读时忽略
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
return Array.from(byPath.values()).sort((a, b) => a.path.localeCompare(b.path));
|
|
916
|
+
}
|
|
917
|
+
catch (error) {
|
|
918
|
+
throw new Error(`Failed to list serial ports: ${error.message}`);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* Get basic information of all configured ports
|
|
923
|
+
*/
|
|
924
|
+
getAllPortInfos() {
|
|
925
|
+
return Object.keys(this.configs).map((key) => {
|
|
926
|
+
const config = this.configs[key];
|
|
927
|
+
const status = this.statusCache.get(key);
|
|
928
|
+
return {
|
|
929
|
+
name: key,
|
|
930
|
+
path: config.path,
|
|
931
|
+
isOpen: this.isOpen(key),
|
|
932
|
+
status: status,
|
|
933
|
+
};
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
}
|