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/link.toml
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
[message]
|
|
4
|
+
gs_usb_backend = "无法加载随 Python 包安装的 libusb,请检查当前平台的 libusb-package wheel"
|
|
5
|
+
deadline = "链路操作超过截止时间"
|
|
6
|
+
usb_short_write = "USB 帧未完整写入"
|
|
7
|
+
usb_busy = "{port} 已被{holder}占用;先在那边断开"
|
|
8
|
+
can_node = "CAN 节点号必须在 1–127"
|
|
9
|
+
can_backend = "CAN 后端与已选配置不符"
|
|
10
|
+
gs_usb_mode = "当前 gs_usb 后端只支持已知速率的经典 CAN 普通会话"
|
|
11
|
+
slcan_rate = "SLCAN 转接器不支持给定的仲裁段或数据段速率"
|
|
12
|
+
sdo_numeric_type = "SDO {address} 快速上传类型或长度不符"
|
|
13
|
+
sdo_expedited_command = "SDO 快速上传命令非法"
|
|
14
|
+
sdo_upload_limit = "SDO 上传超过长度上限"
|
|
15
|
+
sdo_segment_command = "SDO 分段上传起始命令非法"
|
|
16
|
+
sdo_segment_toggle = "SDO 分段上传 toggle 或长度不符"
|
|
17
|
+
sdo_segment_limit = "SDO 分段上传超过声明长度或上限"
|
|
18
|
+
sdo_segment_size = "SDO 分段上传实际长度与声明不符"
|
ehatool/live.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief 实时曲线:试验循环所在的进程把样本攒成每 50 ms 一批放进 multiprocessing 队列(逐个放会让队列的序列化线程
|
|
5
|
+
## 频繁抢占试验循环),绘图进程约每 50 ms 取空队列、重画一次,
|
|
6
|
+
## 滚动显示最近 10 s:目标与主响应、力与两腔压力、电机转速,状态与故障码在标题中。绘图只是旁路,全部样本仍由试验
|
|
7
|
+
## 进程写入 CSV;放进队列不等待,绘图跟不上时丢弃样本,不拖慢 1 kHz 循环。没有 matplotlib 时只提示、不显示。
|
|
8
|
+
|
|
9
|
+
import importlib.util
|
|
10
|
+
import multiprocessing
|
|
11
|
+
import queue
|
|
12
|
+
import time
|
|
13
|
+
|
|
14
|
+
WINDOW_S = 10.0
|
|
15
|
+
REDRAW_S = 0.05
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## @brief 绘图进程的入口:读到 None 即退出。
|
|
19
|
+
def _plot(samples, tracked, unit):
|
|
20
|
+
import matplotlib.pyplot as plt
|
|
21
|
+
|
|
22
|
+
from .cia402 import state_name
|
|
23
|
+
|
|
24
|
+
plt.ion()
|
|
25
|
+
fig, axes = plt.subplots(3, 1, figsize=(9, 7), sharex=True)
|
|
26
|
+
data = {k: [] for k in ("t_s", "target", tracked, "force_n", "pressure_a_mpa", "pressure_b_mpa", "motor_rpm")}
|
|
27
|
+
lines = {
|
|
28
|
+
"target": axes[0].plot([], [], "k--", linewidth=0.8, label="target")[0],
|
|
29
|
+
tracked: axes[0].plot([], [], label=tracked)[0],
|
|
30
|
+
"force_n": axes[1].plot([], [], label="force_n")[0],
|
|
31
|
+
"motor_rpm": axes[2].plot([], [], label="motor_rpm")[0],
|
|
32
|
+
}
|
|
33
|
+
twin = axes[1].twinx()
|
|
34
|
+
lines["pressure_a_mpa"] = twin.plot([], [], "g", linewidth=0.8, label="p_a MPa")[0]
|
|
35
|
+
lines["pressure_b_mpa"] = twin.plot([], [], "r", linewidth=0.8, label="p_b MPa")[0]
|
|
36
|
+
axes[0].set_ylabel(f"{tracked} ({unit})")
|
|
37
|
+
axes[1].set_ylabel("force N")
|
|
38
|
+
axes[2].set_ylabel("motor rpm")
|
|
39
|
+
axes[2].set_xlabel("t / s")
|
|
40
|
+
for ax in (axes[0], axes[1], twin, axes[2]):
|
|
41
|
+
ax.legend(loc="upper left", fontsize=7)
|
|
42
|
+
last = None
|
|
43
|
+
while plt.fignum_exists(fig.number):
|
|
44
|
+
done = False
|
|
45
|
+
try:
|
|
46
|
+
while True:
|
|
47
|
+
batch = samples.get_nowait()
|
|
48
|
+
if batch is None:
|
|
49
|
+
done = True
|
|
50
|
+
break
|
|
51
|
+
for sample in batch:
|
|
52
|
+
last = sample
|
|
53
|
+
for k, v in data.items():
|
|
54
|
+
v.append(sample[k])
|
|
55
|
+
except queue.Empty:
|
|
56
|
+
pass
|
|
57
|
+
if data["t_s"]:
|
|
58
|
+
start = data["t_s"][-1] - WINDOW_S
|
|
59
|
+
first = next(i for i, t in enumerate(data["t_s"]) if t >= start)
|
|
60
|
+
for v in data.values():
|
|
61
|
+
del v[:first]
|
|
62
|
+
for k, line in lines.items():
|
|
63
|
+
line.set_data(data["t_s"], data[k])
|
|
64
|
+
for ax in (axes[0], axes[1], twin, axes[2]):
|
|
65
|
+
ax.relim()
|
|
66
|
+
ax.autoscale_view()
|
|
67
|
+
axes[0].set_xlim(max(0.0, start), max(WINDOW_S, data["t_s"][-1]))
|
|
68
|
+
fig.suptitle(f"{state_name(last['statusword'])} 0x603F = 0x{last['error_code']:04X} t = {last['t_s']:.2f} s",
|
|
69
|
+
fontsize=9)
|
|
70
|
+
if done:
|
|
71
|
+
plt.ioff()
|
|
72
|
+
plt.show()
|
|
73
|
+
return
|
|
74
|
+
plt.pause(REDRAW_S)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Live:
|
|
78
|
+
def __init__(self, exp):
|
|
79
|
+
from .experiment import TRACKED, UNITS
|
|
80
|
+
|
|
81
|
+
self.process = None
|
|
82
|
+
if importlib.util.find_spec("matplotlib") is None:
|
|
83
|
+
print("未安装 matplotlib,不显示实时曲线")
|
|
84
|
+
return
|
|
85
|
+
context = multiprocessing.get_context("spawn")
|
|
86
|
+
self.samples = context.Queue(maxsize=200)
|
|
87
|
+
self.batch, self.flush_at = [], 0.0
|
|
88
|
+
self.process = context.Process(target=_plot, args=(self.samples, TRACKED[exp.mode], UNITS[exp.mode]),
|
|
89
|
+
daemon=True)
|
|
90
|
+
self.process.start()
|
|
91
|
+
|
|
92
|
+
def put(self, sample):
|
|
93
|
+
if self.process is None:
|
|
94
|
+
return
|
|
95
|
+
self.batch.append(sample)
|
|
96
|
+
now = time.monotonic()
|
|
97
|
+
if now >= self.flush_at:
|
|
98
|
+
try:
|
|
99
|
+
self.samples.put_nowait(self.batch)
|
|
100
|
+
except queue.Full:
|
|
101
|
+
pass
|
|
102
|
+
self.batch, self.flush_at = [], now + REDRAW_S
|
|
103
|
+
|
|
104
|
+
## @brief 试验结束:通知绘图进程停止滚动,窗口留到用户关闭。
|
|
105
|
+
def close(self):
|
|
106
|
+
if self.process is not None:
|
|
107
|
+
try:
|
|
108
|
+
if self.batch:
|
|
109
|
+
self.samples.put(self.batch, timeout=1.0)
|
|
110
|
+
self.samples.put(None, timeout=1.0)
|
|
111
|
+
except queue.Full:
|
|
112
|
+
pass
|
ehatool/motor.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief 电机台架流程(CLI 与 WebUI 共用):换电机后的自动标定、模式 −2 的有界转速运行。
|
|
5
|
+
## 结果以返回值与异常给出;进度经 report 回调(CLI 为 print)。tick 在运动循环的每个周期调用一次,可抛出 Cancelled 让
|
|
6
|
+
## 循环按停机顺序收尾(与 Ctrl-C 相同)。
|
|
7
|
+
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
from .cia402 import MODES
|
|
11
|
+
from .link import DriveAborted
|
|
12
|
+
|
|
13
|
+
# 自动标定写入的对象(设备在 0x230C 完成后写入;绝对式编码器另写零点与方向)。
|
|
14
|
+
CALIBRATION_RESULTS = ("motor_pole_pairs", "motor_resistance_ohm", "motor_inductance_mh", "encoder_zero_counts",
|
|
15
|
+
"encoder_direction")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## @brief 自动标定未完成:state 为 0x230D,error 为 0x603F。
|
|
19
|
+
class CalibrationFailed(RuntimeError):
|
|
20
|
+
def __init__(self, state, error):
|
|
21
|
+
super().__init__(f"标定未完成:motor_calibration_state = {state},故障 0x{error:04X}"
|
|
22
|
+
f"(ehatool get error_code --explain 查看原因)")
|
|
23
|
+
self.state, self.error = state, error
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _read_results(dev):
|
|
27
|
+
return {name: dev.read(name) for name in CALIBRATION_RESULTS if name in dev.od.by_name}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
## @brief 自动标定:取得控制权、进入开发者模式,写 0x230C = 1 后以模式 −2、0 rpm 使能,等设备清除 0x230C(完成或失败)。
|
|
31
|
+
## 结果由设备写入对象字典,这里只读出。无论怎样退出(含取消、Ctrl-C、链路错误),未完成的请求都撤回,否则下一次以
|
|
32
|
+
## 模式 −2 使能的主站会意外触发标定。返回 {"before": {...}, "after": {...}};未完成时抛出 CalibrationFailed,取消时抛出
|
|
33
|
+
## 原来的 Cancelled(请求已撤回)。pending 可由宿主循环提供已按预算采集的请求状态,避免在同一控制间隙额外读取。
|
|
34
|
+
def calibrate(dev, ack=False, timeout=10.0, report=print, tick=None, pending=None):
|
|
35
|
+
dev.acquire(ack)
|
|
36
|
+
with dev.developer_session("自动标定"):
|
|
37
|
+
before = _read_results(dev)
|
|
38
|
+
dev.write("motor_calibration_request", 1)
|
|
39
|
+
cancelled = None
|
|
40
|
+
try:
|
|
41
|
+
report("已请求标定,使能后电机会转动;进度与含义见 ehatool get --describe motor_calibration_state")
|
|
42
|
+
try:
|
|
43
|
+
with dev.motion(MODES["motor_speed"], {"motor_rpm": 0.0}) as motion:
|
|
44
|
+
end = time.monotonic() + timeout
|
|
45
|
+
while time.monotonic() < end:
|
|
46
|
+
if not (pending() if pending is not None else dev.read("motor_calibration_request") != 0):
|
|
47
|
+
break
|
|
48
|
+
motion.step(motor_rpm=0.0)
|
|
49
|
+
if tick is not None:
|
|
50
|
+
tick()
|
|
51
|
+
time.sleep(min(0.02, getattr(dev, "live_timeout", None) or 0.02))
|
|
52
|
+
except DriveAborted as error:
|
|
53
|
+
from .link import Cancelled
|
|
54
|
+
if isinstance(error, Cancelled):
|
|
55
|
+
cancelled = error
|
|
56
|
+
report(str(error))
|
|
57
|
+
finished = dev.read("motor_calibration_request") == 0
|
|
58
|
+
error = dev.read("error_code")
|
|
59
|
+
finally:
|
|
60
|
+
if dev.read("motor_calibration_request") != 0:
|
|
61
|
+
dev.write("motor_calibration_request", 0)
|
|
62
|
+
if cancelled is not None:
|
|
63
|
+
raise cancelled
|
|
64
|
+
state = dev.read("motor_calibration_state")
|
|
65
|
+
if not finished or error != 0:
|
|
66
|
+
raise CalibrationFailed(state, error)
|
|
67
|
+
return {"before": before, "after": _read_results(dev)}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
## @brief 模式 −2 以 rpm 运行 seconds 秒后快停、断电(调用方已取得控制权并处于开发者模式)。on_feedback(fb) 每次收到反馈时
|
|
71
|
+
## 调用。
|
|
72
|
+
def run_motor_speed(dev, rpm, seconds, report=print, tick=None, on_feedback=None):
|
|
73
|
+
with dev.motion(MODES["motor_speed"], {"motor_rpm": 0.0}) as motion:
|
|
74
|
+
report(f"已使能,目标 {rpm} rpm")
|
|
75
|
+
end = time.monotonic() + seconds
|
|
76
|
+
next_print = 0.0
|
|
77
|
+
while time.monotonic() < end:
|
|
78
|
+
fb = motion.step(motor_rpm=rpm)
|
|
79
|
+
if fb is not None and on_feedback is not None:
|
|
80
|
+
on_feedback(fb)
|
|
81
|
+
if fb and time.monotonic() >= next_print:
|
|
82
|
+
report(f" {fb['state']:<18} {fb['motor_speed_rpm']:8.1f} rpm err=0x{fb['error_code']:04X}")
|
|
83
|
+
next_print = time.monotonic() + 0.25
|
|
84
|
+
if tick is not None:
|
|
85
|
+
tick()
|
|
86
|
+
time.sleep(min(0.01, getattr(dev, "live_timeout", None) or 0.01))
|
ehatool/od.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief 读取对象字典唯一来源 od/eha_od.toml,并由其推出 PDO 打包格式。
|
|
5
|
+
|
|
6
|
+
import copy
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import pathlib
|
|
10
|
+
import struct
|
|
11
|
+
import tomllib
|
|
12
|
+
|
|
13
|
+
# 包内的主机字典:生成器按型号算好的成品(产品码、修订号与型号默认值都已写入)。源 TOML 不进包。
|
|
14
|
+
PACKAGED_PATH = pathlib.Path(__file__).resolve().parent / "eha_od.json"
|
|
15
|
+
FMT = {"u8": "B", "i8": "b", "u16": "H", "i16": "h", "u32": "I", "i32": "i", "f32": "f"}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## @brief 故障码的反应类别([[error]] 的 reaction)及其在参考文档中的名称。
|
|
19
|
+
REACTIONS = {"hold": "保持", "fault": "故障", "enable": "使能前提(Fault)", "host": "按 0x6007"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
## @brief 位名统一为列表(下标为位号,没有名称的位为空串):TOML 中可写成列表或以位号为键的表。格式不对时返回 None。
|
|
23
|
+
def normalize_bits(bits):
|
|
24
|
+
if isinstance(bits, list):
|
|
25
|
+
return bits
|
|
26
|
+
if not isinstance(bits, dict) or not bits or not all(str(k).isdigit() for k in bits):
|
|
27
|
+
return None
|
|
28
|
+
out = [""] * (max(int(k) for k in bits) + 1)
|
|
29
|
+
for bit, name in bits.items():
|
|
30
|
+
out[int(bit)] = name
|
|
31
|
+
return out
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
## @brief 按型号名取型号表中的一项。
|
|
35
|
+
## @exception ValueError 型号表中没有该型号。
|
|
36
|
+
def find_model(models, name):
|
|
37
|
+
for model in models:
|
|
38
|
+
if model["name"] == name:
|
|
39
|
+
return model
|
|
40
|
+
known = "、".join(model["name"] for model in models) or "(型号表为空)"
|
|
41
|
+
raise ValueError(f"型号表中没有 {name!r},已知型号:{known}")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
## @brief 地址中的整数:无前缀按十进制解析,保留 0x、0o、0b 前缀。
|
|
45
|
+
def address_number(text):
|
|
46
|
+
text = text.strip()
|
|
47
|
+
return int(text, 10) if text.lstrip("+-").isdecimal() else int(text, 0)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def parse_address(key):
|
|
51
|
+
index, separator, sub = key.partition(":")
|
|
52
|
+
return address_number(index), address_number(sub) if separator else None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
## @brief CLI 可直接接受的对象地址,索引用十六进制,子索引用十进制。
|
|
56
|
+
def format_address(index, sub):
|
|
57
|
+
return f"0x{index:04X}:{sub:02d}"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
## @brief 设备身份不在型号表中:带原始身份,调用方据此显示并拒绝写入。
|
|
61
|
+
class UnknownProduct(RuntimeError):
|
|
62
|
+
def __init__(self, vendor_id, product_code):
|
|
63
|
+
self.identity = {"vendor_id": vendor_id, "product_code": product_code}
|
|
64
|
+
super().__init__(f"设备身份不在对象字典的型号表中(厂商 0x{vendor_id:08X},产品 0x{product_code:08X}),"
|
|
65
|
+
"不是本工具支持的 EHA 型号,拒绝写入")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
## @brief 型号无关的视图:各型号一致的字段保留,不一致的(默认值、特性)省略。
|
|
69
|
+
## 用于连接设备前按名字或地址找对象;数值与型号相关的字段须先选定型号。
|
|
70
|
+
def union_view(views):
|
|
71
|
+
merged, order = {}, []
|
|
72
|
+
for view in views.values():
|
|
73
|
+
for obj in view["objects"]:
|
|
74
|
+
name = obj["name"]
|
|
75
|
+
if name not in merged:
|
|
76
|
+
merged[name] = dict(obj)
|
|
77
|
+
order.append(name)
|
|
78
|
+
continue
|
|
79
|
+
kept = merged[name]
|
|
80
|
+
for key in [key for key in kept if key not in obj or obj[key] != kept[key]]:
|
|
81
|
+
del kept[key]
|
|
82
|
+
return [merged[name] for name in order]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
## @brief 对象字典:读取生成的主机字典(包内的多型号成品,或与 SIL 同目录的单一型号字典)。
|
|
86
|
+
## 型号的对象在生成阶段算好:特性筛选、产品码、修订号、设备绑定与型号参数文件的默认值都已写入,运行时不再读参数文件。
|
|
87
|
+
class ObjectDictionary:
|
|
88
|
+
## @param path 字典文件,缺省为包内成品。
|
|
89
|
+
## @param model 型号名。缺省得到型号无关的视图:只有各型号一致的字段,默认值仅在型号间相同时才有。
|
|
90
|
+
## @exception ValueError 对单一型号的字典指定了型号。
|
|
91
|
+
def __init__(self, path=None, model=None):
|
|
92
|
+
path = pathlib.Path(path if path is not None else PACKAGED_PATH)
|
|
93
|
+
self.path = path
|
|
94
|
+
# 摘要与解析使用同一次读取;按 LF 归一化,复制到 Windows 后的换行转换不改变配套关系。
|
|
95
|
+
source = path.read_bytes().replace(b"\r\n", b"\n")
|
|
96
|
+
self.source_sha256 = hashlib.sha256(source).hexdigest() if path.suffix == ".json" else None
|
|
97
|
+
data = json.loads(source) if path.suffix == ".json" else tomllib.loads(source.decode("utf-8"))
|
|
98
|
+
self.device = data["device"]
|
|
99
|
+
self.process_data = data["process_data"]
|
|
100
|
+
self.canopen = data["canopen"]
|
|
101
|
+
self.errors = data.get("error", [])
|
|
102
|
+
self.models = data.get("model", [])
|
|
103
|
+
self.model = None
|
|
104
|
+
if "models" in data:
|
|
105
|
+
# 包内成品:每个型号的对象已筛选、默认值已合并,主机只做读取。
|
|
106
|
+
self.models = [{"name": name, "product_code": view["product_code"]}
|
|
107
|
+
for name, view in data["models"].items()]
|
|
108
|
+
if model is None:
|
|
109
|
+
self.objects = union_view(data["models"])
|
|
110
|
+
else:
|
|
111
|
+
self.model = find_model(self.models, model)
|
|
112
|
+
view = data["models"][model]
|
|
113
|
+
self.objects = copy.deepcopy(view["objects"])
|
|
114
|
+
# 型号没有的外部设备对象不进过程数据,布局按型号取。
|
|
115
|
+
self.process_data = view["process_data"]
|
|
116
|
+
self.canopen = view["canopen"]
|
|
117
|
+
else:
|
|
118
|
+
self.objects = data["object"]
|
|
119
|
+
if model is not None:
|
|
120
|
+
raise ValueError(f"{path} 是单一型号的字典,不能再指定型号 {model!r}")
|
|
121
|
+
for obj in self.objects:
|
|
122
|
+
obj.setdefault("sub", 0)
|
|
123
|
+
if "bits" in obj:
|
|
124
|
+
obj["bits"] = normalize_bits(obj["bits"])
|
|
125
|
+
self.by_name = {obj["name"]: obj for obj in self.objects}
|
|
126
|
+
|
|
127
|
+
## @brief 按设备身份(0x1018:01、0x1018:02)在型号表中找型号;找不到返回 None。
|
|
128
|
+
## 构建生成的 JSON 没有型号表,身份须与字典自身的厂商号、产品码相同。
|
|
129
|
+
def model_for(self, vendor_id, product_code):
|
|
130
|
+
if vendor_id != self.by_name["vendor_id"]["default"]:
|
|
131
|
+
return None
|
|
132
|
+
if not self.models:
|
|
133
|
+
own = self.by_name["product_code"]["default"]
|
|
134
|
+
return {"name": None, "product_code": own} if product_code == own else None
|
|
135
|
+
return next((model for model in self.models if model["product_code"] == product_code), None)
|
|
136
|
+
|
|
137
|
+
## @brief 设备型号的字典:按身份找到型号,返回只含该型号对象的字典(已是该型号时返回自身)。
|
|
138
|
+
## @exception UnknownProduct 身份不在型号表中。
|
|
139
|
+
def for_identity(self, vendor_id, product_code):
|
|
140
|
+
model = self.model_for(vendor_id, product_code)
|
|
141
|
+
if model is None:
|
|
142
|
+
raise UnknownProduct(vendor_id, product_code)
|
|
143
|
+
if model["name"] is None or (self.model is not None and self.model["name"] == model["name"]):
|
|
144
|
+
return self
|
|
145
|
+
return ObjectDictionary(model=model["name"])
|
|
146
|
+
|
|
147
|
+
## @brief 按名字或 "index[:sub]" 查找对象;找不到时抛出 KeyError。
|
|
148
|
+
def lookup(self, key):
|
|
149
|
+
if key in self.by_name:
|
|
150
|
+
return self.by_name[key]
|
|
151
|
+
try:
|
|
152
|
+
index, sub = parse_address(key)
|
|
153
|
+
except ValueError:
|
|
154
|
+
raise KeyError(f"对象字典中没有 {key}") from None
|
|
155
|
+
for obj in self.objects:
|
|
156
|
+
if (obj["index"], obj["sub"]) == (index, sub or 0):
|
|
157
|
+
return obj
|
|
158
|
+
raise KeyError(f"对象字典中没有 {key}")
|
|
159
|
+
|
|
160
|
+
## @brief 离线搜索名称、说明或地址;空查询列出全部,writable 只保留可写对象。
|
|
161
|
+
def search(self, query="", writable=False):
|
|
162
|
+
query = query.strip()
|
|
163
|
+
objects = self.objects
|
|
164
|
+
if query:
|
|
165
|
+
try:
|
|
166
|
+
index, sub = parse_address(query)
|
|
167
|
+
except ValueError:
|
|
168
|
+
text = query.casefold()
|
|
169
|
+
objects = [obj for obj in objects
|
|
170
|
+
if text in obj["name"].casefold() or text in obj.get("desc", "").casefold()]
|
|
171
|
+
else:
|
|
172
|
+
objects = [obj for obj in objects if obj["index"] == index and (sub is None or obj["sub"] == sub)]
|
|
173
|
+
return sorted((obj for obj in objects if not writable or obj["access"] == "rw"),
|
|
174
|
+
key=lambda obj: (obj["index"], obj["sub"]))
|
|
175
|
+
|
|
176
|
+
## @brief PDO 的对象名列表与小端打包格式;direction 为 "rxpdo" 或 "txpdo"。
|
|
177
|
+
def pdo(self, direction):
|
|
178
|
+
return self.layout(self.process_data[direction])
|
|
179
|
+
|
|
180
|
+
## @brief CANopen 默认 PDO:[(对象名列表, 打包格式)];direction 为 "rpdo" 或 "tpdo"。
|
|
181
|
+
def canopen_pdos(self, direction):
|
|
182
|
+
return [self.layout(names) for names in self.canopen[direction]]
|
|
183
|
+
|
|
184
|
+
def layout(self, names):
|
|
185
|
+
return names, struct.Struct("<" + "".join(FMT[self.by_name[n]["type"]] for n in names))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
## @brief 对象值的字节数。
|
|
189
|
+
def size(obj):
|
|
190
|
+
return struct.calcsize(FMT[obj["type"]])
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
## @brief 把对象值打包为小端字节。
|
|
194
|
+
def pack(obj, value):
|
|
195
|
+
return struct.pack("<" + FMT[obj["type"]], value)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
## @brief 从小端字节解出对象值。
|
|
199
|
+
def unpack(obj, data, offset=0):
|
|
200
|
+
return struct.unpack_from("<" + FMT[obj["type"]], data, offset)[0]
|