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/update.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief 固件升级客户端(USB 帧 0x780):开始、顺序写入、结束三步,设备端见 firmware/rtos/updater.h。
|
|
5
|
+
|
|
6
|
+
import pathlib
|
|
7
|
+
import struct
|
|
8
|
+
import sys
|
|
9
|
+
import time
|
|
10
|
+
import tomllib
|
|
11
|
+
import zlib
|
|
12
|
+
|
|
13
|
+
from . import image
|
|
14
|
+
from .link import (ABORT_CANNOT_STORE, ABORT_DEVICE_STATE, COB_UPDATE, LINK_MAX_LEN, STORE_TIMEOUT_S, SdoAbort,
|
|
15
|
+
StreamLink, Device, Cancelled)
|
|
16
|
+
|
|
17
|
+
# 操作与目标,与 link.h(EHA_UPDATE_OP_*)和 updater.h 一致。
|
|
18
|
+
OP_BEGIN, OP_WRITE, OP_FINISH = 1, 2, 3
|
|
19
|
+
TARGET_A, TARGET_B, TARGET_INACTIVE, TARGET_BOOT = 0, 1, 2, 3
|
|
20
|
+
# 写入帧:操作 u8 + 偏移 u32 + 数据。
|
|
21
|
+
CHUNK = LINK_MAX_LEN - 5
|
|
22
|
+
SLOT_NAMES = {0: "A", 1: "B", 255: "非槽开发镜像"}
|
|
23
|
+
# 设备在第一段(镜像头)或结束校验时拒收:型号、链接地址或槽尾格式与设备不符。槽尾格式改变时旧固件拒收新镜像,
|
|
24
|
+
# 新 bootloader 也不启动旧格式的镜像,跨格式只能按首次安装重装。
|
|
25
|
+
IMAGE_REJECTED = "设备拒收此镜像:型号、目标槽或槽尾格式与设备上的固件不符;从槽尾格式不同的旧固件升级时须按首次安装重装"
|
|
26
|
+
RESET_SIGNATURE = 0x74657372
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def request(dev, payload, timeout):
|
|
30
|
+
dev.link.send(COB_UPDATE, payload)
|
|
31
|
+
resp = dev.link.receive(COB_UPDATE, timeout)
|
|
32
|
+
if resp is None or len(resp) < 5 or resp[0] != payload[0]:
|
|
33
|
+
raise TimeoutError(f"升级操作 {payload[0]} 无应答")
|
|
34
|
+
abort = struct.unpack_from("<I", resp, 1)[0]
|
|
35
|
+
if abort:
|
|
36
|
+
raise SdoAbort(abort)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
## @brief 在已发请求结束后检查取消,下一次写入或复位尚未发送。
|
|
40
|
+
def checkpoint(cancel):
|
|
41
|
+
if cancel is not None and cancel.is_set():
|
|
42
|
+
raise Cancelled("已放弃后续写入,未发送复位;已发送的写入不能撤回,目标区域可能不完整,可重新写入")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
## @brief 逐包写镜像;取消仅在一次已发送请求结束后生效,失败/超时不重发。
|
|
46
|
+
## progress 接收阶段、已发送字节与总字节;report 用于 CLI/日志的完整文本行。
|
|
47
|
+
def write_image(dev, target, data, label, *, report=print, progress=None, cancel=None):
|
|
48
|
+
crc = zlib.crc32(data) & 0xFFFFFFFF
|
|
49
|
+
t0 = time.monotonic()
|
|
50
|
+
checkpoint(cancel)
|
|
51
|
+
# 每一步都按擦写的时限等应答:开始时 STM32 擦除两个扇区;写入与结束要等存储锁,其他通道保存参数时锁被擦除占住。
|
|
52
|
+
request(dev, struct.pack("<BBII", OP_BEGIN, target, len(data), crc), STORE_TIMEOUT_S)
|
|
53
|
+
for offset in range(0, len(data), CHUNK):
|
|
54
|
+
checkpoint(cancel)
|
|
55
|
+
try:
|
|
56
|
+
request(dev, struct.pack("<BI", OP_WRITE, offset) + data[offset:offset + CHUNK], STORE_TIMEOUT_S)
|
|
57
|
+
except SdoAbort as error:
|
|
58
|
+
if offset == 0 and error.code == ABORT_DEVICE_STATE:
|
|
59
|
+
error.add_note(IMAGE_REJECTED)
|
|
60
|
+
raise
|
|
61
|
+
if offset % (CHUNK * 512) == 0:
|
|
62
|
+
report(f" {label}: {offset * 100 // len(data):3d}%")
|
|
63
|
+
if progress is not None:
|
|
64
|
+
progress({"stage": "write", "label": label, "written": min(offset + CHUNK, len(data)), "total": len(data)})
|
|
65
|
+
checkpoint(cancel)
|
|
66
|
+
if progress is not None:
|
|
67
|
+
progress({"stage": "verify", "label": label})
|
|
68
|
+
try:
|
|
69
|
+
request(dev, bytes([OP_FINISH]), STORE_TIMEOUT_S)
|
|
70
|
+
except SdoAbort as error:
|
|
71
|
+
if error.code == ABORT_CANNOT_STORE:
|
|
72
|
+
error.add_note(IMAGE_REJECTED)
|
|
73
|
+
raise
|
|
74
|
+
report(f" {label}: {len(data)} 字节,{time.monotonic() - t0:.1f} s,设备校验通过")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
## @brief 发布目录的清单:版本与各型号的三个镜像,布局只在发布目录中有意义。
|
|
78
|
+
RELEASE_MANIFEST = "manifest.toml"
|
|
79
|
+
RELEASE_FORMAT = 1
|
|
80
|
+
## @brief 开发用构建目录中的镜像位置(CMake 的产物布局);发布目录另用清单写相对路径。
|
|
81
|
+
BUILD_LAYOUT = {"slot_a": "output/eha-firmware.bin", "slot_b": "slot_b/output/eha-firmware.bin",
|
|
82
|
+
"bootloader": "bootloader/output/eha-boot.bin"}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
## @brief 取出本次要写的镜像:发布目录按设备型号选,开发用的构建目录按约定路径取。
|
|
86
|
+
## @param source 发布目录(含 manifest.toml)或构建目录(含 output/、slot_b/、bootloader/)。
|
|
87
|
+
## @param product_code 设备的产品码(0x1018:02);发布目录有多个型号时必给,只认型号相同的那一份。
|
|
88
|
+
## @exception ValueError 找不到清单、型号不符、清单缺字段或镜像文件不存在。
|
|
89
|
+
def images(source, product_code=None):
|
|
90
|
+
source = pathlib.Path(source)
|
|
91
|
+
manifest = source / RELEASE_MANIFEST
|
|
92
|
+
if manifest.is_file():
|
|
93
|
+
document = tomllib.loads(manifest.read_text(encoding="utf-8"))
|
|
94
|
+
if document.get("format") != RELEASE_FORMAT:
|
|
95
|
+
raise ValueError(f"{manifest}:格式版本 {document.get('format')!r} 不认识(本工具支持 {RELEASE_FORMAT})")
|
|
96
|
+
models = document.get("model")
|
|
97
|
+
if not models:
|
|
98
|
+
raise ValueError(f"{manifest}:没有型号")
|
|
99
|
+
model = _pick_model(manifest, models, product_code)
|
|
100
|
+
files = {kind: source / model.get(key, "") for kind, key in (("A", "slot_a"), ("B", "slot_b"), ("boot", "bootloader"))}
|
|
101
|
+
missing = [str(path) for path in files.values() if not path.is_file()]
|
|
102
|
+
if missing:
|
|
103
|
+
raise ValueError(f"{manifest}:镜像文件不存在 {'、'.join(missing)}")
|
|
104
|
+
return files
|
|
105
|
+
files = {"A": source / BUILD_LAYOUT["slot_a"], "B": source / BUILD_LAYOUT["slot_b"],
|
|
106
|
+
"boot": source / BUILD_LAYOUT["bootloader"]}
|
|
107
|
+
missing = [str(path) for path in files.values() if not path.is_file()]
|
|
108
|
+
if missing:
|
|
109
|
+
raise ValueError(f"{source} 既不是发布目录(缺 {RELEASE_MANIFEST}),也不是构建目录(缺 {'、'.join(missing)})")
|
|
110
|
+
return files
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
## @brief 发布目录中与设备产品码对应的型号;没有产品码时只接受唯一的型号。
|
|
114
|
+
def _pick_model(manifest, models, product_code):
|
|
115
|
+
if product_code is None:
|
|
116
|
+
if len(models) > 1:
|
|
117
|
+
raise ValueError(f"{manifest}:有多个型号,须按设备身份选择")
|
|
118
|
+
return next(iter(models.values()))
|
|
119
|
+
for model in models.values():
|
|
120
|
+
if model.get("product_code") == product_code:
|
|
121
|
+
return model
|
|
122
|
+
known = "、".join(f"0x{model.get('product_code', 0):08X}" for model in models.values())
|
|
123
|
+
raise ValueError(f"{manifest}:没有产品码 0x{product_code:08X} 的型号(清单中有 {known})")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
## @brief 镜像头中的版本(major << 16 | minor << 8 | patch)。
|
|
127
|
+
def image_version(data):
|
|
128
|
+
return image.find_header(data)[1][4]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
## @brief 写入后核对目标槽:0x2022/0x2023 只对可启动的槽(镜像校验通过且有已写完记录)给出版本,开始写入即为 0。
|
|
132
|
+
## 与镜像头版本一致才说明本次传输成功;FoE 关闭时的失败不会交给主站,只能据此判断。
|
|
133
|
+
## @param read 读对象的函数(名称 → 值)。
|
|
134
|
+
def check_written(read, target, data):
|
|
135
|
+
got, want = read(f"firmware_slot_{target.lower()}_version"), image_version(data)
|
|
136
|
+
if got != want:
|
|
137
|
+
raise RuntimeError(f"槽 {target} 写入未完成(槽版本 0x{got:06X},镜像 0x{want:06X}),不复位;原镜像照常运行")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
## @brief 复位后只读等待原设备的目标槽与版本;每次打开的链路均在本函数关闭。
|
|
141
|
+
## @return 已确认的启动观测,confirmed 为 0/1 或未读到时的 None。
|
|
142
|
+
def wait_running(port, target, timeout=15.0, *, identity, version):
|
|
143
|
+
from .usb_discovery import MESSAGES, UsbIdentityError, open_usb, usb_candidates
|
|
144
|
+
|
|
145
|
+
if target not in ("A", "B"):
|
|
146
|
+
raise ValueError(MESSAGES["invalid_target"])
|
|
147
|
+
expected = {key: identity[key] for key in ("vendor_id", "product_code", "serial_number")}
|
|
148
|
+
if expected["serial_number"] == 0:
|
|
149
|
+
raise ValueError(MESSAGES["zero_serial"])
|
|
150
|
+
expected_serial = f"{expected['serial_number']:08X}"
|
|
151
|
+
deadline = time.monotonic() + timeout
|
|
152
|
+
last = MESSAGES["reconnect_empty"]
|
|
153
|
+
|
|
154
|
+
def remaining():
|
|
155
|
+
budget = deadline - time.monotonic()
|
|
156
|
+
if budget <= 0:
|
|
157
|
+
raise TimeoutError(MESSAGES["deadline"])
|
|
158
|
+
return budget
|
|
159
|
+
|
|
160
|
+
while time.monotonic() < deadline:
|
|
161
|
+
link = None
|
|
162
|
+
result = None
|
|
163
|
+
primary = None
|
|
164
|
+
try:
|
|
165
|
+
candidates = usb_candidates()
|
|
166
|
+
matching = [item for item in candidates if item["serial"] == expected_serial]
|
|
167
|
+
if not matching:
|
|
168
|
+
# 唯一的缺描述符候选可用运行时身份核对,端口改名也能恢复。
|
|
169
|
+
matching = [item for item in candidates if item["serial"] is None]
|
|
170
|
+
if not matching and port is not None:
|
|
171
|
+
matching = [item for item in usb_candidates(port)
|
|
172
|
+
if item["serial"] in (None, expected_serial)]
|
|
173
|
+
if len(matching) > 1:
|
|
174
|
+
raise UsbIdentityError(MESSAGES["ambiguous"].format(
|
|
175
|
+
ports="、".join(item["port"] for item in matching)))
|
|
176
|
+
if matching:
|
|
177
|
+
link = open_usb(matching[0]["port"], expected_serial, verify=True, timeout=min(1.0, remaining()))
|
|
178
|
+
if any(link.identity[key] != value for key, value in expected.items()):
|
|
179
|
+
raise UsbIdentityError(MESSAGES["identity_mismatch"].format(
|
|
180
|
+
expected=expected, actual=link.identity))
|
|
181
|
+
dev = Device(link)
|
|
182
|
+
slot = dev.read("firmware_slot", timeout=min(0.2, remaining()))
|
|
183
|
+
remaining()
|
|
184
|
+
if slot not in (0, 1):
|
|
185
|
+
last = MESSAGES["reconnect_invalid_slot"].format(slot=slot)
|
|
186
|
+
else:
|
|
187
|
+
got = dev.read(f"firmware_slot_{SLOT_NAMES[slot].lower()}_version",
|
|
188
|
+
timeout=min(0.2, remaining()))
|
|
189
|
+
remaining()
|
|
190
|
+
last = MESSAGES["reconnect_slot"].format(slot=SLOT_NAMES[slot], version=got)
|
|
191
|
+
if SLOT_NAMES[slot] == target and got == version:
|
|
192
|
+
result = {"port": matching[0]["port"], "identity": dict(link.identity),
|
|
193
|
+
"slot": target, "version": got, "confirmed": None}
|
|
194
|
+
try:
|
|
195
|
+
confirmed = dev.read("firmware_confirmed", timeout=min(0.2, remaining()))
|
|
196
|
+
remaining()
|
|
197
|
+
result["confirmed"] = confirmed
|
|
198
|
+
except (OSError, RuntimeError, TimeoutError) as error:
|
|
199
|
+
result["confirmation_error"] = MESSAGES["confirmed_unavailable"].format(reason=error)
|
|
200
|
+
# 身份、目标槽与版本已在截止前成立;附属确认查询不抹掉启动观测。
|
|
201
|
+
except UsbIdentityError as error:
|
|
202
|
+
primary = error
|
|
203
|
+
raise
|
|
204
|
+
except (OSError, RuntimeError, TimeoutError) as error:
|
|
205
|
+
primary = error
|
|
206
|
+
result = None
|
|
207
|
+
last = str(error)
|
|
208
|
+
finally:
|
|
209
|
+
if link is not None:
|
|
210
|
+
try:
|
|
211
|
+
link.close()
|
|
212
|
+
except Exception as error:
|
|
213
|
+
message = MESSAGES["close_failed"].format(reason=error)
|
|
214
|
+
if primary is not None:
|
|
215
|
+
primary.add_note(message)
|
|
216
|
+
last += ";" + message
|
|
217
|
+
elif result is not None:
|
|
218
|
+
result["close_error"] = message
|
|
219
|
+
if result is not None:
|
|
220
|
+
return result
|
|
221
|
+
time.sleep(min(0.25, max(0.0, deadline - time.monotonic())))
|
|
222
|
+
raise TimeoutError(MESSAGES["reconnect_timeout"].format(timeout=timeout, target=target, last=last))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
## @brief 单次请求复位;收到应答返回 True,未收到应答返回 False,设备是否复位由后续观测判定。
|
|
226
|
+
def reset(dev):
|
|
227
|
+
try:
|
|
228
|
+
dev.write("device_reset", RESET_SIGNATURE)
|
|
229
|
+
return True
|
|
230
|
+
except TimeoutError:
|
|
231
|
+
return False
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
## @brief 完成最后一次取消检查并报告提交,再发送一次复位。超时与拒绝沿用各传输的语义。
|
|
235
|
+
def commit_reset(send, cancel, progress):
|
|
236
|
+
checkpoint(cancel)
|
|
237
|
+
if progress is not None:
|
|
238
|
+
progress({"stage": "reset", "cancellable": False})
|
|
239
|
+
acknowledged = send()
|
|
240
|
+
if progress is not None:
|
|
241
|
+
progress({"stage": "reset", "cancellable": False, "acknowledged": acknowledged})
|
|
242
|
+
return acknowledged
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _messages():
|
|
246
|
+
from .output import DISPLAY
|
|
247
|
+
return DISPLAY["cli"]
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
## @brief 写入之前核对身份:序列号有效,厂商与产品码在对象字典的型号表中(不向其他产品写镜像)。
|
|
251
|
+
def _identity(dev):
|
|
252
|
+
identity = dict(getattr(dev.link, "identity", None) or dev.read_identity())
|
|
253
|
+
if identity["serial_number"] == 0:
|
|
254
|
+
raise RuntimeError(_messages()["upgrade_serial_zero"])
|
|
255
|
+
if dev.od.model_for(identity["vendor_id"], identity["product_code"]) is None:
|
|
256
|
+
raise RuntimeError(_messages()["identity_mismatch"])
|
|
257
|
+
return identity
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
## @brief 经主机链路升级(CLI 与 WebUI 共用):写入非运行槽、核对槽版本,reset_after 时复位并等原设备从新槽运行。
|
|
261
|
+
## 复位前关闭 dev 的链路。进度经 report;不能升级时抛出 RuntimeError。返回 {"target", "version", "running"}。
|
|
262
|
+
def update_usb(dev, build, *, port=None, reset_after=True, report=print, warn=None, progress=None, cancel=None):
|
|
263
|
+
messages = _messages()
|
|
264
|
+
if not isinstance(dev.link, StreamLink):
|
|
265
|
+
raise RuntimeError("固件升级经主机链路(USB 或串口;EtherCAT 用 FoE)")
|
|
266
|
+
identity = _identity(dev)
|
|
267
|
+
slot = dev.read("firmware_slot")
|
|
268
|
+
if slot == 255:
|
|
269
|
+
raise RuntimeError("设备运行非槽开发镜像,首次安装用 ehatool install")
|
|
270
|
+
if slot not in (0, 1):
|
|
271
|
+
raise RuntimeError(messages["upgrade_slot_invalid"].format(slot=slot))
|
|
272
|
+
target = "B" if slot == 0 else "A"
|
|
273
|
+
data = images(build, identity.get("product_code"))[target].read_bytes()
|
|
274
|
+
version = image_version(data)
|
|
275
|
+
report(f"运行槽 {SLOT_NAMES[slot]},写入槽 {target}")
|
|
276
|
+
write_image(dev, TARGET_INACTIVE, data, f"槽 {target}", report=report, progress=progress, cancel=cancel)
|
|
277
|
+
check_written(dev.read, target, data)
|
|
278
|
+
report(messages["upgrade_written"].format(slot=target, version=version))
|
|
279
|
+
result = {"target": target, "version": version, "running": None, "reset_acknowledged": None}
|
|
280
|
+
if not reset_after:
|
|
281
|
+
return result
|
|
282
|
+
acknowledged = commit_reset(lambda: reset(dev), cancel, progress)
|
|
283
|
+
result["reset_acknowledged"] = acknowledged
|
|
284
|
+
report(messages["reset_ack" if acknowledged else "reset_unknown"])
|
|
285
|
+
dev.link.close()
|
|
286
|
+
running = wait_running(port, target, identity=identity, version=version)
|
|
287
|
+
confirmed = running.get("confirmed")
|
|
288
|
+
state = messages["upgrade_confirmed"] if confirmed == 1 else (
|
|
289
|
+
messages["upgrade_trial"] if confirmed == 0 else messages["upgrade_confirmation_unknown"])
|
|
290
|
+
report(messages["upgrade_running"].format(slot=target, state=state))
|
|
291
|
+
result["running"] = running
|
|
292
|
+
if running.get("confirmation_error"):
|
|
293
|
+
(warn or (lambda text: print(text, file=sys.stderr)))(running["confirmation_error"])
|
|
294
|
+
if running.get("close_error"):
|
|
295
|
+
raise RuntimeError(messages["close_failed"].format(reason=running["close_error"]))
|
|
296
|
+
return result
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
## @brief 首次安装(设备须运行非槽开发镜像):先写槽 A、核对槽版本,再写 bootloader,reset_after 时复位。
|
|
300
|
+
## 设备在槽 A 的第一段数据中按镜像头核对链接地址与产品码,构建目录选错(别的型号)时在 bootloader 区写入之前即被拒收。
|
|
301
|
+
## 先读齐两个镜像,缺任何一个都不开始写入。
|
|
302
|
+
def install_usb(dev, build, *, reset_after=True, report=print, progress=None, cancel=None):
|
|
303
|
+
messages = _messages()
|
|
304
|
+
if not isinstance(dev.link, StreamLink):
|
|
305
|
+
raise RuntimeError("首次安装经主机链路(USB 或串口)")
|
|
306
|
+
identity = _identity(dev)
|
|
307
|
+
if dev.read("firmware_slot") != 255:
|
|
308
|
+
raise RuntimeError("设备从槽启动;现场升级用 ehatool update")
|
|
309
|
+
files = images(build, identity.get("product_code"))
|
|
310
|
+
boot, slot_a = files["boot"].read_bytes(), files["A"].read_bytes()
|
|
311
|
+
version = image_version(slot_a)
|
|
312
|
+
write_image(dev, TARGET_A, slot_a, "槽 A", report=report, progress=progress, cancel=cancel)
|
|
313
|
+
check_written(dev.read, "A", slot_a)
|
|
314
|
+
write_image(dev, TARGET_BOOT, boot, "bootloader", report=report, progress=progress, cancel=cancel)
|
|
315
|
+
report(messages["upgrade_written"].format(slot="A", version=version))
|
|
316
|
+
acknowledged = None
|
|
317
|
+
if reset_after:
|
|
318
|
+
acknowledged = commit_reset(lambda: reset(dev), cancel, progress)
|
|
319
|
+
report(messages["reset_ack" if acknowledged else "reset_unknown"])
|
|
320
|
+
return {"target": "A", "version": version, "reset_acknowledged": acknowledged}
|
ehatool/usb_discovery.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief USB 描述符枚举、唯一选择与同连接上的运行时身份核对。
|
|
5
|
+
|
|
6
|
+
import errno
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import re
|
|
10
|
+
import time
|
|
11
|
+
import tomllib
|
|
12
|
+
|
|
13
|
+
from .link import Device, USB_PID, USB_VID, StreamLink
|
|
14
|
+
from .od import ObjectDictionary
|
|
15
|
+
|
|
16
|
+
with Path(__file__).with_name("usb_discovery.toml").open("rb") as source:
|
|
17
|
+
MESSAGES = tomllib.load(source)["message"]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class UsbIdentityError(RuntimeError):
|
|
21
|
+
"""已经打开的设备与所选身份不相符。"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
## @brief 选择器接受 8 位十六进制序列号,显示统一为大写;零值不能作为身份。
|
|
25
|
+
def normalize_serial(value):
|
|
26
|
+
text = str(value).strip()
|
|
27
|
+
if text.lower().startswith("0x"):
|
|
28
|
+
text = text[2:]
|
|
29
|
+
if not re.fullmatch(r"[0-9a-fA-F]{8}", text) or int(text, 16) == 0:
|
|
30
|
+
raise ValueError(MESSAGES["invalid_serial"])
|
|
31
|
+
return text.upper()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _descriptor_serial(value):
|
|
35
|
+
if value is None:
|
|
36
|
+
return None
|
|
37
|
+
try:
|
|
38
|
+
return normalize_serial(value)
|
|
39
|
+
except ValueError:
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
## @brief 只取 OS 元数据,不打开串口;物理路径的符号链接合并,同序列号不同端口保持多项。
|
|
44
|
+
def usb_candidates(port=None):
|
|
45
|
+
from serial.tools import list_ports
|
|
46
|
+
|
|
47
|
+
candidates = {}
|
|
48
|
+
target = os.path.realpath(port) if port else None
|
|
49
|
+
for item in sorted(list_ports.comports(), key=lambda item: item.device):
|
|
50
|
+
path = os.path.realpath(item.device)
|
|
51
|
+
if target is not None and path != target:
|
|
52
|
+
continue
|
|
53
|
+
if target is None and (item.vid, item.pid) != (USB_VID, USB_PID):
|
|
54
|
+
continue
|
|
55
|
+
candidates.setdefault(path, {
|
|
56
|
+
"via": "usb", "role": "device", "port": port or item.device,
|
|
57
|
+
"name": item.product, "name_source": "usb_descriptor" if item.product else None,
|
|
58
|
+
"manufacturer": item.manufacturer,
|
|
59
|
+
"serial": _descriptor_serial(item.serial_number),
|
|
60
|
+
"serial_source": "usb_descriptor" if _descriptor_serial(item.serial_number) else None,
|
|
61
|
+
"vid": item.vid, "pid": item.pid, "location": item.location,
|
|
62
|
+
"description": item.description, "state": "candidate", "method": "usb_descriptor",
|
|
63
|
+
})
|
|
64
|
+
if port is not None and not candidates:
|
|
65
|
+
candidates[target] = {
|
|
66
|
+
"via": "usb", "role": "device", "port": port, "name": None, "name_source": None,
|
|
67
|
+
"manufacturer": None, "serial": None, "serial_source": None,
|
|
68
|
+
"vid": None, "pid": None, "location": None, "description": None,
|
|
69
|
+
"state": "specified", "method": "explicit_port",
|
|
70
|
+
}
|
|
71
|
+
return list(candidates.values())
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _remaining(deadline):
|
|
75
|
+
remaining = deadline - time.monotonic()
|
|
76
|
+
if remaining <= 0:
|
|
77
|
+
raise TimeoutError(MESSAGES["deadline"])
|
|
78
|
+
return remaining
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
## @brief 在当前已打开的连接上核对产品与序列号,返回实际运行时身份。
|
|
82
|
+
def verify_identity(link, expected_serial=None, *, timeout=1.0):
|
|
83
|
+
deadline = time.monotonic() + timeout
|
|
84
|
+
actual = Device(link).read_identity(timeout=_remaining(deadline))
|
|
85
|
+
_remaining(deadline)
|
|
86
|
+
# 厂商号与产品码须在对象字典的型号表中(任一 EHA 型号)。
|
|
87
|
+
if ObjectDictionary().model_for(actual["vendor_id"], actual["product_code"]) is None:
|
|
88
|
+
raise UsbIdentityError(MESSAGES["not_eha"].format(
|
|
89
|
+
vendor=actual["vendor_id"], product=actual["product_code"]))
|
|
90
|
+
serial = actual["serial_number"]
|
|
91
|
+
if serial == 0:
|
|
92
|
+
raise UsbIdentityError(MESSAGES["zero_serial"])
|
|
93
|
+
if expected_serial is not None and f"{serial:08X}" != normalize_serial(expected_serial):
|
|
94
|
+
raise UsbIdentityError(MESSAGES["identity_mismatch"].format(
|
|
95
|
+
expected=normalize_serial(expected_serial), actual=f"{serial:08X}"))
|
|
96
|
+
link.identity = actual
|
|
97
|
+
return actual
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
## @brief 选择唯一 USB 路径;显式身份或 verify 要求在同句柄上完成核对后才返回。
|
|
101
|
+
def open_usb(port=None, serial=None, *, verify=False, timeout=1.0):
|
|
102
|
+
expected = normalize_serial(serial) if serial is not None else None
|
|
103
|
+
if timeout <= 0:
|
|
104
|
+
raise TimeoutError(MESSAGES["deadline"])
|
|
105
|
+
found = usb_candidates(port)
|
|
106
|
+
if expected is not None and port is None:
|
|
107
|
+
found = [item for item in found if item["serial"] == expected]
|
|
108
|
+
if not found:
|
|
109
|
+
raise RuntimeError(MESSAGES["not_found"])
|
|
110
|
+
if len(found) > 1:
|
|
111
|
+
raise RuntimeError(MESSAGES["ambiguous"].format(ports="、".join(item["port"] for item in found)))
|
|
112
|
+
selected = found[0]
|
|
113
|
+
if expected is not None and selected["serial"] not in (None, expected):
|
|
114
|
+
raise UsbIdentityError(MESSAGES["identity_mismatch"].format(
|
|
115
|
+
expected=expected, actual=selected["serial"]))
|
|
116
|
+
deadline = time.monotonic() + timeout
|
|
117
|
+
link = StreamLink(selected["port"], timeout=min(0.05, timeout), write_timeout=min(0.2, timeout))
|
|
118
|
+
try:
|
|
119
|
+
if verify or expected is not None:
|
|
120
|
+
verify_identity(link, expected or selected["serial"], timeout=_remaining(deadline))
|
|
121
|
+
except BaseException as error:
|
|
122
|
+
try:
|
|
123
|
+
link.close()
|
|
124
|
+
except Exception as close_error:
|
|
125
|
+
error.add_note(MESSAGES["close_failed"].format(reason=close_error))
|
|
126
|
+
raise
|
|
127
|
+
return link
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _access_state(error):
|
|
131
|
+
return "busy" if getattr(error, "errno", None) in (errno.EBUSY, errno.EAGAIN, errno.EWOULDBLOCK) else "unavailable"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
## @brief 普通扫描只列描述符;主动识别逐项读取身份并保留失败候选。
|
|
135
|
+
def scan_usb(*, identify=False, port=None, serial=None):
|
|
136
|
+
expected = normalize_serial(serial) if serial is not None else None
|
|
137
|
+
records, issues = [], []
|
|
138
|
+
try:
|
|
139
|
+
found = usb_candidates(port)
|
|
140
|
+
except (OSError, RuntimeError) as error:
|
|
141
|
+
return [], [{"via": "usb", "state": _access_state(error), "message": str(error)}]
|
|
142
|
+
for item in found:
|
|
143
|
+
if expected is not None and item["serial"] != expected:
|
|
144
|
+
if not identify or (port is None and item["serial"] is not None):
|
|
145
|
+
continue
|
|
146
|
+
records.append(item)
|
|
147
|
+
if not identify:
|
|
148
|
+
continue
|
|
149
|
+
link = None
|
|
150
|
+
try:
|
|
151
|
+
link = open_usb(item["port"], expected, verify=True)
|
|
152
|
+
item.update(identity=dict(link.identity), serial=f"{link.identity['serial_number']:08X}",
|
|
153
|
+
serial_source="sdo", method="sdo", state="identified")
|
|
154
|
+
except (OSError, RuntimeError, TimeoutError) as error:
|
|
155
|
+
item["state"] = _access_state(error)
|
|
156
|
+
issues.append({"via": "usb", "port": item["port"], "state": item["state"], "message": str(error)})
|
|
157
|
+
finally:
|
|
158
|
+
if link is not None:
|
|
159
|
+
try:
|
|
160
|
+
link.close()
|
|
161
|
+
except Exception as error:
|
|
162
|
+
issues.append({"via": "usb", "port": item["port"], "state": "partial",
|
|
163
|
+
"message": MESSAGES["close_failed"].format(reason=error)})
|
|
164
|
+
return records, issues
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# USB 枚举、身份核对和升级重连的宿主提示。
|
|
2
|
+
[message]
|
|
3
|
+
invalid_serial = "设备序列号须为非零的 8 位十六进制数"
|
|
4
|
+
not_found = "未找到匹配的 USB 候选,请用 devices 查看端口和序列号"
|
|
5
|
+
ambiguous = "USB 候选不唯一,请用 --port 指定:{ports}"
|
|
6
|
+
identity_mismatch = "USB 身份不符:期望 {expected},实际 {actual}"
|
|
7
|
+
not_eha = "USB 设备产品身份不符:厂商 0x{vendor:08X},产品 0x{product:08X}"
|
|
8
|
+
zero_serial = "设备序列号为 0,无法按身份自动选择"
|
|
9
|
+
deadline = "USB 身份读取已超过截止时间"
|
|
10
|
+
reconnect_timeout = "复位后 {timeout:g} s 内未确认原设备从槽 {target} 运行;最后观测:{last}"
|
|
11
|
+
reconnect_empty = "尚未发现原设备"
|
|
12
|
+
reconnect_slot = "槽 {slot},版本 0x{version:06X}"
|
|
13
|
+
reconnect_invalid_slot = "设备报告非法运行槽 {slot}"
|
|
14
|
+
confirmed_unavailable = "已观察到目标槽运行,未能读取固件确认状态:{reason}"
|
|
15
|
+
close_failed = "关闭 USB 连接失败:{reason}"
|
|
16
|
+
invalid_target = "升级目标槽须为 A 或 B"
|
ehatool/web/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief ehatool web 的服务端:设备会话、记录与 HTTP/WebSocket 接口。
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def register(sub):
|
|
8
|
+
p = sub.add_parser("web", help="本机 WebUI:在浏览器中查看状态、改参数、标定电机、示波与试验(只监听 127.0.0.1)")
|
|
9
|
+
p.add_argument("--http-port", type=int, default=8765, help="服务端口")
|
|
10
|
+
p.add_argument("--no-browser", action="store_true", help="不自动打开浏览器")
|
|
11
|
+
p.add_argument("--records-dir", help="记录目录;缺省为系统的用户数据目录")
|
|
12
|
+
p.set_defaults(func=serve, device=False)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def serve(args):
|
|
16
|
+
import webbrowser
|
|
17
|
+
import uvicorn
|
|
18
|
+
|
|
19
|
+
from .server import App, PING_INTERVAL_S, PING_TIMEOUT_S, create_app
|
|
20
|
+
|
|
21
|
+
app = App(args.http_port, args.records_dir)
|
|
22
|
+
api = create_app(app)
|
|
23
|
+
url = f"http://127.0.0.1:{args.http_port}/"
|
|
24
|
+
print(f"WebUI:{url}(Ctrl-C 结束)")
|
|
25
|
+
if not args.no_browser:
|
|
26
|
+
webbrowser.open(url)
|
|
27
|
+
uvicorn.run(api, host="127.0.0.1", port=args.http_port, log_level="warning",
|
|
28
|
+
ws_ping_interval=PING_INTERVAL_S, ws_ping_timeout=PING_TIMEOUT_S)
|
ehatool/web/brt_sim.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief Web 的 BRT27 模拟任务:只启动已有 CLI 的具名子命令,适配器占用持续到子进程退出。
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import copy
|
|
8
|
+
import os
|
|
9
|
+
import pathlib
|
|
10
|
+
import signal
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
|
|
16
|
+
from .. import brt27_sim
|
|
17
|
+
from .session import Busy
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
## @brief 同时最多一个模拟任务。停止先请求 CLI 收尾,未退出时升级为终止与强制回收。
|
|
21
|
+
class BrtSimulator:
|
|
22
|
+
def __init__(self, operation):
|
|
23
|
+
self.operation = operation
|
|
24
|
+
self.lock = threading.RLock()
|
|
25
|
+
self.process = self.thread = self.job = None
|
|
26
|
+
|
|
27
|
+
def info(self):
|
|
28
|
+
with self.lock:
|
|
29
|
+
result = copy.deepcopy(self.job)
|
|
30
|
+
if result:
|
|
31
|
+
result["elapsed_s"] = max(0, (result.get("finished_at") or time.time()) - result["started_at"])
|
|
32
|
+
return result
|
|
33
|
+
|
|
34
|
+
def start(self, body):
|
|
35
|
+
params = {
|
|
36
|
+
"adapter": str(body.get("adapter") or ""),
|
|
37
|
+
"rate": int(body["bitrate"]),
|
|
38
|
+
"sensor_node": int(body.get("node", 1)),
|
|
39
|
+
"count": int(body.get("count", 10000)),
|
|
40
|
+
"swing": int(body.get("swing", 0)),
|
|
41
|
+
"hz": float(body.get("hz", 0.5)),
|
|
42
|
+
"period_us": int(body.get("period_us", 1000)),
|
|
43
|
+
"seconds": float(body.get("seconds", 10)),
|
|
44
|
+
}
|
|
45
|
+
for key, field in (("rate", "bitrate"), ("sensor_node", "node"), ("count", "count"),
|
|
46
|
+
("swing", "swing"), ("period_us", "period_us")):
|
|
47
|
+
value = body.get(field, params[key])
|
|
48
|
+
if isinstance(value, bool) or float(value) != params[key]:
|
|
49
|
+
raise ValueError(f"{field} 须为整数")
|
|
50
|
+
brt27_sim.validate(argparse.Namespace(**params))
|
|
51
|
+
with self.lock:
|
|
52
|
+
if self.process is not None:
|
|
53
|
+
raise Busy("BRT27 模拟仍在运行或收尾,先停止并等待退出")
|
|
54
|
+
lease = self.operation("can", params["adapter"])
|
|
55
|
+
lease.__enter__()
|
|
56
|
+
try:
|
|
57
|
+
command = [sys.executable, "-u", "-m", "ehatool.cli", "brt27-sim", params["adapter"], "--stop-on-stdin-close"]
|
|
58
|
+
for key, value in params.items():
|
|
59
|
+
if key != "adapter":
|
|
60
|
+
command.extend(("--" + key.replace("_", "-"), str(value)))
|
|
61
|
+
# 可编辑安装与直接从源码启动时,子进程使用同一份包,避免导入其他 checkout。
|
|
62
|
+
env = dict(os.environ)
|
|
63
|
+
source = str(pathlib.Path(__file__).resolve().parents[2])
|
|
64
|
+
env["PYTHONPATH"] = source + os.pathsep + env.get("PYTHONPATH", "")
|
|
65
|
+
self.process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
|
66
|
+
text=True, encoding="utf-8", errors="replace", env=env)
|
|
67
|
+
started_at = max(time.time(), self.job["started_at"] + 1e-6 if self.job else 0)
|
|
68
|
+
self.job = {"state": "running", "params": params, "started_at": started_at, "log": [],
|
|
69
|
+
"returncode": None, "error": None}
|
|
70
|
+
self.thread = threading.Thread(target=self._read, args=(self.process, lease), name="eha-brt27-sim", daemon=True)
|
|
71
|
+
self.thread.start()
|
|
72
|
+
except BaseException as failure:
|
|
73
|
+
if self.process is not None:
|
|
74
|
+
self.process.kill()
|
|
75
|
+
self.process.wait()
|
|
76
|
+
self.process.stdout.close()
|
|
77
|
+
self.process.stdin.close()
|
|
78
|
+
self.process = None
|
|
79
|
+
if self.job is not None:
|
|
80
|
+
self.job.update(state="failed", error=str(failure), finished_at=time.time())
|
|
81
|
+
lease.__exit__(None, None, None)
|
|
82
|
+
raise
|
|
83
|
+
return self.info()
|
|
84
|
+
|
|
85
|
+
def _read(self, process, lease):
|
|
86
|
+
error = None
|
|
87
|
+
try:
|
|
88
|
+
for line in process.stdout:
|
|
89
|
+
with self.lock:
|
|
90
|
+
self.job["log"].append(line.rstrip())
|
|
91
|
+
self.job["log"] = self.job["log"][-200:]
|
|
92
|
+
code = process.wait()
|
|
93
|
+
except Exception as failure:
|
|
94
|
+
error = str(failure)
|
|
95
|
+
process.kill()
|
|
96
|
+
code = process.wait()
|
|
97
|
+
finally:
|
|
98
|
+
process.stdout.close()
|
|
99
|
+
process.stdin.close()
|
|
100
|
+
lease.__exit__(None, None, None)
|
|
101
|
+
with self.lock:
|
|
102
|
+
stopped = self.job["state"] == "stopping"
|
|
103
|
+
state = "stopped" if stopped else "failed" if code else "done"
|
|
104
|
+
self.job.update(state=state, returncode=code, finished_at=time.time(),
|
|
105
|
+
error=error or (f"模拟器退出码 {code}" if code and not stopped else None))
|
|
106
|
+
self.process = None
|
|
107
|
+
|
|
108
|
+
def stop(self, expected=None):
|
|
109
|
+
with self.lock:
|
|
110
|
+
if expected and any(self.job is None or self.job.get(key) != value for key, value in expected.items()):
|
|
111
|
+
raise Busy("BRT27 模拟任务已改变,本次停止未执行;请核对当前任务")
|
|
112
|
+
process = self.process
|
|
113
|
+
thread = self.thread
|
|
114
|
+
if process is None:
|
|
115
|
+
return self.info()
|
|
116
|
+
self.job["state"] = "stopping"
|
|
117
|
+
if process.poll() is None:
|
|
118
|
+
try:
|
|
119
|
+
process.send_signal(signal.SIGINT)
|
|
120
|
+
except ProcessLookupError:
|
|
121
|
+
pass
|
|
122
|
+
for terminate in (process.terminate, process.kill):
|
|
123
|
+
try:
|
|
124
|
+
process.wait(timeout=2)
|
|
125
|
+
break
|
|
126
|
+
except subprocess.TimeoutExpired:
|
|
127
|
+
terminate()
|
|
128
|
+
process.wait(timeout=2)
|
|
129
|
+
thread.join(timeout=2)
|
|
130
|
+
return self.info()
|