@tuanjie/mcp_serial 0.0.0-stage → 2.3.2
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 +255 -2
- 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 +377 -0
- package/build/services/serial-connection-manager.js +928 -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 +81 -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 +44 -4
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { SerialConnectionManager } from "../services/serial-connection-manager.js";
|
|
3
|
+
import { HistoryService } from "../services/history-service.js";
|
|
4
|
+
import { Logger } from "../utils/logger.js";
|
|
5
|
+
/** 单串口监控默认连接名 */
|
|
6
|
+
const DEFAULT_CONNECTION = "default";
|
|
7
|
+
/**
|
|
8
|
+
* 注册 connect 工具:配置参数并打开串口连接
|
|
9
|
+
*/
|
|
10
|
+
export function registerConnectTool(server) {
|
|
11
|
+
const serialManager = SerialConnectionManager.getInstance();
|
|
12
|
+
const historyService = HistoryService.getInstance();
|
|
13
|
+
server.tool("connect", "连接串口:填入串口路径、波特率等参数并打开连接(单串口监控)", {
|
|
14
|
+
path: z.string().describe("串口路径,如 /dev/ttyUSB0"),
|
|
15
|
+
baudRate: z.number().optional().describe("波特率,默认 9600"),
|
|
16
|
+
dataBits: z.number().optional().describe("数据位:5/6/7/8,默认 8"),
|
|
17
|
+
stopBits: z.number().optional().describe("停止位:1 或 2,默认 1"),
|
|
18
|
+
parity: z
|
|
19
|
+
.enum(["none", "even", "odd", "mark", "space"])
|
|
20
|
+
.optional()
|
|
21
|
+
.describe("校验位,默认 none"),
|
|
22
|
+
rtscts: z.boolean().optional().describe("RTS/CTS 硬件流控,默认 false"),
|
|
23
|
+
xon: z.boolean().optional().describe("XON 软件流控,默认 false"),
|
|
24
|
+
xoff: z.boolean().optional().describe("XOFF 软件流控,默认 false"),
|
|
25
|
+
xany: z.boolean().optional().describe("XANY 软件流控,默认 false"),
|
|
26
|
+
}, async (params) => {
|
|
27
|
+
try {
|
|
28
|
+
if (params.dataBits && ![5, 6, 7, 8].includes(params.dataBits)) {
|
|
29
|
+
throw new Error("dataBits must be 5, 6, 7, or 8");
|
|
30
|
+
}
|
|
31
|
+
if (params.stopBits && ![1, 2].includes(params.stopBits)) {
|
|
32
|
+
throw new Error("stopBits must be 1 or 2");
|
|
33
|
+
}
|
|
34
|
+
const status = await serialManager.connect(DEFAULT_CONNECTION, {
|
|
35
|
+
path: params.path,
|
|
36
|
+
baudRate: params.baudRate,
|
|
37
|
+
dataBits: params.dataBits,
|
|
38
|
+
stopBits: params.stopBits,
|
|
39
|
+
parity: params.parity,
|
|
40
|
+
rtscts: params.rtscts,
|
|
41
|
+
xon: params.xon,
|
|
42
|
+
xoff: params.xoff,
|
|
43
|
+
xany: params.xany,
|
|
44
|
+
});
|
|
45
|
+
historyService.addHistory(DEFAULT_CONNECTION, "connect", `Connected to ${params.path} @ ${params.baudRate || 9600} baud`, true);
|
|
46
|
+
return {
|
|
47
|
+
content: [
|
|
48
|
+
{
|
|
49
|
+
type: "text",
|
|
50
|
+
text: JSON.stringify({
|
|
51
|
+
success: true,
|
|
52
|
+
message: `Connected to ${params.path}`,
|
|
53
|
+
path: params.path,
|
|
54
|
+
baudRate: params.baudRate || 9600,
|
|
55
|
+
status,
|
|
56
|
+
}, null, 2),
|
|
57
|
+
},
|
|
58
|
+
],
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
const errorMessage = Logger.handleError(error, "Failed to connect");
|
|
63
|
+
return {
|
|
64
|
+
content: [{ type: "text", text: errorMessage }],
|
|
65
|
+
isError: true,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { SerialConnectionManager } from "../services/serial-connection-manager.js";
|
|
2
|
+
/**
|
|
3
|
+
* 注册 connection-status 工具:查询当前串口连接状态
|
|
4
|
+
*/
|
|
5
|
+
export function registerConnectionStatusTool(server) {
|
|
6
|
+
server.tool("connection-status", "查询当前串口连接状态(是否已配置、是否已连接、读写字节统计等)", {}, async () => {
|
|
7
|
+
const serialManager = SerialConnectionManager.getInstance();
|
|
8
|
+
const status = serialManager.getConnectionStatus();
|
|
9
|
+
const speed = serialManager.getRealtimeSpeed();
|
|
10
|
+
return {
|
|
11
|
+
content: [
|
|
12
|
+
{
|
|
13
|
+
type: "text",
|
|
14
|
+
text: JSON.stringify({
|
|
15
|
+
...status,
|
|
16
|
+
speed: {
|
|
17
|
+
totalBytesRead: speed.totalBytesRead,
|
|
18
|
+
totalBytesWritten: speed.totalBytesWritten,
|
|
19
|
+
lastReadTime: speed.lastReadTime,
|
|
20
|
+
lastWriteTime: speed.lastWriteTime,
|
|
21
|
+
},
|
|
22
|
+
}, null, 2),
|
|
23
|
+
},
|
|
24
|
+
],
|
|
25
|
+
};
|
|
26
|
+
});
|
|
27
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { SerialConnectionManager } from "../services/serial-connection-manager.js";
|
|
2
|
+
import { HistoryService } from "../services/history-service.js";
|
|
3
|
+
import { Logger } from "../utils/logger.js";
|
|
4
|
+
/** 单串口监控默认连接名 */
|
|
5
|
+
const DEFAULT_CONNECTION = "default";
|
|
6
|
+
/**
|
|
7
|
+
* 注册 disconnect 工具:断开当前串口连接
|
|
8
|
+
*/
|
|
9
|
+
export function registerDisconnectTool(server) {
|
|
10
|
+
const serialManager = SerialConnectionManager.getInstance();
|
|
11
|
+
const historyService = HistoryService.getInstance();
|
|
12
|
+
server.tool("disconnect", "断开当前串口连接(关闭 serialport 会话,保留配置以便下次 connect 重连)", {}, async () => {
|
|
13
|
+
try {
|
|
14
|
+
const wasOpen = serialManager.isOpen(DEFAULT_CONNECTION);
|
|
15
|
+
const config = serialManager.getConnectionStatus();
|
|
16
|
+
const path = config.config?.path || "unknown";
|
|
17
|
+
await serialManager.close(DEFAULT_CONNECTION);
|
|
18
|
+
if (wasOpen) {
|
|
19
|
+
historyService.addHistory(DEFAULT_CONNECTION, "disconnect", `Disconnected from ${path}`, true);
|
|
20
|
+
}
|
|
21
|
+
return {
|
|
22
|
+
content: [
|
|
23
|
+
{
|
|
24
|
+
type: "text",
|
|
25
|
+
text: JSON.stringify({
|
|
26
|
+
success: true,
|
|
27
|
+
message: wasOpen
|
|
28
|
+
? `Disconnected from ${path}`
|
|
29
|
+
: "Serial port was not connected",
|
|
30
|
+
wasConnected: wasOpen,
|
|
31
|
+
path: wasOpen ? path : undefined,
|
|
32
|
+
}, null, 2),
|
|
33
|
+
},
|
|
34
|
+
],
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
const errorMessage = Logger.handleError(error, "Failed to disconnect");
|
|
39
|
+
historyService.addHistory(DEFAULT_CONNECTION, "disconnect", undefined, false, errorMessage);
|
|
40
|
+
return {
|
|
41
|
+
content: [{ type: "text", text: errorMessage }],
|
|
42
|
+
isError: true,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { HistoryService } from "../services/history-service.js";
|
|
3
|
+
import { SerialConnectionManager } from "../services/serial-connection-manager.js";
|
|
4
|
+
import { Logger } from "../utils/logger.js";
|
|
5
|
+
import { isRelativeRangeStartTime, parseHistoryTimeRange } from "../utils/time-format.js";
|
|
6
|
+
/**
|
|
7
|
+
* 注册 export-log 工具:导出串口纯文本日志到指定路径
|
|
8
|
+
*/
|
|
9
|
+
export function registerExportLogTool(server) {
|
|
10
|
+
const historyService = HistoryService.getInstance();
|
|
11
|
+
const serialManager = SerialConnectionManager.getInstance();
|
|
12
|
+
server.tool("export-log", "将串口纯文本日志导出到指定文件路径(发送 <<<,接收 >>>)", {
|
|
13
|
+
path: z.string().describe("导出文件路径(如 /tmp/serial-log.txt)"),
|
|
14
|
+
startTime: z
|
|
15
|
+
.union([z.string(), z.number()])
|
|
16
|
+
.optional()
|
|
17
|
+
.describe("起始时间(可选):YYYYMMDDHHmmssSSS / Unix 毫秒 / 负数秒 / 区间 -A--B 或 -A-0"),
|
|
18
|
+
endTime: z
|
|
19
|
+
.union([z.string(), z.number()])
|
|
20
|
+
.optional()
|
|
21
|
+
.describe("结束时间(可选):同上;0=当前。与 startTime 成对提供,或 startTime 为区间字符串"),
|
|
22
|
+
serialPath: z
|
|
23
|
+
.string()
|
|
24
|
+
.optional()
|
|
25
|
+
.describe("串口路径,如 /dev/ttyUSB0;省略则使用当前连接或全部 *.log"),
|
|
26
|
+
format: z
|
|
27
|
+
.enum(["json", "text"])
|
|
28
|
+
.optional()
|
|
29
|
+
.describe("导出格式:json 或 text,默认 text"),
|
|
30
|
+
}, async ({ path: exportPath, startTime, endTime, serialPath, format }) => {
|
|
31
|
+
try {
|
|
32
|
+
const hasStart = startTime !== undefined;
|
|
33
|
+
const hasEnd = endTime !== undefined;
|
|
34
|
+
const isRange = hasStart && isRelativeRangeStartTime(startTime);
|
|
35
|
+
if (!hasStart && hasEnd) {
|
|
36
|
+
throw new Error("startTime and endTime must both be provided or both omitted");
|
|
37
|
+
}
|
|
38
|
+
if (hasStart && !isRange && !hasEnd) {
|
|
39
|
+
throw new Error("startTime and endTime must both be provided or both omitted");
|
|
40
|
+
}
|
|
41
|
+
let parsedRange;
|
|
42
|
+
if (hasStart) {
|
|
43
|
+
parsedRange = parseHistoryTimeRange(startTime, endTime);
|
|
44
|
+
}
|
|
45
|
+
let resolvedPath = serialPath;
|
|
46
|
+
if (!resolvedPath) {
|
|
47
|
+
try {
|
|
48
|
+
resolvedPath = serialManager.getConfig().path;
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
resolvedPath = undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const result = historyService.exportHistory(exportPath, {
|
|
55
|
+
startTime: parsedRange?.start,
|
|
56
|
+
endTime: parsedRange?.end,
|
|
57
|
+
portPath: resolvedPath,
|
|
58
|
+
format: format || "text",
|
|
59
|
+
});
|
|
60
|
+
return {
|
|
61
|
+
content: [
|
|
62
|
+
{
|
|
63
|
+
type: "text",
|
|
64
|
+
text: JSON.stringify({
|
|
65
|
+
success: true,
|
|
66
|
+
message: `Exported ${result.count} lines to ${result.path}`,
|
|
67
|
+
...result,
|
|
68
|
+
}, null, 2),
|
|
69
|
+
},
|
|
70
|
+
],
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
const errorMessage = Logger.handleError(error, "Failed to export log");
|
|
75
|
+
return {
|
|
76
|
+
content: [{ type: "text", text: errorMessage }],
|
|
77
|
+
isError: true,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { registerSerialDetectTool } from "./serial-detect.js";
|
|
2
|
+
import { registerConnectTool } from "./connect.js";
|
|
3
|
+
import { registerDisconnectTool } from "./disconnect.js";
|
|
4
|
+
import { registerConnectionStatusTool } from "./connection-status.js";
|
|
5
|
+
import { registerRealtimeSpeedTool } from "./realtime-speed.js";
|
|
6
|
+
import { registerSendCommandTool } from "./send-command.js";
|
|
7
|
+
import { registerLogBetweenTool } from "./log-between.js";
|
|
8
|
+
import { registerExportLogTool } from "./export-log.js";
|
|
9
|
+
/**
|
|
10
|
+
* 注册全部 MCP 工具(单串口监控,共 8 个)
|
|
11
|
+
*/
|
|
12
|
+
export function registerAllTools(server) {
|
|
13
|
+
registerSerialDetectTool(server);
|
|
14
|
+
registerConnectTool(server);
|
|
15
|
+
registerDisconnectTool(server);
|
|
16
|
+
registerConnectionStatusTool(server);
|
|
17
|
+
registerRealtimeSpeedTool(server);
|
|
18
|
+
registerSendCommandTool(server);
|
|
19
|
+
registerLogBetweenTool(server);
|
|
20
|
+
registerExportLogTool(server);
|
|
21
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { HistoryService } from "../services/history-service.js";
|
|
3
|
+
import { SerialConnectionManager } from "../services/serial-connection-manager.js";
|
|
4
|
+
import { Logger } from "../utils/logger.js";
|
|
5
|
+
import { parseHistoryTimeRange } from "../utils/time-format.js";
|
|
6
|
+
/**
|
|
7
|
+
* 注册 log-between 工具:按时间段查询串口纯文本日志(.serial-history/*.log)
|
|
8
|
+
*/
|
|
9
|
+
export function registerLogBetweenTool(server) {
|
|
10
|
+
const historyService = HistoryService.getInstance();
|
|
11
|
+
const serialManager = SerialConnectionManager.getInstance();
|
|
12
|
+
server.tool("log-between", "返回指定时间段之间的串口纯文本日志(发送 <<<,接收 >>>,数据源为 .serial-history/*.log)。时间支持负数相对秒数:-N 为 N 秒前;0 为当前;区间 -A--B 或 -A-0", {
|
|
13
|
+
startTime: z
|
|
14
|
+
.union([z.string(), z.number()])
|
|
15
|
+
.describe("起始时间:YYYYMMDDHHmmssSSS / Unix 毫秒 / 负数秒(-60=60秒前)/ 区间 -600--300 或 -60-0"),
|
|
16
|
+
endTime: z
|
|
17
|
+
.union([z.string(), z.number()])
|
|
18
|
+
.optional()
|
|
19
|
+
.describe("结束时间:同上;0=当前时刻。startTime 为 -A--B / -A-0 时可省略"),
|
|
20
|
+
path: z
|
|
21
|
+
.string()
|
|
22
|
+
.optional()
|
|
23
|
+
.describe("串口路径,如 /dev/ttyUSB0;省略则查全部 *.log"),
|
|
24
|
+
}, async ({ startTime, endTime, path: portPath }) => {
|
|
25
|
+
try {
|
|
26
|
+
const { start, end } = parseHistoryTimeRange(startTime, endTime);
|
|
27
|
+
let resolvedPath = portPath;
|
|
28
|
+
if (!resolvedPath) {
|
|
29
|
+
try {
|
|
30
|
+
resolvedPath = serialManager.getConfig().path;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
resolvedPath = undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const records = historyService.listHistoryBetween(start, end, resolvedPath);
|
|
37
|
+
return {
|
|
38
|
+
content: [
|
|
39
|
+
{
|
|
40
|
+
type: "text",
|
|
41
|
+
text: JSON.stringify({
|
|
42
|
+
startTime: start,
|
|
43
|
+
endTime: end,
|
|
44
|
+
path: resolvedPath,
|
|
45
|
+
logFile: resolvedPath
|
|
46
|
+
? historyService.getPortLogPath(resolvedPath)
|
|
47
|
+
: historyService.getHistoryDir(),
|
|
48
|
+
count: records.length,
|
|
49
|
+
lines: records.map((h) => h.line),
|
|
50
|
+
records: records.map((h) => ({
|
|
51
|
+
timestamp: h.timestamp,
|
|
52
|
+
time: h.time,
|
|
53
|
+
line: h.line,
|
|
54
|
+
data: h.data.length > 200 ? h.data.substring(0, 200) + "..." : h.data,
|
|
55
|
+
direction: h.direction,
|
|
56
|
+
portPath: h.portPath,
|
|
57
|
+
})),
|
|
58
|
+
}, null, 2),
|
|
59
|
+
},
|
|
60
|
+
],
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
const errorMessage = Logger.handleError(error, "Failed to query log");
|
|
65
|
+
return {
|
|
66
|
+
content: [{ type: "text", text: errorMessage }],
|
|
67
|
+
isError: true,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { SerialConnectionManager } from "../services/serial-connection-manager.js";
|
|
3
|
+
/**
|
|
4
|
+
* 注册 realtime-speed 工具:查询串口实时字符速率
|
|
5
|
+
*/
|
|
6
|
+
export function registerRealtimeSpeedTool(server) {
|
|
7
|
+
const serialManager = SerialConnectionManager.getInstance();
|
|
8
|
+
server.tool("realtime-speed", "查询串口实时字符速率(多时间窗口统计,单位:字节/秒)", {
|
|
9
|
+
windows: z
|
|
10
|
+
.array(z.number())
|
|
11
|
+
.optional()
|
|
12
|
+
.describe("统计窗口秒数列表,默认 [1, 5, 10, 30]"),
|
|
13
|
+
}, async ({ windows }) => {
|
|
14
|
+
const stats = serialManager.getRealtimeSpeed(undefined, windows);
|
|
15
|
+
return {
|
|
16
|
+
content: [
|
|
17
|
+
{
|
|
18
|
+
type: "text",
|
|
19
|
+
text: JSON.stringify(stats, null, 2),
|
|
20
|
+
},
|
|
21
|
+
],
|
|
22
|
+
};
|
|
23
|
+
});
|
|
24
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { SerialConnectionManager } from "../services/serial-connection-manager.js";
|
|
3
|
+
import { HistoryService } from "../services/history-service.js";
|
|
4
|
+
import { Logger } from "../utils/logger.js";
|
|
5
|
+
import { formatLogTimestamp } from "../utils/time-format.js";
|
|
6
|
+
/** 单串口监控默认连接名 */
|
|
7
|
+
const DEFAULT_CONNECTION = "default";
|
|
8
|
+
/**
|
|
9
|
+
* 过滤命令回显
|
|
10
|
+
*/
|
|
11
|
+
function filterEcho(output, command) {
|
|
12
|
+
const escapedCommand = command.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
13
|
+
const echoPattern1 = new RegExp("^[\\s\\b\\r\\n]*" + escapedCommand + "[\\s\\r\\n]*", "i");
|
|
14
|
+
const echoPattern2 = new RegExp(escapedCommand + "[\\s\\r\\n]+", "gi");
|
|
15
|
+
const echoPattern3 = new RegExp("^[^\\n]*" + escapedCommand + "[^\\n]*\\n?", "i");
|
|
16
|
+
let result = output.replace(echoPattern1, "");
|
|
17
|
+
result = result.replace(echoPattern2, "");
|
|
18
|
+
result = result.replace(echoPattern3, "");
|
|
19
|
+
const lines = result.split("\n");
|
|
20
|
+
const filteredLines = lines.filter((line) => {
|
|
21
|
+
const trimmedLine = line.trim();
|
|
22
|
+
return (trimmedLine.toLowerCase() !== command.toLowerCase() &&
|
|
23
|
+
!trimmedLine.startsWith(command.toLowerCase() + " ") &&
|
|
24
|
+
trimmedLine !== "");
|
|
25
|
+
});
|
|
26
|
+
return filteredLines.join("\n");
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* 注册 send-command 工具:向串口发送命令并收集指定时长内的响应
|
|
30
|
+
*/
|
|
31
|
+
export function registerSendCommandTool(server) {
|
|
32
|
+
const serialManager = SerialConnectionManager.getInstance();
|
|
33
|
+
const historyService = HistoryService.getInstance();
|
|
34
|
+
server.tool("send-command", "向已连接串口发送命令并收集响应:静默约 400ms 即返回;遇确认/分页自动续键。collectMs 为硬超时上限", {
|
|
35
|
+
command: z.string().describe("要发送的命令(不含换行符,工具自动追加 \\r\\n)"),
|
|
36
|
+
collectMs: z
|
|
37
|
+
.number()
|
|
38
|
+
.optional()
|
|
39
|
+
.describe("硬超时毫秒(上限),默认 5000;实际多在静默后提前返回"),
|
|
40
|
+
skipEcho: z
|
|
41
|
+
.boolean()
|
|
42
|
+
.optional()
|
|
43
|
+
.describe("是否过滤命令回显,默认 true"),
|
|
44
|
+
}, async ({ command, collectMs, skipEcho = true }) => {
|
|
45
|
+
const connName = DEFAULT_CONNECTION;
|
|
46
|
+
const startTime = Date.now();
|
|
47
|
+
const windowMs = collectMs ?? 5000;
|
|
48
|
+
Logger.log(`[${connName}] >>> SEND: ${command} (idle collect, hard ${windowMs}ms)`, "info");
|
|
49
|
+
try {
|
|
50
|
+
if (!serialManager.isOpen(connName)) {
|
|
51
|
+
throw new Error(`Serial port is not connected. Use connect tool first.`);
|
|
52
|
+
}
|
|
53
|
+
historyService.addHistory(connName, "write", command, true, undefined, 0, {
|
|
54
|
+
timeout: windowMs,
|
|
55
|
+
});
|
|
56
|
+
serialManager.clearBuffer(connName);
|
|
57
|
+
const sendTimestamp = Date.now();
|
|
58
|
+
const sendTime = formatLogTimestamp(new Date(sendTimestamp));
|
|
59
|
+
await serialManager.write(command + "\r\n", connName);
|
|
60
|
+
const response = await serialManager.readUntilIdle(connName, {
|
|
61
|
+
hardTimeoutMs: windowMs,
|
|
62
|
+
});
|
|
63
|
+
let output = response;
|
|
64
|
+
if (skipEcho) {
|
|
65
|
+
output = filterEcho(output, command);
|
|
66
|
+
}
|
|
67
|
+
output = output
|
|
68
|
+
.replace(/\x08+/g, "")
|
|
69
|
+
.replace(/\r\n/g, "\n")
|
|
70
|
+
.replace(/\r/g, "\n")
|
|
71
|
+
.trim();
|
|
72
|
+
const duration = Date.now() - startTime;
|
|
73
|
+
historyService.addHistory(connName, "read", output, true, undefined, duration, { timeout: windowMs });
|
|
74
|
+
Logger.log(`[${connName}] <<< OUTPUT (${duration}ms, ${output.length} bytes, sendTime=${sendTime}):\n${output.substring(0, 500)}${output.length > 500 ? "..." : ""}`, "info");
|
|
75
|
+
return {
|
|
76
|
+
content: [
|
|
77
|
+
{
|
|
78
|
+
type: "text",
|
|
79
|
+
text: JSON.stringify({
|
|
80
|
+
success: true,
|
|
81
|
+
command,
|
|
82
|
+
sendTime,
|
|
83
|
+
sendTimestamp,
|
|
84
|
+
collectMs: windowMs,
|
|
85
|
+
output,
|
|
86
|
+
length: output.length,
|
|
87
|
+
duration,
|
|
88
|
+
}, null, 2),
|
|
89
|
+
},
|
|
90
|
+
],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
const duration = Date.now() - startTime;
|
|
95
|
+
const errorMessage = Logger.handleError(error, "Failed to send command");
|
|
96
|
+
historyService.addHistory(connName, "read", undefined, false, errorMessage, duration, { timeout: windowMs });
|
|
97
|
+
return {
|
|
98
|
+
content: [
|
|
99
|
+
{
|
|
100
|
+
type: "text",
|
|
101
|
+
text: JSON.stringify({
|
|
102
|
+
success: false,
|
|
103
|
+
command,
|
|
104
|
+
collectMs: windowMs,
|
|
105
|
+
error: errorMessage,
|
|
106
|
+
duration,
|
|
107
|
+
}, null, 2),
|
|
108
|
+
},
|
|
109
|
+
],
|
|
110
|
+
isError: true,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { SerialConnectionManager } from "../services/serial-connection-manager.js";
|
|
2
|
+
/**
|
|
3
|
+
* 注册 serial-detect 工具:探测宿主机可用串口
|
|
4
|
+
*/
|
|
5
|
+
export function registerSerialDetectTool(server) {
|
|
6
|
+
server.tool("serial-detect", "探测宿主机当前可用的串口设备节点", {}, async () => {
|
|
7
|
+
try {
|
|
8
|
+
const ports = await SerialConnectionManager.listPorts();
|
|
9
|
+
return {
|
|
10
|
+
content: [
|
|
11
|
+
{
|
|
12
|
+
type: "text",
|
|
13
|
+
text: JSON.stringify({ count: ports.length, ports }, null, 2),
|
|
14
|
+
},
|
|
15
|
+
],
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
return {
|
|
20
|
+
content: [
|
|
21
|
+
{
|
|
22
|
+
type: "text",
|
|
23
|
+
text: `Error detecting serial ports: ${error.message}`,
|
|
24
|
+
},
|
|
25
|
+
],
|
|
26
|
+
isError: true,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { formatLogTimestamp } from "./time-format.js";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
/**
|
|
5
|
+
* Logger class
|
|
6
|
+
*/
|
|
7
|
+
export class Logger {
|
|
8
|
+
static logFileStream = null;
|
|
9
|
+
static logFileName = "";
|
|
10
|
+
/**
|
|
11
|
+
* Initialize logger with file output
|
|
12
|
+
*/
|
|
13
|
+
static initialize(serviceName = "mcp_serial") {
|
|
14
|
+
try {
|
|
15
|
+
const now = new Date();
|
|
16
|
+
const shanghaiTime = new Date(now.getTime() + 8 * 60 * 60 * 1000);
|
|
17
|
+
const year = shanghaiTime.getUTCFullYear();
|
|
18
|
+
const month = String(shanghaiTime.getUTCMonth() + 1).padStart(2, "0");
|
|
19
|
+
const day = String(shanghaiTime.getUTCDate()).padStart(2, "0");
|
|
20
|
+
const hour = String(shanghaiTime.getUTCHours()).padStart(2, "0");
|
|
21
|
+
const minute = String(shanghaiTime.getUTCMinutes()).padStart(2, "0");
|
|
22
|
+
const logDir = "/var/log";
|
|
23
|
+
if (!fs.existsSync(logDir)) {
|
|
24
|
+
fs.mkdirSync(logDir, { mode: 0o755, recursive: true });
|
|
25
|
+
}
|
|
26
|
+
this.logFileName = path.join(logDir, `${serviceName}_${year}_${month}_${day}_${hour}_${minute}.log`);
|
|
27
|
+
this.logFileStream = fs.createWriteStream(this.logFileName, {
|
|
28
|
+
flags: "a",
|
|
29
|
+
mode: 0o644,
|
|
30
|
+
});
|
|
31
|
+
this.logFileStream.on("error", (err) => {
|
|
32
|
+
process.stderr.write(`[Logger] Failed to write to log file: ${err.message}\n`);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
process.stderr.write(`[Logger] Failed to initialize log file: ${error}\n`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Log a message
|
|
41
|
+
* Note: All logging goes to stderr to avoid interfering with MCP stdio protocol (which uses stdout)
|
|
42
|
+
* Also writes to log file if initialized
|
|
43
|
+
*/
|
|
44
|
+
static log(message, level = "info") {
|
|
45
|
+
const timestamp = formatLogTimestamp();
|
|
46
|
+
const formattedMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
|
|
47
|
+
// Always write to stderr to avoid corrupting MCP protocol messages on stdout
|
|
48
|
+
process.stderr.write(formattedMessage + "\n");
|
|
49
|
+
// Write to log file if initialized
|
|
50
|
+
if (this.logFileStream) {
|
|
51
|
+
try {
|
|
52
|
+
this.logFileStream.write(formattedMessage + "\n");
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
// Silently fail if file write fails
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Handle error
|
|
61
|
+
*/
|
|
62
|
+
static handleError(error, prefix = "", exit = false) {
|
|
63
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
64
|
+
const fullMessage = prefix ? `${prefix}: ${errorMessage}` : errorMessage;
|
|
65
|
+
Logger.log(fullMessage, "error");
|
|
66
|
+
if (exit) {
|
|
67
|
+
Logger.close();
|
|
68
|
+
process.exit(1);
|
|
69
|
+
}
|
|
70
|
+
return fullMessage;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Close log file stream
|
|
74
|
+
*/
|
|
75
|
+
static close() {
|
|
76
|
+
if (this.logFileStream) {
|
|
77
|
+
this.logFileStream.end();
|
|
78
|
+
this.logFileStream = null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 串口收包辅助:静默结束 + 安全自动续键(对齐 mcp_telnet)。
|
|
3
|
+
*/
|
|
4
|
+
/** 无新数据多久视为本轮输出结束(毫秒) */
|
|
5
|
+
export const SERIAL_IDLE_MS = 400;
|
|
6
|
+
const TAIL_WINDOW = 480;
|
|
7
|
+
/**
|
|
8
|
+
* 根据缓冲区尾部判断是否需要自动续键。
|
|
9
|
+
* - space:分页 More
|
|
10
|
+
* - cr:含 `<cr>` 的确认/补全提示
|
|
11
|
+
* - null:不自动处理(含 y/n)
|
|
12
|
+
*/
|
|
13
|
+
export function detectInteractiveAction(buffer) {
|
|
14
|
+
const tail = buffer.slice(-TAIL_WINDOW);
|
|
15
|
+
if (/(?:----\s*More[^\n]*----+|--More--|---More---)\s*$/i.test(tail)) {
|
|
16
|
+
return "space";
|
|
17
|
+
}
|
|
18
|
+
if (/\{[^}\n]*<cr>[^}\n]*\}\s*:\s*$/i.test(tail)) {
|
|
19
|
+
return "cr";
|
|
20
|
+
}
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 串口文本行切分与清洗
|
|
3
|
+
* 支持 \r\n、\n、仅 \r(NPU/嵌入式常见)换行
|
|
4
|
+
*/
|
|
5
|
+
/** 行结束符匹配(\r\n 优先于 \n、\r) */
|
|
6
|
+
const SERIAL_LINE_END_PATTERN = /\r\n|\n|\r/g;
|
|
7
|
+
/**
|
|
8
|
+
* 清洗单行日志内容:去掉首尾控制符、剔除 NUL
|
|
9
|
+
*/
|
|
10
|
+
export function sanitizeSerialLogLine(line) {
|
|
11
|
+
return line
|
|
12
|
+
.replace(/^\r+/, "")
|
|
13
|
+
.replace(/\0/g, "")
|
|
14
|
+
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, "")
|
|
15
|
+
.trimEnd();
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* 流式切分:返回完整行列表与未结束的尾部缓冲
|
|
19
|
+
*/
|
|
20
|
+
export function splitSerialBuffer(buffer) {
|
|
21
|
+
const lines = [];
|
|
22
|
+
let lastIndex = 0;
|
|
23
|
+
const pattern = new RegExp(SERIAL_LINE_END_PATTERN.source, "g");
|
|
24
|
+
let match;
|
|
25
|
+
while ((match = pattern.exec(buffer)) !== null) {
|
|
26
|
+
const sanitized = sanitizeSerialLogLine(buffer.slice(lastIndex, match.index));
|
|
27
|
+
if (sanitized.length > 0) {
|
|
28
|
+
lines.push(sanitized);
|
|
29
|
+
}
|
|
30
|
+
lastIndex = match.index + match[0].length;
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
lines,
|
|
34
|
+
remainder: buffer.slice(lastIndex),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* 切分完整文本(无尾部缓冲):用于发送方向等多行一次性写入
|
|
39
|
+
*/
|
|
40
|
+
export function splitCompleteSerialLines(text) {
|
|
41
|
+
const { lines, remainder } = splitSerialBuffer(text);
|
|
42
|
+
const sanitizedRemainder = sanitizeSerialLogLine(remainder);
|
|
43
|
+
if (sanitizedRemainder.length > 0) {
|
|
44
|
+
lines.push(sanitizedRemainder);
|
|
45
|
+
}
|
|
46
|
+
return lines;
|
|
47
|
+
}
|