ehatool 6.0.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. ehatool/VERSION +1 -0
  2. ehatool/__init__.py +4 -0
  3. ehatool/acceptance.py +92 -0
  4. ehatool/brt27.py +105 -0
  5. ehatool/brt27_sim.py +114 -0
  6. ehatool/calibration.py +111 -0
  7. ehatool/can_sniff.py +162 -0
  8. ehatool/cia402.py +31 -0
  9. ehatool/cli.py +541 -0
  10. ehatool/console.py +31 -0
  11. ehatool/device/__init__.py +4 -0
  12. ehatool/device/can.py +201 -0
  13. ehatool/device/can_discovery.py +387 -0
  14. ehatool/device/can_discovery.toml +19 -0
  15. ehatool/device/io.py +20 -0
  16. ehatool/devices.py +187 -0
  17. ehatool/diagnostics.py +58 -0
  18. ehatool/diagnostics.toml +208 -0
  19. ehatool/discovery.py +95 -0
  20. ehatool/display.toml +127 -0
  21. ehatool/ecat.py +520 -0
  22. ehatool/ecat.toml +17 -0
  23. ehatool/ecat_probe.py +401 -0
  24. ehatool/ecat_probe.toml +14 -0
  25. ehatool/eha_od.json +5871 -0
  26. ehatool/experiment.py +576 -0
  27. ehatool/image.py +70 -0
  28. ehatool/info.py +121 -0
  29. ehatool/info.toml +41 -0
  30. ehatool/install_host.py +243 -0
  31. ehatool/install_host.toml +27 -0
  32. ehatool/link.py +811 -0
  33. ehatool/link.toml +18 -0
  34. ehatool/live.py +112 -0
  35. ehatool/motor.py +86 -0
  36. ehatool/od.py +200 -0
  37. ehatool/odrive.py +450 -0
  38. ehatool/output.py +208 -0
  39. ehatool/ram_load.py +62 -0
  40. ehatool/scope.py +50 -0
  41. ehatool/sil.py +260 -0
  42. ehatool/update.py +320 -0
  43. ehatool/usb_discovery.py +164 -0
  44. ehatool/usb_discovery.toml +16 -0
  45. ehatool/web/__init__.py +28 -0
  46. ehatool/web/brt_sim.py +130 -0
  47. ehatool/web/canbus.py +95 -0
  48. ehatool/web/devices.py +216 -0
  49. ehatool/web/experiments.py +226 -0
  50. ehatool/web/job_params.py +208 -0
  51. ehatool/web/layout.toml +61 -0
  52. ehatool/web/longrun.py +430 -0
  53. ehatool/web/polling.py +41 -0
  54. ehatool/web/recipes/bench.toml +18 -0
  55. ehatool/web/records.py +333 -0
  56. ehatool/web/requests.py +254 -0
  57. ehatool/web/server.py +1051 -0
  58. ehatool/web/session.py +1552 -0
  59. ehatool/web/static/THIRD_PARTY_LICENSES.txt +133 -0
  60. ehatool/web/static/assets/ehapower-logo-Cr84XeX3.png +0 -0
  61. ehatool/web/static/assets/ehapower-mark-Con0OjPM.png +0 -0
  62. ehatool/web/static/assets/index-CdLvwKa-.css +1 -0
  63. ehatool/web/static/assets/index-DiLUQD1i.js +134 -0
  64. ehatool/web/static/index.html +16 -0
  65. ehatool/web/streams.py +64 -0
  66. ehatool/web/workspaces.py +124 -0
  67. ehatool/workflows/__init__.py +4 -0
  68. ehatool/workflows/cancheck.py +394 -0
  69. ehatool/workflows/cancheck.toml +9 -0
  70. ehatool/workflows/checks.py +43 -0
  71. ehatool/workflows/usbcheck.py +212 -0
  72. ehatool-6.0.0.dev0.dist-info/METADATA +38 -0
  73. ehatool-6.0.0.dev0.dist-info/RECORD +77 -0
  74. ehatool-6.0.0.dev0.dist-info/WHEEL +5 -0
  75. ehatool-6.0.0.dev0.dist-info/entry_points.txt +2 -0
  76. ehatool-6.0.0.dev0.dist-info/licenses/LICENSE +21 -0
  77. ehatool-6.0.0.dev0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,16 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <meta name="eha-token" content="__EHA_TOKEN__" />
