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.
- ehatool/VERSION +1 -0
- ehatool/__init__.py +4 -0
- ehatool/acceptance.py +92 -0
- ehatool/brt27.py +105 -0
- ehatool/brt27_sim.py +114 -0
- ehatool/calibration.py +111 -0
- ehatool/can_sniff.py +162 -0
- ehatool/cia402.py +31 -0
- ehatool/cli.py +541 -0
- ehatool/console.py +31 -0
- ehatool/device/__init__.py +4 -0
- ehatool/device/can.py +201 -0
- ehatool/device/can_discovery.py +387 -0
- ehatool/device/can_discovery.toml +19 -0
- ehatool/device/io.py +20 -0
- ehatool/devices.py +187 -0
- ehatool/diagnostics.py +58 -0
- ehatool/diagnostics.toml +208 -0
- ehatool/discovery.py +95 -0
- ehatool/display.toml +127 -0
- ehatool/ecat.py +520 -0
- ehatool/ecat.toml +17 -0
- ehatool/ecat_probe.py +401 -0
- ehatool/ecat_probe.toml +14 -0
- ehatool/eha_od.json +5871 -0
- ehatool/experiment.py +576 -0
- ehatool/image.py +70 -0
- ehatool/info.py +121 -0
- ehatool/info.toml +41 -0
- ehatool/install_host.py +243 -0
- ehatool/install_host.toml +27 -0
- ehatool/link.py +811 -0
- ehatool/link.toml +18 -0
- ehatool/live.py +112 -0
- ehatool/motor.py +86 -0
- ehatool/od.py +200 -0
- ehatool/odrive.py +450 -0
- ehatool/output.py +208 -0
- ehatool/ram_load.py +62 -0
- ehatool/scope.py +50 -0
- ehatool/sil.py +260 -0
- ehatool/update.py +320 -0
- ehatool/usb_discovery.py +164 -0
- ehatool/usb_discovery.toml +16 -0
- ehatool/web/__init__.py +28 -0
- ehatool/web/brt_sim.py +130 -0
- ehatool/web/canbus.py +95 -0
- ehatool/web/devices.py +216 -0
- ehatool/web/experiments.py +226 -0
- ehatool/web/job_params.py +208 -0
- ehatool/web/layout.toml +61 -0
- ehatool/web/longrun.py +430 -0
- ehatool/web/polling.py +41 -0
- ehatool/web/recipes/bench.toml +18 -0
- ehatool/web/records.py +333 -0
- ehatool/web/requests.py +254 -0
- ehatool/web/server.py +1051 -0
- ehatool/web/session.py +1552 -0
- ehatool/web/static/THIRD_PARTY_LICENSES.txt +133 -0
- ehatool/web/static/assets/ehapower-logo-Cr84XeX3.png +0 -0
- ehatool/web/static/assets/ehapower-mark-Con0OjPM.png +0 -0
- ehatool/web/static/assets/index-CdLvwKa-.css +1 -0
- ehatool/web/static/assets/index-DiLUQD1i.js +134 -0
- ehatool/web/static/index.html +16 -0
- ehatool/web/streams.py +64 -0
- ehatool/web/workspaces.py +124 -0
- ehatool/workflows/__init__.py +4 -0
- ehatool/workflows/cancheck.py +394 -0
- ehatool/workflows/cancheck.toml +9 -0
- ehatool/workflows/checks.py +43 -0
- ehatool/workflows/usbcheck.py +212 -0
- ehatool-6.0.0.dev0.dist-info/METADATA +38 -0
- ehatool-6.0.0.dev0.dist-info/RECORD +77 -0
- ehatool-6.0.0.dev0.dist-info/WHEEL +5 -0
- ehatool-6.0.0.dev0.dist-info/entry_points.txt +2 -0
- ehatool-6.0.0.dev0.dist-info/licenses/LICENSE +21 -0
- ehatool-6.0.0.dev0.dist-info/top_level.txt +1 -0
ehatool/web/records.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief WebUI 的记录目录:每条记录一个子目录,含与 CLI 相同字段的样本 CSV(experiment.write_csv 的格式,可被
|
|
5
|
+
## ehatool compare 读取)与 meta.json(格式版本、设备身份、固件版本、来源、时间基、指标、结束原因、是否完整)。
|
|
6
|
+
|
|
7
|
+
import csv
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import os
|
|
11
|
+
import pathlib
|
|
12
|
+
import re
|
|
13
|
+
import sys
|
|
14
|
+
import tempfile
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
from .. import experiment
|
|
18
|
+
from ..output import json_value as clean
|
|
19
|
+
|
|
20
|
+
FORMAT_VERSION = 1
|
|
21
|
+
TOOL_VERSION = pathlib.Path(__file__).resolve().parents[1].joinpath("VERSION").read_text().strip()
|
|
22
|
+
# 记录中可下载的文件名:样本、元数据与参数扫描组内各成员的 CSV。
|
|
23
|
+
FILE_NAME = re.compile(r"^[\w.\-=,]+\.(csv|json|toml|html)$")
|
|
24
|
+
# 验收档案的序列号:十六进制或字母数字,用于目录名。
|
|
25
|
+
SERIAL = re.compile(r"^[0-9A-Za-z_-]{1,32}$")
|
|
26
|
+
# 对比时每条曲线至多返回的点数。
|
|
27
|
+
COMPARE_POINTS = 3000
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
## @brief 读一条阶跃 CSV:首行须有完整有效的试验定义(已知模式、有限的数),每行须有时间、时间基、目标与跟踪量。
|
|
31
|
+
## 返回 (元数据, 样本, StepExperiment);不是阶跃记录时抛出 ValueError。
|
|
32
|
+
def read_step(path):
|
|
33
|
+
try:
|
|
34
|
+
meta, rows = experiment.read_csv(path)
|
|
35
|
+
exp = experiment.experiment_from_meta(meta)
|
|
36
|
+
except (TypeError, KeyError, AttributeError) as error:
|
|
37
|
+
raise ValueError(f"不是阶跃记录(ehatool step / sil step / ecat step 的 CSV):{error}") from None
|
|
38
|
+
numbers = [v for k, v in vars(exp).items() if k != "mode"]
|
|
39
|
+
if exp.mode not in experiment.TRACKED or not all(math.isfinite(v) for v in numbers):
|
|
40
|
+
raise ValueError(f"试验定义无效:模式 {exp.mode}")
|
|
41
|
+
need = {"t_s", "time_source", "target", experiment.TRACKED[exp.mode]}
|
|
42
|
+
if any(not need <= r.keys() or any(r.get(name) is None for name in need) for r in rows):
|
|
43
|
+
raise ValueError("样本缺少时间、时间基、目标或跟踪量")
|
|
44
|
+
return meta, rows, exp
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
## @brief 默认记录目录:macOS 在 Application Support 下,其他系统遵循 XDG_DATA_HOME。
|
|
48
|
+
def default_root():
|
|
49
|
+
if sys.platform == "darwin":
|
|
50
|
+
return pathlib.Path.home() / "Library/Application Support/ehatool/records"
|
|
51
|
+
base = os.environ.get("XDG_DATA_HOME") or str(pathlib.Path.home() / ".local/share")
|
|
52
|
+
return pathlib.Path(base) / "ehatool/records"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def parameter_objects(od):
|
|
56
|
+
return [obj for obj in od.objects if obj.get("persist") or obj["name"].startswith("sim_")]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
## @brief 在运动循环开始前逐项读取可保存参数与仿真配置。单项不存在保留原因,链路错误后停止补读,元数据不足不阻止试验。
|
|
60
|
+
def read_parameters(od, read):
|
|
61
|
+
started = time.time()
|
|
62
|
+
values, read_at, unavailable = {}, {}, {}
|
|
63
|
+
stopped = None
|
|
64
|
+
for obj in parameter_objects(od):
|
|
65
|
+
name = obj["name"]
|
|
66
|
+
if stopped is not None:
|
|
67
|
+
unavailable[name] = f"未继续读取:{stopped}"
|
|
68
|
+
continue
|
|
69
|
+
try:
|
|
70
|
+
value = read(obj)
|
|
71
|
+
if not isinstance(value, (int, float)) or not math.isfinite(value):
|
|
72
|
+
raise ValueError("设备未返回有限数值")
|
|
73
|
+
values[name], read_at[name] = value, time.time()
|
|
74
|
+
except Exception as error:
|
|
75
|
+
unavailable[name] = str(error)
|
|
76
|
+
if isinstance(error, (TimeoutError, OSError)):
|
|
77
|
+
stopped = str(error)
|
|
78
|
+
return {"phase": "before_motion", "source": "SDO 读取", "started_at": started, "finished_at": time.time(),
|
|
79
|
+
"values": values, "read_at": read_at, "unavailable": unavailable, "complete": not unavailable,
|
|
80
|
+
"note": "开始运动循环前逐项读取持久参数与仿真配置;非原子快照,临时参数已写入。设备的实际电机与测量后端身份未由这些参数证明。"}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
## @brief 复制会话已有的参数与读取时间,不额外访问设备,供被动 CAN、EtherCAT 与示波记录使用。
|
|
84
|
+
def cached_parameters(od, state, read_at, source):
|
|
85
|
+
names = [obj["name"] for obj in parameter_objects(od)]
|
|
86
|
+
values = {n: state[n] for n in names if n in state and n in read_at}
|
|
87
|
+
return {"phase": "session_cache", "source": "会话缓存", "finished_at": time.time(), "values": values,
|
|
88
|
+
"read_at": {n: read_at[n] for n in values}, "sources": {n: source.get(n, "未知") for n in values},
|
|
89
|
+
"unavailable": {n: "会话尚未读取" for n in names if n not in values}, "complete": len(values) == len(names),
|
|
90
|
+
"note": "只复制已有持久参数与仿真配置读数,逐项读取时间可能早于本次采样或临时写入,参数在采样期间可能变化。实际电机与测量后端身份未核对。"}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def csv_metadata(info):
|
|
94
|
+
# CSV 的既有首行以分号分隔,JSON 内的分号转义后可沿用 CLI 解析器。
|
|
95
|
+
encoded = lambda value: json.dumps(clean(value), ensure_ascii=False, separators=(",", ":")).replace(";", "\\u003b")
|
|
96
|
+
return {"tool_version": info.get("tool_version") or "", "identity_json": encoded(info.get("identity") or {}),
|
|
97
|
+
"parameter_snapshot_json": encoded(info.get("parameter_snapshot")),
|
|
98
|
+
"record_end_json": encoded(info.get("end")), "record_complete_json": encoded(info.get("complete"))}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def csv_json(meta, key, fallback):
|
|
102
|
+
try:
|
|
103
|
+
return json.loads(meta[key]) if key in meta else fallback
|
|
104
|
+
except (ValueError, TypeError):
|
|
105
|
+
return fallback
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class Records:
|
|
109
|
+
def __init__(self, root=None):
|
|
110
|
+
self.root = pathlib.Path(root) if root else default_root()
|
|
111
|
+
|
|
112
|
+
def _new_dir(self, kind):
|
|
113
|
+
stamp = time.strftime("%Y%m%d-%H%M%S")
|
|
114
|
+
n = 1
|
|
115
|
+
while True:
|
|
116
|
+
path = self.root / (f"{stamp}-{kind}" + (f"-{n}" if n > 1 else ""))
|
|
117
|
+
try:
|
|
118
|
+
path.mkdir(parents=True)
|
|
119
|
+
return path
|
|
120
|
+
except FileExistsError:
|
|
121
|
+
n += 1
|
|
122
|
+
|
|
123
|
+
## @brief 保存一次阶跃试验;返回记录 ID(目录名)。
|
|
124
|
+
def save_step(self, rows, exp, meta, metrics, identity, end, complete, extra=None):
|
|
125
|
+
path = self._new_dir("step")
|
|
126
|
+
info = {"format": FORMAT_VERSION, "kind": "step", "time": time.time(), "identity": identity,
|
|
127
|
+
# 时间基取自样本(主机接收时间 host、SIL 周期数 cycles、DC 时间)。
|
|
128
|
+
"source": meta.get("driver"), "time_base": rows[0]["time_source"] if rows else None,
|
|
129
|
+
"set": meta.get("set", "-"), "experiment": vars(exp), "metrics": metrics,
|
|
130
|
+
"firmware": meta.get("firmware"), "firmware_version": identity.get("version"), "tool_version": meta.get("tool_version", TOOL_VERSION),
|
|
131
|
+
"parameter_snapshot": csv_json(meta, "parameter_snapshot_json", None),
|
|
132
|
+
"end": end, "complete": complete, "samples": len(rows), **(extra or {})}
|
|
133
|
+
if not isinstance(info["parameter_snapshot"], dict):
|
|
134
|
+
info["parameter_snapshot"] = None
|
|
135
|
+
if rows:
|
|
136
|
+
experiment.write_csv(path / "samples.csv", rows, {**meta, **csv_metadata(info), **experiment.experiment_meta(exp)})
|
|
137
|
+
(path / "meta.json").write_text(json.dumps(clean(info), ensure_ascii=False, indent=1))
|
|
138
|
+
return path.name
|
|
139
|
+
|
|
140
|
+
## @brief 保存选定来源的一段实际样本,空单元格保留未采到的值和采样缺口。
|
|
141
|
+
def save_scope(self, recent, identity, parameter_snapshot=None):
|
|
142
|
+
path = self._new_dir("scope")
|
|
143
|
+
names = recent["objects"]
|
|
144
|
+
gaps = recent.get("gaps", 0)
|
|
145
|
+
source = recent.get("source", "usb_scope")
|
|
146
|
+
time_base = recent.get("time_base", "device")
|
|
147
|
+
info = {"format": FORMAT_VERSION, "kind": "scope", "time": time.time(), "identity": identity,
|
|
148
|
+
"firmware": (identity or {}).get("version"), "tool_version": TOOL_VERSION,
|
|
149
|
+
"parameter_snapshot": parameter_snapshot, "source": source, "time_base": time_base, "objects": names,
|
|
150
|
+
"end": "已保存,选定时段内有采样缺口" if gaps else "完成", "complete": not bool(gaps), "gaps": gaps,
|
|
151
|
+
"samples": sum(any(v is not None for v in row[1]) for row in recent["rows"]),
|
|
152
|
+
"scope": {k: v for k, v in recent.items() if k != "rows"}}
|
|
153
|
+
with open(path / "samples.csv", "w", newline="") as f:
|
|
154
|
+
metadata = {"driver": source, "time_base": time_base, **csv_metadata(info)}
|
|
155
|
+
f.write("# " + "; ".join(f"{k}={v}" for k, v in metadata.items()) + "\n")
|
|
156
|
+
writer = csv.writer(f)
|
|
157
|
+
writer.writerow(["t_s", *names])
|
|
158
|
+
t0 = recent["rows"][0][0]
|
|
159
|
+
for t, values in recent["rows"]:
|
|
160
|
+
writer.writerow([f"{t - t0:.6f}", *values])
|
|
161
|
+
(path / "meta.json").write_text(json.dumps(clean(info), ensure_ascii=False, indent=1))
|
|
162
|
+
return path.name
|
|
163
|
+
|
|
164
|
+
## @brief 新建一个记录组目录(参数扫描);成员由调用方写入,save_group 写元数据。
|
|
165
|
+
def new_group(self, kind):
|
|
166
|
+
return self._new_dir(kind)
|
|
167
|
+
|
|
168
|
+
def save_group(self, path, info):
|
|
169
|
+
info = {"format": FORMAT_VERSION, "time": time.time(), "complete": all(not m.get("error") for m in info["members"]),
|
|
170
|
+
"tool_version": TOOL_VERSION, "end": "完成", "samples": len(info["members"]), **info}
|
|
171
|
+
(path / "meta.json").write_text(json.dumps(clean(info), ensure_ascii=False, indent=1))
|
|
172
|
+
return path.name
|
|
173
|
+
|
|
174
|
+
## @brief 导入 CLI 生成的阶跃 CSV(首行为元数据,含试验定义):存为一条记录,指标按记录重算。
|
|
175
|
+
def import_csv(self, name, text):
|
|
176
|
+
with tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as f:
|
|
177
|
+
f.write(text)
|
|
178
|
+
try:
|
|
179
|
+
meta, rows, exp = read_step(f.name)
|
|
180
|
+
finally:
|
|
181
|
+
os.unlink(f.name)
|
|
182
|
+
if not rows:
|
|
183
|
+
raise ValueError("CSV 中没有样本")
|
|
184
|
+
metrics = experiment.metrics(rows, exp) if rows else None
|
|
185
|
+
# 历史 CLI CSV 没有设备身份、原工具版本或结束信息,保持未知,不能补成当前工具或当前设备。
|
|
186
|
+
identity = csv_json(meta, "identity_json", {})
|
|
187
|
+
if not isinstance(identity, dict):
|
|
188
|
+
identity = {}
|
|
189
|
+
end = csv_json(meta, "record_end_json", "导入")
|
|
190
|
+
complete = csv_json(meta, "record_complete_json", None)
|
|
191
|
+
return self.save_step(rows, exp, {**meta, "tool_version": meta.get("tool_version") or None}, metrics, identity,
|
|
192
|
+
end=end if isinstance(end, str) else "导入", complete=complete if isinstance(complete, bool) else None,
|
|
193
|
+
extra={"imported_from": name, "imported_by_version": TOOL_VERSION})
|
|
194
|
+
|
|
195
|
+
## @brief 叠加对比:每项为 {"id", "file"?};按记录的元数据重建试验定义,带宽 band 下重算指标(experiment.metrics),
|
|
196
|
+
## 返回跟踪量与目标的曲线(降采样)。time_base 不同的记录在页面上分开说明。
|
|
197
|
+
def compare(self, items, band=None):
|
|
198
|
+
out = []
|
|
199
|
+
for item in items:
|
|
200
|
+
record_id, name = item.get("id"), item.get("file") or "samples.csv"
|
|
201
|
+
if not isinstance(record_id, str) or not isinstance(name, str):
|
|
202
|
+
raise ValueError("记录 ID 与文件名须为文字")
|
|
203
|
+
if not item.get("file") and self._kind(record_id) == "sweep":
|
|
204
|
+
raise ValueError("参数扫描须选其中一个取值")
|
|
205
|
+
meta, rows, exp = read_step(self.file(record_id, name))
|
|
206
|
+
key = experiment.TRACKED[exp.mode]
|
|
207
|
+
step = max(1, len(rows) // COMPARE_POINTS)
|
|
208
|
+
part = rows[::step]
|
|
209
|
+
markers, previous = [], 0
|
|
210
|
+
for row in rows:
|
|
211
|
+
code = row.get("error_code")
|
|
212
|
+
if code and code != previous:
|
|
213
|
+
markers.append({"t": row["t_s"], "error_code": code})
|
|
214
|
+
if code is not None:
|
|
215
|
+
previous = code
|
|
216
|
+
out.append({"id": item["id"], "file": item.get("file"), "mode": exp.mode, "unit": experiment.UNITS[exp.mode],
|
|
217
|
+
"settle": exp.settle, "time_base": rows[0]["time_source"] if rows else None,
|
|
218
|
+
"label": meta.get("set", "-"), "driver": meta.get("driver"),
|
|
219
|
+
"t": [r["t_s"] for r in part], "y": [r[key] for r in part], "target": [r["target"] for r in part],
|
|
220
|
+
"markers": markers, "metrics": experiment.metrics(rows, exp, band) if rows else None})
|
|
221
|
+
return clean(out)
|
|
222
|
+
|
|
223
|
+
## @brief 验收档案(docs/工作台页面合同.md 的产线配方):每台一个新目录,不覆盖旧档案。body 含 serial、recipe、
|
|
224
|
+
## operator、firmware、tool_version、params_before / params_after(参数文件 TOML 文字)、steps(每步的输入、读数、
|
|
225
|
+
## 结果与判定)、records(本次阶跃记录的 ID,样本复制进档案)、manual(人工确认项)。另写一页可打印的 HTML 摘要。
|
|
226
|
+
def save_archive(self, body):
|
|
227
|
+
serial = str(body["serial"])
|
|
228
|
+
if not SERIAL.match(serial):
|
|
229
|
+
raise ValueError("序列号只能是字母、数字、- 与 _")
|
|
230
|
+
steps, records = body.get("steps") or [], body.get("records") or []
|
|
231
|
+
if not isinstance(steps, list) or not all(isinstance(s, dict) and all(s.get(field) is None or isinstance(s.get(field, {}), dict) for field in
|
|
232
|
+
("readings", "inputs", "observations", "calculations", "parameters")) for s in steps):
|
|
233
|
+
raise ValueError("steps 须为对象列表,readings 须为对象")
|
|
234
|
+
if not isinstance(records, list) or len(records) > 100:
|
|
235
|
+
raise ValueError("records 须为至多 100 条记录 ID")
|
|
236
|
+
records = [str(r) for r in records]
|
|
237
|
+
# 结论由页面按逐步判定给出(logic/assembly.ts 的 overall),这里只核对取值。
|
|
238
|
+
verdict = str(body.get("verdict") or "未判定")
|
|
239
|
+
if verdict not in ("通过", "不通过", "未判定"):
|
|
240
|
+
raise ValueError(f"结论 {verdict} 无效")
|
|
241
|
+
path = self._new_dir(f"acceptance-{serial}")
|
|
242
|
+
copied, missing = [], []
|
|
243
|
+
for record in records:
|
|
244
|
+
try:
|
|
245
|
+
source = self.file(record, "samples.csv")
|
|
246
|
+
except FileNotFoundError:
|
|
247
|
+
missing.append(record)
|
|
248
|
+
continue
|
|
249
|
+
(path / f"{record}.csv").write_bytes(source.read_bytes())
|
|
250
|
+
copied.append(f"{record}.csv")
|
|
251
|
+
try:
|
|
252
|
+
metadata = self.file(record, "meta.json")
|
|
253
|
+
except FileNotFoundError:
|
|
254
|
+
continue
|
|
255
|
+
(path / f"{record}.json").write_bytes(metadata.read_bytes())
|
|
256
|
+
copied.append(f"{record}.json")
|
|
257
|
+
(path / "params_before.toml").write_text(str(body.get("params_before") or ""))
|
|
258
|
+
(path / "params_after.toml").write_text(str(body.get("params_after") or ""))
|
|
259
|
+
(path / "steps.json").write_text(json.dumps(clean(steps), ensure_ascii=False, indent=1))
|
|
260
|
+
info = {"format": FORMAT_VERSION, "kind": "acceptance", "time": time.time(), "serial": serial,
|
|
261
|
+
"recipe": body.get("recipe"), "operator": body.get("operator"), "firmware": body.get("firmware"),
|
|
262
|
+
"tool_version": body.get("tool_version"), "identity": body.get("identity") or {}, "source": "archive",
|
|
263
|
+
"files": copied, "manual": body.get("manual") or [], "samples": 0,
|
|
264
|
+
"references": body.get("references") or {}, "missing_records": missing,
|
|
265
|
+
"params_before_available": bool(body.get("params_before")), "params_after_available": bool(body.get("params_after")),
|
|
266
|
+
"end": verdict,
|
|
267
|
+
"complete": None}
|
|
268
|
+
# 元数据最后写:中途出错的档案不会以完整的样子出现在记录列表中。
|
|
269
|
+
(path / "summary.html").write_text(summary_html(info, steps))
|
|
270
|
+
(path / "meta.json").write_text(json.dumps(clean(info), ensure_ascii=False, indent=1))
|
|
271
|
+
return path.name
|
|
272
|
+
|
|
273
|
+
def _kind(self, record_id):
|
|
274
|
+
try:
|
|
275
|
+
return json.loads(self.file(record_id, "meta.json").read_text()).get("kind")
|
|
276
|
+
except (FileNotFoundError, OSError, ValueError):
|
|
277
|
+
return None
|
|
278
|
+
|
|
279
|
+
def list(self):
|
|
280
|
+
out = []
|
|
281
|
+
if not self.root.is_dir():
|
|
282
|
+
return out
|
|
283
|
+
for path in sorted(self.root.iterdir(), reverse=True):
|
|
284
|
+
meta = path / "meta.json"
|
|
285
|
+
if meta.is_file():
|
|
286
|
+
try:
|
|
287
|
+
info = {"id": path.name, **json.loads(meta.read_text())}
|
|
288
|
+
# 长时运行、只记录与验收档案:可下载的文件按目录中实际存在的列出(中断的运行没有写完元数据)。
|
|
289
|
+
info["files"] = sorted(p.name for p in path.iterdir() if FILE_NAME.match(p.name))
|
|
290
|
+
out.append(info)
|
|
291
|
+
except (OSError, ValueError):
|
|
292
|
+
out.append({"id": path.name, "kind": "unknown", "complete": False})
|
|
293
|
+
return out
|
|
294
|
+
|
|
295
|
+
## @brief 记录中的文件路径;ID 只能是本目录下的子目录名。
|
|
296
|
+
def file(self, record_id, name):
|
|
297
|
+
if pathlib.Path(record_id).name != record_id or "\\" in record_id or record_id.startswith(".") \
|
|
298
|
+
or pathlib.Path(name).name != name or name.startswith(".") or not FILE_NAME.match(name):
|
|
299
|
+
raise FileNotFoundError(record_id)
|
|
300
|
+
path = self.root / record_id / name
|
|
301
|
+
if not path.is_file():
|
|
302
|
+
raise FileNotFoundError(record_id)
|
|
303
|
+
return path
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
## @brief 验收档案的可打印摘要:元数据、逐步判定与读数。内容全部转义。
|
|
307
|
+
def summary_html(info, steps):
|
|
308
|
+
import html
|
|
309
|
+
esc = lambda v: html.escape(str(v if v is not None else "—")) # noqa: E731
|
|
310
|
+
rows = "".join(
|
|
311
|
+
f"<tr><td>{esc(s.get('n'))}</td><td>{esc(s.get('title'))}</td><td>{esc(s.get('verdict', '未判定'))}</td>"
|
|
312
|
+
f"<td>{esc(';'.join(f'{k} = {v}' for k, v in (s.get('readings') or {}).items()))}</td>"
|
|
313
|
+
f"<td>{esc(s.get('note', ''))}</td></tr>" for s in steps)
|
|
314
|
+
details = "".join(f"<h3>{esc(s.get('n'))} {esc(s.get('title'))}</h3>" + "".join(
|
|
315
|
+
f"<h4>{label}</h4><pre>{esc(json.dumps(s[key], ensure_ascii=False, indent=2)) if key in s else '历史档案未记录'}</pre>"
|
|
316
|
+
for key, label in (("inputs", "输入与标准资料"), ("observations", "原始读数与统计"), ("calculations", "计算结果"), ("parameters", "本步参数读数"))) for s in steps)
|
|
317
|
+
manual = "".join(f"<li>{esc(m)}</li>" for m in info.get("manual") or [])
|
|
318
|
+
when = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(info["time"]))
|
|
319
|
+
return f"""<!doctype html><html lang="zh"><meta charset="utf-8"><title>验收档案 {esc(info['serial'])}</title>
|
|
320
|
+
<style>body{{font:13px -apple-system,sans-serif;margin:24px}}table{{border-collapse:collapse;width:100%}}
|
|
321
|
+
td,th{{border:1px solid #ccc;padding:4px 6px;text-align:left;vertical-align:top}}pre{{white-space:pre-wrap;overflow-wrap:anywhere}}</style>
|
|
322
|
+
<h1>验收档案</h1>
|
|
323
|
+
<p>序列号 {esc(info['serial'])} · 配方 {esc(info.get('recipe'))} · 操作员 {esc(info.get('operator'))} · {esc(when)}</p>
|
|
324
|
+
<p>固件 {esc(info.get('firmware'))} · 工具 {esc(info.get('tool_version'))} · 结论 <b>{esc(info['end'])}</b></p>
|
|
325
|
+
<table><tr><th>步</th><th>内容</th><th>判定</th><th>读数与结果</th><th>备注</th></tr>{rows}</table>
|
|
326
|
+
<h2>人工确认</h2><ul>{manual or '<li>—</li>'}</ul>
|
|
327
|
+
<h2>量具与标准资料</h2><pre>{esc(json.dumps(info.get('references') or {}, ensure_ascii=False, indent=2))}</pre>
|
|
328
|
+
<h2>逐步原始数据</h2>{details}
|
|
329
|
+
<p>全部参数见 params_before.toml 与 params_after.toml,阶跃曲线见同目录的 CSV。</p>
|
|
330
|
+
<p>标定前参数快照:{'已保存' if info.get('params_before_available') else '未记录'};标定后参数快照:{'已保存' if info.get('params_after_available') else '未记录'}。</p>
|
|
331
|
+
<p>缺少的引用记录:{esc('、'.join(info.get('missing_records') or []) or '无')}。历史字段缺失表示未记录。</p>
|
|
332
|
+
</html>
|
|
333
|
+
"""
|
ehatool/web/requests.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief Web 请求的 JSON 形状与基本类型。设备权限、对象范围、控制时序仍由原有业务入口检查。
|
|
5
|
+
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr, model_validator
|
|
9
|
+
|
|
10
|
+
Scalar = StrictInt | StrictFloat | StrictStr
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class RequestBody(BaseModel):
|
|
14
|
+
# 协议可追加字段;既有调用方提交的扩展字段仍交给对应业务流程处理。
|
|
15
|
+
model_config = ConfigDict(extra="allow", allow_inf_nan=False)
|
|
16
|
+
|
|
17
|
+
## @brief 仅输出请求显式给出的字段,保留业务流程自己的缺省值。
|
|
18
|
+
def payload(self):
|
|
19
|
+
return self.model_dump(exclude_unset=True)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SessionRequest(RequestBody):
|
|
23
|
+
via: Literal["usb", "can", "ecat"] = "usb"
|
|
24
|
+
port: StrictStr | None = None
|
|
25
|
+
adapter: StrictStr | None = None
|
|
26
|
+
bitrate: Scalar | None = None
|
|
27
|
+
data_bitrate: Scalar | None = None
|
|
28
|
+
node: Scalar | None = None
|
|
29
|
+
ifname: StrictStr | None = None
|
|
30
|
+
slave: Scalar | None = None
|
|
31
|
+
dc: StrictBool = False
|
|
32
|
+
|
|
33
|
+
@model_validator(mode="after")
|
|
34
|
+
def required_connection_fields(self):
|
|
35
|
+
missing_can = not self.adapter or self.bitrate is None or (self.node is None and "node" in self.model_fields_set)
|
|
36
|
+
if self.via == "can" and missing_can:
|
|
37
|
+
raise ValueError("CAN 连接需要 adapter、bitrate 与有效节点号")
|
|
38
|
+
if self.via == "ecat" and not self.ifname:
|
|
39
|
+
raise ValueError("EtherCAT 连接需要 ifname")
|
|
40
|
+
return self
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class DiscoveryRequest(SessionRequest):
|
|
44
|
+
via: Literal["usb", "can", "ecat"]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class WorkspaceRequest(RequestBody):
|
|
48
|
+
connection: SessionRequest
|
|
49
|
+
page: Literal["overview", "experiments"] = "overview"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ProfileSegment(RequestBody):
|
|
53
|
+
mode: Literal["csp", "csv", "cst", "impedance"]
|
|
54
|
+
target: Scalar
|
|
55
|
+
seconds: Scalar
|
|
56
|
+
rate: Scalar | None = None
|
|
57
|
+
stiffness: Scalar | None = None
|
|
58
|
+
damping: Scalar | None = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class SessionCloseRequest(RequestBody):
|
|
62
|
+
opened_at: StrictInt | StrictFloat | None = None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class WriteRequest(RequestBody):
|
|
66
|
+
value: Scalar
|
|
67
|
+
opened_at: StrictInt | StrictFloat | None = None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class ActionRequest(RequestBody):
|
|
71
|
+
opened_at: StrictInt | StrictFloat | None = None
|
|
72
|
+
on: StrictBool | None = None
|
|
73
|
+
values: dict[str, Scalar] | None = None
|
|
74
|
+
names: list[StrictStr] | None = None
|
|
75
|
+
objects: list[StrictStr] | None = None
|
|
76
|
+
seconds: Scalar | None = None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class StopRequest(RequestBody):
|
|
80
|
+
kind: StrictStr | None = None
|
|
81
|
+
opened_at: StrictInt | StrictFloat | None = None
|
|
82
|
+
job_id: StrictInt | None = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class TaskStopRequest(RequestBody):
|
|
86
|
+
id: StrictInt | None = None
|
|
87
|
+
started_at: StrictInt | StrictFloat | None = None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class ScopeRequest(RequestBody):
|
|
91
|
+
opened_at: StrictInt | StrictFloat | None = None
|
|
92
|
+
objects: list[StrictStr] = Field(default_factory=list)
|
|
93
|
+
divider: Scalar = 1
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class ScopeSaveRequest(RequestBody):
|
|
97
|
+
opened_at: StrictInt | StrictFloat | None = None
|
|
98
|
+
seconds: Scalar = 30
|
|
99
|
+
source: StrictStr | None = None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class TaskParams(RequestBody):
|
|
103
|
+
profile: list[ProfileSegment] | None = None
|
|
104
|
+
ack: StrictBool = False
|
|
105
|
+
mode: StrictStr | None = None
|
|
106
|
+
start: Scalar | None = None
|
|
107
|
+
target: Scalar | None = None
|
|
108
|
+
settle: Scalar | None = None
|
|
109
|
+
seconds: Scalar | None = None
|
|
110
|
+
rate: Scalar | None = None
|
|
111
|
+
stiffness: Scalar | None = None
|
|
112
|
+
damping: Scalar | None = None
|
|
113
|
+
push: Scalar | None = None
|
|
114
|
+
band: Scalar | None = None
|
|
115
|
+
set: list[StrictStr] = Field(default_factory=list)
|
|
116
|
+
timeout: Scalar | None = None
|
|
117
|
+
rpm: Scalar | None = None
|
|
118
|
+
initial: dict[str, Scalar] | None = None
|
|
119
|
+
duration_s: Scalar | None = None
|
|
120
|
+
accept: list[StrictInt] | None = None
|
|
121
|
+
rates: StrictBool = False
|
|
122
|
+
build: StrictStr | None = None
|
|
123
|
+
reset: StrictBool = True
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class JobRequest(RequestBody):
|
|
127
|
+
kind: StrictStr
|
|
128
|
+
params: TaskParams = Field(default_factory=TaskParams)
|
|
129
|
+
opened_at: StrictInt | StrictFloat | None = None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class ConsoleRequest(RequestBody):
|
|
133
|
+
port: StrictStr | None = None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class PreviewRequest(RequestBody):
|
|
137
|
+
build: StrictStr
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class RamLoadRequest(RequestBody):
|
|
141
|
+
image: StrictStr
|
|
142
|
+
openocd_port: Scalar = 4444
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class CompareItem(RequestBody):
|
|
146
|
+
id: StrictStr
|
|
147
|
+
member: StrictInt | None = None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class CompareRequest(RequestBody):
|
|
151
|
+
items: list[CompareItem]
|
|
152
|
+
band: Scalar | None = None
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class ImportRequest(RequestBody):
|
|
156
|
+
name: StrictStr = ""
|
|
157
|
+
text: StrictStr = Field(max_length=64 * 1024 * 1024)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class CalibrationRequest(RequestBody):
|
|
161
|
+
x1_um: Scalar | None = None
|
|
162
|
+
x2_um: Scalar | None = None
|
|
163
|
+
x3_um: Scalar | None = None
|
|
164
|
+
c1: Scalar | None = None
|
|
165
|
+
c2: Scalar | None = None
|
|
166
|
+
c3: Scalar | None = None
|
|
167
|
+
count: Scalar | None = None
|
|
168
|
+
x_um: Scalar | None = None
|
|
169
|
+
um_per_count: Scalar | None = None
|
|
170
|
+
reference_count: Scalar | None = None
|
|
171
|
+
reversed: StrictBool | Scalar | None = None
|
|
172
|
+
raw1: Scalar | None = None
|
|
173
|
+
raw2: Scalar | None = None
|
|
174
|
+
mpa1: Scalar | None = None
|
|
175
|
+
mpa2: Scalar | None = None
|
|
176
|
+
rpm: Scalar | None = None
|
|
177
|
+
observed: StrictStr | None = None
|
|
178
|
+
motor_reversed: Scalar | None = None
|
|
179
|
+
position_delta_um: Scalar | None = None
|
|
180
|
+
position_error_um: Scalar | None = None
|
|
181
|
+
pressure_a_delta: Scalar | None = None
|
|
182
|
+
pressure_b_delta: Scalar | None = None
|
|
183
|
+
pressure_a_error: Scalar | None = None
|
|
184
|
+
pressure_b_error: Scalar | None = None
|
|
185
|
+
positive_channel: Scalar | None = None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class CanRequest(RequestBody):
|
|
189
|
+
adapter: StrictStr
|
|
190
|
+
bitrate: Scalar
|
|
191
|
+
data_bitrate: Scalar | None = None
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class BrtSetupRequest(CanRequest):
|
|
195
|
+
node: Scalar | None = None
|
|
196
|
+
count: Scalar | None = None
|
|
197
|
+
period_us: Scalar | None = None
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
class BrtSimRequest(BrtSetupRequest):
|
|
201
|
+
swing: Scalar | None = None
|
|
202
|
+
hz: Scalar | None = None
|
|
203
|
+
seconds: Scalar | None = None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class CanListenRequest(CanRequest):
|
|
207
|
+
seconds: Scalar = 1
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class CanWriteRequest(CanRequest):
|
|
211
|
+
nodes: list[StrictInt]
|
|
212
|
+
values: dict[str, Scalar]
|
|
213
|
+
save: StrictBool = False
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class SilRequest(TaskParams):
|
|
217
|
+
mode: StrictStr = "motor_speed"
|
|
218
|
+
start: Scalar
|
|
219
|
+
target: Scalar
|
|
220
|
+
model: StrictStr | None = None
|
|
221
|
+
sweep: StrictStr | None = None
|
|
222
|
+
sil: StrictStr | None = None
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class ArchiveRequest(RequestBody):
|
|
226
|
+
serial: StrictStr | StrictInt
|
|
227
|
+
recipe: StrictStr = ""
|
|
228
|
+
operator: StrictStr = ""
|
|
229
|
+
firmware: StrictStr = ""
|
|
230
|
+
tool_version: StrictStr = ""
|
|
231
|
+
identity: dict = Field(default_factory=dict)
|
|
232
|
+
params_before: StrictStr = ""
|
|
233
|
+
params_after: StrictStr = ""
|
|
234
|
+
steps: list[dict] = Field(default_factory=list)
|
|
235
|
+
records: list[StrictStr] = Field(default_factory=list)
|
|
236
|
+
verdict: StrictStr = "未判定"
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class TargetMessage(RequestBody):
|
|
240
|
+
opened_at: StrictInt | StrictFloat | None = None
|
|
241
|
+
job_id: StrictInt | None = None
|
|
242
|
+
type: Literal["target"]
|
|
243
|
+
values: dict[str, Scalar] = Field(default_factory=dict)
|
|
244
|
+
jog: StrictBool = False
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class VisibilityMessage(RequestBody):
|
|
248
|
+
type: Literal["visibility"]
|
|
249
|
+
hidden: StrictBool
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class SubscribeMessage(RequestBody):
|
|
253
|
+
type: Literal["subscribe"]
|
|
254
|
+
objects: list[StrictStr]
|