xusbcan-cli 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,72 @@
1
+ """周期发送:基于 can.Bus.send_periodic(软件层,跨后端通用)。
2
+
3
+ 2E 的硬件定时发送(auto_send)只作为 backend 的 _send_periodic_internal 可选覆盖,
4
+ core 不出现厂商分支。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ from dataclasses import dataclass, field
11
+ from typing import Any
12
+
13
+ from ..models.frame import CanFrame
14
+ from ..models.result import ErrorCode, Result
15
+
16
+
17
+ @dataclass
18
+ class PeriodicTask:
19
+ """会话内的一条周期发送任务。task 是 python-can 的 CyclicSendTaskABC。"""
20
+
21
+ name: str
22
+ frame: CanFrame
23
+ period: float # 秒
24
+ task: Any # can.broadcastmanager.CyclicSendTaskABC
25
+ started_at: float = field(default_factory=time.time)
26
+
27
+ def stop(self) -> None:
28
+ try:
29
+ self.task.stop()
30
+ except Exception:
31
+ pass
32
+
33
+ def to_dict(self) -> dict:
34
+ return {
35
+ "name": self.name,
36
+ "arbitration_id": self.frame.arbitration_id,
37
+ "data": self.frame.data.hex(),
38
+ "is_extended": self.frame.is_extended,
39
+ "is_fd": self.frame.is_fd,
40
+ "period_ms": round(self.period * 1000.0, 3),
41
+ }
42
+
43
+
44
+ def start(session, name: str, frame: CanFrame, period: float) -> Result:
45
+ """在已打开的 session 上启动一条周期发送。session 由调用方保证已打开。"""
46
+ if period <= 0:
47
+ return Result.err(ErrorCode.INVALID_ARGUMENT, f"周期必须为正: {period}")
48
+ try:
49
+ task = session.bus.send_periodic(frame.to_can_message(), period)
50
+ except Exception as e:
51
+ return Result.err(ErrorCode.INTERNAL_ERROR, f"启动周期发送失败: {e}")
52
+ pt = PeriodicTask(name=name, frame=frame, period=period, task=task)
53
+ if not session.add_periodic(name, pt):
54
+ pt.stop() # 名字冲突:回滚刚启动的任务
55
+ return Result.err(
56
+ ErrorCode.INVALID_ARGUMENT,
57
+ f"周期任务已存在: {name}",
58
+ context={"alias": session.name, "name": name},
59
+ )
60
+ return Result.ok(pt.to_dict())
61
+
62
+
63
+ def stop(session, name: str) -> Result:
64
+ task = session.pop_periodic(name)
65
+ if task is None:
66
+ return Result.err(ErrorCode.SESSION_NOT_FOUND, f"周期任务不存在: {name}")
67
+ task.stop()
68
+ return Result.ok({"name": name, "stopped": True})
69
+
70
+
71
+ def list_tasks(session) -> Result:
72
+ return Result.ok({"tasks": [t.to_dict() for t in session.snapshot_periodic()]})
@@ -0,0 +1,282 @@
1
+ """会话管理:SessionManager + Session。
2
+
3
+ 会话状态机只有 closed / open / error 三态;设备打开、通道初始化、句柄引用计数
4
+ 只属于 backend(如 ZlgBus / ZlgDevicePool),绝不进入 Session——否则 core 会重新
5
+ 长出厂商生命周期。
6
+
7
+ core 只面向 can.Bus 与领域模型;唯一接触适配层的地方是通过 registry(不 import
8
+ adapters.zlg)。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import threading
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass, field
16
+ from enum import StrEnum
17
+ from typing import Any
18
+
19
+ import can
20
+
21
+ from ..adapters.registry import open_device
22
+ from ..models.device import DeviceSpec
23
+ from ..models.result import ErrorCode, Result
24
+
25
+ # 关闭时 join 的超时(秒)。取值 > zlg 无 ACK 发送阻塞的 ~3.5s(见 architecture §12.10),
26
+ # 保证能收回监听线程;收不回时该会话进入 error 并返回 CLOSE_TIMEOUT。
27
+ CLOSE_TIMEOUT_S = 5.0
28
+
29
+
30
+ class SessionState(StrEnum):
31
+ CLOSED = "closed"
32
+ OPEN = "open"
33
+ ERROR = "error"
34
+
35
+
36
+ def map_error(exc: BaseException) -> ErrorCode:
37
+ """把 python-can 异常集中翻译成 ErrorCode(core 只翻译这一次,CLI/MCP 不各自翻译)。"""
38
+ if isinstance(exc, can.CanInterfaceNotImplementedError):
39
+ return ErrorCode.DEVICE_OPEN_FAILED
40
+ if isinstance(exc, can.CanInitializationError):
41
+ return ErrorCode.DEVICE_OPEN_FAILED
42
+ if isinstance(exc, can.CanOperationError):
43
+ return ErrorCode.DEVICE_NOT_OPEN
44
+ if isinstance(exc, can.CanError):
45
+ # 含 CanTimeoutError:超时本应在调用点按「成功超时」处理,逃逸到此属内部错误。
46
+ return ErrorCode.INTERNAL_ERROR
47
+ return ErrorCode.INTERNAL_ERROR
48
+
49
+
50
+ @dataclass
51
+ class Session:
52
+ """一条已打开的会话(一路通道)。持有 can.Bus 与领域模型,不含厂商生命周期。"""
53
+
54
+ name: str # 配置别名,如 can0 / can1
55
+ bus: can.BusABC
56
+ spec: DeviceSpec
57
+ state: SessionState = SessionState.OPEN
58
+ receive_owner: str | None = None # "monitor"(有界采集运行时占用)
59
+ periodic: dict[str, Any] = field(default_factory=dict) # name -> PeriodicTask
60
+ monitor: Any | None = None # 运行中的 Monitor
61
+ _lock: threading.RLock = field(default_factory=threading.RLock, repr=False)
62
+
63
+ # ---- 接收所有者(core 内部,供 monitor.py / commands.py 使用)----
64
+
65
+ def acquire_receive(self, owner: str) -> bool:
66
+ """占用接收所有权;已被占用返回 False。"""
67
+ with self._lock:
68
+ if self.receive_owner is not None:
69
+ return False
70
+ self.receive_owner = owner
71
+ return True
72
+
73
+ def release_receive(self, owner: str) -> None:
74
+ with self._lock:
75
+ if self.receive_owner == owner:
76
+ self.receive_owner = None
77
+
78
+ # ---- 监听(core 内部)----
79
+
80
+ def set_monitor(self, monitor: Any) -> None:
81
+ with self._lock:
82
+ self.monitor = monitor
83
+
84
+ def clear_monitor(self, monitor: Any) -> None:
85
+ with self._lock:
86
+ if self.monitor is monitor:
87
+ self.monitor = None
88
+
89
+ # ---- 周期任务(core 内部)----
90
+
91
+ def add_periodic(self, name: str, task: Any) -> bool:
92
+ """登记一条周期任务;名字已存在返回 False。"""
93
+ with self._lock:
94
+ if name in self.periodic:
95
+ return False
96
+ self.periodic[name] = task
97
+ return True
98
+
99
+ def pop_periodic(self, name: str) -> Any:
100
+ with self._lock:
101
+ return self.periodic.pop(name, None)
102
+
103
+ def snapshot_periodic(self) -> list:
104
+ with self._lock:
105
+ return list(self.periodic.values())
106
+
107
+ def close(self) -> Result:
108
+ """只做三步:停周期任务 → 停监听 → bus.shutdown()。
109
+
110
+ 设备句柄的引用归还由 backend 的 shutdown() 内部完成(最后一路才真正关设备)。
111
+ """
112
+ with self._lock:
113
+ if self.state is SessionState.CLOSED:
114
+ return Result.ok({"state": self.state.value})
115
+ tasks = list(self.periodic.values())
116
+ self.periodic.clear()
117
+ monitor = self.monitor
118
+ self.monitor = None
119
+
120
+ # 1. 停周期任务(best-effort,不阻断 shutdown)
121
+ for task in tasks:
122
+ try:
123
+ task.stop()
124
+ except Exception:
125
+ pass
126
+
127
+ # 2. 停监听(先置停止标志再 join,带超时)
128
+ if monitor is not None:
129
+ monitor.stop()
130
+ if not monitor.join(timeout=CLOSE_TIMEOUT_S):
131
+ with self._lock:
132
+ self.state = SessionState.ERROR
133
+ return Result.err(
134
+ ErrorCode.CLOSE_TIMEOUT,
135
+ f"关闭监听超时: {self.name}",
136
+ context={"alias": self.name},
137
+ )
138
+
139
+ # 3. shutdown
140
+ try:
141
+ self.bus.shutdown()
142
+ except can.CanError as e:
143
+ with self._lock:
144
+ self.state = SessionState.ERROR
145
+ return Result.err(map_error(e), f"关闭设备失败: {e}", detail=str(e))
146
+ except Exception as e:
147
+ with self._lock:
148
+ self.state = SessionState.ERROR
149
+ return Result.err(ErrorCode.INTERNAL_ERROR, f"关闭设备失败: {e}")
150
+
151
+ with self._lock:
152
+ self.receive_owner = None
153
+ self.state = SessionState.CLOSED
154
+ return Result.ok({"state": self.state.value})
155
+
156
+
157
+ def _default_opener(spec: DeviceSpec) -> Result:
158
+ return open_device(spec)
159
+
160
+
161
+ class SessionManager:
162
+ """按别名管理会话。opener 可注入(默认 registry.open_device),测试用假 BusABC 注入。"""
163
+
164
+ def __init__(
165
+ self,
166
+ opener: Callable[[DeviceSpec], Any] | None = None,
167
+ specs: dict[str, DeviceSpec] | None = None,
168
+ ) -> None:
169
+ self._opener = opener if opener is not None else _default_opener
170
+ self._specs: dict[str, DeviceSpec] = dict(specs or {})
171
+ self._sessions: dict[str, Session] = {}
172
+ self._lock = threading.RLock()
173
+
174
+ # ---- 配置 ----
175
+
176
+ def register(self, alias: str, spec: DeviceSpec) -> None:
177
+ with self._lock:
178
+ self._specs[alias] = spec
179
+
180
+ def get_spec(self, alias: str) -> DeviceSpec | None:
181
+ return self._specs.get(alias)
182
+
183
+ @property
184
+ def specs(self) -> dict[str, DeviceSpec]:
185
+ return dict(self._specs)
186
+
187
+ @property
188
+ def sessions(self) -> dict[str, Session]:
189
+ return dict(self._sessions)
190
+
191
+ def get(self, alias: str) -> Session | None:
192
+ return self._sessions.get(alias)
193
+
194
+ # ---- 打开 / 关闭 ----
195
+
196
+ def _open_bus(self, spec: DeviceSpec) -> Result:
197
+ r = self._opener(spec)
198
+ if isinstance(r, Result):
199
+ return r
200
+ # 注入的假 BusABC 直接返回对象(不包 Result)
201
+ return Result.ok(r)
202
+
203
+ def open(self, alias: str) -> Result:
204
+ with self._lock:
205
+ existing = self._sessions.get(alias)
206
+ if existing is not None and existing.state is SessionState.OPEN:
207
+ return Result.ok({"state": existing.state.value, "reused": True})
208
+ spec = self._specs.get(alias)
209
+ if spec is None:
210
+ return Result.err(ErrorCode.SESSION_NOT_FOUND, f"会话不存在: {alias}")
211
+ result = self._open_bus(spec) # 打开放在锁外,避免阻塞其它别名
212
+ if result.status == "error":
213
+ return result
214
+ session = Session(name=alias, bus=result.data, spec=spec)
215
+ with self._lock:
216
+ existing = self._sessions.get(alias)
217
+ if existing is not None and existing.state is SessionState.OPEN:
218
+ session.close() # 并发下已被打开,放弃本次、复用已有
219
+ return Result.ok({"state": "open", "reused": True})
220
+ self._sessions[alias] = session
221
+ return Result.ok({"state": "open", "reused": False})
222
+
223
+ def close(self, alias: str) -> Result:
224
+ with self._lock:
225
+ session = self._sessions.get(alias)
226
+ if session is None:
227
+ return Result.err(ErrorCode.SESSION_NOT_FOUND, f"会话不存在或未打开: {alias}")
228
+ result = session.close()
229
+ if result.status == "ok":
230
+ with self._lock:
231
+ if self._sessions.get(alias) is session:
232
+ self._sessions.pop(alias, None)
233
+ # 失败时保留会话(state=error),该路上后续发送被拒绝
234
+ return result
235
+
236
+ def close_all(self) -> None:
237
+ with self._lock:
238
+ sessions = list(self._sessions.values())
239
+ self._sessions.clear()
240
+ for s in sessions:
241
+ try:
242
+ s.close()
243
+ except Exception:
244
+ pass
245
+
246
+ # ---- 复用规则(一次性 vs 会话共用同一条路径)----
247
+
248
+ def acquire(self, alias: str) -> tuple[Session | None, Result | None, bool]:
249
+ """按别名取会话。返回 (session, error, reused):
250
+
251
+ - 已打开 → (session, None, True):复用,调用方返回时**不得 shutdown**;
252
+ - 未打开 → 一次性打开 (session, None, False):调用方需 try/finally shutdown;
253
+ - 失败 → (None, errorResult, False)。
254
+ """
255
+ with self._lock:
256
+ session = self._sessions.get(alias)
257
+ if session is not None:
258
+ if session.state is SessionState.OPEN:
259
+ return session, None, True
260
+ if session.state is SessionState.ERROR:
261
+ return None, Result.err(
262
+ ErrorCode.DEVICE_NOT_OPEN,
263
+ f"会话处于错误状态: {alias}",
264
+ context={"alias": alias},
265
+ ), False
266
+ spec = self._specs.get(alias)
267
+ if spec is None:
268
+ return None, Result.err(ErrorCode.SESSION_NOT_FOUND, f"会话不存在: {alias}"), False
269
+ result = self._open_bus(spec)
270
+ if result.status == "error":
271
+ return None, result, False
272
+ session = Session(name=alias, bus=result.data, spec=spec)
273
+ return session, None, False
274
+
275
+ def release(self, session: Session | None, reused: bool) -> None:
276
+ """释放 acquire 取得的会话。reused=True 时不动;否则 shutdown(一次性路径)。"""
277
+ if session is None or reused:
278
+ return
279
+ try:
280
+ session.close()
281
+ except Exception:
282
+ pass
@@ -0,0 +1 @@
1
+ """MCP 服务器:薄封装 core 的模型上下文协议工具。"""
xusbcan/mcp/server.py ADDED
@@ -0,0 +1,41 @@
1
+ """MCP 服务器入口:FastMCP + 配置加载 + 常驻 SessionManager。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+
8
+ from mcp.server.mcpserver import MCPServer
9
+
10
+ from ..config.loader import load_config
11
+ from ..core import SessionManager
12
+ from ..models.result import Result
13
+ from .tools import register_tools
14
+
15
+ mcp = MCPServer("xusbcan")
16
+
17
+
18
+ def _build_manager(config_path: str | None) -> tuple[Result, SessionManager | None]:
19
+ result = load_config(config_path)
20
+ if result.status == "error":
21
+ return result, None
22
+ cfg = result.data
23
+ manager = SessionManager()
24
+ for entry in cfg.devices:
25
+ manager.register(entry.name, entry.spec)
26
+ return result, manager
27
+
28
+
29
+ def main(config_path: str | None = None) -> int:
30
+ result, manager = _build_manager(config_path)
31
+ if result.status == "error":
32
+ print(json.dumps(result.to_dict(), ensure_ascii=False), file=sys.stderr)
33
+ return 1
34
+ assert manager is not None
35
+ register_tools(mcp, manager)
36
+ mcp.run()
37
+ return 0
38
+
39
+
40
+ if __name__ == "__main__":
41
+ raise SystemExit(main())
xusbcan/mcp/tools.py ADDED
@@ -0,0 +1,90 @@
1
+ """MCP 工具定义:薄封装 core,只做「参数解析 → 调 core → 序列化 Result」。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from .. import core
8
+ from ..models.frame import CanFrame
9
+ from ..models.result import ErrorCode, Result
10
+
11
+
12
+ def _json(result: Result) -> str:
13
+ return json.dumps(result.to_dict(), ensure_ascii=False)
14
+
15
+
16
+ def register_tools(mcp, manager: core.SessionManager) -> None:
17
+ """把 core 命令注册为 MCP 工具。工具签名是统一语义,不含厂商概念。"""
18
+
19
+ @mcp.tool()
20
+ def list_devices() -> str:
21
+ """列出配置中的所有设备:别名、通道、能力、是否已打开。返回 JSON。"""
22
+ return _json(core.list_devices(manager))
23
+
24
+ @mcp.tool()
25
+ def send_frame(device: str, arbitration_id: int, data: str, is_extended: bool = False) -> str:
26
+ """发送一帧 CAN 报文。device 为别名;data 为十六进制字节串(如 "01 02 03")。返回 JSON。"""
27
+ try:
28
+ frame = CanFrame(
29
+ arbitration_id=arbitration_id,
30
+ data=core.parse_hex(data),
31
+ is_extended=is_extended,
32
+ )
33
+ except ValueError as e:
34
+ return _json(Result.err(ErrorCode.INVALID_ARGUMENT, str(e)))
35
+ return _json(core.send(manager, device, frame))
36
+
37
+ @mcp.tool()
38
+ def receive_frame(device: str, timeout: float = 1.0) -> str:
39
+ """接收一帧 CAN 报文。timeout 为超时(秒);超时返回 status=ok 且 frame=null。"""
40
+ return _json(core.receive(manager, device, timeout))
41
+
42
+ @mcp.tool()
43
+ def monitor(device: str, duration_s: float = 1.0, max_frames: int = 500) -> str:
44
+ """有界监听一段时间。duration_s 上限 30 秒;返回 data.frames[] + count + truncated。"""
45
+ return _json(core.monitor(manager, device, duration_s, max_frames))
46
+
47
+ @mcp.tool()
48
+ def get_status(device: str) -> str:
49
+ """查询会话/设备状态:state、features、receive_owner。返回结构化 JSON。"""
50
+ return _json(core.status(manager, device))
51
+
52
+ @mcp.tool()
53
+ def open_device(device: str) -> str:
54
+ """打开设备会话(常驻进程持有,后续 send/receive 复用该会话)。返回结构化 JSON。"""
55
+ return _json(core.open_session(manager, device))
56
+
57
+ @mcp.tool()
58
+ def close_device(device: str) -> str:
59
+ """关闭设备会话,释放资源。返回结构化 JSON。"""
60
+ return _json(core.close_session(manager, device))
61
+
62
+ @mcp.tool()
63
+ def periodic_start(
64
+ device: str,
65
+ name: str,
66
+ arbitration_id: int,
67
+ data: str,
68
+ period_s: float,
69
+ is_extended: bool = False,
70
+ ) -> str:
71
+ """启动周期发送任务。name 为任务名;period_s 为周期(秒)。返回 JSON。"""
72
+ try:
73
+ frame = CanFrame(
74
+ arbitration_id=arbitration_id,
75
+ data=core.parse_hex(data),
76
+ is_extended=is_extended,
77
+ )
78
+ except ValueError as e:
79
+ return _json(Result.err(ErrorCode.INVALID_ARGUMENT, str(e)))
80
+ return _json(core.periodic_start(manager, device, name, frame, period_s))
81
+
82
+ @mcp.tool()
83
+ def periodic_stop(device: str, name: str) -> str:
84
+ """停止并移除一条周期发送任务。返回结构化 JSON。"""
85
+ return _json(core.periodic_stop(manager, device, name))
86
+
87
+ @mcp.tool()
88
+ def periodic_list(device: str) -> str:
89
+ """列出当前会话的所有周期发送任务。返回结构化 JSON。"""
90
+ return _json(core.periodic_list(manager, device))
@@ -0,0 +1,14 @@
1
+ """领域模型(数据契约):跨层共享的稳定数据结构。"""
2
+
3
+ from .device import BitrateConfig, DeviceSpec
4
+ from .frame import CanFrame
5
+ from .result import ErrorCode, ErrorInfo, Result
6
+
7
+ __all__ = [
8
+ "BitrateConfig",
9
+ "DeviceSpec",
10
+ "CanFrame",
11
+ "ErrorCode",
12
+ "ErrorInfo",
13
+ "Result",
14
+ ]
@@ -0,0 +1,27 @@
1
+ """统一设备抽象:把「厂商 + 型号 + 通道 + 波特率」收敛成一个结构化对象。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+
8
+ @dataclass
9
+ class BitrateConfig:
10
+ """波特率配置。上层只见「标称/数据段 + 可选采样点」,不见厂商 Timing 寄存器。"""
11
+
12
+ nominal: int # 标称波特率(仲裁段),如 500_000
13
+ data: int | None = None # 数据段波特率(CAN FD 用)
14
+ sjw: int | None = None # v1 不解释,留在模型里
15
+ tseg1: int | None = None # v1 不解释
16
+ tseg2: int | None = None # v1 不解释
17
+
18
+
19
+ @dataclass
20
+ class DeviceSpec:
21
+ """设备描述。vendor/model 只是声明式字符串,用于查表选 Profile。"""
22
+
23
+ vendor: str # 厂商标识:zlg / peak / vector / canalyst ...
24
+ model: str # 型号:USBCAN-2E-U / PCAN-USB / VN1630 ...
25
+ channel: int = 0 # 统一逻辑通道号(映射由 Profile 完成)
26
+ bitrate: BitrateConfig | None = None
27
+ extra: dict = field(default_factory=dict) # 厂商专有参数逃生舱
@@ -0,0 +1,68 @@
1
+ """统一帧模型:跨层传递的报文数据契约,是对 python-can Message 的投影。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ import can
8
+
9
+
10
+ @dataclass
11
+ class CanFrame:
12
+ arbitration_id: int
13
+ data: bytes
14
+ is_extended: bool = False
15
+ is_fd: bool = False
16
+ is_remote: bool = False
17
+ bitrate_switch: bool = False
18
+ error_state_indicator: bool = False
19
+ timestamp: float | None = None
20
+ channel: int = 0
21
+ dlc: int | None = None
22
+
23
+ @classmethod
24
+ def from_can_message(cls, m: can.Message) -> CanFrame:
25
+ return cls(
26
+ arbitration_id=m.arbitration_id,
27
+ data=bytes(m.data),
28
+ is_extended=m.is_extended_id,
29
+ is_fd=m.is_fd,
30
+ is_remote=m.is_remote_frame,
31
+ bitrate_switch=m.bitrate_switch,
32
+ error_state_indicator=m.error_state_indicator,
33
+ timestamp=m.timestamp,
34
+ channel=m.channel if isinstance(m.channel, int) else 0,
35
+ dlc=m.dlc,
36
+ )
37
+
38
+ def to_can_message(self) -> can.Message:
39
+ return can.Message(
40
+ arbitration_id=self.arbitration_id,
41
+ data=self.data,
42
+ is_extended_id=self.is_extended,
43
+ is_fd=self.is_fd,
44
+ is_remote_frame=self.is_remote,
45
+ bitrate_switch=self.bitrate_switch,
46
+ error_state_indicator=self.error_state_indicator,
47
+ timestamp=self.timestamp if self.timestamp is not None else 0.0,
48
+ channel=self.channel,
49
+ dlc=self.dlc,
50
+ )
51
+
52
+ def to_dict(self) -> dict:
53
+ """序列化契约(§4.2):data 为无空格小写十六进制;channel 不进输出 JSON。"""
54
+ d: dict = {
55
+ "arbitration_id": self.arbitration_id,
56
+ "data": self.data.hex(),
57
+ "is_extended": self.is_extended,
58
+ "is_fd": self.is_fd,
59
+ "is_remote": self.is_remote,
60
+ "bitrate_switch": self.bitrate_switch,
61
+ "error_state_indicator": self.error_state_indicator,
62
+ }
63
+ if self.timestamp is not None:
64
+ d["timestamp"] = self.timestamp
65
+ if self.dlc is not None:
66
+ d["dlc"] = self.dlc
67
+ # 注意:channel 不进入输出 JSON,通道以会话和 list/status 为准。
68
+ return d
@@ -0,0 +1,95 @@
1
+ """结构化结果契约:CLI 与 MCP 输出同一个 Result schema。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import dataclass, field
7
+ from enum import StrEnum
8
+ from typing import Any
9
+
10
+ SCHEMA_VERSION = "1.0"
11
+
12
+
13
+ class ErrorCode(StrEnum):
14
+ """枚举化错误码。error.code 是 Agent 的程序化分支依据。"""
15
+
16
+ DEVICE_NOT_FOUND = "DEVICE_NOT_FOUND"
17
+ DEVICE_BUSY = "DEVICE_BUSY"
18
+ DEVICE_OPEN_FAILED = "DEVICE_OPEN_FAILED"
19
+ DLL_NOT_FOUND = "DLL_NOT_FOUND"
20
+ DEVICE_NOT_OPEN = "DEVICE_NOT_OPEN"
21
+ INVALID_ARGUMENT = "INVALID_ARGUMENT"
22
+ BITRATE_NOT_SUPPORTED = "BITRATE_NOT_SUPPORTED"
23
+ CAPABILITY_UNSUPPORTED = "CAPABILITY_UNSUPPORTED"
24
+ CHANNEL_OUT_OF_RANGE = "CHANNEL_OUT_OF_RANGE"
25
+ BUS_OFF = "BUS_OFF"
26
+ SEND_FAILED = "SEND_FAILED"
27
+ SESSION_NOT_FOUND = "SESSION_NOT_FOUND"
28
+ MONITOR_ACTIVE = "MONITOR_ACTIVE"
29
+ CLOSE_TIMEOUT = "CLOSE_TIMEOUT"
30
+ CONFIG_ERROR = "CONFIG_ERROR"
31
+ INTERNAL_ERROR = "INTERNAL_ERROR"
32
+
33
+
34
+ @dataclass
35
+ class ErrorInfo:
36
+ code: str
37
+ message: str
38
+ detail: str | None = None
39
+ context: dict = field(default_factory=dict) # 仅诊断用,可含厂商名
40
+
41
+ def to_dict(self) -> dict:
42
+ d: dict = {"code": self.code, "message": self.message}
43
+ if self.detail is not None:
44
+ d["detail"] = self.detail
45
+ if self.context:
46
+ d["context"] = self.context
47
+ return d
48
+
49
+
50
+ @dataclass
51
+ class Result:
52
+ status: str # "ok" | "error"
53
+ data: Any = None
54
+ error: ErrorInfo | None = None
55
+ meta: dict = field(default_factory=dict)
56
+
57
+ @classmethod
58
+ def ok(cls, data: Any = None, **meta: Any) -> Result:
59
+ m = {"timestamp": _now(), "schema_version": SCHEMA_VERSION}
60
+ m.update(meta)
61
+ return cls(status="ok", data=data, meta=m)
62
+
63
+ @classmethod
64
+ def err(
65
+ cls,
66
+ code: ErrorCode | str,
67
+ message: str,
68
+ *,
69
+ data: Any = None,
70
+ detail: str | None = None,
71
+ context: dict | None = None,
72
+ **meta: Any,
73
+ ) -> Result:
74
+ m = {"timestamp": _now(), "schema_version": SCHEMA_VERSION}
75
+ m.update(meta)
76
+ code_str = code.value if isinstance(code, ErrorCode) else str(code)
77
+ return cls(
78
+ status="error",
79
+ data=data,
80
+ error=ErrorInfo(code=code_str, message=message, detail=detail, context=context or {}),
81
+ meta=m,
82
+ )
83
+
84
+ def to_dict(self) -> dict:
85
+ d: dict = {
86
+ "status": self.status,
87
+ "data": self.data,
88
+ "error": self.error.to_dict() if self.error else None,
89
+ "meta": self.meta,
90
+ }
91
+ return d
92
+
93
+
94
+ def _now() -> str:
95
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())