7
+ <meta name="color-scheme" content="light dark" />
8
+ <link rel="icon" type="image/png" href="/assets/ehapower-mark-Con0OjPM.png" />
9
+ <title>EHA 工作台</title>
10
+ <script type="module" crossorigin src="/assets/index-DiLUQD1i.js"></script>
11
+ <link rel="stylesheet" crossorigin href="/assets/index-CdLvwKa-.css">
12
+ </head>
13
+ <body>
14
+ <div id="app"></div>
15
+ </body>
16
+ </html>
ehatool/web/streams.py ADDED
@@ -0,0 +1,64 @@
1
+ # Copyright The eha-firmware Contributors
2
+
3
+ ## @file
4
+ ## @brief 已经采集到的对象值按来源与时间基保留最近 60 s。读历史和推送批次与采集互不覆盖。
5
+
6
+ import collections
7
+ import threading
8
+ import time
9
+
10
+
11
+ class SampleBuffer:
12
+ def __init__(self, source, time_base, objects, span=60.0):
13
+ self.source, self.time_base, self.span = source, time_base, span
14
+ self.dynamic = objects is None
15
+ self.objects = list(objects or [])
16
+ self.allowed = set(self.objects)
17
+ self.started = time.monotonic()
18
+ self.rows, self.pending = collections.deque(), []
19
+ self.samples, self.gaps, self.gap_pending = 0, 0, False
20
+ self.lock = threading.Lock()
21
+
22
+ ## @brief values 只含本次实际读到的对象。无反馈只记待断线,在下个样本前插空,不复制旧读数。
23
+ def append(self, t, values):
24
+ with self.lock:
25
+ if values is None:
26
+ if not self.gap_pending:
27
+ self.gaps += 1
28
+ self.gap_pending = True
29
+ return
30
+ values = {name: value for name, value in values.items() if isinstance(value, (int, float)) and (self.dynamic or name in self.allowed)}
31
+ if self.dynamic:
32
+ for name in values:
33
+ if name not in self.allowed:
34
+ self.objects.append(name)
35
+ self.allowed.add(name)
36
+ if not values:
37
+ return
38
+ if self.rows and t <= self.rows[-1][0]:
39
+ # DC 重新起算或同来源时钟退回后,从新时刻重新积累,保持曲线时间有序。
40
+ self.rows.clear()
41
+ self.pending.clear()
42
+ self.started = time.monotonic()
43
+ if self.gap_pending and self.rows:
44
+ gap = ((self.rows[-1][0] + t) / 2, None)
45
+ self.rows.append(gap)
46
+ self.pending.append(gap)
47
+ self.gap_pending = False
48
+ row = (t, values)
49
+ self.rows.append(row)
50
+ self.pending.append(row)
51
+ self.samples += 1
52
+ while self.rows and self.rows[0][0] < t - self.span:
53
+ self.rows.popleft()
54
+
55
+ def payload(self, history=False):
56
+ with self.lock:
57
+ rows = list(self.rows) if history else self.pending
58
+ if not history:
59
+ self.pending = []
60
+ info = {"type": "samples", "id": f"{self.source}:{self.time_base}", "source": self.source,
61
+ "time_base": self.time_base, "started": self.started, "objects": self.objects.copy(),
62
+ "gaps": self.gaps, "samples": self.samples}
63
+ # 只在锁内复制引用。构造推送/保存所需数组留在锁外,采集线程持续追加。
64
+ return {**info, "t": [r[0] for r in rows], "values": [r[1] for r in rows]}
@@ -0,0 +1,124 @@
1
+ # Copyright The eha-firmware Contributors
2
+
3
+ ## @file
4
+ ## @brief 同一进程内的独立本机工作台。每个端口保持一个设备会话,共用记录目录和物理资源占用。
5
+
6
+ import socket
7
+ import threading
8
+ import time
9
+
10
+ from .session import Busy
11
+
12
+
13
+ class WorkspaceServers:
14
+ def __init__(self, root):
15
+ self.root = root
16
+ self.children = []
17
+ self.lock = threading.Lock()
18
+ self.closing = False
19
+
20
+ def _info(self, app):
21
+ session = app.session
22
+ return {"url": f"http://127.0.0.1:{app.port}/", "identity": session.identity if session else None,
23
+ "can_close": self._can_close(app)}
24
+
25
+ def _can_close(self, app):
26
+ with app.resource_lock:
27
+ simulator = getattr(app, "brt_sim", None)
28
+ jobs = [app.sil.info(), simulator.info() if simulator is not None else None]
29
+ workers = [app.console.thread, app.sil.thread, simulator.thread if simulator is not None else None]
30
+ return (app.parent is not None and not app.closing and app.session is None and not app.active_operations
31
+ and app.console.port is None and not any(t and t.is_alive() for t in workers)
32
+ and not any(j and j.get("state") in ("running", "stopping") for j in jobs)
33
+ and (simulator is None or simulator.process is None))
34
+
35
+ def list(self):
36
+ with self.lock:
37
+ return [self._info(self.root), *(self._info(app) for app, _, _ in self.children)]
38
+
39
+ ## @brief 只连接所选设备,不发使能或试验命令。返回独立端口的可再次打开 URL,响应丢失时可从实例列表恢复。
40
+ def open(self, connection, page="overview"):
41
+ import uvicorn
42
+ from .server import App, PING_INTERVAL_S, PING_TIMEOUT_S, create_app
43
+ if page not in ("overview", "experiments"):
44
+ raise ValueError("新工作台只能打开概览或试验页面")
45
+ if not isinstance(connection, dict):
46
+ raise ValueError("没有选择要连接的设备")
47
+ with self.lock:
48
+ if self.closing:
49
+ raise Busy("工作台服务正在关闭")
50
+ sock = socket.socket()
51
+ child = None
52
+ service = None
53
+ thread = None
54
+ try:
55
+ sock.bind(("127.0.0.1", 0))
56
+ sock.listen(128)
57
+ child = App(sock.getsockname()[1], od=self.root.od, link_factory=self.root.link_factory, shared_with=self.root)
58
+ config = uvicorn.Config(create_app(child), log_level="warning", timeout_graceful_shutdown=3,
59
+ ws_ping_interval=PING_INTERVAL_S, ws_ping_timeout=PING_TIMEOUT_S)
60
+ service = uvicorn.Server(config)
61
+ thread = threading.Thread(target=service.run, kwargs={"sockets": [sock]}, name="eha-workspace", daemon=True)
62
+ thread.start()
63
+ deadline = time.monotonic() + 5
64
+ while not service.started and thread.is_alive() and time.monotonic() < deadline:
65
+ time.sleep(0.01)
66
+ if not service.started:
67
+ raise RuntimeError("新工作台服务未能启动")
68
+ child.open(connection)
69
+ except BaseException as error:
70
+ if child is not None and child.session is not None and service is not None and service.started:
71
+ # 初始化结果未知时保留可断开的实例,不能遗失仍持有端口的会话。
72
+ self.children.append((child, service, thread))
73
+ raise RuntimeError(f"{error};请在 {self._info(child)['url']} 核对并断开") from error
74
+ if service is not None:
75
+ service.should_exit = True
76
+ if thread is not None:
77
+ thread.join(timeout=5)
78
+ if child is not None:
79
+ child.close()
80
+ sock.close()
81
+ raise
82
+ self.children.append((child, service, thread))
83
+ return {**self._info(child), "url": f"http://127.0.0.1:{child.port}/#{page}"}
84
+
85
+ ## @brief 显式回收已断开且没有后台任务的子工作台,其他标签仍可在列表中重新打开存续实例。
86
+ def close(self, port):
87
+ with self.lock:
88
+ entry = next((e for e in self.children if e[0].port == port), None)
89
+ if entry is None:
90
+ raise ValueError("没有找到该子工作台")
91
+ app, service, thread = entry
92
+ with app.resource_lock:
93
+ if not self._can_close(app):
94
+ raise Busy("先停止后台任务、关闭控制台并断开设备,再关闭工作台")
95
+ app.closing = True
96
+ service.should_exit = True
97
+ thread.join(timeout=25)
98
+ if thread.is_alive():
99
+ raise RuntimeError("工作台仍在关闭,请稍后核对")
100
+ self.children.remove(entry)
101
+ return {"closed": True}
102
+
103
+ ## @brief 根服务关闭时先通知全部子服务退出,再等待其会话、控制台与试验进程完成收尾。
104
+ def close_children(self):
105
+ with self.lock:
106
+ self.closing = True
107
+ children, self.children = self.children, []
108
+ for _, service, _ in children:
109
+ service.should_exit = True
110
+ errors = []
111
+ for app, service, thread in children:
112
+ thread.join(timeout=25)
113
+ if thread.is_alive():
114
+ service.force_exit = True
115
+ thread.join(timeout=5)
116
+ if thread.is_alive():
117
+ errors.append(f"端口 {app.port} 的子工作台尚未退出")
118
+ if app.session is not None:
119
+ try:
120
+ app.close()
121
+ except BaseException as error:
122
+ errors.append(f"端口 {app.port} 的设备尚未关闭:{error}")
123
+ if errors:
124
+ raise RuntimeError(";".join(errors))
@@ -0,0 +1,4 @@
1
+ # Copyright The eha-firmware Contributors
2
+
3
+ ## @file
4
+ ## @brief 主机联调与设备操作流程。
@@ -0,0 +1,394 @@
1
+ # Copyright The eha-firmware Contributors
2
+
3
+ ## @file
4
+ ## @brief ehatool can-check:对外 CAN(CANopen 从站)联调检查,逐项给出通过或失败。
5
+ ##
6
+ ## 检查项:标识与分段 SDO、SDO 中止码、NMT 与心跳、TPDO 事件定时器、SYNC 触发 TPDO、RPDO 控制(模式 -2)、
7
+ ## 主机失联时的 EMCY、0x1001 与故障复位、通信复位后重报 EMCY、0x1016 主机心跳保活(boot-up 与长度不符的心跳不算)、
8
+ ## CiA402 中止连接事件(NMT Stop、Reset Communication 当周期按 0x6007 反应,Pre-operational 不算,运行中 Reset Node
9
+ ## 只做通信复位、不复位芯片);--rates 另外逐个切换对外 CAN 速率(保存并复位),
10
+ ## 在每个速率下用经典帧与 CAN FD 帧(数据段加速)各访问一次 SDO,结束时写回开始时的速率并保存。
11
+ ## 运行模式 -2 会使能驱动(仿真构建门极关断),期间自行进入开发者模式、结束时退出;驱动保持未运行时才切换速率与复位。
12
+
13
+ import pathlib
14
+ import struct
15
+ import time
16
+ import tomllib
17
+
18
+ from ..cia402 import CW_DISABLE_VOLTAGE, CW_ENABLE, CW_FAULT_RESET, CW_SHUTDOWN
19
+ from ..device.can import CanLink
20
+ from ..link import Device, SdoAbort, add_ack
21
+ from ..update import RESET_SIGNATURE
22
+ from .checks import Check, abort_code, timed_stream as drive
23
+
24
+ NMT_START, NMT_STOP, NMT_PREOP, NMT_RESET_NODE, NMT_RESET_COMM = 0x01, 0x02, 0x80, 0x81, 0x82
25
+ ## @brief NMT 命令发出后仍可收到在途 PDO 的时长:设备处理延迟一个周期(1 ms)加适配器两向 USB 延迟。
26
+ NMT_LATENCY_S = 0.005
27
+ HB_BOOTUP, HB_OPERATIONAL, HB_PREOP = 0x00, 0x05, 0x7F
28
+ EMCY_HOST_TIMEOUT = 0x8130
29
+ SAVE = 0x65766173
30
+ # 速率组合 (仲裁段, 数据段);数据段 0 为纯经典 CAN。受 slcan 适配器限制,数据段只有 2/5 Mbit/s。
31
+ RATES = [(125000, 0), (250000, 0), (1000000, 0), (250000, 2000000), (500000, 5000000), (1000000, 5000000),
32
+ (500000, 2000000)]
33
+ with pathlib.Path(__file__).with_name("cancheck.toml").open("rb") as file:
34
+ MESSAGES = tomllib.load(file)
35
+
36
+
37
+ def raw_send(link, cob_id, data=b"", fd=False):
38
+ link.bus.send(link.can.Message(arbitration_id=cob_id, data=bytes(data), is_extended_id=False, is_fd=fd,
39
+ bitrate_switch=fd), timeout=0.3)
40
+
41
+
42
+ ## @brief 收集 seconds 内的帧,返回 [(时刻, 标识, 数据)]。
43
+ def collect(link, seconds, ids=None):
44
+ frames, end = [], time.monotonic() + seconds
45
+ while (remaining := end - time.monotonic()) > 0:
46
+ msg = link.bus.recv(remaining)
47
+ if (msg is not None and not (msg.is_extended_id or msg.is_remote_frame or msg.is_error_frame)
48
+ and (ids is None or msg.arbitration_id in ids)):
49
+ frames.append((time.monotonic(), msg.arbitration_id, bytes(msg.data)))
50
+ return frames
51
+
52
+
53
+ ## @brief 发一帧 SDO 请求并等应答;fd 为真时以 CAN FD 帧(BRS)发送。
54
+ def sdo_raw(link, request, fd=False, timeout=0.3):
55
+ end = time.monotonic() + timeout
56
+ link.bus.send(link.can.Message(arbitration_id=0x600 + link.node, data=bytes(request), is_extended_id=False,
57
+ is_fd=fd, bitrate_switch=fd), timeout=max(0, end - time.monotonic()))
58
+ while (remaining := end - time.monotonic()) > 0:
59
+ msg = link.bus.recv(remaining)
60
+ if (msg is None or msg.arbitration_id != 0x580 + link.node or msg.is_extended_id or msg.is_remote_frame
61
+ or msg.is_error_frame or len(msg.data) != 8 or bytes(msg.data[1:4]) != request[1:4]):
62
+ continue
63
+ response = bytes(msg.data)
64
+ if response[0] == 0x80:
65
+ return response
66
+ if request[0] == 0x40:
67
+ if response[0] in (0x43, 0x47, 0x4B, 0x4F):
68
+ return response
69
+ elif request[0] & 0xE0 == 0x20 and response[0] == 0x60:
70
+ return response
71
+ raise TimeoutError("SDO 无应答")
72
+
73
+
74
+ ## @brief 分段上传(CiA301):读字符串类对象。
75
+ def sdo_upload(link, index, sub):
76
+ return Device(link).sdo_upload(index, sub, timeout=1.0, max_size=4096)
77
+
78
+
79
+ ## @brief 快速 SDO 写 4 字节,中止时抛出 SdoAbort。
80
+ def sdo_write_u32(link, index, sub, value):
81
+ resp = sdo_raw(link, struct.pack("<BHBI", 0x23, index, sub, value))
82
+ if resp[0] == 0x80:
83
+ raise SdoAbort(struct.unpack_from("<I", resp, 4)[0])
84
+
85
+
86
+ def check_identity(check, dev):
87
+ link = dev.link
88
+ name, version = sdo_upload(link, 0x1008, 0).decode(), sdo_upload(link, 0x100A, 0).decode()
89
+ check.item("分段 SDO 读 0x1008/0x100A", bool(name and version), f"{name!r},{version!r}")
90
+ identity = [dev.read(n) for n in ("vendor_id", "product_code", "revision", "serial_number")]
91
+ # 产品码须在对象字典的型号表中(任一 EHA 型号)。
92
+ known = dev.od.model_for(*identity[:2]) is not None
93
+ ok = check.item("快速 SDO 读 0x1018", known and identity[2] != 0,
94
+ "厂商 0x{:08X} 产品 0x{:08X} 修订 0x{:08X} 序列号 0x{:08X}".format(*identity))
95
+ if not ok:
96
+ return False
97
+ codes = (abort_code(lambda: sdo_upload(link, 0x1234, 0)),
98
+ abort_code(lambda: dev.write("statusword", 0)),
99
+ abort_code(lambda: dev.write("command_timeout_ms", 1)))
100
+ check.item("0x1014 只读(EMCY COB-ID 不可配置)", abort_code(lambda: sdo_write_u32(dev.link, 0x1014, 0, 0x80 + dev.link.node))
101
+ == 0x06010002)
102
+ check.item("SDO 中止码(无对象 / 只读 / 低于下限)", codes == (0x06020000, 0x06010002, 0x06090032),
103
+ " / ".join(f"0x{c:08X}" for c in codes))
104
+ return ok
105
+
106
+
107
+ def check_nmt(check, dev):
108
+ link, hb = dev.link, 0x700 + dev.link.node
109
+ raw_send(link, 0x000, [NMT_RESET_COMM, link.node])
110
+ frames = collect(link, 2.5, {hb})
111
+ check.item("NMT 复位通信后发启动报文", bool(frames) and frames[0][2] == bytes([HB_BOOTUP]))
112
+ beats = [t for t, _, d in frames if d == bytes([HB_OPERATIONAL])]
113
+ period = dev.read("heartbeat_producer_ms")
114
+ interval = (beats[-1] - beats[0]) / (len(beats) - 1) * 1000 if len(beats) > 1 else 0.0
115
+ check.item("心跳周期与 0x1017 一致(Operational)", abs(interval - period) < 0.1 * period,
116
+ f"{len(beats)} 帧,间隔 {interval:.0f} ms,0x1017 = {period} ms")
117
+ tpdo1 = 0x180 + link.node
118
+ sent = time.monotonic()
119
+ raw_send(link, 0x000, [NMT_PREOP, link.node])
120
+ frames = collect(link, 1.2, {tpdo1, hb})
121
+ # 设备在下一个 1 ms 周期才执行 NMT 命令,执行前到期的 TPDO 照常发出,加上适配器两向的 USB 延迟,命令后约 2 ms
122
+ # 内仍可能收到一帧(实测最长 1.8 ms)。只计 5 ms 之后的帧:短于 TPDO1 事件周期,多发一帧或持续发送都会被发现。
123
+ pdos = sum(1 for t, i, _ in frames if i == tpdo1 and t - sent > NMT_LATENCY_S)
124
+ in_flight = sum(1 for t, i, _ in frames if i == tpdo1 and t - sent <= NMT_LATENCY_S)
125
+ # 命令到达前可能刚发出一帧 Operational 心跳;从第一帧 0x7F 起都应为 Pre-operational。
126
+ states = [d[0] for _, i, d in frames if i == hb]
127
+ after = states[states.index(HB_PREOP):] if HB_PREOP in states else []
128
+ check.item("NMT Pre-operational:TPDO 停发,心跳状态 0x7F", pdos == 0 and after and set(after) == {HB_PREOP},
129
+ f"TPDO1 {pdos} 帧(命令后 {NMT_LATENCY_S * 1000:.0f} ms 内在途 {in_flight} 帧不计),心跳状态序列 {states}")
130
+ raw_send(link, 0x000, [NMT_START, link.node])
131
+ pdos = len(collect(link, 0.5, {tpdo1}))
132
+ check.item("NMT Start:TPDO 恢复", pdos > 0, f"0.5 s 内 TPDO1 {pdos} 帧")
133
+
134
+
135
+ def check_pdo_timing(check, dev):
136
+ link, tpdo1 = dev.link, 0x180 + dev.link.node
137
+ event = struct.unpack("<H", sdo_upload(link, 0x1800, 5))[0]
138
+ count = len(collect(link, 1.0, {tpdo1}))
139
+ expected = 1000 / event if event else 0
140
+ check.item("TPDO1 事件定时器", event > 0 and abs(count - expected) <= 0.1 * expected,
141
+ f"0x1800:05 = {event} ms,1 s 内 {count} 帧")
142
+ sdo_raw(link, struct.pack("<BHBB3x", 0x2F, 0x1800, 2, 1)) # 传输类型 1:每个 SYNC 发送
143
+ try:
144
+ sync_count, frames = 50, []
145
+ for _ in range(sync_count):
146
+ raw_send(link, 0x080)
147
+ frames += collect(link, 0.02, {tpdo1})
148
+ check.item("SYNC 触发 TPDO1(传输类型 1)", abs(len(frames) - sync_count) <= 2,
149
+ f"{sync_count} 个 SYNC,收到 {len(frames)} 帧")
150
+ finally:
151
+ sdo_raw(link, struct.pack("<BHBB3x", 0x2F, 0x1800, 2, 255))
152
+
153
+
154
+ def enable(dev):
155
+ for cw in (CW_FAULT_RESET, CW_SHUTDOWN, CW_ENABLE):
156
+ drive(dev, cw, 0.0, 0.05)
157
+
158
+
159
+ def check_control(check, dev):
160
+ link = dev.link
161
+ # 朝行程中点方向运行(中点在默认软限位 5–95 mm 之间),反复检查不会把活塞推到软限位、被行程包络挡住。
162
+ rpm = 300.0 if dev.read("position_actual_um") < 50000 else -300.0
163
+ enable(dev)
164
+ fb = drive(dev, CW_ENABLE, rpm, 1.0)
165
+ check.item(f"RPDO 控制模式 -2 到 {rpm:.0f} rpm,TPDO 反馈", fb is not None and fb["state"] == "OperationEnabled"
166
+ and abs(fb["motor_speed_rpm"] - rpm) < 10.0,
167
+ f"{fb['state']},{fb['motor_speed_rpm']:.1f} rpm" if fb else "无反馈")
168
+ # 停发 RPDO:超过 0x2000 后按 0x6007 快停,故障码 0x8130 经 EMCY 报告。
169
+ emcy = 0x080 + link.node
170
+ frames = collect(link, 0.6, {emcy})
171
+ codes = [struct.unpack_from("<H", d)[0] for _, _, d in frames]
172
+ sw = dev.read("statusword")
173
+ check.item("主机失联:EMCY 0x8130,statusword 位 7", EMCY_HOST_TIMEOUT in codes and sw & 0x80 != 0,
174
+ f"EMCY {[f'0x{c:04X}' for c in codes]},statusword 0x{sw:04X}")
175
+ # 0x1001:通信类错误同时置位 0(通用,CiA301 必备位)与位 4(通信)。
176
+ reg = dev.read("error_register")
177
+ check.item("0x1001 置位 0 通用与位 4 通信", reg & 0x11 == 0x11, f"0x{reg:02X}")
178
+ # 通信复位清零了 EMCY 状态与 0x1001:仍存在的失联须重新报告。
179
+ raw_send(link, 0x000, [NMT_RESET_COMM, link.node])
180
+ frames = collect(link, 0.5, {emcy})
181
+ codes = [struct.unpack_from("<H", d)[0] for _, _, d in frames]
182
+ reg = dev.read("error_register")
183
+ check.item("通信复位后重报 EMCY 0x8130 与 0x1001", EMCY_HOST_TIMEOUT in codes and reg & 0x11 == 0x11,
184
+ f"EMCY {[f'0x{c:04X}' for c in codes]},0x1001 = 0x{reg:02X}")
185
+ # 0x80 只确认(保持通电),随即 0x00 断电:停发后不会因命令超时再次锁存。
186
+ # 两帧相隔 20 ms:同一 RPDO 在一个周期内到达两帧时只处理后一帧,复位沿会丢失。
187
+ raw_send(link, 0x200 + link.node, struct.pack("<HbH", CW_FAULT_RESET, -2, 0)) # RPDO1:控制字、模式、力千分比
188
+ time.sleep(0.02)
189
+ raw_send(link, 0x200 + link.node, struct.pack("<HbH", CW_DISABLE_VOLTAGE, -2, 0))
190
+ frames = collect(link, 0.3, {emcy})
191
+ cleared = [d for _, _, d in frames if d[:2] == b"\x00\x00"]
192
+ check.item("故障复位后 EMCY 清除(错误码 0x0000)", bool(cleared) and dev.read("error_code") == 0)
193
+ drive(dev, CW_DISABLE_VOLTAGE, 0.0, 0.05)
194
+
195
+
196
+ ## @brief 0x1016 主机心跳只作附加条件:RPDO 持续、心跳在线时运行;心跳停止即失联;只发心跳不发 RPDO 也失联
197
+ ## (心跳不能为停发的属主保活)。
198
+ def check_host_heartbeat(check, dev):
199
+ link, host = dev.link, 0x7F
200
+ dev.write("host_heartbeat", host << 16 | 300)
201
+
202
+ def run_for(seconds, heartbeat, commands):
203
+ end, next_hb = time.monotonic() + seconds, 0.0
204
+ while time.monotonic() < end:
205
+ if heartbeat and time.monotonic() >= next_hb:
206
+ raw_send(link, 0x700 + host, [HB_OPERATIONAL])
207
+ next_hb = time.monotonic() + 0.1
208
+ if commands:
209
+ dev.command(CW_ENABLE, -2, 0.0)
210
+ time.sleep(0.01)
211
+
212
+ def recover():
213
+ drive(dev, CW_FAULT_RESET, 0.0, 0.05)
214
+ drive(dev, CW_DISABLE_VOLTAGE, 0.0, 0.05)
215
+
216
+ try:
217
+ # 配置了 0x1016 时,属主通道从未收到或停止收到心跳都算失联:先开始发心跳再使能。
218
+ run_for(0.2, heartbeat=True, commands=False)
219
+ enable(dev)
220
+ run_for(1.0, heartbeat=True, commands=True)
221
+ alive = dev.read("statusword") & 0x6F == 0x27
222
+ run_for(0.6, heartbeat=False, commands=True)
223
+ hb_lost = dev.read("error_code") == EMCY_HOST_TIMEOUT
224
+ recover()
225
+ run_for(0.2, heartbeat=True, commands=False)
226
+ enable(dev)
227
+ run_for(0.6, heartbeat=True, commands=False)
228
+ cmd_lost = dev.read("error_code") == EMCY_HOST_TIMEOUT
229
+ check.item("0x1016 主机心跳:在线时运行,停发即失联,不能为停发的 RPDO 保活", alive and hb_lost and cmd_lost,
230
+ f"RPDO 与心跳在线时运行 {alive},心跳停发后失联 {hb_lost},只发心跳时失联 {cmd_lost}")
231
+ # 只发 boot-up(状态 0)与 2 字节的心跳:都不算保活,RPDO 持续时也按心跳超时失联。
232
+ recover()
233
+ run_for(0.2, heartbeat=True, commands=False)
234
+ enable(dev)
235
+ end, bad_lost = time.monotonic() + 0.6, False
236
+ while time.monotonic() < end:
237
+ raw_send(link, 0x700 + host, [HB_BOOTUP])
238
+ raw_send(link, 0x700 + host, [HB_OPERATIONAL, 0])
239
+ dev.command(CW_ENABLE, -2, 0.0)
240
+ time.sleep(0.01)
241
+ bad_lost = dev.read("error_code") == EMCY_HOST_TIMEOUT
242
+ check.item("boot-up 与长度不符的心跳不算保活", bad_lost)
243
+ finally:
244
+ recover()
245
+ dev.write("host_heartbeat", 0)
246
+
247
+
248
+ ## @brief 0x6007 的触发事件:属主为 CAN 运行中,NMT Stop 与 Reset Communication 当周期失联(0x2000 临时设为 2 s,
249
+ ## 命令超时不可能先到);Pre-operational 不是触发事件;运行中 Reset Node 先按 0x6007 反应,再只做通信复位
250
+ ## (发 boot-up、芯片不复位:仍在 QuickStopActive 通电)。
251
+ def check_abort_events(check, dev):
252
+ link = dev.link
253
+ timeout = dev.read("command_timeout_ms")
254
+ dev.write("command_timeout_ms", 2000)
255
+
256
+ def run(nmt, seconds=0.15):
257
+ enable(dev)
258
+ drive(dev, CW_ENABLE, 0.0, 0.2)
259
+ raw_send(link, 0x000, [nmt, link.node])
260
+ frames = collect(link, seconds, {0x700 + link.node})
261
+ raw_send(link, 0x000, [NMT_START, link.node])
262
+ time.sleep(0.05)
263
+ error, sw = dev.read("error_code"), dev.read("statusword")
264
+ drive(dev, CW_FAULT_RESET, 0.0, 0.05)
265
+ drive(dev, CW_DISABLE_VOLTAGE, 0.0, 0.05)
266
+ return error, sw, [d for _, _, d in frames]
267
+
268
+ try:
269
+ for name, nmt in (("NMT Stop", NMT_STOP), ("Reset Communication", NMT_RESET_COMM)):
270
+ error, sw, _ = run(nmt)
271
+ check.item(f"{name}:当周期失联(0x8130),不等命令超时", error == EMCY_HOST_TIMEOUT,
272
+ f"0x603F = 0x{error:04X},statusword 0x{sw:04X}")
273
+ error, sw, _ = run(NMT_PREOP, 0.1)
274
+ check.item("Pre-operational 不是中止连接事件:0.1 s 后恢复仍在运行", error == 0 and sw & 0x6F == 0x27,
275
+ f"0x603F = 0x{error:04X},statusword 0x{sw:04X}")
276
+ error, sw, beats = run(NMT_RESET_NODE, 0.3)
277
+ check.item("运行中 Reset Node:按 0x6007 保持,只做通信复位(boot-up),芯片未复位",
278
+ error == EMCY_HOST_TIMEOUT and sw & 0x6F == 0x07 and bytes([HB_BOOTUP]) in beats,
279
+ f"0x603F = 0x{error:04X},statusword 0x{sw:04X},心跳 {[d.hex() for d in beats]}")
280
+ finally:
281
+ drive(dev, CW_DISABLE_VOLTAGE, 0.0, 0.05)
282
+ dev.write("command_timeout_ms", timeout)
283
+
284
+
285
+ def reopen(link, bitrate, data_bitrate):
286
+ config = dict(link.config)
287
+ link.close()
288
+ return CanLink(link.interface, link.channel, bitrate, data_bitrate, link.node, config=config)
289
+
290
+
291
+ def require_rate_backend(link):
292
+ if link.interface != "slcan":
293
+ raise RuntimeError(MESSAGES["rates_backend"].format(interface=link.interface))
294
+
295
+
296
+ def identity_key(identity):
297
+ return tuple(identity[name] for name in ("vendor_id", "product_code", "serial_number"))
298
+
299
+
300
+ def rate_identity(dev, expected=None):
301
+ identity = dev.read_identity()
302
+ # 产品码须在对象字典的型号表中(任一 EHA 型号)。
303
+ if dev.od.model_for(identity["vendor_id"], identity["product_code"]) is None:
304
+ raise RuntimeError(MESSAGES["rates_identity_product"])
305
+ if identity["serial_number"] == 0:
306
+ raise RuntimeError(MESSAGES["rates_identity_zero"])
307
+ if expected is not None and identity_key(identity) != identity_key(expected):
308
+ raise RuntimeError(MESSAGES["rates_identity_changed"])
309
+ return identity
310
+
311
+
312
+ ## @brief 切换到下一个速率:写 0x2003/0x2004、保存、复位,按新速率重新打开适配器并等启动报文。
313
+ def switch_rate(dev, bitrate, data_bitrate, *, identity=None):
314
+ require_rate_backend(dev.link)
315
+ before = rate_identity(dev, identity)
316
+ dev.write("can_bitrate", bitrate)
317
+ dev.write("can_data_bitrate", data_bitrate)
318
+ dev.write("store_parameters", SAVE)
319
+ try:
320
+ dev.write("device_reset", RESET_SIGNATURE)
321
+ except TimeoutError:
322
+ pass
323
+ dev.link = reopen(dev.link, bitrate, data_bitrate)
324
+ frames = collect(dev.link, 5.0, {0x700 + dev.link.node})
325
+ rate_identity(dev, before)
326
+ return any(data == bytes([HB_BOOTUP]) for _, _, data in frames)
327
+
328
+
329
+ def check_rates(check, dev):
330
+ require_rate_backend(dev.link)
331
+ identity = rate_identity(dev)
332
+ original = dev.read("can_bitrate"), dev.read("can_data_bitrate")
333
+ check.report(MESSAGES["rates_original"].format(bitrate=original[0], data_bitrate=original[1]))
334
+ try:
335
+ for bitrate, data_bitrate in RATES:
336
+ booted = switch_rate(dev, bitrate, data_bitrate, identity=identity)
337
+ request = struct.pack("<BHB4x", 0x40, 0x1018, 2)
338
+ product = struct.pack("<I", identity["product_code"])
339
+ response = sdo_raw(dev.link, request)
340
+ classic = response[0] == 0x43 and response[4:8] == product
341
+ fd = None
342
+ if data_bitrate:
343
+ response = sdo_raw(dev.link, request, fd=True)
344
+ fd = response[0] == 0x43 and response[4:8] == product
345
+ label = f"{bitrate // 1000} k" + (f" / {data_bitrate // 1000000} M(CAN FD)" if data_bitrate else "(经典)")
346
+ check.item(f"速率 {label}", booted and classic and fd is not False,
347
+ f"启动报文 {booted},经典帧 SDO {classic}" + (f",FD 帧 SDO {fd}" if data_bitrate else ""))
348
+ except BaseException as error:
349
+ # 复位或重开后的目标不明时,无法判断向谁写回,保留首个异常供调用方处理。
350
+ error.add_note(MESSAGES["rates_interrupted"].format(bitrate=original[0], data_bitrate=original[1]))
351
+ raise
352
+ # 所有切换均已核对原设备,写回开始时的速率并保存。
353
+ restored = switch_rate(dev, *original, identity=identity)
354
+ check.item(f"写回原速率 {original[0] // 1000} k / {original[1] // 1000} k", restored,
355
+ "启动报文已收到" if restored else "复位后未收到启动报文,已核对原设备身份")
356
+
357
+
358
+ def register(sub):
359
+ p = sub.add_parser("can-check", help="对外 CAN(CANopen)联调检查:SDO、NMT、心跳、PDO、SYNC、EMCY、主机心跳")
360
+ p.add_argument("--rates", action="store_true",
361
+ help=MESSAGES["rates_help"])
362
+ add_ack(p)
363
+ p.set_defaults(func=command)
364
+
365
+
366
+ def run(dev, args, *, report=print):
367
+ if not isinstance(dev.link, CanLink):
368
+ raise RuntimeError("can-check 须经 --can 指定 CAN 适配器")
369
+ if args.rates:
370
+ require_rate_backend(dev.link)
371
+ rate_identity(dev)
372
+ check = Check(report)
373
+ if not check_identity(check, dev):
374
+ # 后续项会使能并驱动电机:节点上不是 EHA 驱动器时不能继续。
375
+ raise RuntimeError(f"节点 {dev.link.node} 不是 EHA 驱动器,停止检查")
376
+ # 其余检查项写入之前取得控制权:驱动在运行、其他主机持有控制权或有待确认的保护(无 --ack)时不检查。
377
+ dev.acquire(args.ack)
378
+ check_nmt(check, dev)
379
+ check_pdo_timing(check, dev)
380
+ # 运动类检查项异常退出(SDO 超时、Ctrl-C)时先停机,再退出开发者模式。
381
+ with dev.developer_session("模式 -2"), dev.stopped_on_error(-2):
382
+ check_control(check, dev)
383
+ check_host_heartbeat(check, dev)
384
+ check_abort_events(check, dev)
385
+ if args.rates:
386
+ check_rates(check, dev)
387
+ return check.summary()
388
+
389
+
390
+ ## @brief CLI 负责退出码;可复用流程返回检查结果。
391
+ def command(dev, args):
392
+ result = run(dev, args)
393
+ if not result["ok"]:
394
+ raise SystemExit(1)
@@ -0,0 +1,9 @@
1
+ # Copyright The eha-firmware Contributors
2
+
3
+ rates_backend = "can-check --rates 的速率表需要支持 CAN FD 与 SLCAN 速率命令的 slcan 转接器;当前后端为 {interface},请使用普通 can-check 或选定合适的转接器"
4
+ rates_identity_zero = "设备序列号为 0,无法在复位切换速率后核对原设备"
5
+ rates_identity_product = "节点的厂商或产品码与 EHA 不符,停止切换速率"
6
+ rates_identity_changed = "切换速率后读到的设备身份与原设备不同,停止检查"
7
+ rates_original = "开始时的设备 CAN 速率为 {bitrate} / {data_bitrate} bit/s"
8
+ rates_interrupted = "速率检查中断,设备当前速率或复位结果需核对。开始时速率为 {bitrate} / {data_bitrate} bit/s;停止自动写回"
9
+ rates_help = "经支持 CAN FD 速率命令的 slcan 转接器切换速率(保存参数并复位);检查正常完成后写回开始时速率,异常时停止并报告"
@@ -0,0 +1,43 @@
1
+ # Copyright The eha-firmware Contributors
2
+
3
+ ## @file
4
+ ## @brief 联调检查共用的结果记录与定时命令发送。
5
+
6
+ import time
7
+
8
+ from ..link import SdoAbort
9
+
10
+
11
+ class Check:
12
+ def __init__(self, report=print):
13
+ self.failed = 0
14
+ self.results = []
15
+ self.report = report
16
+
17
+ def item(self, name, ok, detail=""):
18
+ self.report(f"{'通过' if ok else '失败'} {name}{':' + detail if detail else ''}")
19
+ self.results.append({"name": name, "ok": bool(ok), "detail": detail})
20
+ self.failed += 0 if ok else 1
21
+ return ok
22
+
23
+ def summary(self):
24
+ self.report(f"共 {self.failed} 项失败" if self.failed else "全部通过")
25
+ return {"ok": self.failed == 0, "failed": self.failed, "checks": self.results}
26
+
27
+
28
+ ## @brief 执行 SDO 操作,正常完成返回 0,设备中止返回其原始中止码;其他异常继续抛出。
29
+ def abort_code(func):
30
+ try:
31
+ func()
32
+ except SdoAbort as error:
33
+ return error.code
34
+ return 0
35
+
36
+
37
+ ## @brief 按 period 发送模式 −2 命令 seconds 秒,返回最后一次有效反馈。
38
+ def timed_stream(dev, controlword, rpm, seconds, period=0.01):
39
+ fb, end = None, time.monotonic() + seconds
40
+ while time.monotonic() < end:
41
+ fb = dev.command(controlword, -2, rpm) or fb
42
+ time.sleep(period)
43
+ return fb