ehatool 6.0.0.dev0__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.
Files changed (77) hide show
  1. ehatool/VERSION +1 -0
  2. ehatool/__init__.py +4 -0
  3. ehatool/acceptance.py +92 -0
  4. ehatool/brt27.py +105 -0
  5. ehatool/brt27_sim.py +114 -0
  6. ehatool/calibration.py +111 -0
  7. ehatool/can_sniff.py +162 -0
  8. ehatool/cia402.py +31 -0
  9. ehatool/cli.py +541 -0
  10. ehatool/console.py +31 -0
  11. ehatool/device/__init__.py +4 -0
  12. ehatool/device/can.py +201 -0
  13. ehatool/device/can_discovery.py +387 -0
  14. ehatool/device/can_discovery.toml +19 -0
  15. ehatool/device/io.py +20 -0
  16. ehatool/devices.py +187 -0
  17. ehatool/diagnostics.py +58 -0
  18. ehatool/diagnostics.toml +208 -0
  19. ehatool/discovery.py +95 -0
  20. ehatool/display.toml +127 -0
  21. ehatool/ecat.py +520 -0
  22. ehatool/ecat.toml +17 -0
  23. ehatool/ecat_probe.py +401 -0
  24. ehatool/ecat_probe.toml +14 -0
  25. ehatool/eha_od.json +5871 -0
  26. ehatool/experiment.py +576 -0
  27. ehatool/image.py +70 -0
  28. ehatool/info.py +121 -0
  29. ehatool/info.toml +41 -0
  30. ehatool/install_host.py +243 -0
  31. ehatool/install_host.toml +27 -0
  32. ehatool/link.py +811 -0
  33. ehatool/link.toml +18 -0
  34. ehatool/live.py +112 -0
  35. ehatool/motor.py +86 -0
  36. ehatool/od.py +200 -0
  37. ehatool/odrive.py +450 -0
  38. ehatool/output.py +208 -0
  39. ehatool/ram_load.py +62 -0
  40. ehatool/scope.py +50 -0
  41. ehatool/sil.py +260 -0
  42. ehatool/update.py +320 -0
  43. ehatool/usb_discovery.py +164 -0
  44. ehatool/usb_discovery.toml +16 -0
  45. ehatool/web/__init__.py +28 -0
  46. ehatool/web/brt_sim.py +130 -0
  47. ehatool/web/canbus.py +95 -0
  48. ehatool/web/devices.py +216 -0
  49. ehatool/web/experiments.py +226 -0
  50. ehatool/web/job_params.py +208 -0
  51. ehatool/web/layout.toml +61 -0
  52. ehatool/web/longrun.py +430 -0
  53. ehatool/web/polling.py +41 -0
  54. ehatool/web/recipes/bench.toml +18 -0
  55. ehatool/web/records.py +333 -0
  56. ehatool/web/requests.py +254 -0
  57. ehatool/web/server.py +1051 -0
  58. ehatool/web/session.py +1552 -0
  59. ehatool/web/static/THIRD_PARTY_LICENSES.txt +133 -0
  60. ehatool/web/static/assets/ehapower-logo-Cr84XeX3.png +0 -0
  61. ehatool/web/static/assets/ehapower-mark-Con0OjPM.png +0 -0
  62. ehatool/web/static/assets/index-CdLvwKa-.css +1 -0
  63. ehatool/web/static/assets/index-DiLUQD1i.js +134 -0
  64. ehatool/web/static/index.html +16 -0
  65. ehatool/web/streams.py +64 -0
  66. ehatool/web/workspaces.py +124 -0
  67. ehatool/workflows/__init__.py +4 -0
  68. ehatool/workflows/cancheck.py +394 -0
  69. ehatool/workflows/cancheck.toml +9 -0
  70. ehatool/workflows/checks.py +43 -0
  71. ehatool/workflows/usbcheck.py +212 -0
  72. ehatool-6.0.0.dev0.dist-info/METADATA +38 -0
  73. ehatool-6.0.0.dev0.dist-info/RECORD +77 -0
  74. ehatool-6.0.0.dev0.dist-info/WHEEL +5 -0
  75. ehatool-6.0.0.dev0.dist-info/entry_points.txt +2 -0
  76. ehatool-6.0.0.dev0.dist-info/licenses/LICENSE +21 -0
  77. ehatool-6.0.0.dev0.dist-info/top_level.txt +1 -0
