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/cli.py
ADDED
|
@@ -0,0 +1,541 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief ehatool:EHA 主机工具的唯一入口。经 USB CDC 或对外 CAN 读写对象字典、运行与阶跃试验、示波、
|
|
5
|
+
## 固件升级与首次安装、CAN 联调检查;另有 EtherCAT 主站联调(ecat)、RAM 加载(ram-load)与控制台(console)。
|
|
6
|
+
##
|
|
7
|
+
## ehatool info
|
|
8
|
+
## ehatool get --list 压力
|
|
9
|
+
## ehatool --json get --explain error_code
|
|
10
|
+
## ehatool get --explain error_code
|
|
11
|
+
## ehatool set --describe soft_position_max_um
|
|
12
|
+
## ehatool get 0x6041
|
|
13
|
+
## ehatool set soft_position_max_um 90000
|
|
14
|
+
## ehatool dev on
|
|
15
|
+
## ehatool run --rpm 1500 --seconds 3
|
|
16
|
+
## ehatool step csp --start 50 --target 70 --seconds 2 --out step_csp
|
|
17
|
+
## ehatool sil step csp --start 50 --target 70 --sweep position_kp=400,600,800
|
|
18
|
+
## ehatool compare step_csp.csv kp_600.csv
|
|
19
|
+
## ehatool scope position_actual_um,motor_speed_rpm --rate 1000
|
|
20
|
+
## ehatool update build/hpm-integrated
|
|
21
|
+
## ehatool usb-check
|
|
22
|
+
## ehatool --can slcan:/dev/cu.usbmodem<序号> can-check
|
|
23
|
+
## ehatool brt27-sim slcan:/dev/cu.usbmodem<序号> --swing 2000
|
|
24
|
+
## ehatool can-sniff slcan:/dev/cu.usbmodem<序号> --rate 1000000 --seconds 5
|
|
25
|
+
## sudo ehatool ecat <网卡> --dc --target 70
|
|
26
|
+
## ehatool odrive status
|
|
27
|
+
## ehatool odrive watch
|
|
28
|
+
|
|
29
|
+
import argparse
|
|
30
|
+
import math
|
|
31
|
+
import pathlib
|
|
32
|
+
import struct
|
|
33
|
+
import sys
|
|
34
|
+
import time
|
|
35
|
+
|
|
36
|
+
from . import brt27_sim, can_sniff, console, ecat, experiment, motor, odrive, ram_load, scope, sil, update
|
|
37
|
+
from .workflows import cancheck, usbcheck
|
|
38
|
+
from . import web
|
|
39
|
+
from . import od as odmod
|
|
40
|
+
from .device.can import CanLink
|
|
41
|
+
from .diagnostics import decode_error_code
|
|
42
|
+
from .info import bit_names, print_info, read_info
|
|
43
|
+
from .output import DISPLAY, emit_json, object_attributes, print_object_detail, print_object_list, render_diagnostic
|
|
44
|
+
from .link import ABORT_DEVICE_STATE, COB_SCOPE, Device, LinkDriver, SdoAbort, StreamLink, add_ack
|
|
45
|
+
|
|
46
|
+
MESSAGES = DISPLAY["cli"]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def cmd_info(dev, args):
|
|
50
|
+
info = read_info(dev)
|
|
51
|
+
if args.json:
|
|
52
|
+
return {"info": info}
|
|
53
|
+
print_info(info, sys.stdout)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
## @brief 把同一次构建中对应的镜像写入非运行槽并复位试运行;新镜像正常运行 10 s 后自动确认,否则回退。
|
|
57
|
+
def cmd_update(dev, args):
|
|
58
|
+
result = update.update_usb(dev, args.source, port=args.port, reset_after=not args.no_reset)
|
|
59
|
+
if result["running"] is not None:
|
|
60
|
+
dev.link = None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
## @brief 首次安装:设备不从槽启动时(HPM 经 ehatool ram-load,STM32 经调试口写入开发镜像),经 USB 写入 bootloader 与槽 A
|
|
64
|
+
## 并复位。bootloader 区只在不从槽启动时可写(firmware/rtos/updater.h)。
|
|
65
|
+
def cmd_install(dev, args):
|
|
66
|
+
update.install_usb(dev, args.source, reset_after=not args.no_reset)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def object_record(obj, *, detailed=False):
|
|
70
|
+
record = dict(obj) if detailed else {"name": obj["name"], "index": obj["index"]}
|
|
71
|
+
record.pop("sub", None)
|
|
72
|
+
record["subindex"] = obj["sub"]
|
|
73
|
+
return record
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def exit_json(error, exit_status=1, **fields):
|
|
77
|
+
emit_json({"ok": False, "error": error, **fields}, sys.stdout)
|
|
78
|
+
raise SystemExit(exit_status)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class CommandParser(argparse.ArgumentParser):
|
|
82
|
+
def error(self, message):
|
|
83
|
+
# 参数解析也可能在解析器取得 --json 之前失败。双横线之后的同名字符串是位置参数。
|
|
84
|
+
for token in sys.argv[1:]:
|
|
85
|
+
if token == "--":
|
|
86
|
+
break
|
|
87
|
+
if token == "--json":
|
|
88
|
+
exit_json({"kind": "usage", "message": message}, 2)
|
|
89
|
+
super().error(message)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
## @brief 在开链路前完成 get/set 的离线查询;在线操作将准确的对象记录交给 Device。
|
|
93
|
+
def prepare_object_command(args, parser, od):
|
|
94
|
+
if args.object is not None and (args.list_query is not None or args.describe is not None):
|
|
95
|
+
parser.error(MESSAGES["extra_arguments"])
|
|
96
|
+
# 型号决定哪些对象存在、默认值是多少;连接设备前还没有型号时,列出与查看都须由 --model 指定。
|
|
97
|
+
if (args.list_query is not None or args.describe is not None) and od.model is None:
|
|
98
|
+
models = "、".join(model["name"] for model in od.models) or "—"
|
|
99
|
+
raise KeyError(MESSAGES["model_required"].format(models=models))
|
|
100
|
+
if args.list_query is not None:
|
|
101
|
+
objects = od.search(args.list_query, writable=args.cmd == "set")
|
|
102
|
+
if not objects:
|
|
103
|
+
key = "no_writable_match" if args.cmd == "set" else "no_match"
|
|
104
|
+
raise KeyError(MESSAGES[key].format(query=args.list_query))
|
|
105
|
+
if args.json:
|
|
106
|
+
return {"objects": [object_record(obj, detailed=True) for obj in objects]}
|
|
107
|
+
print_object_list(objects, sys.stdout)
|
|
108
|
+
return {}
|
|
109
|
+
key = args.describe if args.describe is not None else args.object
|
|
110
|
+
if key is None:
|
|
111
|
+
parser.error(MESSAGES["object_required"])
|
|
112
|
+
obj = od.lookup(key)
|
|
113
|
+
if args.describe is not None:
|
|
114
|
+
if args.json:
|
|
115
|
+
detail = {"object": object_record(obj, detailed=True)}
|
|
116
|
+
if obj["name"] == "error_code":
|
|
117
|
+
detail["errors"] = od.errors
|
|
118
|
+
return detail
|
|
119
|
+
print_object_detail(od, obj, sys.stdout)
|
|
120
|
+
return {}
|
|
121
|
+
if args.cmd == "get" and args.explain and obj["name"] != "error_code":
|
|
122
|
+
parser.error(MESSAGES["explain_only"])
|
|
123
|
+
if args.cmd == "set" and args.value is None:
|
|
124
|
+
if not args.json:
|
|
125
|
+
print_object_detail(od, obj, sys.stderr)
|
|
126
|
+
parser.error(MESSAGES["value_required"])
|
|
127
|
+
args.object = obj
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def cmd_get(dev, args):
|
|
132
|
+
value = dev.read(args.object)
|
|
133
|
+
diagnostic = decode_error_code(dev.od, value) if args.explain else None
|
|
134
|
+
if args.json:
|
|
135
|
+
result = {"object": object_record(args.object), "value": value}
|
|
136
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
137
|
+
result["value_status"] = "nonfinite"
|
|
138
|
+
if diagnostic is not None:
|
|
139
|
+
result["diagnostic"] = diagnostic
|
|
140
|
+
return result
|
|
141
|
+
print(render_diagnostic(diagnostic) if diagnostic is not None else value)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def cmd_set(dev, args):
|
|
145
|
+
dev.write(args.object, args.value)
|
|
146
|
+
if args.json:
|
|
147
|
+
return {"object": object_record(args.object)}
|
|
148
|
+
print("ok")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def cmd_params(dev, args):
|
|
152
|
+
for obj in dev.od.objects:
|
|
153
|
+
value = dev.read(obj)
|
|
154
|
+
flags = ("rw" if obj["access"] == "rw" else "ro") + (" persist" if obj.get("persist") else "") + \
|
|
155
|
+
(" 开发者" if obj.get("developer") else "")
|
|
156
|
+
shown = f"{value:.3f}" if obj["type"] == "f32" else str(value)
|
|
157
|
+
print(f"{odmod.format_address(obj['index'], obj['sub'])} {obj['name']:<28} {shown:>14} {obj.get('unit', ''):<6} {flags}")
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
## @brief 开发者模式(0x2009):on 进入、off 退出,只在驱动未运行时被接受;缺省只显示当前状态。
|
|
161
|
+
def cmd_dev(dev, args):
|
|
162
|
+
if args.action != "status":
|
|
163
|
+
try:
|
|
164
|
+
dev.set_developer(args.action == "on")
|
|
165
|
+
except SdoAbort as error:
|
|
166
|
+
if error.code != ABORT_DEVICE_STATE:
|
|
167
|
+
raise
|
|
168
|
+
sys.exit(f"{error}\n切换开发者模式要求驱动未运行。")
|
|
169
|
+
print("开发者模式:" + ("开启" if dev.developer() else "关闭(用户模式)"))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
## @brief 以 100 Hz 发送控制命令:取得控制权 → 使能 → 跟随转速 → 快停 → 断电。模式 -2 需开发者模式,取得控制权后自行进入。
|
|
173
|
+
def cmd_run(dev, args):
|
|
174
|
+
dev.acquire(args.ack)
|
|
175
|
+
with dev.developer_session("模式 -2"):
|
|
176
|
+
motor.run_motor_speed(dev, args.rpm, args.seconds)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
## @brief 自动标定(换电机后用,流程见 motor.calibrate):结果由设备写入 0x2300、0x2302、0x2303,本工具只读出显示;
|
|
180
|
+
## --save 时再写 0x1010 保存。
|
|
181
|
+
def cmd_calibrate(dev, args):
|
|
182
|
+
try:
|
|
183
|
+
result = motor.calibrate(dev, args.ack, args.timeout)
|
|
184
|
+
except motor.CalibrationFailed as error:
|
|
185
|
+
sys.exit(str(error))
|
|
186
|
+
for name in ("motor_pole_pairs", "motor_resistance_ohm", "motor_inductance_mh"):
|
|
187
|
+
print(f" {name} = {result['after'][name]}")
|
|
188
|
+
if args.save:
|
|
189
|
+
dev.write("store_parameters", 0x65766173)
|
|
190
|
+
print("已保存(0x1010)")
|
|
191
|
+
else:
|
|
192
|
+
print("尚未保存:确认后 ehatool set store_parameters 0x65766173")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
## @brief 阶跃试验(experiment.py,与 sil step、ecat step 同一试验定义、CSV 字段与指标):先取得控制权,再改动试验条件
|
|
196
|
+
## (--set、开发者模式、仿真外力),约 200 Hz 发送控制命令并记录反馈,结束时快停。时间取主机时间。
|
|
197
|
+
def cmd_step(dev, args):
|
|
198
|
+
driver = LinkDriver(dev)
|
|
199
|
+
channel = "can" if isinstance(dev.link, CanLink) else "usb"
|
|
200
|
+
experiment.execute(driver, args, {"driver": channel, "firmware": f"rev 0x{dev.read('revision'):08X}"})
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
## @brief 示波:经 USB 以 1000/分频 Hz 采样最多 8 个对象,写 CSV(装有 matplotlib 时另出 PNG)。
|
|
204
|
+
def cmd_scope(dev, args):
|
|
205
|
+
if not isinstance(dev.link, StreamLink):
|
|
206
|
+
sys.exit("示波流只经主机链路(USB 或串口)提供")
|
|
207
|
+
names = args.objects.split(",")
|
|
208
|
+
if not math.isfinite(args.rate) or args.rate <= 0:
|
|
209
|
+
raise ValueError("采样率须为正数")
|
|
210
|
+
divider = max(1, round(1000 / args.rate))
|
|
211
|
+
objs = scope.configure(dev, names, divider)
|
|
212
|
+
decoder = scope.Decoder(objs)
|
|
213
|
+
rows = []
|
|
214
|
+
try:
|
|
215
|
+
end = time.monotonic() + args.seconds
|
|
216
|
+
while time.monotonic() < end:
|
|
217
|
+
sample = decoder.decode(dev.link.receive(COB_SCOPE, 0.1))
|
|
218
|
+
if sample is not None:
|
|
219
|
+
t, values, gap = sample
|
|
220
|
+
if gap and rows:
|
|
221
|
+
rows.append(((rows[-1][0] + t) / 2, [float("nan")] * len(objs)))
|
|
222
|
+
rows.append((t, values))
|
|
223
|
+
finally:
|
|
224
|
+
dev.write("scope_divider", 0)
|
|
225
|
+
if not rows:
|
|
226
|
+
sys.exit("没有收到示波样本")
|
|
227
|
+
t0 = rows[0][0]
|
|
228
|
+
names = [o["name"] for o in objs]
|
|
229
|
+
with open(f"{args.out}.csv", "w") as f:
|
|
230
|
+
f.write("t_s," + ",".join(names) + "\n")
|
|
231
|
+
for t_us, values in rows:
|
|
232
|
+
f.write(f"{t_us - t0:.6f}," + ",".join(str(v) for v in values) + "\n")
|
|
233
|
+
span = rows[-1][0] - t0
|
|
234
|
+
print(f"{decoder.samples} 个样本,{span:.2f} s,约 {decoder.samples / span if span else 0:.0f} Hz,丢帧 {decoder.gaps} 处;已写 {args.out}.csv")
|
|
235
|
+
try:
|
|
236
|
+
import matplotlib
|
|
237
|
+
matplotlib.use("Agg")
|
|
238
|
+
import matplotlib.pyplot as plt
|
|
239
|
+
except ImportError:
|
|
240
|
+
return
|
|
241
|
+
t = [r[0] - t0 for r in rows]
|
|
242
|
+
fig, axes = plt.subplots(len(objs), 1, figsize=(8, 2.2 * len(objs)), sharex=True, squeeze=False)
|
|
243
|
+
for n, name in enumerate(names):
|
|
244
|
+
axes[n][0].plot(t, [r[1][n] for r in rows])
|
|
245
|
+
axes[n][0].set_ylabel(name, fontsize=8)
|
|
246
|
+
axes[-1][0].set_xlabel("t / s")
|
|
247
|
+
fig.tight_layout()
|
|
248
|
+
fig.savefig(f"{args.out}.png", dpi=110)
|
|
249
|
+
print(f"已写 {args.out}.png")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def main():
|
|
253
|
+
parser = CommandParser(
|
|
254
|
+
description="EHA 主机工具:经 USB CDC 或对外 CAN(CANopen)读写对象字典并驱动执行器。",
|
|
255
|
+
epilog="示例:ehatool get 0x6041;ehatool set store_parameters 0x65766173;"
|
|
256
|
+
"ehatool step csp --start 50 --target 70。各子命令用 <子命令> --help 查看参数。")
|
|
257
|
+
version = (pathlib.Path(__file__).resolve().parent / "VERSION").read_text().strip()
|
|
258
|
+
parser.add_argument("--version", action="version", version=f"ehatool {version}(与固件、对象字典同一产品版本)")
|
|
259
|
+
json_help = MESSAGES["json_help"]
|
|
260
|
+
parser.add_argument("--json", action="store_true", help=json_help)
|
|
261
|
+
parser.add_argument("--port", help="主机链路的串口(USB CDC 或 UART),缺省自动查找 USB 1209:0001")
|
|
262
|
+
parser.add_argument("--baud", type=int, help="主机链路为 UART 时的波特率;USB CDC 不需要")
|
|
263
|
+
parser.add_argument("--can", metavar="接口:通道", help="改用对外 CAN(CANopen),例如 slcan:/dev/cu.usbmodem<序号>")
|
|
264
|
+
parser.add_argument("--via", choices=("usb", "can", "ecat"), help=MESSAGES["via_help"])
|
|
265
|
+
parser.add_argument("--serial", help=MESSAGES["serial_help"])
|
|
266
|
+
parser.add_argument("--node", type=int, default=None, help="CAN 节点号;缺省 1,devices 缺省列全部节点")
|
|
267
|
+
parser.add_argument("--bitrate", type=int, default=None, help="CAN 仲裁段速率 bit/s,须与当前总线一致")
|
|
268
|
+
parser.add_argument("--data-bitrate", type=int, default=None, help="CAN FD 数据段速率 bit/s;0 按经典 CAN 打开")
|
|
269
|
+
parser.add_argument("--model", dest="od_model", metavar="型号",
|
|
270
|
+
help="离线查询(get/set --list、--describe)所用的型号,取 od/eha_od.toml 的 [[model]];"
|
|
271
|
+
"连上设备后按设备身份(0x1018)选型号,与此不符时以设备为准并提示")
|
|
272
|
+
sub = parser.add_subparsers(dest="cmd", required=True, metavar="子命令")
|
|
273
|
+
devices = sub.add_parser("devices", help=MESSAGES["devices_help"])
|
|
274
|
+
devices.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help=json_help)
|
|
275
|
+
devices.add_argument("--probe", action="store_true", help=MESSAGES["probe_help"])
|
|
276
|
+
devices.add_argument("--identify", action="store_true", help=MESSAGES["identify_help"])
|
|
277
|
+
devices.add_argument("--ifname", help=MESSAGES["ifname_help"])
|
|
278
|
+
devices.set_defaults(device=False)
|
|
279
|
+
info = sub.add_parser("info", help="设备标识与状态、固件运行槽与两槽版本、参数来源")
|
|
280
|
+
info.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help=json_help)
|
|
281
|
+
info.set_defaults(func=cmd_info)
|
|
282
|
+
for name, help_text, func in (("get", "读一个对象;离线查询可读对象", cmd_get),
|
|
283
|
+
("set", "写一个对象;离线查询可写对象", cmd_set)):
|
|
284
|
+
p = sub.add_parser(name, help=help_text)
|
|
285
|
+
p.add_argument("--json", action="store_true", default=argparse.SUPPRESS, help=json_help)
|
|
286
|
+
query = p.add_mutually_exclusive_group()
|
|
287
|
+
query.add_argument("--list", dest="list_query", nargs="?", const="", metavar="关键词",
|
|
288
|
+
help="离线列出对象,可按名称、说明或地址筛选")
|
|
289
|
+
query.add_argument("--describe", metavar="对象", help="离线显示准确名称或地址对应的完整说明")
|
|
290
|
+
if name == "get":
|
|
291
|
+
query.add_argument("--explain", action="store_true", help="读取 error_code(0x603F)并解释本次返回的故障/保护码")
|
|
292
|
+
p.add_argument("object", nargs="?", help="对象名或 index[:sub],例如 statusword、0x6041、0x1018:2")
|
|
293
|
+
if name == "set":
|
|
294
|
+
p.add_argument("value", nargs="?", help="新值,按对象类型解析,整数可用 0x 前缀;省略时显示详情")
|
|
295
|
+
p.set_defaults(func=func)
|
|
296
|
+
sub.add_parser("params", help="列出全部对象及当前值、单位与属性(开发者级对象另有标注)").set_defaults(func=cmd_params)
|
|
297
|
+
p = sub.add_parser("dev", help="开发者模式(0x2009):on 进入、off 退出,缺省显示状态;只在驱动未运行时可切换,复位后回到用户模式")
|
|
298
|
+
p.add_argument("action", nargs="?", choices=["on", "off", "status"], default="status")
|
|
299
|
+
p.set_defaults(func=cmd_dev)
|
|
300
|
+
p = sub.add_parser("step", help="阶跃试验:经 USB 或 CAN 运行,记录 CSV 与指标(与 sil step、ecat step 相同)")
|
|
301
|
+
experiment.add_step_arguments(p)
|
|
302
|
+
add_ack(p)
|
|
303
|
+
p.set_defaults(func=cmd_step)
|
|
304
|
+
p = sub.add_parser("scope", help="USB 示波:按给定频率采样最多 8 个对象,写 CSV/PNG")
|
|
305
|
+
p.add_argument("objects", help="对象名或 index[:sub],逗号分隔,例如 position_actual_um,motor_speed_rpm")
|
|
306
|
+
p.add_argument("--rate", type=float, default=1000.0, help="采样率 Hz(1000/整数分频)")
|
|
307
|
+
p.add_argument("--seconds", type=float, default=2.0, help="记录时间 s")
|
|
308
|
+
p.add_argument("--out", default="scope", help="输出文件前缀")
|
|
309
|
+
p.set_defaults(func=cmd_scope)
|
|
310
|
+
p = sub.add_parser("update", help="经主机链路(USB 或串口)升级固件:写入非运行槽并复位试运行")
|
|
311
|
+
p.add_argument("source", help="发布目录(含 manifest.toml,按设备型号选镜像)或构建目录,例如 build/hpm-integrated")
|
|
312
|
+
p.add_argument("--no-reset", action="store_true", help="写入后不复位")
|
|
313
|
+
p.set_defaults(func=cmd_update)
|
|
314
|
+
p = sub.add_parser("install", help="首次安装(设备运行非槽开发镜像,0x2020 = 255):经主机链路先写槽 A、再写 bootloader 并复位")
|
|
315
|
+
p.add_argument("source", help="发布目录(含 manifest.toml)或构建目录,例如 build/hpm-integrated")
|
|
316
|
+
p.add_argument("--no-reset", action="store_true", help="写入后不复位")
|
|
317
|
+
p.set_defaults(func=cmd_install)
|
|
318
|
+
p = sub.add_parser("run", help="电机转速模式(-2,期间自行进入开发者模式)运行一段时间后快停")
|
|
319
|
+
p.add_argument("--rpm", type=float, default=1000.0, help="目标电机转速 rpm")
|
|
320
|
+
p.add_argument("--seconds", type=float, default=2.0, help="运行时间 s")
|
|
321
|
+
add_ack(p)
|
|
322
|
+
p.set_defaults(func=cmd_run)
|
|
323
|
+
p = sub.add_parser("calibrate", help="换电机后自动标定极对数、线电阻、线电感与编码器零点(模式 -2,电机会转动)")
|
|
324
|
+
p.add_argument("--timeout", type=float, default=10.0, help="等待标定完成的时间 s")
|
|
325
|
+
p.add_argument("--save", action="store_true", help="标定完成后保存参数(0x1010)")
|
|
326
|
+
add_ack(p)
|
|
327
|
+
p.set_defaults(func=cmd_calibrate)
|
|
328
|
+
p = sub.add_parser("compare", help="叠加对比试验记录(step、sil step、ecat step 的 CSV),打印各自的指标")
|
|
329
|
+
p.add_argument("csv", nargs="+", help="试验记录")
|
|
330
|
+
p.add_argument("--band", type=float, default=None, help="调节时间的绝对带宽;缺省为阶跃量的 2%%")
|
|
331
|
+
p.add_argument("--out", default="compare.png", help="叠图文件")
|
|
332
|
+
p.set_defaults(func=lambda args: experiment.compare(args.csv, args.out, args.band), device=False)
|
|
333
|
+
for module in (usbcheck, cancheck, sil, ecat, ram_load, console, brt27_sim, can_sniff, odrive, web):
|
|
334
|
+
module.register(sub)
|
|
335
|
+
args = parser.parse_args()
|
|
336
|
+
if args.json and args.cmd not in ("info", "get", "set", "devices"):
|
|
337
|
+
parser.error(MESSAGES["json_commands"])
|
|
338
|
+
validate_selectors(args, parser)
|
|
339
|
+
|
|
340
|
+
try:
|
|
341
|
+
if args.cmd == "devices":
|
|
342
|
+
from .discovery import scan_devices
|
|
343
|
+
from .output import print_devices
|
|
344
|
+
result = scan_devices(args)
|
|
345
|
+
failed = result.get("status") in ("busy", "unavailable")
|
|
346
|
+
if failed and args.json:
|
|
347
|
+
message = MESSAGES["discovery_" + result["status"]]
|
|
348
|
+
exit_json({"kind": "device_access", "message": message}, **result)
|
|
349
|
+
if not args.json:
|
|
350
|
+
print_devices(result, sys.stdout)
|
|
351
|
+
if failed:
|
|
352
|
+
raise SystemExit(1)
|
|
353
|
+
elif not getattr(args, "device", True):
|
|
354
|
+
args.func(args)
|
|
355
|
+
return
|
|
356
|
+
else:
|
|
357
|
+
result = execute_device_command(args, sub.choices[args.cmd])
|
|
358
|
+
except (Exception, KeyboardInterrupt) as error:
|
|
359
|
+
report_failure(args, error)
|
|
360
|
+
if args.json:
|
|
361
|
+
emit_json({"ok": True, **result}, sys.stdout)
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def report_failure(args, error):
|
|
365
|
+
status = 1
|
|
366
|
+
if isinstance(error, SdoAbort):
|
|
367
|
+
detail = dict(error.diagnostic)
|
|
368
|
+
if args.json:
|
|
369
|
+
message = None
|
|
370
|
+
else:
|
|
371
|
+
message = str(error)
|
|
372
|
+
if obj := detail.get("object"):
|
|
373
|
+
message += "\n" + MESSAGES["object_hint"].format(**obj, attributes=object_attributes(obj))
|
|
374
|
+
if hint := detail.get("hint_zh"):
|
|
375
|
+
message += "\n" + hint
|
|
376
|
+
else:
|
|
377
|
+
message = str(error)
|
|
378
|
+
if isinstance(error, KeyboardInterrupt):
|
|
379
|
+
status, kind, message = 130, "interrupted", MESSAGES["interrupted"]
|
|
380
|
+
elif isinstance(error, KeyError):
|
|
381
|
+
kind, message = "unknown_object", str(error.args[0])
|
|
382
|
+
elif isinstance(error, TimeoutError):
|
|
383
|
+
kind = "timeout"
|
|
384
|
+
elif isinstance(error, (struct.error, OverflowError, ValueError)):
|
|
385
|
+
kind, message = "invalid_value", MESSAGES["invalid_value"].format(reason=message)
|
|
386
|
+
elif isinstance(error, (OSError, RuntimeError, ImportError)) or isinstance(
|
|
387
|
+
error, getattr(sys.modules.get("can"), "CanError", ())):
|
|
388
|
+
kind = "device_access"
|
|
389
|
+
else:
|
|
390
|
+
if not args.json:
|
|
391
|
+
raise error
|
|
392
|
+
kind = "unexpected_error"
|
|
393
|
+
detail = {"kind": kind, "message": message}
|
|
394
|
+
if notes := getattr(error, "__notes__", None):
|
|
395
|
+
detail["cleanup_error"] = "\n".join(notes)
|
|
396
|
+
if not args.json:
|
|
397
|
+
message += "\n" + detail["cleanup_error"]
|
|
398
|
+
if args.json:
|
|
399
|
+
exit_json(detail, status)
|
|
400
|
+
print(message, file=sys.stderr)
|
|
401
|
+
raise SystemExit(status)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
## @brief 在任何传输打开前核对命令、通道与显式选择条件。
|
|
405
|
+
def validate_selectors(args, parser):
|
|
406
|
+
if args.serial is not None:
|
|
407
|
+
serial = args.serial.removeprefix("0x").removeprefix("0X")
|
|
408
|
+
if len(serial) != 8 or any(char not in "0123456789abcdefABCDEF" for char in serial):
|
|
409
|
+
parser.error(MESSAGES["serial_invalid"])
|
|
410
|
+
if int(serial, 16) == 0:
|
|
411
|
+
parser.error(MESSAGES["serial_zero"])
|
|
412
|
+
args.serial = serial.upper()
|
|
413
|
+
if args.port and args.can:
|
|
414
|
+
parser.error(MESSAGES["port_can_conflict"])
|
|
415
|
+
if args.can:
|
|
416
|
+
interface, separator, channel = args.can.partition(":")
|
|
417
|
+
if not separator or not interface or not channel:
|
|
418
|
+
parser.error(MESSAGES["can_format"])
|
|
419
|
+
if args.node is not None and not 1 <= args.node <= 127:
|
|
420
|
+
parser.error(MESSAGES["node_range"])
|
|
421
|
+
if args.bitrate is not None and args.bitrate <= 0:
|
|
422
|
+
parser.error(MESSAGES["bitrate_positive"])
|
|
423
|
+
if args.data_bitrate is not None and args.data_bitrate < 0:
|
|
424
|
+
parser.error(MESSAGES["data_bitrate_nonnegative"])
|
|
425
|
+
implied = "can" if args.can else "usb" if args.port else None
|
|
426
|
+
if implied and args.via and implied != args.via:
|
|
427
|
+
parser.error(MESSAGES["selector_conflict"])
|
|
428
|
+
via = args.via or implied
|
|
429
|
+
can_options = any(value is not None for value in (args.node, args.bitrate, args.data_bitrate))
|
|
430
|
+
selectors = bool(via or args.serial or can_options)
|
|
431
|
+
if args.cmd in ("console", "ram-load", "sil", "compare", "brt27-sim"):
|
|
432
|
+
if selectors:
|
|
433
|
+
parser.error(MESSAGES["selector_unsupported"].format(command=args.cmd))
|
|
434
|
+
return
|
|
435
|
+
if args.cmd == "ecat":
|
|
436
|
+
if args.slave is not None and (args.slave < 0 or (args.ifname == "auto" and args.slave != 0)):
|
|
437
|
+
parser.error(MESSAGES["slave_range"])
|
|
438
|
+
if via not in (None, "ecat") or can_options:
|
|
439
|
+
parser.error(MESSAGES["ecat_only"])
|
|
440
|
+
return
|
|
441
|
+
if args.cmd == "devices":
|
|
442
|
+
if args.ifname and via not in (None, "ecat"):
|
|
443
|
+
parser.error(MESSAGES["ifname_only"])
|
|
444
|
+
if args.ifname and not via:
|
|
445
|
+
args.via = via = "ecat"
|
|
446
|
+
if args.probe and (via not in (None, "ecat") or can_options):
|
|
447
|
+
parser.error(MESSAGES["probe_only"])
|
|
448
|
+
if can_options and via not in (None, "can"):
|
|
449
|
+
parser.error(MESSAGES["can_selector_conflict"])
|
|
450
|
+
return
|
|
451
|
+
if via == "ecat":
|
|
452
|
+
parser.error(MESSAGES["ecat_command"])
|
|
453
|
+
effective = via or "usb"
|
|
454
|
+
if can_options and effective != "can":
|
|
455
|
+
parser.error(MESSAGES["can_options_require"])
|
|
456
|
+
if args.cmd in ("scope", "update", "install", "usb-check") and effective != "usb":
|
|
457
|
+
parser.error(MESSAGES["usb_only"].format(command=args.cmd))
|
|
458
|
+
if args.cmd == "can-check" and effective != "can":
|
|
459
|
+
parser.error(MESSAGES["can_only"])
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def open_command_link(args):
|
|
463
|
+
via = args.via or ("can" if args.can else "usb")
|
|
464
|
+
if via == "can":
|
|
465
|
+
from .device.can_discovery import resolve_can
|
|
466
|
+
return resolve_can(args)[0]
|
|
467
|
+
mutating = args.cmd in ("set", "run", "calibrate", "step", "scope", "update", "install", "usb-check") or (
|
|
468
|
+
args.cmd == "dev" and args.action != "status")
|
|
469
|
+
if args.serial is not None or (mutating and args.port is None):
|
|
470
|
+
from .usb_discovery import open_usb
|
|
471
|
+
return open_usb(args.port, args.serial, verify=True)
|
|
472
|
+
return StreamLink(args.port, baudrate=args.baud)
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
## @brief 按设备身份(0x1018 的厂商号与产品码)选型号,之后的对象访问只用该型号可见的对象。
|
|
476
|
+
## USB 发现已在同一句柄上读过身份时复用,否则先读这两项。产品码不在型号表中时只允许读,写入由 Device 拒绝;
|
|
477
|
+
## 所选对象不属于设备的型号时不发请求。
|
|
478
|
+
def adopt_device_model(dev, args):
|
|
479
|
+
warn = (lambda text: print(text, file=sys.stderr)) if not args.json else None
|
|
480
|
+
identity = getattr(dev.link, "identity", None)
|
|
481
|
+
if identity is None:
|
|
482
|
+
identity = {name: dev.read(name) for name in ("vendor_id", "product_code")}
|
|
483
|
+
dev.adopt_identity(identity, warn)
|
|
484
|
+
if dev.unknown_product is not None and not args.json:
|
|
485
|
+
print(dev.unknown_product, file=sys.stderr)
|
|
486
|
+
if isinstance(getattr(args, "object", None), dict):
|
|
487
|
+
try:
|
|
488
|
+
args.object = dev.od.lookup(args.object["name"])
|
|
489
|
+
except KeyError:
|
|
490
|
+
model = dev.od.model["name"] if dev.od.model else "?"
|
|
491
|
+
raise KeyError(MESSAGES["object_not_in_model"].format(name=args.object["name"], model=model)) from None
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def execute_device_command(args, parser):
|
|
495
|
+
od = odmod.ObjectDictionary(model=args.od_model) if args.od_model else odmod.ObjectDictionary()
|
|
496
|
+
if args.cmd in ("get", "set"):
|
|
497
|
+
offline = prepare_object_command(args, parser, od)
|
|
498
|
+
if offline is not None:
|
|
499
|
+
return offline
|
|
500
|
+
link = open_command_link(args)
|
|
501
|
+
dev = None
|
|
502
|
+
primary = None
|
|
503
|
+
try:
|
|
504
|
+
dev = Device(link, od)
|
|
505
|
+
adopt_device_model(dev, args)
|
|
506
|
+
try:
|
|
507
|
+
result = args.func(dev, args)
|
|
508
|
+
except SdoAbort as error:
|
|
509
|
+
if error.code == ABORT_DEVICE_STATE:
|
|
510
|
+
if args.cmd == "set" and args.object.get("pdo") != "rx":
|
|
511
|
+
error.diagnostic["object"] = object_record(args.object, detailed=True)
|
|
512
|
+
elif args.cmd != "get":
|
|
513
|
+
try:
|
|
514
|
+
note = dev.holder_note()
|
|
515
|
+
except Exception as cause:
|
|
516
|
+
note = MESSAGES["owner_read_failed"].format(reason=cause)
|
|
517
|
+
if note:
|
|
518
|
+
error.diagnostic["hint_zh"] = note
|
|
519
|
+
raise
|
|
520
|
+
except BaseException as error:
|
|
521
|
+
primary = error
|
|
522
|
+
raise
|
|
523
|
+
finally:
|
|
524
|
+
try:
|
|
525
|
+
current = dev.link if dev is not None else link
|
|
526
|
+
if current is not None:
|
|
527
|
+
current.close()
|
|
528
|
+
except Exception as close_error:
|
|
529
|
+
message = MESSAGES["close_failed"].format(reason=close_error)
|
|
530
|
+
if primary is not None:
|
|
531
|
+
primary.add_note(message)
|
|
532
|
+
elif args.json:
|
|
533
|
+
# 设备已应答,关闭失败不能抹掉已完成的读写结果。
|
|
534
|
+
exit_json({"kind": "close_failed", "message": message}, result=result)
|
|
535
|
+
else:
|
|
536
|
+
raise
|
|
537
|
+
return result
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
if __name__ == "__main__":
|
|
541
|
+
main()
|
ehatool/console.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief ehatool console:读调试口 UART(115200 8N1)。用 pyserial 在同一个打开的端口上设置波特率,
|
|
5
|
+
## 避免 macOS 上 stty 设置在端口关闭后失效。
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def register(sub):
|
|
12
|
+
p = sub.add_parser("console", help="读取调试口控制台 UART 并逐行打印(Ctrl-C 结束)")
|
|
13
|
+
p.add_argument("uart", help="调试口 UART,例如 /dev/cu.usbserial-<序号>(FT2232 的 B 通道)")
|
|
14
|
+
p.add_argument("--seconds", type=float, default=0.0, help="读取时长 s,0 为一直读")
|
|
15
|
+
p.set_defaults(func=run, device=False)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def run(args):
|
|
19
|
+
import serial
|
|
20
|
+
|
|
21
|
+
end = time.monotonic() + args.seconds if args.seconds > 0 else None
|
|
22
|
+
with serial.Serial(args.uart, 115200, timeout=0.2) as port:
|
|
23
|
+
try:
|
|
24
|
+
while end is None or time.monotonic() < end:
|
|
25
|
+
line = port.readline()
|
|
26
|
+
if line:
|
|
27
|
+
sys.stdout.write(line.decode(errors="replace"))
|
|
28
|
+
sys.stdout.flush()
|
|
29
|
+
except KeyboardInterrupt:
|
|
30
|
+
pass
|
|
31
|
+
|