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.
xusbcan/cli/app.py ADDED
@@ -0,0 +1,106 @@
1
+ """CLI:argparse 命令定义,薄封装 core。
2
+
3
+ 一次性命令:list / send / receive / monitor / status(每次调用自己 open → 操作 → close)。
4
+ stdout 只放一个 JSON 对象(Result);日志/诊断走 stderr。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+
13
+ from ..config.loader import load_config
14
+ from ..core import (
15
+ SessionManager,
16
+ list_devices,
17
+ monitor,
18
+ parse_hex,
19
+ receive,
20
+ send,
21
+ status,
22
+ )
23
+ from ..models.frame import CanFrame
24
+ from ..models.result import ErrorCode, Result
25
+
26
+
27
+ def build_parser() -> argparse.ArgumentParser:
28
+ parser = argparse.ArgumentParser(
29
+ prog="xusbcan", description="面向 AI Agent 的 CAN 总线调试工具"
30
+ )
31
+ parser.add_argument(
32
+ "--config", help="配置文件路径(默认按 XUSBCAN_CONFIG / ./xusbcan.toml 搜索)"
33
+ )
34
+ sub = parser.add_subparsers(dest="command", required=True)
35
+
36
+ sub.add_parser("list", help="列出设备(只读配置与会话表)")
37
+
38
+ p = sub.add_parser("send", help="发送一帧 CAN 报文")
39
+ p.add_argument("alias", help="设备逻辑别名")
40
+ p.add_argument("--id", required=True, help="报文 ID(支持 0x 前缀)")
41
+ p.add_argument("--data", default="", help='十六进制数据,如 "01 02 03"')
42
+ p.add_argument("--ext", action="store_true", help="扩展帧")
43
+ p.add_argument("--fd", action="store_true", help="CAN FD(2E 卡不支持)")
44
+
45
+ p = sub.add_parser("receive", help="接收一帧(带超时)")
46
+ p.add_argument("alias", help="设备逻辑别名")
47
+ p.add_argument("--timeout", type=float, default=1.0, help="超时(秒,默认 1)")
48
+
49
+ p = sub.add_parser("monitor", help="有界监听")
50
+ p.add_argument("alias", help="设备逻辑别名")
51
+ p.add_argument("--duration", type=float, default=1.0, help="时长(秒,上限 30)")
52
+ p.add_argument("--max-frames", type=int, default=500, help="最大帧数")
53
+
54
+ p = sub.add_parser("status", help="查询会话/设备状态")
55
+ p.add_argument("alias", help="设备逻辑别名")
56
+
57
+ return parser
58
+
59
+
60
+ def dispatch(args: argparse.Namespace) -> Result:
61
+ cfg_result = load_config(args.config)
62
+ if cfg_result.status == "error":
63
+ return cfg_result
64
+ cfg = cfg_result.data
65
+
66
+ mgr = SessionManager()
67
+ for entry in cfg.devices:
68
+ mgr.register(entry.name, entry.spec)
69
+
70
+ cmd = args.command
71
+ if cmd == "list":
72
+ return list_devices(mgr)
73
+ if cmd == "send":
74
+ try:
75
+ arb_id = int(args.id, 0)
76
+ data = parse_hex(args.data)
77
+ except ValueError as e:
78
+ return Result.err(ErrorCode.INVALID_ARGUMENT, str(e))
79
+ frame = CanFrame(
80
+ arbitration_id=arb_id,
81
+ data=data,
82
+ is_extended=args.ext,
83
+ is_fd=args.fd,
84
+ )
85
+ return send(mgr, args.alias, frame)
86
+ if cmd == "receive":
87
+ return receive(mgr, args.alias, args.timeout)
88
+ if cmd == "monitor":
89
+ return monitor(mgr, args.alias, args.duration, args.max_frames)
90
+ if cmd == "status":
91
+ return status(mgr, args.alias)
92
+ return Result.err(ErrorCode.INVALID_ARGUMENT, f"未知命令: {cmd}")
93
+
94
+
95
+ def main(argv=None) -> int:
96
+ if hasattr(sys.stdout, "reconfigure"):
97
+ sys.stdout.reconfigure(encoding="utf-8")
98
+ parser = build_parser()
99
+ args = parser.parse_args(argv)
100
+ result = dispatch(args)
101
+ print(json.dumps(result.to_dict(), ensure_ascii=False))
102
+ return 0 if result.status == "ok" else 1
103
+
104
+
105
+ if __name__ == "__main__":
106
+ sys.exit(main())
@@ -0,0 +1,5 @@
1
+ """配置加载:TOML → DeviceSpec,供 CLI 与 MCP 共用。"""
2
+
3
+ from .loader import Config, DeviceEntry, find_config_path, load_config
4
+
5
+ __all__ = ["Config", "DeviceEntry", "find_config_path", "load_config"]
@@ -0,0 +1,78 @@
1
+ """配置加载(标准库 tomllib)。
2
+
3
+ 搜索顺序(定死,CLI/MCP 一致,避免同一台机器上打开不同的卡):
4
+ 1. --config 命令行参数
5
+ 2. 环境变量 XUSBCAN_CONFIG
6
+ 3. 当前目录 xusbcan.toml
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import tomllib
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+
16
+ from ..models.device import BitrateConfig, DeviceSpec
17
+ from ..models.result import ErrorCode, Result
18
+
19
+
20
+ @dataclass
21
+ class DeviceEntry:
22
+ """配置里的一个设备条目:逻辑别名 + DeviceSpec。别名是 SessionManager 的 key。"""
23
+
24
+ name: str
25
+ spec: DeviceSpec
26
+
27
+
28
+ @dataclass
29
+ class Config:
30
+ server: dict = field(default_factory=dict)
31
+ devices: list[DeviceEntry] = field(default_factory=list)
32
+
33
+
34
+ def find_config_path(explicit: str | None = None) -> Path | None:
35
+ """按搜索顺序找配置文件,找不到返回 None。"""
36
+ if explicit:
37
+ return Path(explicit)
38
+ env = os.environ.get("XUSBCAN_CONFIG")
39
+ if env:
40
+ return Path(env)
41
+ local = Path("xusbcan.toml")
42
+ if local.exists():
43
+ return local
44
+ return None
45
+
46
+
47
+ def load_config(explicit: str | None = None) -> Result:
48
+ """加载配置并解析为 Config。失败返回 Result.err(CONFIG_ERROR)。"""
49
+ path = find_config_path(explicit)
50
+ if path is None:
51
+ return Result.err(
52
+ ErrorCode.CONFIG_ERROR,
53
+ "未找到配置文件(--config / XUSBCAN_CONFIG / ./xusbcan.toml)",
54
+ )
55
+
56
+ try:
57
+ with open(path, "rb") as f:
58
+ raw = tomllib.load(f)
59
+ except (OSError, tomllib.TOMLDecodeError) as e:
60
+ return Result.err(ErrorCode.CONFIG_ERROR, f"读取配置失败: {e}")
61
+
62
+ cfg = Config(server=raw.get("server", {}))
63
+ for d in raw.get("devices", []):
64
+ try:
65
+ nominal = d.get("nominal")
66
+ bitrate = BitrateConfig(nominal=nominal) if nominal else None
67
+ spec = DeviceSpec(
68
+ vendor=d["vendor"],
69
+ model=d["model"],
70
+ channel=d.get("channel", 0),
71
+ bitrate=bitrate,
72
+ extra=d.get("extra", {}),
73
+ )
74
+ except KeyError as e:
75
+ return Result.err(ErrorCode.CONFIG_ERROR, f"设备配置缺少字段: {e}")
76
+ cfg.devices.append(DeviceEntry(name=d["name"], spec=spec))
77
+
78
+ return Result.ok(cfg)
@@ -0,0 +1,50 @@
1
+ """core 层:CLI 与 MCP 共享的业务逻辑。
2
+
3
+ 只面向 can.Bus 与领域模型;唯一接触适配层的地方是通过 registry(不 import
4
+ adapters.zlg),绝不 import 厂商代码。
5
+ """
6
+
7
+ from .commands import (
8
+ capture,
9
+ close_session,
10
+ list_devices,
11
+ map_error,
12
+ monitor,
13
+ open_session,
14
+ parse_hex,
15
+ periodic_list,
16
+ periodic_start,
17
+ periodic_stop,
18
+ receive,
19
+ receive_frame,
20
+ send,
21
+ status,
22
+ transmit,
23
+ )
24
+ from .monitor import Monitor
25
+ from .periodic import PeriodicTask
26
+ from .session import CLOSE_TIMEOUT_S, Session, SessionManager, SessionState
27
+
28
+ __all__ = [
29
+ "Session",
30
+ "SessionManager",
31
+ "SessionState",
32
+ "CLOSE_TIMEOUT_S",
33
+ "map_error",
34
+ "PeriodicTask",
35
+ "Monitor",
36
+ "transmit",
37
+ "receive_frame",
38
+ "capture",
39
+ "send",
40
+ "receive",
41
+ "monitor",
42
+ "open_session",
43
+ "close_session",
44
+ "list_devices",
45
+ "status",
46
+ "periodic_start",
47
+ "periodic_stop",
48
+ "periodic_list",
49
+ "parse_hex",
50
+ ]
@@ -0,0 +1,270 @@
1
+ """命令处理器:一次性命令与会话命令共用同一套 transmit / receive_frame / capture。
2
+
3
+ 分层:
4
+ - 底层(面向已打开的 Session):transmit / receive_frame / capture
5
+ - 别名级(复用规则):send / receive / monitor
6
+ - 会话命令:open_session / close_session / periodic_*
7
+ - 查询:list_devices / status
8
+
9
+ 十六进制解析、Result 序列化、异常翻译都只放一份,CLI 与 MCP 共用。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Iterable
15
+
16
+ import can
17
+
18
+ from ..adapters.registry import Profile, resolve
19
+ from ..models.frame import CanFrame
20
+ from ..models.result import ErrorCode, Result
21
+ from . import monitor as monitor_mod
22
+ from . import periodic as periodic_mod
23
+ from .session import Session, SessionManager, SessionState, map_error
24
+
25
+ __all__ = [
26
+ "map_error",
27
+ "parse_hex",
28
+ "transmit",
29
+ "receive_frame",
30
+ "capture",
31
+ "send",
32
+ "receive",
33
+ "monitor",
34
+ "open_session",
35
+ "close_session",
36
+ "list_devices",
37
+ "status",
38
+ "periodic_start",
39
+ "periodic_stop",
40
+ "periodic_list",
41
+ ]
42
+
43
+
44
+ # --------------------------------------------------------------------------- #
45
+ # 公共工具
46
+ # --------------------------------------------------------------------------- #
47
+
48
+
49
+ def parse_hex(s: str) -> bytes:
50
+ """十六进制字符串 → bytes。支持 "010203" 与 "01 02 03"、"0x01 0x02"。"""
51
+ if not isinstance(s, str):
52
+ raise ValueError(f"数据必须是字符串: {s!r}")
53
+ cleaned = s.strip().replace("0x", "").replace("0X", "")
54
+ cleaned = "".join(cleaned.split())
55
+ if cleaned == "":
56
+ return b""
57
+ if len(cleaned) % 2 != 0:
58
+ raise ValueError(f"十六进制数据长度必须为偶数: {s!r}")
59
+ try:
60
+ return bytes.fromhex(cleaned)
61
+ except ValueError as e:
62
+ raise ValueError(f"非法十六进制数据: {s!r}") from e
63
+
64
+
65
+ def profile_features(profile: Profile) -> dict:
66
+ """Profile → list/status 里的 features 字段(§4.5)。"""
67
+ return {
68
+ "fd": profile.fd,
69
+ "channels": profile.channels,
70
+ "interface": profile.interface,
71
+ }
72
+
73
+
74
+ # --------------------------------------------------------------------------- #
75
+ # 底层(面向已打开的 Session,一次性与会话共用)
76
+ # --------------------------------------------------------------------------- #
77
+
78
+
79
+ def transmit(session: Session, frames: CanFrame | Iterable[CanFrame]) -> Result:
80
+ """在已打开的 session 上发送若干帧。多帧发送不是全有或全无。"""
81
+ if isinstance(frames, CanFrame):
82
+ frames = [frames]
83
+ else:
84
+ frames = list(frames)
85
+ if not frames:
86
+ return Result.err(ErrorCode.INVALID_ARGUMENT, "没有要发送的帧")
87
+ sent = 0
88
+ for i, frame in enumerate(frames):
89
+ try:
90
+ session.bus.send(frame.to_can_message())
91
+ sent += 1
92
+ except can.CanError as e:
93
+ return Result.err(
94
+ ErrorCode.SEND_FAILED,
95
+ f"发送失败(第 {i + 1} 帧): {e}",
96
+ data={"sent": sent, "failed_index": i},
97
+ detail=str(e),
98
+ )
99
+ except Exception as e:
100
+ return Result.err(
101
+ ErrorCode.INTERNAL_ERROR,
102
+ f"发送异常(第 {i + 1} 帧): {e}",
103
+ data={"sent": sent, "failed_index": i},
104
+ detail=str(e),
105
+ )
106
+ return Result.ok({"sent": sent})
107
+
108
+
109
+ def receive_frame(session: Session, timeout: float | None) -> Result:
110
+ """在已打开的 session 上收一帧。超时是成功态;监听运行中返回 MONITOR_ACTIVE。"""
111
+ if session.receive_owner is not None:
112
+ return Result.err(
113
+ ErrorCode.MONITOR_ACTIVE,
114
+ "监听/采集已在进行",
115
+ context={"alias": session.name},
116
+ )
117
+ try:
118
+ msg = session.bus.recv(timeout=timeout)
119
+ except can.CanTimeoutError:
120
+ return Result.ok({"frame": None, "reason": "timeout"})
121
+ except can.CanError as e:
122
+ return Result.err(map_error(e), f"接收失败: {e}", detail=str(e))
123
+ except Exception as e:
124
+ return Result.err(ErrorCode.INTERNAL_ERROR, f"接收异常: {e}")
125
+ if msg is None:
126
+ return Result.ok({"frame": None, "reason": "timeout"})
127
+ return Result.ok({"frame": CanFrame.from_can_message(msg).to_dict()})
128
+
129
+
130
+ def capture(
131
+ session: Session,
132
+ duration_s: float | None = None,
133
+ max_frames: int | None = None,
134
+ ) -> Result:
135
+ """在已打开的 session 上有界采集(复用 monitor 实现)。"""
136
+ return monitor_mod.capture_bounded(session, duration_s, max_frames)
137
+
138
+
139
+ # --------------------------------------------------------------------------- #
140
+ # 别名级(复用规则:已打开复用不 shutdown;未打开一次性 try/finally 关闭)
141
+ # --------------------------------------------------------------------------- #
142
+
143
+
144
+ def send(manager: SessionManager, alias: str, frames: CanFrame | Iterable[CanFrame]) -> Result:
145
+ session, err, reused = manager.acquire(alias)
146
+ if err is not None:
147
+ return err
148
+ assert session is not None
149
+ try:
150
+ return transmit(session, frames)
151
+ finally:
152
+ manager.release(session, reused)
153
+
154
+
155
+ def receive(manager: SessionManager, alias: str, timeout: float | None) -> Result:
156
+ session, err, reused = manager.acquire(alias)
157
+ if err is not None:
158
+ return err
159
+ assert session is not None
160
+ try:
161
+ return receive_frame(session, timeout)
162
+ finally:
163
+ manager.release(session, reused)
164
+
165
+
166
+ def monitor(
167
+ manager: SessionManager,
168
+ alias: str,
169
+ duration_s: float | None = None,
170
+ max_frames: int | None = None,
171
+ ) -> Result:
172
+ session, err, reused = manager.acquire(alias)
173
+ if err is not None:
174
+ return err
175
+ assert session is not None
176
+ try:
177
+ return capture(session, duration_s, max_frames)
178
+ finally:
179
+ manager.release(session, reused)
180
+
181
+
182
+ # --------------------------------------------------------------------------- #
183
+ # 会话命令
184
+ # --------------------------------------------------------------------------- #
185
+
186
+
187
+ def open_session(manager: SessionManager, alias: str) -> Result:
188
+ return manager.open(alias)
189
+
190
+
191
+ def close_session(manager: SessionManager, alias: str) -> Result:
192
+ return manager.close(alias)
193
+
194
+
195
+ def _require_open(manager: SessionManager, alias: str) -> tuple[Session | None, Result | None]:
196
+ """周期/监听等会话命令要求会话已显式打开(常驻持有),不复用一次性路径。"""
197
+ session = manager.get(alias)
198
+ if session is None:
199
+ return None, Result.err(ErrorCode.SESSION_NOT_FOUND, f"会话未打开: {alias}")
200
+ if session.state is not SessionState.OPEN:
201
+ return None, Result.err(ErrorCode.DEVICE_NOT_OPEN, f"会话状态异常: {alias}")
202
+ return session, None
203
+
204
+
205
+ def periodic_start(
206
+ manager: SessionManager, alias: str, name: str, frame: CanFrame, period: float
207
+ ) -> Result:
208
+ session, err = _require_open(manager, alias)
209
+ if err is not None:
210
+ return err
211
+ return periodic_mod.start(session, name, frame, period)
212
+
213
+
214
+ def periodic_stop(manager: SessionManager, alias: str, name: str) -> Result:
215
+ session, err = _require_open(manager, alias)
216
+ if err is not None:
217
+ return err
218
+ return periodic_mod.stop(session, name)
219
+
220
+
221
+ def periodic_list(manager: SessionManager, alias: str) -> Result:
222
+ session, err = _require_open(manager, alias)
223
+ if err is not None:
224
+ return err
225
+ return periodic_mod.list_tasks(session)
226
+
227
+
228
+ # --------------------------------------------------------------------------- #
229
+ # 查询
230
+ # --------------------------------------------------------------------------- #
231
+
232
+
233
+ def list_devices(manager: SessionManager) -> Result:
234
+ """§13:只读配置与会话表,不调 OpenDevice。"""
235
+ devices = []
236
+ for name, spec in manager.specs.items():
237
+ try:
238
+ profile = resolve(spec)
239
+ except KeyError:
240
+ profile = None
241
+ session = manager.get(name)
242
+ opened = session is not None and session.state is SessionState.OPEN
243
+ devices.append(
244
+ {
245
+ "name": name,
246
+ "channel": spec.channel,
247
+ "opened": opened,
248
+ "features": profile_features(profile) if profile else {},
249
+ }
250
+ )
251
+ return Result.ok({"devices": devices})
252
+
253
+
254
+ def status(manager: SessionManager, alias: str) -> Result:
255
+ """§4.5:data 含 state / features / receive_owner。"""
256
+ spec = manager.get_spec(alias)
257
+ if spec is None:
258
+ return Result.err(ErrorCode.SESSION_NOT_FOUND, f"会话不存在: {alias}")
259
+ try:
260
+ profile = resolve(spec)
261
+ except KeyError as e:
262
+ return Result.err(ErrorCode.CONFIG_ERROR, str(e))
263
+ session = manager.get(alias)
264
+ return Result.ok(
265
+ {
266
+ "state": (session.state if session is not None else SessionState.CLOSED).value,
267
+ "features": profile_features(profile),
268
+ "receive_owner": session.receive_owner if session is not None else None,
269
+ }
270
+ )
@@ -0,0 +1,178 @@
1
+ """监听(有界采集)。
2
+
3
+ MCP 形态:有界采集,duration_s(默认 1、上限 30)+ max_frames(默认 500),
4
+ 返回普通 Result,帧在 data.frames,带 count / truncated。运行期间 session 标记
5
+ 接收所有者,receive_frame 返回 MONITOR_ACTIVE。常驻监听用 receive_frame 轮询。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import threading
11
+ import time
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ import can
16
+
17
+ from ..models.frame import CanFrame
18
+ from ..models.result import ErrorCode, Result
19
+ from .session import CLOSE_TIMEOUT_S, map_error
20
+
21
+ DEFAULT_DURATION_S = 1.0
22
+ MAX_DURATION_S = 30.0
23
+ DEFAULT_MAX_FRAMES = 500
24
+ # 采集循环的轮询步长:用小步长让 stop()/close() 能及时收回线程,
25
+ # 而不是整段 duration 阻塞在某一次 recv 里。
26
+ POLL_INTERVAL_S = 0.1
27
+
28
+
29
+ @dataclass
30
+ class Monitor:
31
+ """有界采集器。在守护线程里跑;session.monitor 引用它,stop() 置位后 join()。"""
32
+
33
+ name: str # 会话别名
34
+ bus: Any # can.BusABC
35
+ duration_s: float
36
+ max_frames: int
37
+ frames: list[CanFrame] = field(default_factory=list)
38
+ truncated: bool = False
39
+ error: BaseException | None = None
40
+ _stop: threading.Event = field(default_factory=threading.Event, repr=False)
41
+ _thread: threading.Thread | None = field(default=None, repr=False)
42
+ _lock: threading.Lock = field(default_factory=threading.Lock, repr=False)
43
+
44
+ def start(self) -> None:
45
+ self._thread = threading.Thread(
46
+ target=self._run, name=f"xusbcan-monitor-{self.name}", daemon=True
47
+ )
48
+ self._thread.start()
49
+
50
+ def stop(self) -> None:
51
+ self._stop.set()
52
+
53
+ def join(self, timeout: float | None = None) -> bool:
54
+ """等待采集线程结束;返回是否已结束(False = join 超时)。"""
55
+ if self._thread is None:
56
+ return True
57
+ self._thread.join(timeout)
58
+ return not self._thread.is_alive()
59
+
60
+ def _run(self) -> None:
61
+ deadline = time.monotonic() + self.duration_s
62
+ while not self._stop.is_set():
63
+ remaining = deadline - time.monotonic()
64
+ if remaining <= 0:
65
+ break
66
+ timeout = min(remaining, POLL_INTERVAL_S)
67
+ try:
68
+ msg = self.bus.recv(timeout=timeout)
69
+ except can.CanError as e:
70
+ self.error = e
71
+ break
72
+ if msg is None:
73
+ continue # 到点或步长内无帧,循环重算 deadline
74
+ frame = CanFrame.from_can_message(msg)
75
+ with self._lock:
76
+ if len(self.frames) < self.max_frames:
77
+ self.frames.append(frame)
78
+ else:
79
+ # 超过 max_frames:丢弃后续并停止采集
80
+ self.truncated = True
81
+ self._stop.set()
82
+ break
83
+
84
+ def _result_data(self) -> dict:
85
+ with self._lock:
86
+ frames = list(self.frames)
87
+ return {
88
+ "frames": [f.to_dict() for f in frames],
89
+ "count": len(frames),
90
+ "truncated": self.truncated,
91
+ }
92
+
93
+ def to_result(self) -> Result:
94
+ if self.error is not None:
95
+ return Result.err(
96
+ map_error(self.error),
97
+ f"监听失败: {self.error}",
98
+ detail=str(self.error),
99
+ )
100
+ return Result.ok(self._result_data())
101
+
102
+
103
+ def _normalize_duration(duration_s: float | None) -> float | None:
104
+ if duration_s is None:
105
+ return DEFAULT_DURATION_S
106
+ if duration_s < 0:
107
+ return None
108
+ return min(float(duration_s), MAX_DURATION_S)
109
+
110
+
111
+ def _normalize_max_frames(max_frames: int | None) -> int | None:
112
+ if max_frames is None:
113
+ return DEFAULT_MAX_FRAMES
114
+ if max_frames <= 0:
115
+ return None
116
+ return max_frames
117
+
118
+
119
+ def capture_bounded(session, duration_s: float | None, max_frames: int | None) -> Result:
120
+ """有界采集(MCP / 一次性共用)。占用接收所有者,采集完返回 Result。"""
121
+ d = _normalize_duration(duration_s)
122
+ if d is None:
123
+ return Result.err(ErrorCode.INVALID_ARGUMENT, f"duration_s 不能为负: {duration_s}")
124
+ m = _normalize_max_frames(max_frames)
125
+ if m is None:
126
+ return Result.err(ErrorCode.INVALID_ARGUMENT, f"max_frames 必须为正: {max_frames}")
127
+
128
+ if not session.acquire_receive("monitor"):
129
+ return Result.err(
130
+ ErrorCode.MONITOR_ACTIVE,
131
+ "监听/采集已在进行",
132
+ context={"alias": session.name},
133
+ )
134
+
135
+ monitor = Monitor(name=session.name, bus=session.bus, duration_s=d, max_frames=m)
136
+ session.set_monitor(monitor)
137
+ try:
138
+ monitor.start()
139
+ # 多给一点余量,避免与 close 的 join 超时误判
140
+ monitor.join(timeout=d + CLOSE_TIMEOUT_S)
141
+ return monitor.to_result()
142
+ finally:
143
+ session.clear_monitor(monitor)
144
+ session.release_receive("monitor")
145
+
146
+
147
+ def start_monitor(
148
+ session, duration_s: float | None = None, max_frames: int | None = None
149
+ ) -> Result:
150
+ """后台启动监听(会话形态,不阻塞)。运行期间 receive_frame 返回 MONITOR_ACTIVE。"""
151
+ d = _normalize_duration(duration_s)
152
+ if d is None:
153
+ return Result.err(ErrorCode.INVALID_ARGUMENT, f"duration_s 不能为负: {duration_s}")
154
+ m = _normalize_max_frames(max_frames)
155
+ if m is None:
156
+ return Result.err(ErrorCode.INVALID_ARGUMENT, f"max_frames 必须为正: {max_frames}")
157
+
158
+ if not session.acquire_receive("monitor"):
159
+ return Result.err(
160
+ ErrorCode.MONITOR_ACTIVE,
161
+ "监听/采集已在进行",
162
+ context={"alias": session.name},
163
+ )
164
+ monitor = Monitor(name=session.name, bus=session.bus, duration_s=d, max_frames=m)
165
+ session.set_monitor(monitor)
166
+ monitor.start()
167
+ return Result.ok({"monitor": session.name, "started": True})
168
+
169
+
170
+ def stop_monitor(session) -> Result:
171
+ monitor = session.monitor
172
+ if monitor is None:
173
+ return Result.err(ErrorCode.SESSION_NOT_FOUND, "没有正在运行的监听")
174
+ monitor.stop()
175
+ monitor.join(timeout=CLOSE_TIMEOUT_S)
176
+ session.clear_monitor(monitor)
177
+ session.release_receive("monitor")
178
+ return monitor.to_result()