ehatool/web/server.py ADDED
@@ -0,0 +1,1051 @@
1
+ # Copyright The eha-firmware Contributors
2
+
3
+ ## @file
4
+ ## @brief ehatool web:本机 WebUI 服务(FastAPI)。只监听 127.0.0.1,校验 Host 与 Origin;所有接口与 WebSocket 握手都要求
5
+ ## 服务启动时生成、注入页面的令牌;只接受具名动作,不执行任意命令。设计见 docs/工作台页面合同.md。
6
+
7
+ import asyncio
8
+ import contextlib
9
+ import collections
10
+ import csv
11
+ import itertools
12
+ import math
13
+ import os
14
+ import pathlib
15
+ import secrets
16
+ import threading
17
+ import time
18
+ from urllib.parse import quote
19
+
20
+ from ..od import ObjectDictionary
21
+ from ..link import ControlRefused, Device, OWNER_LOST, SdoAbort
22
+ from .records import Records, cached_parameters, clean
23
+ from .polling import page_objects
24
+ from .. import experiment, update
25
+ from .job_params import (COMMAND_OBJECTS, LIMITS, LONGRUN_MODES, MANUAL_FIELDS, MANUAL_MODES, MODE_LABELS, MODE_TEXT, user_path)
26
+ from .session import Busy, DeviceSession, LinkLost, SessionOpenPending
27
+
28
+ STATIC = pathlib.Path(__file__).with_name("static")
29
+ TOOL_VERSION = (pathlib.Path(__file__).resolve().parents[1] / "VERSION").read_text().strip()
30
+ # 页面的 WebSocket 握手后若这么久没有任何帧(含协议层 ping 的应答),视为离开(危害清单:ping 超时 1 s)。
31
+ PING_INTERVAL_S = PING_TIMEOUT_S = 0.5
32
+ # 每个页面的待发事件上限;超过时丢弃示波批次(显示帧),状态与任务事件照发。
33
+ CLIENT_QUEUE = 400
34
+
35
+
36
+ ## @brief 服务状态:一台设备会话(W1 只接 USB)、已连接的页面、记录目录。
37
+ class App:
38
+ def __init__(self, port, records_dir=None, link_factory=None, od=None, shared_with=None):
39
+ self.port = port
40
+ self.token = secrets.token_urlsafe(24)
41
+ self.od = od or ObjectDictionary()
42
+ self.records = shared_with.records if shared_with is not None else Records(records_dir)
43
+ # 服务重启前仍在运行的长时任务:记为“中断,结果未知”,不自动重新开始。
44
+ from .longrun import mark_interrupted
45
+ if shared_with is None:
46
+ mark_interrupted(self.records.root)
47
+ self.session = None
48
+ self.closing = False
49
+ self.active_operations = 0
50
+ self.resource_lock = shared_with.resource_lock if shared_with is not None else threading.RLock()
51
+ self.session_resource = None
52
+ self.resource_operations = shared_with.resource_operations if shared_with is not None else set()
53
+ self.session_resources = shared_with.session_resources if shared_with is not None else set()
54
+ self.clients = {}
55
+ self.dropped = {}
56
+ self.poll_subscriptions = {}
57
+ self.poll_lock = threading.Lock()
58
+ self.drop_totals = {}
59
+ self.loop = None
60
+ self.ids = itertools.count(1)
61
+ self.link_factory = link_factory
62
+ self.console = Console(self.publish)
63
+ from .experiments import SilRunner
64
+ self.sil = SilRunner(self.records, self.publish)
65
+ from .brt_sim import BrtSimulator
66
+ self.brt_sim = BrtSimulator(lambda via, identifier: self.transport_operation(via, identifier))
67
+ self.parent = shared_with
68
+ from .workspaces import WorkspaceServers
69
+ self.workspaces = shared_with.workspaces if shared_with is not None else WorkspaceServers(self)
70
+
71
+ ## @brief 线程安全地把事件发给全部页面。
72
+ def publish(self, event):
73
+ if self.loop is None:
74
+ return
75
+ self.loop.call_soon_threadsafe(self._fanout, event)
76
+
77
+ def _fanout(self, event):
78
+ display = event["type"] in ("scope", "samples", "step_rows", "manual_rows", "sil_rows", "console")
79
+ key = f"{event['type']}:{event.get('id', '')}"
80
+ for client, q in list(self.clients.items()):
81
+ if display and q.qsize() >= CLIENT_QUEUE:
82
+ losses = self.dropped.setdefault(client, {})
83
+ losses[key] = losses.get(key, 0) + 1
84
+ self.drop_totals[client] = self.drop_totals.get(client, 0) + 1
85
+ continue
86
+ loss = self.dropped.get(client, {}).pop(key, 0) if display else 0
87
+ q.put_nowait({**event, "display_dropped": loss} if loss else event)
88
+
89
+ ## @brief 合并所有已连接浏览器的对象订阅,设备断开/重连不会丢失页面当前选择。
90
+ def set_poll_subscription(self, client, names):
91
+ known = {obj["name"] for obj in self.od.objects}
92
+ if not isinstance(names, list) or len(names) > len(known) or any(not isinstance(n, str) or n not in known for n in names):
93
+ raise ValueError("轮询订阅须为对象字典中的对象名列表")
94
+ with self.poll_lock:
95
+ self.poll_subscriptions[client] = tuple(dict.fromkeys(names))
96
+ self._update_poll_objects()
97
+
98
+ def remove_poll_subscription(self, client):
99
+ with self.poll_lock:
100
+ self.poll_subscriptions.pop(client, None)
101
+ self._update_poll_objects()
102
+
103
+ def _update_poll_objects(self):
104
+ if self.session is not None:
105
+ self.session.set_poll_objects(name for names in self.poll_subscriptions.values() for name in names)
106
+
107
+ def allowed_hosts(self):
108
+ return {f"127.0.0.1:{self.port}", f"localhost:{self.port}"}
109
+
110
+ ## @brief 临时打开物理资源。预占与释放只短暂持锁,采集或子进程存续期间不会阻塞服务停止;调用者须关闭资源后再退出。
111
+ @contextlib.contextmanager
112
+ def transport_operation(self, via, identifier):
113
+ resource = (via, str(identifier or ""))
114
+ with self.resource_lock:
115
+ if self.closing:
116
+ raise Busy("工作台正在关闭")
117
+ if resource in self.session_resources or resource in self.resource_operations:
118
+ raise Busy("该物理端口正在使用:先断开设备或停止占用它的任务")
119
+ self.resource_operations.add(resource)
120
+ self.active_operations += 1
121
+ try:
122
+ yield
123
+ finally:
124
+ with self.resource_lock:
125
+ self.resource_operations.remove(resource)
126
+ self.active_operations -= 1
127
+
128
+ ## @brief 启动后台资源与空闲工作台回收互斥,开始关闭后拒绝新的资源占用。
129
+ def start_resource(self, operation, *args):
130
+ with self.resource_lock:
131
+ if self.closing:
132
+ raise Busy("工作台正在关闭")
133
+ return operation(*args)
134
+
135
+ ## @brief 按页面的选择打开设备:USB 串口;CAN 适配器、速率与节点号;EtherCAT 网卡与从站序号。
136
+ def open(self, body):
137
+ return self.start_resource(self._open, body)
138
+
139
+ def _open(self, body):
140
+ from . import devices
141
+ if self.session is not None:
142
+ raise Busy("已连接一台设备,先断开")
143
+ via = body.get("via", "usb")
144
+ resource = (via, str(body.get({"usb": "port", "can": "adapter", "ecat": "ifname"}.get(via)) or ""))
145
+ # 自动选择 USB 端口之前还不知道会选中哪一个,先拒绝与临时 USB 识别重叠。
146
+ occupied = self.resource_operations | self.session_resources
147
+ auto_usb_busy = via == "usb" and not body.get("port") and any(r[0] == "usb" for r in occupied)
148
+ if resource in occupied or auto_usb_busy:
149
+ raise Busy("该物理端口正在使用:先停止占用它的任务")
150
+ if self.link_factory is not None:
151
+ make = lambda: devices.UsbDevice("fake", self.od, link=self.link_factory()) # noqa: E731
152
+ elif via == "usb":
153
+ make = lambda: devices.UsbDevice(body.get("port"), self.od) # noqa: E731
154
+ elif via == "can":
155
+ interface, _, channel = str(body.get("adapter", "")).partition(":")
156
+ if not channel:
157
+ raise ValueError("CAN 适配器写成 接口:通道,例如 slcan:/dev/cu.usbmodem<序号>")
158
+ make = lambda: devices.CanDevice(interface, channel, int(body["bitrate"]), int(body.get("data_bitrate") or 0), # noqa: E731
159
+ int(body.get("node", 1)), self.od)
160
+ elif via == "ecat":
161
+ slave = body.get("slave")
162
+ dc = body.get("dc", False)
163
+ if not isinstance(dc, bool):
164
+ raise ValueError("DC 选项须为开或关")
165
+ make = lambda: devices.EcatDevice(str(body["ifname"]), self.od, None if slave in (None, "") else int(slave), dc=dc) # noqa: E731
166
+ else:
167
+ raise ValueError(f"未知通道 {via}")
168
+ with self.poll_lock:
169
+ objects = tuple(dict.fromkeys(name for names in self.poll_subscriptions.values() for name in names))
170
+ try:
171
+ session = DeviceSession(make, self.od, self.publish, self.records, poll_objects=objects)
172
+ except SessionOpenPending as error:
173
+ self.session = error.session
174
+ self.session_resource = (via, self.session.dev.path) if via == "usb" else resource
175
+ self.session_resources.add(self.session_resource)
176
+ self.publish({"type": "session", "session": self.session.snapshot()})
177
+ raise
178
+ actual_resource = (via, session.dev.path) if via == "usb" else resource
179
+ if actual_resource in occupied:
180
+ session.close()
181
+ raise Busy("该物理端口正在另一工作台中使用")
182
+ self.session = session
183
+ self.session_resource = actual_resource
184
+ self.session_resources.add(actual_resource)
185
+ with self.poll_lock:
186
+ self._update_poll_objects()
187
+ snapshot = self.session.snapshot()
188
+ self.publish({"type": "session", "session": snapshot, "history": self.session.sample_history()})
189
+ return snapshot
190
+
191
+ def close(self, expected_opened_at=None):
192
+ with self.resource_lock:
193
+ if expected_opened_at is not None and (self.session is None or self.session.opened_at != expected_opened_at):
194
+ raise Busy("设备会话已切换,本次断开未执行")
195
+ if self.session is not None:
196
+ # 关闭完成后再清空引用和广播,避免端口仍占用时重连以及旧关闭事件覆盖新连接。
197
+ self.session.close()
198
+ self.session = None
199
+ self.session_resources.discard(self.session_resource)
200
+ self.session_resource = None
201
+ self.publish({"type": "session", "session": None})
202
+
203
+ ## @brief 各后台资源分别收尾。一个关闭失败仍执行其余关闭,并向调用者保留首个失败。
204
+ def shutdown(self):
205
+ with self.resource_lock:
206
+ self.closing = True
207
+ failure = None
208
+ cleanups = [self.brt_sim.stop, self.console.stop, lambda: self.sil.stop(5), self.close]
209
+ if self.parent is None:
210
+ cleanups.insert(0, self.workspaces.close_children)
211
+ for cleanup in cleanups:
212
+ try:
213
+ cleanup()
214
+ except BaseException as error:
215
+ if failure is None:
216
+ failure = error
217
+ if failure is not None:
218
+ raise failure
219
+
220
+
221
+ ## @brief 调试口候选:FT2232 等 USB 串口(macOS 的 cu.usbserial*,Linux 的 ttyUSB*),不含产品 USB 口(CDC,usbmodem / ttyACM)。
222
+ def console_ports(exclude=None):
223
+ import glob
224
+ return [p for p in sorted(glob.glob("/dev/cu.usbserial*") + glob.glob("/dev/ttyUSB*")) if p != exclude]
225
+
226
+
227
+ ## @brief 调试口控制台(UART 115200 8N1,只读):读线程把每行推给页面。只打开候选列表中的端口,独占打开;启停串行。
228
+ class Console:
229
+ def __init__(self, publish):
230
+ import threading
231
+ self.publish, self.port, self.thread, self.stopping = publish, None, None, None
232
+ self.lock = threading.Lock()
233
+
234
+ def start(self, port, exclude=None):
235
+ with self.lock:
236
+ return self._start(port, exclude)
237
+
238
+ def _start(self, port, exclude):
239
+ import threading
240
+ import serial
241
+ self._stop()
242
+ if port not in console_ports(exclude):
243
+ raise ValueError(f"{port} 不在调试口候选中(产品 USB 口与会话正在使用的端口除外)")
244
+ handle = serial.Serial(port, 115200, timeout=0.2, exclusive=True)
245
+ self.port, self.stopping = port, threading.Event()
246
+
247
+ def reader(stopping=self.stopping):
248
+ try:
249
+ while not stopping.is_set():
250
+ line = handle.readline()
251
+ if line:
252
+ self.publish({"type": "console", "line": line.decode(errors="replace").rstrip()})
253
+ except OSError as error:
254
+ self.publish({"type": "console", "line": f"[读取停止:{error}]"})
255
+ finally:
256
+ handle.close()
257
+
258
+ self.thread = threading.Thread(target=reader, name="eha-console", daemon=True)
259
+ try:
260
+ self.thread.start()
261
+ except BaseException:
262
+ handle.close()
263
+ self.port = self.thread = self.stopping = None
264
+ raise
265
+ return {"open": port}
266
+
267
+ def stop(self, _port=None):
268
+ with self.lock:
269
+ return self._stop()
270
+
271
+ def _stop(self):
272
+ if self.stopping is not None:
273
+ self.stopping.set()
274
+ self.thread.join(timeout=2)
275
+ if self.thread.is_alive():
276
+ raise Busy("控制台尚未关闭,调试口仍被占用;稍后重试")
277
+ self.port = self.thread = self.stopping = None
278
+ return {"open": None}
279
+
280
+
281
+ ## @brief 参数页的分组:layout.toml 的索引区间展开为对象名(区间覆盖全部对象、互不重叠由测试检查)。
282
+ def layout_groups(od):
283
+ import tomllib
284
+ with open(pathlib.Path(__file__).with_name("layout.toml"), "rb") as f:
285
+ groups = tomllib.load(f)["group"]
286
+ out = []
287
+ for g in groups:
288
+ names = [o["name"] for o in od.objects if any(lo <= o["index"] <= hi for lo, hi in g["ranges"])]
289
+ out.append({"name": g["name"], "names": names, "managed": bool(g.get("managed"))})
290
+ return out
291
+
292
+
293
+ def od_payload(od):
294
+ device = od.device
295
+ objects = [dict(o) for o in od.objects]
296
+ # 沿用设备访问与状态显示的现有解码,前端只呈现文字,不另维护模式和通道编号表。
297
+ labels = {
298
+ "modes_of_operation": MODE_TEXT, "modes_of_operation_display": MODE_TEXT,
299
+ "firmware_slot": update.SLOT_NAMES,
300
+ "firmware_boot_confirmed": {**update.SLOT_NAMES, 255: "无已确认镜像"},
301
+ "control_owner": {channel | flag: Device.owner_text(channel | flag)
302
+ for channel in range(4) for flag in (0, OWNER_LOST)},
303
+ }
304
+ for obj in objects:
305
+ if obj["name"] in labels:
306
+ obj["display_values"] = {str(value): text for value, text in labels[obj["name"]].items()}
307
+ modes = [{"key": k, "label": MODE_LABELS[k],
308
+ "fields": [{"key": f, "label": MANUAL_FIELDS[f][0], "unit": MANUAL_FIELDS[f][1]} for f in fields]}
309
+ for k, fields in MANUAL_MODES.items()]
310
+ # 阶跃试验:定义与缺省值取自 experiment.py,工作台范围取自 job_params(设备与 SIL 共用)。
311
+ step = {"modes": [{"key": k, "label": MODE_LABELS[k], "unit": experiment.UNITS[k], "track": experiment.TRACKED[k]}
312
+ for k in experiment.TRACKED],
313
+ "defaults": experiment.STEP_DEFAULTS, "limits": {key: list(v) for (kind, key), v in LIMITS.items() if kind == "step"},
314
+ "longrun_modes": list(LONGRUN_MODES)}
315
+ # 型号(连接后为设备的型号,未连接或产品码未知时为全集字典,即 None)。
316
+ model = od.model["name"] if od.model else None
317
+ return {"device": device, "model": model, "objects": objects, "errors": od.errors,
318
+ "layout": layout_groups(od), "commands": list(COMMAND_OBJECTS), "manual_modes": modes, "step": step,
319
+ "brt27": brt27_defaults(od), "poll_pages": page_objects(od)}
320
+
321
+
322
+ ## @brief 装配标定的计算(ehatool.calibration 的纯函数),参数按名称从页面送来。
323
+ def compute_calibration(calibration, name, body):
324
+ number = lambda key: float(body[key]) # noqa: E731
325
+ if name == "position":
326
+ cal = calibration.position_two_point(number("x1_um"), int(body["c1"]), number("x2_um"), int(body["c2"]))
327
+ if body.get("c3") is not None:
328
+ cal["check_error_um"] = calibration.position_check(cal, int(body["c3"]), number("x3_um"))
329
+ return cal
330
+ if name == "reference":
331
+ return {"reference_count": calibration.reference_for(int(body["count"]), number("x_um"), number("um_per_count"),
332
+ bool(body.get("reversed")))}
333
+ if name == "position_check":
334
+ cal = {"um_per_count": number("um_per_count"), "reference_count": number("reference_count"),
335
+ "reversed": number("reversed")}
336
+ count, x_um = number("count"), number("x_um")
337
+ if not all(math.isfinite(v) for v in (*cal.values(), count, x_um)):
338
+ raise ValueError("输入须为有限的数")
339
+ if cal["um_per_count"] <= 0 or cal["reversed"] not in (0, 1) or not cal["reference_count"].is_integer() or not count.is_integer():
340
+ raise ValueError("每计数位移须为正,方向须为 0 或 1,计数与零点须为整数")
341
+ return {"check_error_um": calibration.position_check(cal, int(count), x_um)}
342
+ if name == "pressure":
343
+ return calibration.pressure_two_point(int(body["raw1"]), number("mpa1"), int(body["raw2"]), number("mpa2"))
344
+ if name == "direction":
345
+ return calibration.direction_check(number("rpm"), str(body["observed"]), int(body["motor_reversed"]),
346
+ number("position_delta_um"), number("position_error_um"),
347
+ number("pressure_a_delta"), number("pressure_b_delta"),
348
+ number("pressure_a_error"), number("pressure_b_error"),
349
+ int(body["positive_channel"]))
350
+ raise ValueError(f"未知计算 {name}")
351
+
352
+
353
+ ## @brief 总线视图与成组写入用的适配器:已有 CAN 会话时拒绝(同一个适配器不能被两处打开,另一个适配器上的总线
354
+ ## 也不在这里同时处理)。
355
+ @contextlib.contextmanager
356
+ def _bus_link(app, body):
357
+ from ..device.can import CanLink
358
+ adapter = body.get("adapter")
359
+ with app.transport_operation("can", adapter):
360
+ if app.session is not None and app.session.via == "can":
361
+ raise Busy("已有 CAN 设备会话:先断开")
362
+ if app.session is not None and app.session.running_job():
363
+ raise Busy("设备会话中有任务在运行:成组访问总线可能改到被测设备,先停止")
364
+ interface, _, channel = str(adapter or "").partition(":")
365
+ if not channel:
366
+ raise ValueError("CAN 适配器写成 接口:通道,例如 slcan:/dev/cu.usbmodem<序号>")
367
+ link = CanLink(interface, channel, int(body["bitrate"]), int(body.get("data_bitrate") or 0), 1)
368
+ with contextlib.closing(link):
369
+ yield link
370
+
371
+
372
+ ## @brief 总线视图(canbus.listen):不发任何帧。适配器以正常模式打开,照常应答 ACK 位:只侦听模式不应答,总线上只有
373
+ ## 设备与本适配器时设备的帧得不到 ACK,会一直重发、进入错误被动,什么也收不到(实板上 0x2049 的发送错误计数到 132)。
374
+ def bus_listen(app, body):
375
+ from .canbus import listen
376
+ seconds = float(body.get("seconds", 1.0))
377
+ if not 0.2 <= seconds <= 10:
378
+ raise ValueError("侦听时间须在 0.2–10 s")
379
+ with _bus_link(app, body) as link:
380
+ nodes = listen(link.bus, app.od, seconds)
381
+ from ..cia402 import state_name
382
+ # 节点自己报告的 CiA402 状态(TPDO 中的 statusword),供成组写入前提示哪些节点正在运行。
383
+ return clean({"nodes": [{"node": n, **v, "state": state_name(v["values"]["statusword"]) if "statusword" in v["values"] else None}
384
+ for n, v in sorted(nodes.items())], "now": time.time()})
385
+
386
+
387
+ ## @brief 成组写参数(canbus.group_write):values 为 {对象名: 文字},按通用写入的规则检查并按类型解析,按对象字典顺序写入。
388
+ def bus_write(app, body):
389
+ from .canbus import group_write
390
+ from .job_params import parse_value, write_refusal
391
+ nodes = body.get("nodes")
392
+ if not isinstance(nodes, list) or not nodes or not all(isinstance(n, int) and 1 <= n <= 127 for n in nodes):
393
+ raise ValueError("节点须为 1–127 的列表")
394
+ values = body.get("values")
395
+ if not isinstance(values, dict) or not values:
396
+ raise ValueError("没有要写入的对象")
397
+ writes = []
398
+ from ..od import pack
399
+ for name, text in values.items():
400
+ obj = app.od.lookup(str(name))
401
+ refusal = write_refusal(obj)
402
+ if refusal:
403
+ raise ValueError(refusal)
404
+ value = parse_value(obj, text)
405
+ try:
406
+ pack(obj, value) # 超出类型范围的整数在写入前拒绝;对象字典的范围由设备检查
407
+ except Exception:
408
+ raise ValueError(f"{obj['name']} = {text} 超出 {obj['type']} 的范围") from None
409
+ writes.append((obj, value))
410
+ order = {o["name"]: i for i, o in enumerate(app.od.objects)}
411
+ writes.sort(key=lambda w: order[w[0]["name"]])
412
+ with _bus_link(app, body) as link:
413
+ results = group_write(link, app.od, sorted(set(nodes)), writes, bool(body.get("save")))
414
+ return clean({"results": [{"node": n, "rows": rows} for n, rows in results.items()]})
415
+
416
+
417
+ ## @brief BRT27 设置的缺省值:节点、周期与计数取设备描述的 [settings](ehatool.brt27),速率取对象字典 0x2007
418
+ ## 的出厂值(与所接传感器一致)。计数引用对象字典时取该对象的出厂值。
419
+ def brt27_defaults(od):
420
+ from .. import brt27
421
+ values = brt27.defaults()
422
+ if values["count"] is None:
423
+ # 对象字典里没有写 default 的对象按类型零值。
424
+ values["count"] = od.lookup("position_reference_count").get("default", 0)
425
+ return {**values, "bitrate": od.lookup("sensor_can_bitrate").get("default")}
426
+
427
+
428
+ ## @brief BRT27 设置(ehatool.brt27):经接在内部传感器 CAN(J8)上的 PC 适配器;不经设备会话。
429
+ ## od 用来取缺省值(设备描述引用对象字典的项)。
430
+ def setup_brt27(od, body):
431
+ from .. import brt27
432
+ from ..device.can import CanLink
433
+ interface, _, channel = str(body.get("adapter", "")).partition(":")
434
+ if not channel:
435
+ raise ValueError("CAN 适配器写成 接口:通道,例如 slcan:/dev/cu.usbmodem<序号>")
436
+ d = brt27_defaults(od)
437
+ pick = lambda key: int(d[key] if body.get(key) in (None, "") else body[key]) # noqa: E731
438
+ node, count, period = pick("node"), pick("count"), pick("period_us")
439
+ brt27.setup_frames(node, count, period)
440
+ link = CanLink(interface, channel, int(body["bitrate"]), 0, 1)
441
+ log = []
442
+ try:
443
+ result = brt27.setup(link.bus, link.can.Message, node, count, period, report=log.append)
444
+ finally:
445
+ link.close()
446
+ return {"ok": True, "log": log, **result}
447
+
448
+
449
+ ## @brief 产线配方:recipes/ 下的 TOML,每个文件一种产品。配方写明执行哪些步骤、引用的参数文件与验收判据;不存数值。
450
+ def load_recipes():
451
+ import tomllib
452
+ out = []
453
+ for path in sorted(pathlib.Path(__file__).with_name("recipes").glob("*.toml")):
454
+ try:
455
+ with open(path, "rb") as f:
456
+ recipe = tomllib.load(f)
457
+ # 引用的参数文件(recipes/params/ 下,只取文件名)随配方送给页面,由页面生成草稿,写入仍由操作员确认。
458
+ name = str(recipe.get("params") or "")
459
+ if name:
460
+ recipe["params_text"] = (path.parent / "params" / pathlib.Path(name).name).read_text()
461
+ out.append({"id": path.stem, **recipe})
462
+ except (OSError, ValueError) as error:
463
+ out.append({"id": path.stem, "error": str(error)})
464
+ return out
465
+
466
+
467
+ def create_app(app):
468
+ from fastapi import Body, FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
469
+ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, StreamingResponse
470
+ from fastapi.exceptions import RequestValidationError
471
+ from pydantic import ValidationError
472
+ from . import requests as schema
473
+
474
+ @contextlib.asynccontextmanager
475
+ async def lifespan(_):
476
+ app.loop = asyncio.get_running_loop()
477
+ try:
478
+ yield
479
+ finally:
480
+ await asyncio.to_thread(app.shutdown)
481
+
482
+ api = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
483
+
484
+ @api.exception_handler(RequestValidationError)
485
+ async def invalid_request(_, error):
486
+ fields = ", ".join(".".join(str(part) for part in item["loc"]) for item in error.errors())
487
+ return JSONResponse({"detail": f"请求参数无效:{fields}"}, status_code=400,
488
+ headers={"Cache-Control": "no-store"})
489
+
490
+ @api.middleware("http")
491
+ async def guard(request: Request, call_next):
492
+ if request.headers.get("host") not in app.allowed_hosts():
493
+ return JSONResponse({"error": "Host 不被接受"}, status_code=403)
494
+ origin = request.headers.get("origin")
495
+ if origin is not None and origin not in {f"http://{host}" for host in app.allowed_hosts()}:
496
+ return JSONResponse({"error": "Origin 不被接受"}, status_code=403)
497
+ if request.url.path.startswith("/api/") and request.headers.get("x-eha-token") != app.token:
498
+ return JSONResponse({"error": "令牌无效"}, status_code=403)
499
+ response = await call_next(request)
500
+ # 接口的响应都是设备当时的状态,不可缓存:浏览器会按启发式缓存 410 等响应,之后同一地址的读取不再到达服务。
501
+ if request.url.path.startswith("/api/"):
502
+ response.headers["Cache-Control"] = "no-store"
503
+ return response
504
+
505
+ def session():
506
+ if app.session is None:
507
+ raise HTTPException(409, "没有连接设备")
508
+ return app.session
509
+
510
+ ## @brief 请求到达时绑定会话,有 opened_at 的操作在设备线程实际执行前核对连接。
511
+ async def run(fn, *, live, opened_at=None, operation="操作"):
512
+ s = session()
513
+
514
+ def execute():
515
+ if opened_at is not None and opened_at != s.opened_at:
516
+ raise Busy(f"设备会话已切换,本次{operation}未执行")
517
+ return fn(s)
518
+
519
+ with device_errors():
520
+ return await asyncio.wait_for(asyncio.wrap_future(s.call(execute, live=live)), 30)
521
+
522
+ @contextlib.contextmanager
523
+ def device_errors():
524
+ try:
525
+ yield
526
+ except HTTPException:
527
+ raise
528
+ except (Busy, ControlRefused) as error:
529
+ raise HTTPException(409, str(error)) from None
530
+ except LinkLost as error:
531
+ raise HTTPException(410, str(error)) from None
532
+ except KeyError as error:
533
+ raise HTTPException(400, f"没有对象 {error.args[0]}") from None
534
+ except ValueError as error:
535
+ raise HTTPException(400, str(error)) from None
536
+ except SdoAbort as error:
537
+ d = error.diagnostic
538
+ raise HTTPException(422, f"设备拒绝:{d.get('description_zh', '')}。{d.get('meaning_zh', '')}") from None
539
+ except TimeoutError as error:
540
+ raise HTTPException(504, f"设备无应答,结果未知:{error}") from None
541
+ except Exception as error:
542
+ raise HTTPException(500, f"{type(error).__name__}:{error}") from None
543
+
544
+ @api.get("/")
545
+ async def index():
546
+ html = (STATIC / "index.html").read_text(encoding="utf-8")
547
+ return HTMLResponse(html.replace("__EHA_TOKEN__", app.token), headers={"Cache-Control": "no-store"})
548
+
549
+ @api.get("/assets/{name}")
550
+ async def asset(name: str):
551
+ path = STATIC / "assets" / name
552
+ if pathlib.Path(name).name != name or "\\" in name or name.startswith(".") or not path.is_file():
553
+ raise HTTPException(404)
554
+ return FileResponse(path)
555
+
556
+ ## @brief 页面字典:已连接时为该设备型号可见的对象,否则为全集。页面在会话切换(opened_at 变化)时重新获取。
557
+ @api.get("/api/od")
558
+ async def get_od():
559
+ return od_payload(app.session.od if app.session is not None else app.od)
560
+
561
+ ## @brief 三路设备的被动枚举(不探测、不识别,与 ehatool devices 缺省相同)。
562
+ @api.get("/api/devices")
563
+ async def devices():
564
+ import argparse
565
+ from ..discovery import scan_devices
566
+ args = argparse.Namespace(via=None, port=None, can=None, node=None, bitrate=None, data_bitrate=None, ifname=None,
567
+ identify=False, probe=False, serial=None)
568
+ result = await asyncio.to_thread(scan_devices, args)
569
+ return clean({**result, "connected": app.session.identity if app.session else None})
570
+
571
+ ## @brief 显式探测或识别选中资源;复用 CLI 发现流程,完成后关闭临时句柄。
572
+ @api.post("/api/devices/{action}")
573
+ async def discover(action: str, body: schema.DiscoveryRequest = Body(...)):
574
+ body = body.payload()
575
+ import argparse
576
+ from ..discovery import scan_devices
577
+
578
+ def perform():
579
+ def integer(key, default=None):
580
+ value = body.get(key, default)
581
+ if isinstance(value, bool) or not isinstance(value, (int, str)):
582
+ raise ValueError(f"{key} 须为整数")
583
+ return int(value)
584
+
585
+ via = body.get("via")
586
+ if action not in ("probe", "identify") or via not in ("usb", "can", "ecat") or via == "usb" and action == "probe":
587
+ raise ValueError("选择 USB 识别、CAN 探测或识别、EtherCAT 探测或识别")
588
+ field = {"usb": "port", "can": "adapter", "ecat": "ifname"}[via]
589
+ resource = body.get(field)
590
+ if not isinstance(resource, str) or not resource.strip():
591
+ raise ValueError(f"先填写 {field}")
592
+ resource = resource.strip()
593
+ node = None
594
+ bitrate = data_bitrate = None
595
+ if via == "can":
596
+ if ":" not in resource or not all(resource.split(":", 1)):
597
+ raise ValueError("CAN 适配器须为 接口:通道")
598
+ bitrate, data_bitrate = integer("bitrate"), integer("data_bitrate", 0)
599
+ if bitrate <= 0 or data_bitrate < 0 or 0 < data_bitrate < bitrate:
600
+ raise ValueError("CAN 仲裁速率须大于 0,数据速率为 0 或不低于仲裁速率")
601
+ if action == "identify":
602
+ node = integer("node")
603
+ if not 1 <= node <= 127:
604
+ raise ValueError("CAN 节点号须为 1–127")
605
+ args = argparse.Namespace(via=via, port=resource if via == "usb" else None,
606
+ can=resource if via == "can" else None, node=node, bitrate=bitrate,
607
+ data_bitrate=data_bitrate, ifname=resource if via == "ecat" else None,
608
+ identify=action == "identify" or via == "can", probe=action == "probe" and via == "ecat", serial=None)
609
+ with app.transport_operation(via, resource):
610
+ if app.session is not None and app.session.running_job():
611
+ raise Busy("设备任务运行中,先停止或等待任务结束再探测")
612
+ return clean(scan_devices(args))
613
+
614
+ with device_errors():
615
+ return await asyncio.to_thread(perform)
616
+
617
+ @api.post("/api/session")
618
+ async def connect(body: schema.SessionRequest = Body(...)):
619
+ body = body.payload()
620
+ try:
621
+ return await asyncio.to_thread(app.open, body)
622
+ except Busy as error:
623
+ raise HTTPException(409, str(error)) from None
624
+ except (KeyError, ValueError) as error:
625
+ raise HTTPException(400, str(error)) from None
626
+ except (OSError, RuntimeError, TimeoutError, SdoAbort) as error:
627
+ raise HTTPException(502, f"连接失败:{error}") from None
628
+
629
+ @api.get("/api/workspaces")
630
+ async def workspaces():
631
+ entries = await asyncio.to_thread(app.workspaces.list)
632
+ return [{**entry, "can_close": entry["can_close"] and entry["url"] != f"http://127.0.0.1:{app.port}/"} for entry in entries]
633
+
634
+ @api.delete("/api/workspaces/{port}")
635
+ async def close_workspace(port: int):
636
+ with device_errors():
637
+ if port == app.port:
638
+ raise Busy("请从其他工作台关闭本页面")
639
+ return await asyncio.to_thread(app.workspaces.close, port)
640
+
641
+ @api.post("/api/workspaces")
642
+ async def open_workspace(body: schema.WorkspaceRequest = Body(...)):
643
+ with device_errors():
644
+ return await asyncio.to_thread(app.workspaces.open, body.connection.payload(), body.page)
645
+
646
+ @api.delete("/api/session")
647
+ async def disconnect(body: schema.SessionCloseRequest = Body(default_factory=schema.SessionCloseRequest)):
648
+ try:
649
+ await asyncio.to_thread(app.close, body.opened_at)
650
+ except Busy as error:
651
+ raise HTTPException(409, str(error)) from None
652
+ return {"ok": True}
653
+
654
+ @api.get("/api/session")
655
+ async def get_session():
656
+ return session().snapshot()
657
+
658
+ def request_client(request):
659
+ value = request.headers.get("x-eha-client", "")
660
+ return int(value) if value.isdigit() and int(value) in app.clients else None
661
+
662
+ @api.get("/api/objects/{name}")
663
+ async def read_object(name: str):
664
+ def read(s):
665
+ key = s.od.lookup(name)["name"]
666
+ value = s.read(key)
667
+ return {"name": key, "value": value, "read_at": s.read_at[key], "source": s.source[key]}
668
+ return clean(await run(read, live=True))
669
+
670
+ @api.put("/api/objects/{name}")
671
+ async def write_object(name: str, request: Request, body: schema.WriteRequest = Body(...)):
672
+ return clean(await run(lambda s: s.write(name, body.value, request_client(request)),
673
+ live=True, opened_at=body.opened_at, operation="写入"))
674
+
675
+ @api.post("/api/actions/{name}")
676
+ async def action(name: str, request: Request, body: schema.ActionRequest = Body(default_factory=schema.ActionRequest)):
677
+ params = body.payload()
678
+ return clean(await run(lambda s: s.action(name, params, request_client(request)),
679
+ live=name == "save", opened_at=body.opened_at, operation="动作"))
680
+
681
+ @api.post("/api/stop")
682
+ async def stop(body: schema.StopRequest = Body(default_factory=schema.StopRequest)):
683
+ body = body.payload()
684
+ s = session()
685
+ with device_errors():
686
+ return clean(await asyncio.to_thread(s.stop, expected=body or None))
687
+
688
+ @api.post("/api/scope")
689
+ async def scope(body: schema.ScopeRequest = Body(...)):
690
+ return await run(lambda s: s.scope_configure(body.objects, body.divider),
691
+ live=True, opened_at=body.opened_at, operation="示波配置")
692
+
693
+ @api.post("/api/scope/save")
694
+ async def scope_save(body: schema.ScopeSaveRequest = Body(default_factory=schema.ScopeSaveRequest)):
695
+ body = body.payload()
696
+ try:
697
+ if isinstance(body.get("seconds"), bool):
698
+ raise ValueError()
699
+ seconds = float(body.get("seconds", 30))
700
+ except (TypeError, ValueError, OverflowError):
701
+ raise HTTPException(400, "保存时长须为 0–60 s 之间的有限数") from None
702
+ current = session()
703
+ if body.get("opened_at") is not None and body["opened_at"] != current.opened_at:
704
+ raise HTTPException(409, "设备会话已切换,本次示波保存未执行")
705
+
706
+ def save():
707
+ recent = current.scope_recent(seconds, body.get("source"))
708
+ snapshot = cached_parameters(current.od, current.state.copy(), current.read_at.copy(), current.source.copy())
709
+ return app.records.save_scope(recent, current.identity, snapshot)
710
+
711
+ with device_errors():
712
+ return {"record": await asyncio.to_thread(save)}
713
+
714
+ @api.post("/api/jobs")
715
+ async def start_job(request: Request, body: schema.JobRequest = Body(...)):
716
+ body = body.payload()
717
+ origin = request_client(request)
718
+ if origin is None:
719
+ raise HTTPException(400, "发起任务的页面必须保持 WebSocket 连接")
720
+ with device_errors():
721
+ s = session()
722
+ if "opened_at" in body and body["opened_at"] != s.opened_at:
723
+ raise Busy("设备会话已切换,请在当前设备上重新确认任务")
724
+ job = s.start_job(str(body.get("kind")), dict(body.get("params", {})), origin)
725
+ return {"id": job["id"]}
726
+
727
+ def session_port():
728
+ s = app.session
729
+ return s.identity.get("port") if s is not None and s.identity is not None else None
730
+
731
+ @api.get("/api/console")
732
+ async def console_list():
733
+ return {"ports": console_ports(session_port()), "open": app.console.port}
734
+
735
+ @api.post("/api/console")
736
+ async def console(body: schema.ConsoleRequest = Body(...)):
737
+ body = body.payload()
738
+ try:
739
+ if body.get("port"):
740
+ return await asyncio.to_thread(app.start_resource, app.console.start, body["port"], session_port())
741
+ return await asyncio.to_thread(app.console.stop)
742
+ except Busy as error:
743
+ raise HTTPException(409, str(error)) from None
744
+ except (OSError, ValueError) as error:
745
+ raise HTTPException(400, str(error)) from None
746
+
747
+ ## @brief 升级前的预览:发布目录或构建目录中各镜像的镜像头(版本、链接地址、长度、CRC 是否正确)与将写入的槽。
748
+ @api.post("/api/firmware/preview")
749
+ async def firmware_preview(body: schema.PreviewRequest = Body(...)):
750
+ body = body.payload()
751
+ from .. import image, update
752
+ try:
753
+ source = user_path(body.get("build"))
754
+ except ValueError as error:
755
+ raise HTTPException(400, str(error)) from None
756
+ # 发布目录按设备型号选镜像;未连接设备时要求清单里只有一个型号。
757
+ identity = getattr(app.session, "identity", None) if app.session else None
758
+ product_code = identity["product_code"] if identity else None
759
+ try:
760
+ files = update.images(source, product_code)
761
+ except ValueError as error:
762
+ raise HTTPException(400, str(error)) from None
763
+ images = {}
764
+ for name, path in files.items():
765
+ try:
766
+ images[name] = image.describe(path.read_bytes())
767
+ except (OSError, ValueError) as error:
768
+ images[name] = f"不可用:{error}"
769
+ slot = app.session.state.get("firmware_slot") if app.session else None
770
+ return {"images": images, "target": {0: "B", 1: "A"}.get(slot), "ram": slot == 255}
771
+
772
+ @api.post("/api/ram-load")
773
+ async def ram_load(body: schema.RamLoadRequest = Body(...)):
774
+ body = body.payload()
775
+ from .. import ram_load as loader
776
+ s = app.session
777
+ if s is not None and (s.running_job() or s.state.get("running")):
778
+ raise HTTPException(409, "设备正在运行(或本服务有任务):RAM 加载会复位并暂停芯片,先停止")
779
+ try:
780
+ image = user_path(body.get("image"))
781
+ except ValueError as error:
782
+ raise HTTPException(400, str(error)) from None
783
+ lines = []
784
+ try:
785
+ await asyncio.to_thread(loader.load, image, int(body.get("openocd_port", 4444)), lines.append)
786
+ except (RuntimeError, OSError) as error:
787
+ return {"ok": False, "log": lines + [str(error)]}
788
+ if s is not None:
789
+ s.reset_requested, s.reset_outcome = False, "unknown"
790
+ return {"ok": True, "log": lines}
791
+
792
+ @api.get("/api/records")
793
+ async def records():
794
+ return await asyncio.to_thread(app.records.list)
795
+
796
+ @api.post("/api/records/compare")
797
+ async def records_compare(body: schema.CompareRequest = Body(...)):
798
+ body = body.payload()
799
+ items = body["items"]
800
+ if not 1 <= len(items) <= 6:
801
+ raise HTTPException(400, "选 1–6 条阶跃记录")
802
+ band = body.get("band")
803
+ try:
804
+ band = None if band in (None, "") else float(band)
805
+ if band is not None and not band > 0:
806
+ raise ValueError("带宽须为正数")
807
+ return await asyncio.to_thread(app.records.compare, items, band)
808
+ except FileNotFoundError:
809
+ raise HTTPException(404, "没有这条记录") from None
810
+ except ValueError as error:
811
+ raise HTTPException(400, f"记录无法对比:{error}") from None
812
+
813
+ @api.post("/api/records/import")
814
+ async def records_import(body: schema.ImportRequest = Body(...)):
815
+ try:
816
+ return {"record": await asyncio.to_thread(app.records.import_csv, body.name, body.text)}
817
+ except (ValueError, KeyError) as error:
818
+ raise HTTPException(400, f"无法导入:{error}") from None
819
+
820
+ @api.post("/api/calibration/{name}")
821
+ async def calibration_compute(name: str, body: schema.CalibrationRequest = Body(...)):
822
+ body = body.payload()
823
+ from .. import calibration
824
+ try:
825
+ return compute_calibration(calibration, name, body)
826
+ except (TypeError, ValueError, KeyError, ZeroDivisionError) as error:
827
+ raise HTTPException(400, f"无法计算:{error}") from None
828
+
829
+ @api.post("/api/brt27/setup")
830
+ async def brt27_setup(body: schema.BrtSetupRequest = Body(...)):
831
+ body = body.payload()
832
+ try:
833
+ def setup():
834
+ with app.transport_operation("can", body.get("adapter")):
835
+ return setup_brt27(app.od, body)
836
+ return await asyncio.to_thread(setup)
837
+ except Busy as error:
838
+ raise HTTPException(409, str(error)) from None
839
+ except (ValueError, KeyError) as error:
840
+ raise HTTPException(400, str(error)) from None
841
+ except ImportError as error:
842
+ raise HTTPException(400, f"没有安装 python-can:{error}") from None
843
+ except (RuntimeError, OSError) as error:
844
+ return {"ok": False, "log": [str(error)]}
845
+
846
+ @api.get("/api/brt27/sim")
847
+ async def brt27_sim_info():
848
+ return {"job": app.brt_sim.info()}
849
+
850
+ @api.post("/api/brt27/sim")
851
+ async def brt27_sim_start(body: schema.BrtSimRequest = Body(...)):
852
+ body = body.payload()
853
+ try:
854
+ return {"job": await asyncio.to_thread(app.start_resource, app.brt_sim.start, body)}
855
+ except Busy as error:
856
+ raise HTTPException(409, str(error)) from None
857
+ except (TypeError, ValueError, KeyError, OverflowError) as error:
858
+ raise HTTPException(400, str(error)) from None
859
+ except OSError as error:
860
+ raise HTTPException(502, f"无法启动 BRT27 模拟器:{error}") from None
861
+
862
+ @api.delete("/api/brt27/sim")
863
+ async def brt27_sim_stop(body: schema.TaskStopRequest = Body(default_factory=schema.TaskStopRequest)):
864
+ try:
865
+ return {"job": await asyncio.to_thread(app.brt_sim.stop, expected=body.payload() or None)}
866
+ except Busy as error:
867
+ raise HTTPException(409, str(error)) from None
868
+
869
+ @api.get("/api/records/space")
870
+ async def records_space():
871
+ from .longrun import free_bytes
872
+ app.records.root.mkdir(parents=True, exist_ok=True)
873
+ return {"free_bytes": free_bytes(app.records.root)}
874
+
875
+ @api.get("/api/recipes")
876
+ async def recipes():
877
+ return await asyncio.to_thread(load_recipes)
878
+
879
+ @api.post("/api/archive")
880
+ async def archive(body: schema.ArchiveRequest = Body(...)):
881
+ body = body.payload()
882
+ try:
883
+ return {"record": await asyncio.to_thread(app.records.save_archive, body)}
884
+ except (TypeError, ValueError, KeyError, AttributeError) as error:
885
+ raise HTTPException(400, f"无法存档:{error}") from None
886
+
887
+ async def run_bus(operation, body):
888
+ try:
889
+ return await asyncio.to_thread(operation, app, body)
890
+ except (ValueError, KeyError, TypeError) as error:
891
+ raise HTTPException(400, str(error)) from None
892
+ except Busy as error:
893
+ raise HTTPException(409, str(error)) from None
894
+ except (OSError, RuntimeError) as error:
895
+ raise HTTPException(502, f"打开适配器失败:{error}") from None
896
+
897
+ @api.post("/api/canbus/listen")
898
+ async def canbus_listen(body: schema.CanListenRequest = Body(...)):
899
+ return await run_bus(bus_listen, body.payload())
900
+
901
+ @api.post("/api/canbus/write")
902
+ async def canbus_write(body: schema.CanWriteRequest = Body(...)):
903
+ return await run_bus(bus_write, body.payload())
904
+
905
+ @api.post("/api/sil")
906
+ async def sil_start(body: schema.SilRequest = Body(...)):
907
+ body = body.payload()
908
+ try:
909
+ return {"id": (await asyncio.to_thread(app.start_resource, app.sil.start, body))["id"]}
910
+ except RuntimeError as error:
911
+ raise HTTPException(409, str(error)) from None
912
+ except (ValueError, KeyError) as error:
913
+ raise HTTPException(400, str(error)) from None
914
+
915
+ @api.post("/api/sil/stop")
916
+ async def sil_stop(body: schema.TaskStopRequest = Body(default_factory=schema.TaskStopRequest)):
917
+ try:
918
+ app.sil.stop(expected=body.payload() or None)
919
+ except RuntimeError as error:
920
+ raise HTTPException(409, str(error)) from None
921
+ return {"ok": True}
922
+
923
+ @api.get("/api/records/{record_id}/events")
924
+ async def record_events(record_id: str):
925
+ def read_events():
926
+ with app.records.file(record_id, "events.csv").open(newline="") as source:
927
+ return list(collections.deque(csv.DictReader(source), maxlen=500))
928
+ try:
929
+ return await asyncio.to_thread(read_events)
930
+ except FileNotFoundError:
931
+ raise HTTPException(404, "这条记录没有持久化事件日志") from None
932
+
933
+ class RecordDownload(StreamingResponse):
934
+ """从同一文件句柄发送请求开始时的长度,追加写入和元数据替换不会改变本次下载。"""
935
+ def __init__(self, source, size, media, filename):
936
+ self.source = source
937
+
938
+ def chunks():
939
+ remaining = size
940
+ while remaining:
941
+ chunk = source.read(min(64 * 1024, remaining))
942
+ if not chunk:
943
+ break
944
+ remaining -= len(chunk)
945
+ yield chunk
946
+
947
+ encoded = quote(filename, safe="")
948
+ disposition = f'filename="{filename}"' if encoded == filename else f"filename*=UTF-8''{encoded}"
949
+ super().__init__(chunks(), media_type=media, headers={"Content-Length": str(size),
950
+ "Content-Disposition": f"attachment; {disposition}"})
951
+
952
+ async def __call__(self, scope, receive, send):
953
+ try:
954
+ await super().__call__(scope, receive, send)
955
+ finally:
956
+ # 中途断开时流迭代器也可能尚未开始,文件句柄在响应生命周期结束时统一关闭。
957
+ await asyncio.to_thread(self.source.close)
958
+
959
+ @api.get("/api/records/{record_id}/{name}")
960
+ async def record_file(record_id: str, name: str):
961
+ def open_record():
962
+ source = app.records.file(record_id, name).open("rb")
963
+ try:
964
+ return source, os.fstat(source.fileno()).st_size
965
+ except OSError:
966
+ source.close()
967
+ raise
968
+
969
+ try:
970
+ source, size = await asyncio.to_thread(open_record)
971
+ except FileNotFoundError:
972
+ raise HTTPException(404) from None
973
+ media = {"csv": "text/csv", "json": "application/json", "toml": "application/toml",
974
+ "html": "text/html; charset=utf-8"}[name.rsplit(".", 1)[1]]
975
+ return RecordDownload(source, size, media, f"{record_id}-{name}")
976
+
977
+ @api.websocket("/api/live")
978
+ async def live(ws: WebSocket):
979
+ origin = ws.headers.get("origin", "")
980
+ host = ws.headers.get("host")
981
+ if (ws.query_params.get("token") != app.token or host not in app.allowed_hosts()
982
+ or origin not in {f"http://{h}" for h in app.allowed_hosts()}):
983
+ await ws.close(code=4403)
984
+ return
985
+ await ws.accept()
986
+ client = next(app.ids)
987
+ q = asyncio.Queue()
988
+ app.clients[client] = q
989
+ try:
990
+ current = app.session
991
+ history = await asyncio.to_thread(current.sample_history) if current else []
992
+ await ws.send_json(clean({"type": "hello", "client": client, "tool_version": TOOL_VERSION, "sil_job": app.sil.info(),
993
+ "session": current.snapshot() if current else None,
994
+ "history": history}))
995
+ except Exception:
996
+ app.clients.pop(client, None)
997
+ app.dropped.pop(client, None)
998
+ app.drop_totals.pop(client, None)
999
+ return
1000
+
1001
+ async def sender():
1002
+ notified = 0
1003
+ while True:
1004
+ event = await q.get()
1005
+ total = app.drop_totals.get(client, 0)
1006
+ if total > notified:
1007
+ await ws.send_json({"type": "display_loss", "count": total - notified})
1008
+ notified = total
1009
+ await ws.send_json(event)
1010
+
1011
+ task = asyncio.create_task(sender())
1012
+ try:
1013
+ while True:
1014
+ message = await ws.receive_json()
1015
+ if not isinstance(message, dict):
1016
+ continue
1017
+ if message.get("type") == "subscribe":
1018
+ try:
1019
+ subscription = schema.SubscribeMessage.model_validate(message)
1020
+ app.set_poll_subscription(client, subscription.objects)
1021
+ q.put_nowait({"type": "subscribed", "objects": list(app.poll_subscriptions[client])})
1022
+ except ValueError as error:
1023
+ q.put_nowait({"type": "subscription_error", "message": str(error)})
1024
+ continue
1025
+ s = app.session
1026
+ if s is None:
1027
+ continue
1028
+ if message.get("type") == "target":
1029
+ try:
1030
+ target = schema.TargetMessage.model_validate(message)
1031
+ s.set_target(client, target.values, target.jog, target.opened_at, target.job_id)
1032
+ except (TypeError, ValueError, ValidationError):
1033
+ pass
1034
+ elif message.get("type") == "visibility":
1035
+ try:
1036
+ if schema.VisibilityMessage.model_validate(message).hidden:
1037
+ s.origin_hidden(client)
1038
+ except ValidationError:
1039
+ pass
1040
+ except (WebSocketDisconnect, ValueError):
1041
+ pass
1042
+ finally:
1043
+ task.cancel()
1044
+ app.clients.pop(client, None)
1045
+ app.remove_poll_subscription(client)
1046
+ app.dropped.pop(client, None)
1047
+ app.drop_totals.pop(client, None)
1048
+ if app.session is not None:
1049
+ app.session.origin_left(client)
1050
+
1051
+ return api