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/device/can.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief CAN 适配器初始化、CANopen 报文收发与默认 PDO 交换。
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
|
|
10
|
+
from .io import MESSAGES, _remaining
|
|
11
|
+
|
|
12
|
+
# CiA301 预定义连接集:RPDO/TPDO 1–4 的 COB-ID 基址。
|
|
13
|
+
RPDO_COB = (0x200, 0x300, 0x400, 0x500)
|
|
14
|
+
TPDO_COB = (0x180, 0x280, 0x380, 0x480)
|
|
15
|
+
# CAN 上一次命令等待 TPDO 反馈的时限;TPDO 事件定时器须小于它。
|
|
16
|
+
CAN_FEEDBACK_S = 0.05
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def initialize_gs_usb_backend():
|
|
20
|
+
"""在直接访问 USB 的平台先加载随 Python 包安装的 libusb。"""
|
|
21
|
+
if sys.platform not in ("darwin", "win32"):
|
|
22
|
+
return
|
|
23
|
+
from libusb_package import get_libusb1_backend
|
|
24
|
+
|
|
25
|
+
# PyUSB 缓存由公开 API 加载的库,随后 GsUsb.scan/find 使用同一后端。
|
|
26
|
+
if get_libusb1_backend() is None:
|
|
27
|
+
raise RuntimeError(MESSAGES["gs_usb_backend"])
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _lock_serial_port(channel):
|
|
31
|
+
if os.name != "posix":
|
|
32
|
+
return None
|
|
33
|
+
import fcntl
|
|
34
|
+
# 与 pyserial exclusive 使用同一设备上的 flock;开锁句柄不改串口配置或清缓冲。
|
|
35
|
+
path = str(channel).partition("@")[0]
|
|
36
|
+
descriptor = os.open(path, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
|
|
37
|
+
try:
|
|
38
|
+
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
39
|
+
except BaseException:
|
|
40
|
+
os.close(descriptor)
|
|
41
|
+
raise
|
|
42
|
+
return descriptor
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _standard_data(message):
|
|
46
|
+
return (not (getattr(message, "is_extended_id", False) or getattr(message, "is_remote_frame", False)
|
|
47
|
+
or getattr(message, "is_error_frame", False))
|
|
48
|
+
and getattr(message, "dlc", len(message.data)) == len(message.data))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
## @brief 对外 CAN 通道(python-can),设备为 CANopen 从站。快速 SDO 与 USB 帧格式相同;
|
|
52
|
+
## 控制用默认 RPDO/TPDO(od/eha_od.toml 的 [canopen])。data_bitrate 为 0 时按经典 CAN 打开。
|
|
53
|
+
class CanLink:
|
|
54
|
+
def __init__(self, interface, channel, bitrate, data_bitrate, node, *, config=None, listen_only=False):
|
|
55
|
+
import can
|
|
56
|
+
|
|
57
|
+
if not 1 <= node <= 127:
|
|
58
|
+
raise ValueError(MESSAGES["can_node"])
|
|
59
|
+
self.can = can
|
|
60
|
+
self.interface, self.channel = interface, channel
|
|
61
|
+
self.bitrate, self.data_bitrate, self.node = bitrate, data_bitrate, node
|
|
62
|
+
self.config = dict(config or {})
|
|
63
|
+
self._deadline, self._closed = None, False
|
|
64
|
+
self._serial_lock = None
|
|
65
|
+
self.bus = None
|
|
66
|
+
if self.config.get("interface", interface) != interface:
|
|
67
|
+
raise ValueError(MESSAGES["can_backend"])
|
|
68
|
+
options = dict(self.config)
|
|
69
|
+
options.update(interface=interface, channel=channel, ignore_config=True)
|
|
70
|
+
if interface == "gs_usb" and (listen_only or data_bitrate):
|
|
71
|
+
raise ValueError(MESSAGES["gs_usb_mode"])
|
|
72
|
+
if interface == "gs_usb":
|
|
73
|
+
initialize_gs_usb_backend()
|
|
74
|
+
if interface == "slcan":
|
|
75
|
+
from can.interfaces.slcan import slcanBus
|
|
76
|
+
# 上游先开串口后校验速率;先检查它的能力表,避免非法值留下半开的串口。
|
|
77
|
+
if bitrate not in slcanBus._BITRATES or data_bitrate not in slcanBus._DATA_BITRATES:
|
|
78
|
+
raise ValueError(MESSAGES["slcan_rate"])
|
|
79
|
+
options.setdefault("sleep_after_open", 0.5)
|
|
80
|
+
options["listen_only"] = listen_only
|
|
81
|
+
if data_bitrate:
|
|
82
|
+
# python-can 的 SLCAN 构造器只经 timing 传数据段速率,在第一次 O 前写 S/Y。
|
|
83
|
+
options.pop("bitrate", None)
|
|
84
|
+
options["timing"] = can.BitTimingFd.from_sample_point(
|
|
85
|
+
f_clock=80_000_000, nom_bitrate=bitrate, nom_sample_point=80,
|
|
86
|
+
data_bitrate=data_bitrate, data_sample_point=75)
|
|
87
|
+
else:
|
|
88
|
+
options["bitrate"] = bitrate
|
|
89
|
+
options.pop("timing", None)
|
|
90
|
+
elif interface != "socketcan":
|
|
91
|
+
options["bitrate"] = bitrate
|
|
92
|
+
if listen_only:
|
|
93
|
+
options["listen_only"] = True
|
|
94
|
+
if data_bitrate:
|
|
95
|
+
options.update(fd=True, data_bitrate=data_bitrate)
|
|
96
|
+
else:
|
|
97
|
+
# SocketCAN 的速率由内核接口配置决定,Bus 构造参数不会重配它。
|
|
98
|
+
options.pop("bitrate", None)
|
|
99
|
+
options.pop("data_bitrate", None)
|
|
100
|
+
if data_bitrate:
|
|
101
|
+
options["fd"] = True
|
|
102
|
+
try:
|
|
103
|
+
if interface == "slcan":
|
|
104
|
+
self._serial_lock = _lock_serial_port(channel)
|
|
105
|
+
self.bus = can.Bus(**options)
|
|
106
|
+
except BaseException:
|
|
107
|
+
if self._serial_lock is not None:
|
|
108
|
+
os.close(self._serial_lock)
|
|
109
|
+
self._serial_lock = None
|
|
110
|
+
raise
|
|
111
|
+
|
|
112
|
+
def close(self):
|
|
113
|
+
if not getattr(self, "_closed", False):
|
|
114
|
+
primary = None
|
|
115
|
+
try:
|
|
116
|
+
self.bus.shutdown()
|
|
117
|
+
except BaseException as error:
|
|
118
|
+
primary = error
|
|
119
|
+
raise
|
|
120
|
+
finally:
|
|
121
|
+
try:
|
|
122
|
+
serial_port = getattr(self.bus, "serialPortOrig", None)
|
|
123
|
+
if serial_port is not None:
|
|
124
|
+
serial_port.close()
|
|
125
|
+
except Exception as error:
|
|
126
|
+
if primary is None:
|
|
127
|
+
raise
|
|
128
|
+
primary.add_note(str(error))
|
|
129
|
+
finally:
|
|
130
|
+
if getattr(self, "_serial_lock", None) is not None:
|
|
131
|
+
os.close(self._serial_lock)
|
|
132
|
+
self._serial_lock = None
|
|
133
|
+
self._closed = True
|
|
134
|
+
|
|
135
|
+
## @brief 在事务截止时间内清除积压;持续繁忙时超时,不等待队列无限变空。
|
|
136
|
+
def drain(self):
|
|
137
|
+
deadline = getattr(self, "_deadline", None)
|
|
138
|
+
if deadline is None:
|
|
139
|
+
deadline = time.monotonic() + CAN_FEEDBACK_S
|
|
140
|
+
while True:
|
|
141
|
+
_remaining(deadline)
|
|
142
|
+
if self.bus.recv(0) is None:
|
|
143
|
+
return
|
|
144
|
+
|
|
145
|
+
def send(self, cob_id, data):
|
|
146
|
+
deadline = getattr(self, "_deadline", None)
|
|
147
|
+
remaining = _remaining(deadline)
|
|
148
|
+
message = self.can.Message(arbitration_id=cob_id | self.node, data=bytes(data), is_extended_id=False,
|
|
149
|
+
is_fd=len(data) > 8, bitrate_switch=len(data) > 8)
|
|
150
|
+
if remaining is None:
|
|
151
|
+
self.bus.send(message)
|
|
152
|
+
else:
|
|
153
|
+
self.bus.send(message, timeout=remaining)
|
|
154
|
+
_remaining(deadline)
|
|
155
|
+
|
|
156
|
+
def receive(self, function, timeout=0.2):
|
|
157
|
+
deadline = time.monotonic() + timeout
|
|
158
|
+
transaction = getattr(self, "_deadline", None)
|
|
159
|
+
if transaction is not None:
|
|
160
|
+
deadline = min(deadline, transaction)
|
|
161
|
+
while (remaining := deadline - time.monotonic()) > 0:
|
|
162
|
+
msg = self.bus.recv(remaining)
|
|
163
|
+
if (msg is not None and _standard_data(msg) and msg.arbitration_id == (function | self.node)
|
|
164
|
+
and len(msg.data) == 8):
|
|
165
|
+
if time.monotonic() < deadline:
|
|
166
|
+
return bytes(msg.data)
|
|
167
|
+
return None
|
|
168
|
+
|
|
169
|
+
## @brief 用默认 RPDO 下发目标(RPDO1 含 controlword,最后发送),等待发送之后到达的 TPDO1–4 各一帧组成反馈。
|
|
170
|
+
## 发送前丢弃积压的帧:反馈不会是之前某个时刻的旧状态。
|
|
171
|
+
def command(self, od, values):
|
|
172
|
+
self.drain()
|
|
173
|
+
rpdos = od.canopen_pdos("rpdo")
|
|
174
|
+
for n in list(range(1, len(rpdos))) + [0]:
|
|
175
|
+
names, layout = rpdos[n]
|
|
176
|
+
self.send(RPDO_COB[n], layout.pack(*(values.get(name, 0) for name in names)))
|
|
177
|
+
fb, pending = {}, {TPDO_COB[n]: pdo for n, pdo in enumerate(od.canopen_pdos("tpdo"))}
|
|
178
|
+
deadline = time.monotonic() + CAN_FEEDBACK_S
|
|
179
|
+
if getattr(self, "_deadline", None) is not None:
|
|
180
|
+
deadline = min(deadline, self._deadline)
|
|
181
|
+
while pending and (remaining := deadline - time.monotonic()) > 0:
|
|
182
|
+
msg = self.bus.recv(remaining)
|
|
183
|
+
if msg is None or not _standard_data(msg):
|
|
184
|
+
continue
|
|
185
|
+
pdo = pending.get(msg.arbitration_id - self.node)
|
|
186
|
+
if pdo is not None:
|
|
187
|
+
names, layout = pdo
|
|
188
|
+
if len(msg.data) == layout.size:
|
|
189
|
+
pending.pop(msg.arbitration_id - self.node)
|
|
190
|
+
fb.update(zip(names, layout.unpack(bytes(msg.data))))
|
|
191
|
+
return None if pending else fb
|
|
192
|
+
|
|
193
|
+
## @brief 只收不发 seconds 秒,返回其间出现过的 ids 中的 COB-ID。
|
|
194
|
+
def listen(self, seconds, ids):
|
|
195
|
+
self.drain()
|
|
196
|
+
heard, deadline = set(), time.monotonic() + seconds
|
|
197
|
+
while (remaining := deadline - time.monotonic()) > 0:
|
|
198
|
+
msg = self.bus.recv(remaining)
|
|
199
|
+
if msg is not None and _standard_data(msg) and msg.arbitration_id in ids:
|
|
200
|
+
heard.add(msg.arbitration_id)
|
|
201
|
+
return heard
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief CAN 适配器枚举、既有总线观察与独占台架的 CANopen 身份读取。
|
|
5
|
+
|
|
6
|
+
import errno
|
|
7
|
+
import json
|
|
8
|
+
import pathlib
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
import tomllib
|
|
13
|
+
|
|
14
|
+
from .can import CanLink, initialize_gs_usb_backend
|
|
15
|
+
from ..link import Device
|
|
16
|
+
|
|
17
|
+
# 对应 CANable / CANable 2 上游 USB 描述符;未知转接器仍可用显式接口。
|
|
18
|
+
SLCAN_IDS = {(0xAD50, 0x60C4), (0x16D0, 0x117E)}
|
|
19
|
+
OBSERVE_S = 1.1
|
|
20
|
+
SCAN_S = 40.0
|
|
21
|
+
REQUEST_S = 0.2
|
|
22
|
+
MESSAGES = tomllib.loads(pathlib.Path(__file__).with_suffix(".toml").read_text())["messages"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _access_errors():
|
|
26
|
+
# python-can 为可选依赖,CanError 的基类是 Exception。
|
|
27
|
+
backend = sys.modules.get("can")
|
|
28
|
+
return (ImportError, OSError, RuntimeError, ValueError, getattr(backend, "CanError", RuntimeError))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _access_state(error):
|
|
32
|
+
for cause in (error, error.__cause__, error.__context__):
|
|
33
|
+
code = getattr(cause, "errno", None)
|
|
34
|
+
if code in (errno.EBUSY, errno.EAGAIN, errno.EWOULDBLOCK):
|
|
35
|
+
return "busy"
|
|
36
|
+
if code in (errno.EACCES, errno.EPERM):
|
|
37
|
+
return "permission"
|
|
38
|
+
return "unavailable"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _issue(state, message, **scope):
|
|
42
|
+
return {"via": "can", "state": state, "message": str(message), **scope}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _record(interface, channel, **fields):
|
|
46
|
+
return {"via": "can", "role": "adapter", "interface": interface, "channel": channel,
|
|
47
|
+
"node": None, "serial": None, "name": None, "state": "candidate",
|
|
48
|
+
"config": {"interface": interface, "channel": channel}, **fields}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _socketcan_adapters():
|
|
52
|
+
result = subprocess.run(["ip", "-details", "-json", "link", "show"], check=True,
|
|
53
|
+
capture_output=True, text=True, timeout=2)
|
|
54
|
+
adapters = []
|
|
55
|
+
for info in json.loads(result.stdout):
|
|
56
|
+
if info.get("link_type") != "can":
|
|
57
|
+
continue
|
|
58
|
+
channel = info["ifname"]
|
|
59
|
+
linkinfo = info.get("linkinfo", {})
|
|
60
|
+
details = linkinfo.get("info_data", {})
|
|
61
|
+
kind = linkinfo.get("info_kind")
|
|
62
|
+
config = {"interface": "socketcan", "channel": channel}
|
|
63
|
+
parent = pathlib.Path("/sys/class/net") / channel / "device"
|
|
64
|
+
try:
|
|
65
|
+
location = str(parent.resolve(strict=True))
|
|
66
|
+
except OSError:
|
|
67
|
+
location = None
|
|
68
|
+
adapters.append(_record("socketcan", channel, config=config,
|
|
69
|
+
name=channel, state="candidate" if "UP" in info.get("flags", []) else "down",
|
|
70
|
+
virtual=kind == "vcan", location=location,
|
|
71
|
+
bitrate=details.get("bittiming", {}).get("bitrate"),
|
|
72
|
+
data_bitrate=details.get("data_bittiming", {}).get("bitrate"),
|
|
73
|
+
fd="FD" in details.get("ctrlmode", []), method="netlink"))
|
|
74
|
+
return adapters
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class BackendUnavailable(ImportError):
|
|
78
|
+
"""可选的厂商运行库未安装。"""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _native_adapters(interface):
|
|
82
|
+
# 隔离厂商枚举:库的线程超时不能终止阻塞的原生驱动。
|
|
83
|
+
script = """import json, sys
|
|
84
|
+
try:
|
|
85
|
+
import can
|
|
86
|
+
interface = sys.argv[1]
|
|
87
|
+
cls = can.interface._get_class_for_interface(interface)
|
|
88
|
+
if interface == "kvaser":
|
|
89
|
+
import can.interfaces.kvaser.canlib as driver
|
|
90
|
+
if driver.__canlib is None:
|
|
91
|
+
raise ImportError("Kvaser CANlib is not installed")
|
|
92
|
+
elif interface == "pcan":
|
|
93
|
+
from can.interfaces.pcan.basic import PCANBasic
|
|
94
|
+
try:
|
|
95
|
+
PCANBasic()
|
|
96
|
+
except OSError as error:
|
|
97
|
+
raise ImportError(str(error)) from error
|
|
98
|
+
records = cls._detect_available_configs()
|
|
99
|
+
print(json.dumps({"records": records}))
|
|
100
|
+
except ImportError as error:
|
|
101
|
+
print(json.dumps({"missing": str(error)}))
|
|
102
|
+
except Exception as error:
|
|
103
|
+
print(json.dumps({"error": str(error)}))
|
|
104
|
+
"""
|
|
105
|
+
response = subprocess.run([sys.executable, "-c", script, interface], capture_output=True,
|
|
106
|
+
text=True, check=True, timeout=2)
|
|
107
|
+
payload = json.loads(response.stdout)
|
|
108
|
+
if "missing" in payload:
|
|
109
|
+
raise BackendUnavailable(payload["missing"])
|
|
110
|
+
if "error" in payload:
|
|
111
|
+
raise RuntimeError(payload["error"])
|
|
112
|
+
records = []
|
|
113
|
+
for found in payload["records"]:
|
|
114
|
+
config = {**found, "interface": interface}
|
|
115
|
+
if "channel" not in config:
|
|
116
|
+
continue
|
|
117
|
+
records.append(_record(interface, str(config["channel"]), config=config,
|
|
118
|
+
name=str(config["channel"]), method="native_driver"))
|
|
119
|
+
return records
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _tty_parent(device):
|
|
123
|
+
if not sys.platform.startswith("linux"):
|
|
124
|
+
return None
|
|
125
|
+
try:
|
|
126
|
+
path = pathlib.Path("/sys/class/tty") / pathlib.Path(device).name / "device"
|
|
127
|
+
return str(path.resolve(strict=True))
|
|
128
|
+
except OSError:
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _merge_slcand(records):
|
|
133
|
+
merged = []
|
|
134
|
+
for record in records:
|
|
135
|
+
if record["interface"] == "slcan" and record.get("sysfs_parent"):
|
|
136
|
+
parent = record["sysfs_parent"]
|
|
137
|
+
same = [r for r in records if r["interface"] == "socketcan" and r.get("location") == parent]
|
|
138
|
+
if len(same) == 1:
|
|
139
|
+
same[0]["serial_port"] = record["channel"]
|
|
140
|
+
same[0]["adapter_serial"] = record.get("adapter_serial")
|
|
141
|
+
continue
|
|
142
|
+
merged.append(record)
|
|
143
|
+
return merged
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def enumerate_adapters(adapter=None):
|
|
147
|
+
"""只枚举元数据。显式 interface:channel 可覆盖没有自动枚举的厂商后端。"""
|
|
148
|
+
records, issues = [], []
|
|
149
|
+
if sys.platform.startswith("linux"):
|
|
150
|
+
try:
|
|
151
|
+
records.extend(_socketcan_adapters())
|
|
152
|
+
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
|
153
|
+
issues.append(_issue("unavailable", error, interface="socketcan"))
|
|
154
|
+
try:
|
|
155
|
+
from serial.tools.list_ports import comports
|
|
156
|
+
for port in comports():
|
|
157
|
+
if (port.vid, port.pid) in SLCAN_IDS:
|
|
158
|
+
records.append(_record("slcan", port.device, name=port.product,
|
|
159
|
+
adapter_serial=port.serial_number, location=port.location,
|
|
160
|
+
manufacturer=port.manufacturer, sysfs_parent=_tty_parent(port.device),
|
|
161
|
+
method="usb_descriptor"))
|
|
162
|
+
except (ImportError, OSError) as error:
|
|
163
|
+
issues.append(_issue("unavailable", error, interface="slcan"))
|
|
164
|
+
if sys.platform == "darwin":
|
|
165
|
+
try:
|
|
166
|
+
from gs_usb.gs_usb import GsUsb
|
|
167
|
+
initialize_gs_usb_backend()
|
|
168
|
+
for item in GsUsb.scan():
|
|
169
|
+
usb = item.gs_usb
|
|
170
|
+
config = {"interface": "gs_usb", "channel": usb.product or "gs_usb",
|
|
171
|
+
"bus": item.bus, "address": item.address}
|
|
172
|
+
records.append(_record("gs_usb", str(item.bus) + "/" + str(item.address), config=config,
|
|
173
|
+
name=usb.product, adapter_serial=item.serial_number,
|
|
174
|
+
method="usb_descriptor", fd=False))
|
|
175
|
+
except ImportError as error:
|
|
176
|
+
issues.append(_issue("unavailable", error, interface="gs_usb", blocking=False,
|
|
177
|
+
kind="optional_dependency"))
|
|
178
|
+
except (OSError, RuntimeError) as error:
|
|
179
|
+
issues.append(_issue("unavailable", error, interface="gs_usb"))
|
|
180
|
+
# 仅探测已有明确枚举 API 的后端,不遍历会启动设备的所有插件。
|
|
181
|
+
if sys.platform in ("darwin", "win32") or sys.platform.startswith("linux"):
|
|
182
|
+
native = ("pcan", "kvaser") if sys.platform != "win32" else ("pcan", "kvaser", "vector")
|
|
183
|
+
if adapter is not None:
|
|
184
|
+
native = tuple(n for n in native if adapter.startswith(n + ":"))
|
|
185
|
+
for interface in native:
|
|
186
|
+
try:
|
|
187
|
+
records.extend(_native_adapters(interface))
|
|
188
|
+
except BackendUnavailable as error:
|
|
189
|
+
issues.append(_issue("unavailable", MESSAGES["native_unavailable"].format(
|
|
190
|
+
interface=interface, reason=error), interface=interface, blocking=False,
|
|
191
|
+
kind="optional_dependency"))
|
|
192
|
+
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error:
|
|
193
|
+
issues.append(_issue("unavailable", MESSAGES["native_unavailable"].format(
|
|
194
|
+
interface=interface, reason=error), interface=interface))
|
|
195
|
+
records = _merge_slcand(records)
|
|
196
|
+
if adapter is not None:
|
|
197
|
+
interface, separator, channel = adapter.partition(":")
|
|
198
|
+
if not separator or not interface or not channel:
|
|
199
|
+
raise ValueError(MESSAGES["adapter_format"])
|
|
200
|
+
matches = [r for r in records if (r["interface"], str(r["channel"])) == (interface, channel)]
|
|
201
|
+
if not matches:
|
|
202
|
+
missing = [i for i in issues if i.get("interface") == interface]
|
|
203
|
+
if missing:
|
|
204
|
+
return [], [{**i, "blocking": True} for i in missing]
|
|
205
|
+
if interface == "socketcan" and sys.platform.startswith("linux"):
|
|
206
|
+
return [], [_issue("unavailable", MESSAGES["missing_socketcan"], interface=interface, channel=channel)]
|
|
207
|
+
if interface == "gs_usb":
|
|
208
|
+
return [], [_issue("unavailable", MESSAGES["missing_usb"], interface=interface, channel=channel)]
|
|
209
|
+
matches = [_record(interface, channel, method="explicit")]
|
|
210
|
+
# 显式接口无需自动枚举成功,驱动真正打开时仍会给出错误。
|
|
211
|
+
return matches, []
|
|
212
|
+
return sorted(records, key=lambda r: (r["interface"], str(r["channel"]))), issues
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _standard(message):
|
|
216
|
+
return not (message.is_extended_id or message.is_remote_frame or message.is_error_frame)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _observe(bus, deadline):
|
|
220
|
+
nodes, requests = {}, set()
|
|
221
|
+
while (remaining := deadline - time.monotonic()) > 0:
|
|
222
|
+
message = bus.recv(remaining)
|
|
223
|
+
if message is None:
|
|
224
|
+
break
|
|
225
|
+
if not _standard(message):
|
|
226
|
+
continue
|
|
227
|
+
cob, data = message.arbitration_id, bytes(message.data)
|
|
228
|
+
if 0x701 <= cob <= 0x77F and len(data) == 1 and data[0] in (0, 4, 5, 0x7F):
|
|
229
|
+
nodes[cob - 0x700] = data[0]
|
|
230
|
+
if 0x601 <= cob <= 0x67F and len(data) == 8:
|
|
231
|
+
requests.add(cob - 0x600)
|
|
232
|
+
return nodes, requests
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _node_record(adapter, node, **fields):
|
|
236
|
+
return {**adapter, "role": "device", "node": node, "name": None,
|
|
237
|
+
"serial": None, "state": "observed", "complete": False,
|
|
238
|
+
"method": "heartbeat", **fields}
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _open(adapter, bitrate, data_bitrate, node):
|
|
242
|
+
if adapter["state"] == "down":
|
|
243
|
+
raise RuntimeError(MESSAGES["interface_down"])
|
|
244
|
+
configured = adapter.get("bitrate")
|
|
245
|
+
if adapter["interface"] == "socketcan":
|
|
246
|
+
if bitrate is not None and configured is not None and bitrate != configured:
|
|
247
|
+
raise ValueError(MESSAGES["bitrate_mismatch"].format(actual=configured, requested=bitrate))
|
|
248
|
+
actual_data = adapter.get("data_bitrate") or 0
|
|
249
|
+
if data_bitrate is not None and not adapter.get("virtual") and data_bitrate != actual_data:
|
|
250
|
+
raise ValueError(MESSAGES["data_bitrate_mismatch"].format(actual=actual_data, requested=data_bitrate))
|
|
251
|
+
return CanLink("socketcan", adapter["channel"], configured or bitrate or 0, actual_data,
|
|
252
|
+
node, config=adapter["config"])
|
|
253
|
+
if bitrate is None:
|
|
254
|
+
raise ValueError(MESSAGES["bitrate_required"])
|
|
255
|
+
return CanLink(adapter["interface"], adapter["config"]["channel"], bitrate, data_bitrate or 0,
|
|
256
|
+
node, config=adapter["config"])
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _identity_record(link, adapter, node, deadline):
|
|
260
|
+
link.node = node
|
|
261
|
+
device = Device(link)
|
|
262
|
+
identity = device.read_identity(timeout=min(1.0, max(0, deadline - time.monotonic())), deadline=deadline)
|
|
263
|
+
# 读身份时 Device 已按型号表选型号;不在表中的产品码记在 unknown_product。
|
|
264
|
+
known = device.unknown_product is None
|
|
265
|
+
record = _node_record(adapter, node, **identity, state="identified" if known else "other_product",
|
|
266
|
+
serial=f'{identity["serial_number"]:08X}' if identity["serial_number"] else None,
|
|
267
|
+
method="sdo", complete=True)
|
|
268
|
+
if known:
|
|
269
|
+
try:
|
|
270
|
+
record["name"] = device.read_string(0x1008, timeout=0.5, deadline=deadline, max_size=256)
|
|
271
|
+
except _access_errors() as error:
|
|
272
|
+
record["name_error"] = str(error)
|
|
273
|
+
return record
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def scan_can(*, identify=False, adapter=None, node=None, bitrate=None, data_bitrate=None, serial=None):
|
|
277
|
+
"""返回适配器和节点记录。identify 表示调用方已把所选总线交给该台架使用。"""
|
|
278
|
+
if node is not None and not 1 <= node <= 127:
|
|
279
|
+
raise ValueError(MESSAGES["node_range"])
|
|
280
|
+
records, issues = enumerate_adapters(adapter)
|
|
281
|
+
if identify and any(i.get("blocking", True) for i in issues):
|
|
282
|
+
return records, issues
|
|
283
|
+
if identify and len(records) > 1:
|
|
284
|
+
issues.append(_issue("partial", MESSAGES["adapter_ambiguous"]))
|
|
285
|
+
return records, issues
|
|
286
|
+
output = list(records)
|
|
287
|
+
for record in records:
|
|
288
|
+
link = None
|
|
289
|
+
try:
|
|
290
|
+
if not identify:
|
|
291
|
+
if record["interface"] != "socketcan" or record["state"] == "down":
|
|
292
|
+
continue
|
|
293
|
+
link = _open(record, None, None, node or 1)
|
|
294
|
+
heard, _ = _observe(link.bus, time.monotonic() + OBSERVE_S)
|
|
295
|
+
output.extend(_node_record(record, n, nmt_state=state) for n, state in sorted(heard.items())
|
|
296
|
+
if node is None or n == node)
|
|
297
|
+
continue
|
|
298
|
+
link = _open(record, bitrate, data_bitrate, node or 1)
|
|
299
|
+
if record["interface"] != "socketcan":
|
|
300
|
+
record.update(bitrate=bitrate, data_bitrate=data_bitrate or 0)
|
|
301
|
+
deadline = time.monotonic() + SCAN_S
|
|
302
|
+
heard, external_requests = _observe(link.bus, min(deadline, time.monotonic() + OBSERVE_S))
|
|
303
|
+
targets = [node] if node is not None else list(range(1, 128))
|
|
304
|
+
if external_requests and (node is None or node in external_requests):
|
|
305
|
+
output.extend(_node_record(record, n, nmt_state=state) for n, state in sorted(heard.items()))
|
|
306
|
+
issues.append(_issue("busy", MESSAGES["scan_busy"], channel=record["channel"]))
|
|
307
|
+
continue
|
|
308
|
+
scanned, pending, unresolved = [], [], []
|
|
309
|
+
for target in targets:
|
|
310
|
+
if time.monotonic() >= deadline:
|
|
311
|
+
pending = targets[len(scanned):]
|
|
312
|
+
break
|
|
313
|
+
responded = False
|
|
314
|
+
try:
|
|
315
|
+
# 空地址用一次产品码上传判断,避免每个地址消耗完整身份超时。
|
|
316
|
+
link.node = target
|
|
317
|
+
Device(link).read("product_code", timeout=REQUEST_S, deadline=deadline)
|
|
318
|
+
responded = True
|
|
319
|
+
item = _identity_record(link, record, target, deadline)
|
|
320
|
+
if serial is None or item["serial"] == serial:
|
|
321
|
+
output.append(item)
|
|
322
|
+
except TimeoutError as error:
|
|
323
|
+
if responded or target in heard or node is not None:
|
|
324
|
+
unresolved.append(target)
|
|
325
|
+
output.append(_node_record(record, target, state="unknown", error=str(error),
|
|
326
|
+
method="sdo" if responded else "heartbeat" if target in heard else "sdo"))
|
|
327
|
+
issues.append(_issue("partial", error, channel=record["channel"], node=target))
|
|
328
|
+
except _access_errors() as error:
|
|
329
|
+
unresolved.append(target)
|
|
330
|
+
output.append(_node_record(record, target, state="unknown", error=str(error), method="sdo"))
|
|
331
|
+
issues.append(_issue("partial", error, channel=record["channel"], node=target))
|
|
332
|
+
scanned.append(target)
|
|
333
|
+
record.update(scanned=scanned, pending=pending, unresolved=unresolved, complete=not pending and not unresolved,
|
|
334
|
+
method="sdo_scan", state="partial" if pending or unresolved else "scanned")
|
|
335
|
+
if pending:
|
|
336
|
+
issues.append(_issue("partial", MESSAGES["scan_partial"], channel=record["channel"], pending=pending))
|
|
337
|
+
except _access_errors() as error:
|
|
338
|
+
state = _access_state(error)
|
|
339
|
+
record["state"] = state
|
|
340
|
+
issues.append(_issue(state, error, interface=record["interface"], channel=record["channel"]))
|
|
341
|
+
finally:
|
|
342
|
+
if link is not None:
|
|
343
|
+
try:
|
|
344
|
+
link.close()
|
|
345
|
+
except Exception as error:
|
|
346
|
+
issues.append(_issue("unavailable", error, channel=record["channel"]))
|
|
347
|
+
return output, issues
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def resolve_can(args):
|
|
351
|
+
"""打开唯一适配器并在同一句柄上确认目标,调用者负责关闭返回链路。"""
|
|
352
|
+
records, issues = enumerate_adapters(getattr(args, "can", None))
|
|
353
|
+
blocking = [i for i in issues if i.get("blocking", True)]
|
|
354
|
+
if len(records) != 1 or blocking:
|
|
355
|
+
raise RuntimeError(MESSAGES["resolve_adapter"].format(
|
|
356
|
+
candidates="、".join(f'{r["interface"]}:{r["channel"]}' for r in records),
|
|
357
|
+
issues=";".join(i["message"] for i in blocking)))
|
|
358
|
+
adapter = records[0]
|
|
359
|
+
node, serial = getattr(args, "node", None), getattr(args, "serial", None)
|
|
360
|
+
if node is not None and not 1 <= node <= 127:
|
|
361
|
+
raise ValueError(MESSAGES["node_range"])
|
|
362
|
+
link = _open(adapter, getattr(args, "bitrate", None), getattr(args, "data_bitrate", None), node or 1)
|
|
363
|
+
try:
|
|
364
|
+
deadline = time.monotonic() + 5.0
|
|
365
|
+
heard, requests = _observe(link.bus, min(deadline, time.monotonic() + OBSERVE_S))
|
|
366
|
+
if requests and (node is None or node in requests):
|
|
367
|
+
raise RuntimeError(MESSAGES["resolve_busy"])
|
|
368
|
+
if node is None:
|
|
369
|
+
if getattr(args, "cmd", None) not in ("info", "get", "params") or serial is None:
|
|
370
|
+
raise RuntimeError(MESSAGES["node_required"])
|
|
371
|
+
targets = sorted(heard)
|
|
372
|
+
if not targets:
|
|
373
|
+
raise RuntimeError(MESSAGES["no_heartbeat"])
|
|
374
|
+
else:
|
|
375
|
+
targets = [node]
|
|
376
|
+
candidates = []
|
|
377
|
+
for target in targets:
|
|
378
|
+
item = _identity_record(link, adapter, target, deadline)
|
|
379
|
+
if item["state"] == "identified" and item["serial"] and (serial is None or item["serial"] == serial):
|
|
380
|
+
candidates.append(item)
|
|
381
|
+
if len(candidates) != 1:
|
|
382
|
+
raise RuntimeError(MESSAGES["identity_ambiguous"])
|
|
383
|
+
link.node = candidates[0]["node"]
|
|
384
|
+
return link, candidates[0]["serial"]
|
|
385
|
+
except BaseException:
|
|
386
|
+
link.close()
|
|
387
|
+
raise
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
[messages]
|
|
3
|
+
adapter_format = "CAN 适配器须为 interface:channel"
|
|
4
|
+
missing_socketcan = "系统未列出该 CAN 接口"
|
|
5
|
+
missing_usb = "未找到该 USB CAN 转接器"
|
|
6
|
+
interface_down = "CAN 接口未启用,请先配置并启用该接口"
|
|
7
|
+
bitrate_mismatch = "CAN 接口当前仲裁速率为 {actual},与指定的 {requested} 不符"
|
|
8
|
+
data_bitrate_mismatch = "CAN 接口当前数据速率为 {actual},与指定的 {requested} 不符"
|
|
9
|
+
bitrate_required = "主动识别该 CAN 转接器须给出 --bitrate,静默总线不能自动推断速率"
|
|
10
|
+
node_range = "CAN 节点号须为 1–127"
|
|
11
|
+
adapter_ambiguous = "有多个 CAN 适配器,主动识别前请用 --can 指定一个"
|
|
12
|
+
scan_busy = "观察到其他 CAN 主站的 SDO 请求,保留观察结果"
|
|
13
|
+
scan_partial = "CAN 扫描截止,仍有节点号未查完"
|
|
14
|
+
resolve_adapter = "CAN 适配器未能唯一确定,请运行 devices 并用 --can 指定:{candidates};{issues}"
|
|
15
|
+
resolve_busy = "观察到其他主站使用 SDO 通道,无法主动核对身份"
|
|
16
|
+
node_required = "自动执行须明确 --node;请先运行 devices --identify 获取节点号"
|
|
17
|
+
no_heartbeat = "观察窗口没有 CAN 节点,请在独占台架运行 devices --identify"
|
|
18
|
+
identity_ambiguous = "CAN 设备身份没有唯一匹配,请明确 --can、--node 和 --serial"
|
|
19
|
+
native_unavailable = "{interface} 自动枚举不可用:{reason}"
|
ehatool/device/io.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief 串口与 CAN 事务共用的截止时间和链路诊断文字。
|
|
5
|
+
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import time
|
|
8
|
+
import tomllib
|
|
9
|
+
|
|
10
|
+
with (Path(__file__).resolve().parents[1] / "link.toml").open("rb") as source:
|
|
11
|
+
MESSAGES = tomllib.load(source)["message"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _remaining(deadline):
|
|
15
|
+
if deadline is None:
|
|
16
|
+
return None
|
|
17
|
+
remaining = deadline - time.monotonic()
|
|
18
|
+
if remaining <= 0:
|
|
19
|
+
raise TimeoutError(MESSAGES["deadline"])
|
|
20
|
+
return remaining
|