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/longrun.py ADDED
@@ -0,0 +1,430 @@
1
+ # Copyright The eha-firmware Contributors
2
+
3
+ ## @file
4
+ ## @brief 长时运行与只记录(docs/工作台页面合同.md)中不依赖设备会话的部分:按大小分卷的记录写入、故障前后数据的
5
+ ## 环形缓冲、每个循环的摘要、收尾条件的判断与系统防休眠断言。危害清单“无人值守长时运行”一行的机制在这里与
6
+ ## session._job_longrun 中实现。
7
+
8
+ import collections
9
+ import contextlib
10
+ import dataclasses
11
+ import csv
12
+ import json
13
+ import os
14
+ import shutil
15
+ import select
16
+ import subprocess
17
+ import sys
18
+ import time
19
+ import threading
20
+
21
+ from .. import experiment
22
+ from .records import clean
23
+
24
+ ## @brief 每卷记录的上限(字节),超过即开新卷。
25
+ VOLUME_BYTES = 20 * 1024 * 1024
26
+ ## @brief 故障前后各保留的数据时长(s)。
27
+ AROUND_S = 30.0
28
+ ## @brief 记录目录所在磁盘可用空间低于此值即收尾(字节)。
29
+ MIN_FREE_BYTES = 1024 ** 3
30
+ ## @brief 冲刷到磁盘(fsync)的间隔(s)。
31
+ FSYNC_S = 30.0
32
+
33
+
34
+ ## @brief 按大小分卷的 CSV:samples-0001.csv、samples-0002.csv……每卷有表头。写入出错(磁盘满、I/O 错误、外置盘拔出)
35
+ ## 原样抛出,由调用方按收尾处理。
36
+ class Volumes:
37
+ def __init__(self, directory, stem, fields, limit=VOLUME_BYTES):
38
+ self.directory, self.stem, self.fields, self.limit = directory, stem, list(fields), limit
39
+ self.index, self.file, self.writer, self.rows = 0, None, None, 0
40
+
41
+ def _open(self):
42
+ self.close()
43
+ file = open(self.directory / f"{self.stem}-{self.index + 1:04d}.csv", "w", newline="")
44
+ self.index, self.file = self.index + 1, file
45
+ self.writer = csv.DictWriter(self.file, self.fields, extrasaction="ignore")
46
+ self.writer.writeheader()
47
+
48
+ def write(self, row):
49
+ if self.file is None or self.file.tell() >= self.limit:
50
+ self._open()
51
+ self.writer.writerow(row)
52
+ self.rows += 1
53
+
54
+ def flush(self):
55
+ if self.file is not None:
56
+ self.file.flush()
57
+ os.fsync(self.file.fileno())
58
+
59
+ ## @brief 关闭当前卷。磁盘写满时关闭也会因冲刷缓冲而失败:已经在收尾,不再抛出(原因已由写入时的错误给出)。
60
+ def close(self):
61
+ file, self.file = self.file, None
62
+ if file is not None:
63
+ try:
64
+ file.close()
65
+ except OSError:
66
+ pass
67
+
68
+ def names(self):
69
+ return [f"{self.stem}-{n:04d}.csv" for n in range(1, self.index + 1)]
70
+
71
+
72
+
73
+ ## @brief 最近 seconds 秒的样本(按样本里的 t_s);故障时取出故障前的部分,之后再收 seconds 秒得到故障后的部分。
74
+ class Ring:
75
+ def __init__(self, seconds=AROUND_S):
76
+ self.seconds, self.rows = seconds, collections.deque()
77
+
78
+ def put(self, row):
79
+ self.rows.append(row)
80
+ while self.rows and row["t_s"] - self.rows[0]["t_s"] > self.seconds:
81
+ self.rows.popleft()
82
+
83
+ def snapshot(self):
84
+ return list(self.rows)
85
+
86
+
87
+ ## @brief 一个循环(一次阶跃)的摘要:experiment.metrics 的指标,加上本循环中最大跟随误差(跟踪量与目标之差的绝对值)
88
+ ## 与诊断对象的读数(板温、母线电压、两核负载、最长执行时间等,由调用方在循环之间读取)。
89
+ def cycle_summary(n, t_s, rows, exp, diagnostics):
90
+ key = experiment.TRACKED[exp.mode]
91
+ metrics = experiment.metrics(rows, exp) if rows else {}
92
+ errors = [abs(r[key] - r["target"]) for r in rows]
93
+ return clean({"cycle": n, "t_s": t_s, "overshoot_pct": metrics.get("overshoot_pct"), "settling_s": metrics.get("settling_s"),
94
+ "steady_error": metrics.get("steady_error"), "max_error": max(errors) if errors else None,
95
+ "samples": len(rows), **diagnostics})
96
+
97
+
98
+ ## @brief 运行剖面的一段统计。每条反馈只累计常数个数值,稳态误差取预定段时长最后 10% 的样本。
99
+ ## 段切换无需等待扫描文件或后台统计,保载时长独立于记录大小;单阶跃继续使用 experiment.metrics。
100
+ class ProfileStats:
101
+ def __init__(self, exp):
102
+ self.exp = exp
103
+ self.count = self.tail_count = 0
104
+ self.max_error, self.peak, self.tail_sum = 0.0, 0.0, 0.0
105
+ self.settling, self.outside = 0.0, False
106
+
107
+ def put(self, row, t):
108
+ exp = self.exp
109
+ value = row[experiment.TRACKED[exp.mode]]
110
+ self.count += 1
111
+ self.max_error = max(self.max_error, abs(row["target"] - value))
112
+ if 0.9 * exp.seconds <= t <= exp.seconds:
113
+ self.tail_sum += row["target"] - value
114
+ self.tail_count += 1
115
+ size = exp.target - exp.start
116
+ if size == 0:
117
+ return
118
+ sign = 1 if size > 0 else -1
119
+ self.peak = max(self.peak, sign * (value - exp.target))
120
+ if abs(value - exp.target) > 0.02 * abs(size):
121
+ self.settling, self.outside = None, True
122
+ elif self.outside:
123
+ self.settling, self.outside = t, False
124
+
125
+ def summary(self, cycle, t_s, diagnostics):
126
+ size = abs(self.exp.target - self.exp.start)
127
+ return clean({"cycle": cycle, "t_s": t_s, "overshoot_pct": self.peak / size * 100 if size else None,
128
+ "settling_s": self.settling if size else None,
129
+ "steady_error": self.tail_sum / self.tail_count if self.tail_count else None,
130
+ "max_error": self.max_error if self.count else None, "samples": self.count, **diagnostics})
131
+
132
+
133
+ ## @brief 收尾条件:返回原因,继续时返回 None。出现故障或保护(statusword 位 3 或位 7,或 0x603F 非零)、到达时长
134
+ ## deadline(单调时钟)。反馈停更由运动会话判出(Motion 的 stale_s),用户停止与记录写入出错由调用方处理。
135
+ def stop_reason(feedback, now, deadline):
136
+ if now >= deadline:
137
+ return "到达时长"
138
+ sw, error = feedback["statusword"], feedback.get("error_code", 0)
139
+ if sw & 0x08 or sw & 0x80 or error:
140
+ return f"出现故障或保护(statusword 0x{sw:04X},0x603F = 0x{error:04X})"
141
+ return None
142
+
143
+
144
+ ## @brief 记录目录所在磁盘的可用空间(字节)。
145
+ def free_bytes(directory):
146
+ return shutil.disk_usage(directory).free
147
+
148
+
149
+ ## @brief 无人值守任务的事件日志。逐行冲刷,页面离开或进程异常退出后仍可读取已写入的部分。
150
+ class EventLog:
151
+ def __init__(self, directory):
152
+ self.directory, self.error = directory, None
153
+ self.lock = threading.Lock()
154
+ self.file = open(directory / "events.csv", "w", newline="")
155
+ self.writer = csv.DictWriter(self.file, ("t", "kind", "text"))
156
+ self.writer.writeheader()
157
+
158
+ def write(self, event):
159
+ with self.lock:
160
+ if self.file is None:
161
+ return
162
+ try:
163
+ self.writer.writerow(event)
164
+ self.file.flush()
165
+ except OSError as error:
166
+ self.error = error
167
+ raise
168
+
169
+ def close(self):
170
+ with self.lock:
171
+ file, self.file = self.file, None
172
+ if file is not None:
173
+ try:
174
+ file.flush()
175
+ os.fsync(file.fileno())
176
+ finally:
177
+ file.close()
178
+
179
+
180
+ ## @brief 系统防休眠断言。macOS 用 caffeinate,Linux 有 systemd 登录管理器且获准时取得 sleep inhibitor。
181
+ ## Linux 子进程在取得抑制锁后才报告就绪,标准输入关闭即释放,服务崩溃也能释放锁。
182
+ class KeepAwake:
183
+ def __init__(self):
184
+ self.proc = None
185
+ if sys.platform == "darwin" and shutil.which("caffeinate"):
186
+ self.proc = subprocess.Popen(["caffeinate", "-i", "-w", str(os.getpid())])
187
+ elif sys.platform.startswith("linux") and shutil.which("systemd-inhibit"):
188
+ try:
189
+ self.proc = subprocess.Popen(
190
+ ["systemd-inhibit", "--what=sleep", "--mode=block", "--who=ehatool", "--why=EHA 长时记录",
191
+ sys.executable, "-c", "import sys; print('ready', flush=True); sys.stdin.buffer.read()"],
192
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
193
+ ready, _, _ = select.select([self.proc.stdout], [], [], 2.0)
194
+ if not ready or self.proc.stdout.readline() != b"ready\n":
195
+ self.release()
196
+ except OSError:
197
+ self.release()
198
+
199
+ @property
200
+ def held(self):
201
+ return self.proc is not None and self.proc.poll() is None
202
+
203
+ def release(self):
204
+ if self.proc is None:
205
+ return
206
+ if self.proc.stdin is not None and not self.proc.stdin.closed:
207
+ self.proc.stdin.close()
208
+ try:
209
+ if self.proc.stdin is None and self.proc.poll() is None:
210
+ self.proc.terminate()
211
+ self.proc.wait(timeout=2)
212
+ except subprocess.TimeoutExpired:
213
+ self.proc.kill()
214
+ self.proc.wait(timeout=2)
215
+ if self.proc.stdout is not None and not self.proc.stdout.closed:
216
+ self.proc.stdout.close()
217
+
218
+
219
+ ## @brief 任务的状态文件:开始时写 running,结束时写结果。服务重启后,仍为 running 的任务记为“中断,结果未知”。
220
+ def write_state(directory, info):
221
+ tmp = directory / "meta.json.tmp"
222
+ tmp.write_text(json.dumps(clean(info), ensure_ascii=False, indent=1))
223
+ os.replace(tmp, directory / "meta.json")
224
+
225
+
226
+ def mark_interrupted(root):
227
+ if not root.is_dir():
228
+ return []
229
+ marked = []
230
+ for path in root.iterdir():
231
+ meta = path / "meta.json"
232
+ if not meta.is_file():
233
+ continue
234
+ try:
235
+ info = json.loads(meta.read_text())
236
+ except (OSError, ValueError):
237
+ continue
238
+ if info.get("kind") in ("longrun", "recording"):
239
+ if info.get("state") == "running":
240
+ info.update(state="interrupted", end="中断,结果未知", complete=False)
241
+ write_state(path, info)
242
+ marked.append(path.name)
243
+ return marked
244
+
245
+
246
+
247
+ ## @brief 每个循环结束后读取的诊断对象(板温、母线电压、两核负载与最长执行时间)。
248
+ DIAGNOSTICS = ("power_stage_temp_c", "dc_link_voltage_mv", "control_load_pct", "core1_load_pct", "drive_cycle_max_us",
249
+ "core1_loop_max_us")
250
+ FIELDS = ("cycle", "segment", "mode") + experiment.FIELDS
251
+ POST_FIELDS = ("statusword", "error_code", "position_actual_um", "velocity_actual_um_s", "motor_speed_rpm")
252
+
253
+
254
+ class StopRun(Exception):
255
+ pass
256
+
257
+
258
+ ## @brief 长时运行:重复阶跃 exp,或依次循环 profile 各段。相同模式共用运动会话,切模式先快停断电再使能。
259
+ ## 直到 seconds 秒、出现故障或保护、反馈停更(运动会话判出)、记录写入出错或 cancel(driver 的发送在 cancel 后拒绝
260
+ ## Enable operation,由会话收尾)。全部样本按大小分卷写入 directory;每个循环一行摘要写入 cycles-*.csv 并交给
261
+ ## on_cycle(剖面按段记录 mode 与 segment);出现故障或保护时,前后各 AROUND_S 秒另存为 fault.csv。
262
+ ## 返回 {"cycles", "reason", "files"}。driver 须已 prepare。
263
+ def run_longrun(driver, exp, seconds, directory, cancel, on_cycle=lambda s: None, on_rows=lambda rows: None,
264
+ around_s=AROUND_S, clock=time.monotonic, report=lambda text: None, read=None, free=free_bytes, profile=None):
265
+ from ..link import Cancelled, DriveAborted, SdoAbort
266
+ # 循环之间的读取用调用方给的短等待(运动中不发控制数据的时间须远小于 0x2000)。
267
+ read = read or driver.sdo_read
268
+ samples = Volumes(directory, "samples", FIELDS)
269
+ cycles = Volumes(directory, "cycles", ("cycle", "segment", "mode", "t_s", "overshoot_pct", "settling_s", "steady_error", "max_error",
270
+ "samples") + DIAGNOSTICS)
271
+ ring = Ring(around_s)
272
+ start, deadline = clock(), clock() + seconds
273
+ n, reason, next_sync = 0, None, clock() + FSYNC_S
274
+ next_space = clock()
275
+ steps = profile or [exp]
276
+ previous_mode, previous_target, last_position = None, 0.0, None
277
+ diagnostics = dict.fromkeys(DIAGNOSTICS)
278
+ diagnostic_index = 0
279
+
280
+ def check_disk(now):
281
+ nonlocal next_sync, next_space
282
+ try:
283
+ if now >= next_sync:
284
+ next_sync = now + FSYNC_S
285
+ samples.flush()
286
+ cycles.flush()
287
+ if now >= next_space:
288
+ next_space = now + 1.0
289
+ if free(directory) < MIN_FREE_BYTES:
290
+ raise StopRun("可用磁盘不足 1 GB")
291
+ except OSError as error:
292
+ raise StopRun(f"记录写入出错:{error}") from None
293
+
294
+ try:
295
+ check_disk(clock())
296
+ with contextlib.ExitStack() as active:
297
+ session = None
298
+ while reason is None:
299
+ n += 1
300
+ for segment, definition in enumerate(steps, 1):
301
+ if cancel.is_set():
302
+ raise Cancelled("用户停止")
303
+ if clock() >= deadline:
304
+ raise StopRun("到达时长")
305
+ if previous_mode != definition.mode:
306
+ active.close()
307
+ session = None
308
+ origin = 0.0
309
+ if definition.positional:
310
+ origin = last_position if session is not None and last_position is not None else driver.position_mm()
311
+ current = definition
312
+ if profile:
313
+ baseline = previous_target if previous_mode == definition.mode else 0.0
314
+ current = dataclasses.replace(definition, start=origin if definition.positional else baseline)
315
+ if session is None:
316
+ # 模式改变须先完成上一运动会话的快停和断电,再由正常使能流程核对新模式与属主。
317
+ if cancel.is_set():
318
+ raise Cancelled("用户停止")
319
+ if clock() >= deadline:
320
+ raise StopRun("到达时长")
321
+ session = active.enter_context(driver.session(experiment.MODES[current.mode], current.fields(current.target_at(0.0, origin))))
322
+ if profile:
323
+ report(f"循环 {n},第 {segment} 段:{current.mode},目标 {current.target} {experiment.UNITS[current.mode]},持续 {current.seconds} s")
324
+ rows = []
325
+ stats = ProfileStats(current) if profile else None
326
+ t0, t, pending = None, 0.0, []
327
+ diagnostic_due = False
328
+
329
+ while t < current.duration:
330
+ if cancel.is_set():
331
+ raise Cancelled("用户停止")
332
+ if clock() >= deadline:
333
+ raise StopRun("到达时长")
334
+ value = current.target_at(t, origin)
335
+ got = session.exchange(**current.fields(value))
336
+ now = clock()
337
+ if got is not None:
338
+ t_dev, fb = got
339
+ t0 = t_dev if t0 is None else t0
340
+ t = t_dev - t0
341
+ r = {"cycle": n, "segment": segment, "mode": current.mode,
342
+ **experiment.row(now - start, driver.time_source, value, fb)}
343
+ last_position = r["position_mm"]
344
+ ring.put(r)
345
+ try:
346
+ samples.write(r)
347
+ except OSError as error:
348
+ raise StopRun(f"记录写入出错:{error}") from None
349
+ why = stop_reason(fb, now, deadline)
350
+ if why is not None:
351
+ raise StopRun(why)
352
+ if stats is not None:
353
+ stats.put(r, t)
354
+ else:
355
+ rows.append({**r, "t_s": t})
356
+ pending.append(r)
357
+ check_disk(now)
358
+ if diagnostic_due:
359
+ # 两次 SDO 等待之间先交换控制数据,六项诊断分散到发送周期,不在段尾集中阻塞。
360
+ name = DIAGNOSTICS[diagnostic_index % len(DIAGNOSTICS)]
361
+ try:
362
+ diagnostics[name] = read(driver.od.lookup(name))
363
+ except (KeyError, TimeoutError, OSError, SdoAbort, RuntimeError):
364
+ diagnostics[name] = None
365
+ diagnostic_index += 1
366
+ diagnostic_due = False
367
+ if len(pending) >= 20:
368
+ on_rows(pending)
369
+ pending = []
370
+ diagnostic_due = True
371
+ on_rows(pending)
372
+ summary = stats.summary(n, clock() - start, diagnostics) if stats is not None else cycle_summary(n, clock() - start, rows, current, diagnostics)
373
+ summary.update(segment=segment, mode=current.mode)
374
+ try:
375
+ cycles.write(summary)
376
+ except OSError as error:
377
+ raise StopRun(f"记录写入出错:{error}") from None
378
+ check_disk(clock())
379
+ on_cycle(summary)
380
+ previous_mode, previous_target = current.mode, current.target
381
+
382
+ except StopRun as stop:
383
+ reason = str(stop)
384
+ except DriveAborted as error: # 故障、离开运行、反馈停更、属主变更、用户停止(Cancelled)
385
+ reason = str(error)
386
+ except Exception as error: # 链路错误、SDO 超时等:运动会话已收尾,原因与已写的文件照样交回
387
+ reason = f"失败:{type(error).__name__}:{error}"
388
+ finally:
389
+ for volume in (samples, cycles):
390
+ try:
391
+ volume.flush()
392
+ except OSError as error:
393
+ reason = f"{reason or ''};记录写入出错:{error}"
394
+ finally:
395
+ volume.close()
396
+ files = samples.names() + cycles.names()
397
+ # 是否另存故障前后的数据,以收尾后设备报告的状态为准(Fault 或锁存的保护,或 0x603F 非零)。
398
+ try:
399
+ sw, error_code = driver.sdo_read(driver.od.lookup("statusword")), driver.sdo_read(driver.od.lookup("error_code"))
400
+ fault = bool(sw & 0x88 or error_code)
401
+ except (TimeoutError, OSError, SdoAbort, RuntimeError):
402
+ fault = False
403
+ if fault:
404
+ report(f"设备报告故障或保护:另存故障前 {around_s:.0f} s 的控制周期数据,并经 SDO 读取之后 {around_s:.0f} s(驱动已断电)")
405
+ try:
406
+ files.append(_save_fault(driver, directory, ring.snapshot(), start, around_s, cancel, clock))
407
+ except OSError as error:
408
+ report(f"故障前后的数据没有存下:{error}")
409
+ return {"cycles": n, "reason": reason or "已停止", "files": files}
410
+
411
+
412
+ ## @brief 故障前(环形缓冲,控制周期的全部样本)与故障后 around_s 秒(收尾断电之后经 SDO 约 20 Hz 读取,source 列为
413
+ ## “SDO”)的数据,存为 fault.csv。cancel 时提前结束。
414
+ def _save_fault(driver, directory, before, start, around_s, cancel, clock):
415
+ path = directory / "fault.csv"
416
+ with open(path, "w", newline="") as f:
417
+ writer = csv.writer(f)
418
+ writer.writerow(("t_s", "source") + POST_FIELDS)
419
+ for r in before:
420
+ writer.writerow((r["t_s"], "控制周期", r["statusword"], r["error_code"], r["position_mm"] * 1000,
421
+ r["velocity_mm_s"] * 1000, r["motor_rpm"]))
422
+ end = clock() + around_s
423
+ while clock() < end and not cancel.is_set():
424
+ try:
425
+ values = [driver.sdo_read(driver.od.lookup(name)) for name in POST_FIELDS]
426
+ writer.writerow((clock() - start, "SDO") + tuple(values))
427
+ except Exception: # 链路中断、磁盘写满:保留已写的部分
428
+ break
429
+ cancel.wait(0.05)
430
+ return path.name
ehatool/web/polling.py ADDED
@@ -0,0 +1,41 @@
1
+ # Copyright The eha-firmware Contributors
2
+
3
+ ## @file
4
+ ## @brief 工作台可见页面的对象订阅。这里只编排页面所需对象,类型和可用性取对象字典。
5
+
6
+ FAST_S, SLOW_S = 0.2, 1.0
7
+ CORE_FAST = ("statusword", "error_code", "control_owner", "modes_of_operation_display")
8
+ CORE_SLOW = ("developer_mode", "abort_connection_option", "quick_stop_option", "command_timeout_ms",
9
+ "firmware_slot", "firmware_confirmed", "firmware_debug")
10
+ FAST_OBJECTS = (*CORE_FAST, "motor_speed_rpm", "motor_encoder_count", "position_actual_um",
11
+ "velocity_actual_um_s", "force_actual_n")
12
+ PAGE_OBJECTS = {
13
+ "overview": ("motor_speed_rpm", "modes_of_operation", "firmware_boot_confirmed", "firmware_slot_a_version",
14
+ "firmware_slot_b_version", "params_source", "param_check", "control_load_pct", "core1_load_pct",
15
+ "drive_cycle_max_us", "core1_loop_max_us", "chip_temperature_c", "power_stage_temp_c",
16
+ "dc_link_voltage_mv", "reset_cause", "sync0_missed_count", "ipc_read_failures",
17
+ "can_error_state", "core1_init_error"),
18
+ "motor": ("motor_speed_rpm", "motor_encoder_count", "encoder_counts_per_rev", "motor_calibration_state",
19
+ "motor_speed_kp", "motor_speed_ki"),
20
+ "control": ("position_actual_um", "velocity_actual_um_s", "force_actual_n", "motor_speed_rpm",
21
+ "soft_position_min_um", "soft_position_max_um", "velocity_limit_um_s"),
22
+ "assembly": ("params_source", "param_check", "sim_real_sensors", "position_actual_um"),
23
+ "maintenance": ("firmware_slot_a_version", "firmware_slot_b_version", "firmware_boot_confirmed"),
24
+ "longrun": ("dc_link_voltage_mv", "power_stage_temp_c", "control_load_pct", "core1_load_pct",
25
+ "drive_cycle_max_us", "core1_loop_max_us"),
26
+ }
27
+
28
+
29
+ ## @brief 返回对象字典内存在的页面订阅,允许较早固件/不同产品缺少部分对象。
30
+ def page_objects(od):
31
+ names = {obj["name"] for obj in od.objects}
32
+ pages = {page: [name for name in objects if name in names] for page, objects in PAGE_OBJECTS.items()}
33
+ pages["control"].extend(obj["name"] for obj in od.objects if 0x2220 <= obj["index"] <= 0x2229)
34
+ return pages
35
+
36
+
37
+ ## @brief 合并页面订阅与全局状态。每个对象只保留一个周期,快对象取 0.2 s,其余取 1 s。
38
+ def periods(od, objects):
39
+ known = {obj["name"] for obj in od.objects}
40
+ names = dict.fromkeys((*CORE_FAST, *CORE_SLOW, *objects))
41
+ return {name: FAST_S if name in FAST_OBJECTS else SLOW_S for name in names if name in known}
@@ -0,0 +1,18 @@
1
+ # 产品配方(docs/工作台页面合同.md):执行哪些步骤、引用的参数文件、验收判据。配方不存参数数值。
2
+ # params:由参数页导出的参数文件,放在 recipes/params/ 下;留空则不按配方写入参数,各步骤照常由操作员输入。
3
+ # criteria:验收判据。门限来自产品需求,首版留空:没有 min/max 的判据只记录数值,摘要中为“未判定”。
4
+ name = "开发板台架(示例)"
5
+ steps = [1, 2, 3, 4, 5, 6, 7, 8]
6
+ params = ""
7
+
8
+ [[criteria]]
9
+ item = "csp.overshoot_pct"
10
+ label = "CSP 阶跃超调"
11
+
12
+ [[criteria]]
13
+ item = "csp.settling_s"
14
+ label = "CSP 阶跃调节时间"
15
+
16
+ [[criteria]]
17
+ item = "csv.overshoot_pct"
18
+ label = "CSV 阶跃超调"