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
ehatool/link.py ADDED
@@ -0,0 +1,811 @@
1
+ # Copyright The eha-firmware Contributors
2
+
3
+ ## @file
4
+ ## @brief USB CDC 与对外 CAN(CANopen)链路、快速 SDO 与控制命令客户端;USB 帧格式见 firmware/app/link/link.h。
5
+
6
+ import binascii
7
+ import collections
8
+ import contextlib
9
+ import os
10
+ from pathlib import Path
11
+ import struct
12
+ import sys
13
+ import tempfile
14
+ import time
15
+
16
+ from . import od as odmod
17
+ from .cia402 import CW_DISABLE_VOLTAGE, CW_ENABLE, CW_FAULT_RESET, CW_QUICK_STOP, CW_SHUTDOWN, state_name
18
+ from .diagnostics import decode_sdo_abort
19
+
20
+ from .device.can import CAN_FEEDBACK_S, RPDO_COB, TPDO_COB, CanLink
21
+ from .device.io import MESSAGES, _remaining
22
+
23
+ # 与固件 usb.c 的 VID:PID 一致。
24
+ USB_VID, USB_PID = 0x1209, 0x0001
25
+ # USB 帧功能码与长度,与 link.h 一致。
26
+ COB_FUNCTION_MASK = 0x780
27
+ COB_SCOPE, COB_RXPDO, COB_TXPDO, COB_SDO_TX, COB_SDO_RX, COB_UPDATE = 0x280, 0x300, 0x380, 0x580, 0x600, 0x780
28
+ LINK_MAX_LEN = 64
29
+ # 0x2009 进入开发者模式的签名(ASCII "devl" 小端);写 0 退出。
30
+ DEVELOPER_SIGNATURE = 0x6C766564
31
+ # 0x2005 控制属主:低 7 位为通道(与固件 eha_channel_t 一致),位 7 为已失联。
32
+ CHANNEL_NAMES = {0: "无", 1: "EtherCAT", 2: "CAN", 3: "主机链路"}
33
+ OWNER_LOST = 0x80
34
+ # 非属主写控制对象、状态不允许时的 SDO 中止码。
35
+ ABORT_DEVICE_STATE = 0x08000022
36
+ ABORT_CANNOT_STORE = 0x08000020
37
+ # statusword 位 7:保护锁存待确认。
38
+ SW_LATCHED = 0x0080
39
+ # 运行:OperationEnabled 或 QuickStopActive(与固件 eha_drive_cycle_running 一致)。
40
+ RUNNING = ("OperationEnabled", "QuickStopActive")
41
+ # 探测写入受理后等待 0x2005 指向本通道的时限(写入在下一个 1 ms 驱动周期提交)。
42
+ OWNER_CONFIRM_S = 0.05
43
+ # 运动中经 SDO 复核属主的间隔(只在 0x6007 = 0、失联后驱动照常运行时才有意义)。
44
+ OWNER_RECHECK_S = 0.5
45
+ # USB 链路收到但当前没人等的帧中,只暂存示波帧(1 kHz 下约 4 s),其余照旧丢弃。
46
+ STASH_LIMIT = {COB_SCOPE: 4096}
47
+ ## @brief 等擦写 Flash 的请求(0x1010/0x1011、升级的开始)应答的时长,两个平台共用。STM32H723 一个 128 KiB 扇区实测
48
+ ## 约 0.9 s,数据手册上限约 4 s;恢复出厂与升级开始各擦两个扇区,按上限 8 s 加余量。
49
+ STORE_TIMEOUT_S = 10.0
50
+
51
+
52
+ def cobs_encode(data):
53
+ out, block = bytearray(), bytearray()
54
+ for byte in data:
55
+ if byte == 0:
56
+ out += bytes([len(block) + 1]) + block
57
+ block = bytearray()
58
+ else:
59
+ block.append(byte)
60
+ if len(block) == 254:
61
+ out += b"\xff" + block
62
+ block = bytearray()
63
+ out += bytes([len(block) + 1]) + block
64
+ return bytes(out)
65
+
66
+
67
+ ## @brief CRC-16/CCITT-FALSE(多项式 0x1021、初值 0xFFFF、不反射),与固件 eha_crc16 相同;b"123456789" 为 0x29B1。
68
+ def crc16(data):
69
+ return binascii.crc_hqx(bytes(data), 0xFFFF)
70
+
71
+
72
+ ## @brief USB 帧:COBS(cob_id u16 + 数据 + CRC-16 u16),不含结尾 0x00(格式见 firmware/app/link/link.h)。
73
+ def frame_encode(cob_id, data):
74
+ raw = struct.pack("<H", cob_id) + bytes(data)
75
+ return cobs_encode(raw + struct.pack("<H", crc16(raw)))
76
+
77
+
78
+ ## @brief 解码一帧并校验 CRC;返回 (cob_id, 数据),非法或 CRC 不符时抛 ValueError。
79
+ def frame_decode(encoded):
80
+ raw = cobs_decode(encoded)
81
+ if len(raw) < 4 or crc16(raw[:-2]) != struct.unpack_from("<H", raw, len(raw) - 2)[0]:
82
+ raise ValueError("帧长度或 CRC 不符")
83
+ return struct.unpack_from("<H", raw)[0], raw[2:-2]
84
+
85
+
86
+ def cobs_decode(data):
87
+ out, i = bytearray(), 0
88
+ while i < len(data):
89
+ code = data[i]
90
+ if code == 0 or i + code > len(data):
91
+ raise ValueError("COBS 编码非法")
92
+ out += data[i + 1 : i + code]
93
+ i += code
94
+ if code != 0xFF and i < len(data):
95
+ out.append(0)
96
+ return bytes(out)
97
+
98
+
99
+ ## @brief 取缓冲中第一帧指定功能码的数据。跳过坏帧,完整的其他帧可交给 keep 暂存。
100
+ ## 返回后,后续帧及不完整的尾部仍在缓冲中;function 为 None 时只处理已收齐的帧。
101
+ def take_frame(buffer, function, keep=None):
102
+ while (end := buffer.find(0)) >= 0:
103
+ encoded = buffer[:end]
104
+ del buffer[:end + 1]
105
+ try:
106
+ cob_id, data = frame_decode(encoded)
107
+ except ValueError:
108
+ continue
109
+ received = cob_id & COB_FUNCTION_MASK
110
+ if received == function:
111
+ return data
112
+ if keep is not None:
113
+ keep(received, data)
114
+ return None
115
+
116
+
117
+ @contextlib.contextmanager
118
+ def _bounded_io(link, deadline):
119
+ # 保持 drain/send 接口不变,链路在每个阻塞点读取本事务的同一截止时间。
120
+ bounded = isinstance(link, (StreamLink, CanLink))
121
+ previous = getattr(link, "_deadline", None)
122
+ if bounded:
123
+ if deadline is None:
124
+ deadline = previous
125
+ elif previous is not None:
126
+ deadline = min(previous, deadline)
127
+ link._deadline = deadline
128
+ try:
129
+ yield
130
+ finally:
131
+ if bounded:
132
+ link._deadline = previous
133
+
134
+
135
+ ## @brief 记录串口当前由哪个进程打开的文件(排他锁本身不说明持有者)。放在本用户的目录中:macOS 的临时目录按用户
136
+ ## 隔离,Linux 用 XDG_RUNTIME_DIR,没有时在共享临时目录的文件名中带用户号。
137
+ def port_holder_file(port):
138
+ name = f"ehatool-{Path(str(port)).name}.pid"
139
+ runtime = os.environ.get("XDG_RUNTIME_DIR")
140
+ if runtime:
141
+ return Path(runtime) / name
142
+ if sys.platform.startswith("linux"):
143
+ name = f"ehatool-{os.getuid()}-{Path(str(port)).name}.pid"
144
+ return Path(tempfile.gettempdir()) / name
145
+
146
+
147
+ ## @brief 串口的持有者说明(进程号与命令);没有记录或该进程已不在时为空串。只在 POSIX 上判断进程是否存活。
148
+ def port_holder(port):
149
+ if os.name != "posix":
150
+ return ""
151
+ try:
152
+ pid, _, command = port_holder_file(port).read_text().partition(" ")
153
+ os.kill(int(pid), 0)
154
+ except (OSError, ValueError):
155
+ return ""
156
+ return f"进程 {pid}({command})"
157
+
158
+
159
+ ## @brief 主机链路:设备的字节流端口(USB CDC 或串口),帧为 COBS(cob_id u16 + 数据 + CRC-16) + 0x00。控制用
160
+ ## 过程数据帧:载荷由 od/eha_od.toml 的 [process_data] 定义,每发一帧控制数据,设备回一帧上一周期结束时的反馈。
161
+ ## @param port 串口路径;缺省按 USB VID:PID 自动查找。
162
+ ## @param baudrate 串口波特率;USB CDC 不使用,缺省不设置(pyserial 默认值)。
163
+ class StreamLink:
164
+ def __init__(self, port=None, *, timeout=0.05, write_timeout=0.2, baudrate=None):
165
+ import serial
166
+ import serial.tools.list_ports
167
+
168
+ if port is None:
169
+ found = [p.device for p in serial.tools.list_ports.comports() if (p.vid, p.pid) == (USB_VID, USB_PID)]
170
+ if not found:
171
+ raise RuntimeError(f"未找到 EHA USB 设备({USB_VID:04x}:{USB_PID:04x}),请指定串口")
172
+ if len(found) > 1:
173
+ raise RuntimeError(f"找到多台 EHA USB 设备({'、'.join(found)}),请用 --port 指定")
174
+ port = found[0]
175
+ options = {"timeout": timeout, "write_timeout": write_timeout}
176
+ if baudrate is not None:
177
+ options["baudrate"] = baudrate
178
+ # POSIX 排他锁在 pyserial 配置和清接收队列前取得,协作客户端不会互相吞应答。
179
+ if os.name == "posix":
180
+ options["exclusive"] = True
181
+ self.holder_file = port_holder_file(port)
182
+ try:
183
+ self.serial = serial.Serial(port, **options)
184
+ except serial.SerialException as error:
185
+ holder = port_holder(port)
186
+ if holder:
187
+ raise RuntimeError(MESSAGES["usb_busy"].format(port=port, holder=holder)) from error
188
+ raise
189
+ with contextlib.suppress(OSError):
190
+ command = " ".join([Path(sys.argv[0]).name] + sys.argv[1:])
191
+ self.holder_file.write_text(f"{os.getpid()} {command}")
192
+ self.buffer = bytearray()
193
+ self.stash = {}
194
+ self._deadline = None
195
+ self._closed = False
196
+
197
+ def close(self):
198
+ if not getattr(self, "_closed", False):
199
+ self.serial.close()
200
+ self._closed = True
201
+ with contextlib.suppress(OSError, IndexError):
202
+ if self.holder_file.read_text().split()[0] == str(os.getpid()):
203
+ self.holder_file.unlink()
204
+
205
+ def _stash(self, function, data):
206
+ limit = STASH_LIMIT.get(function)
207
+ if limit:
208
+ self.stash.setdefault(function, collections.deque(maxlen=limit)).append(data)
209
+
210
+ ## @brief 丢弃已收到而未读的应答与反馈:之后读到的都晚于下一次发送。示波帧不是对请求的应答,转入暂存,不丢失。
211
+ ## 不完整的尾部字节丢弃,其余部分到达时校验不过而被丢弃(与清接收队列相同)。
212
+ def drain(self):
213
+ _remaining(getattr(self, "_deadline", None))
214
+ waiting = self.serial.in_waiting
215
+ if waiting:
216
+ self.buffer += self.serial.read(waiting)
217
+ take_frame(self.buffer, None, self._stash)
218
+ self.buffer.clear()
219
+ _remaining(getattr(self, "_deadline", None))
220
+
221
+ ## @brief 不等待:读出已到达的字节,返回已收到的 function 帧(暂存的与新拆出的,按到达顺序)并清空其暂存。
222
+ def collect(self, function):
223
+ waiting = self.serial.in_waiting
224
+ if waiting:
225
+ self.buffer += self.serial.read(waiting)
226
+ while (data := take_frame(self.buffer, function, self._stash)) is not None:
227
+ self._stash(function, data)
228
+ return list(self.stash.pop(function, ()))
229
+
230
+ def send(self, cob_id, data):
231
+ deadline = getattr(self, "_deadline", None)
232
+ remaining = _remaining(deadline)
233
+ previous = self.serial.write_timeout
234
+ try:
235
+ if remaining is not None:
236
+ self.serial.write_timeout = min(previous, remaining) if previous is not None else remaining
237
+ encoded = frame_encode(cob_id, data) + b"\x00"
238
+ if self.serial.write(encoded) != len(encoded):
239
+ raise TimeoutError(MESSAGES["usb_short_write"])
240
+ _remaining(deadline)
241
+ finally:
242
+ self.serial.write_timeout = previous
243
+
244
+ ## @brief 发一帧 RxPDO 映像,等待之后到达的 TxPDO 映像;超时返回 None。values 以对象名为键,缺省为 0。
245
+ def command(self, od, values):
246
+ self.drain()
247
+ names, layout = od.pdo("rxpdo")
248
+ self.send(COB_RXPDO, layout.pack(*(values.get(name, 0) for name in names)))
249
+ resp = self.receive(COB_TXPDO, CAN_FEEDBACK_S)
250
+ names, layout = od.pdo("txpdo")
251
+ return dict(zip(names, layout.unpack(resp))) if resp is not None and len(resp) == layout.size else None
252
+
253
+ def receive(self, function, timeout=0.2):
254
+ stashed = getattr(self, "stash", {}).get(function)
255
+ if stashed:
256
+ return stashed.popleft()
257
+ deadline = time.monotonic() + timeout
258
+ transaction = getattr(self, "_deadline", None)
259
+ if transaction is not None:
260
+ deadline = min(deadline, transaction)
261
+ previous = self.serial.timeout
262
+ try:
263
+ while (remaining := deadline - time.monotonic()) > 0:
264
+ self.serial.timeout = min(previous, remaining) if previous is not None else remaining
265
+ self.buffer += self.serial.read(min(self.serial.in_waiting or 1, 4096))
266
+ data = take_frame(self.buffer, function, self._stash)
267
+ if data is not None:
268
+ return data
269
+ # 合法编码帧至多约 70 字节;无定界符的持续噪声不能无限积累。
270
+ if len(self.buffer) > 2 * (LINK_MAX_LEN + 6):
271
+ self.buffer.clear()
272
+ return None
273
+ finally:
274
+ self.serial.timeout = previous
275
+
276
+
277
+ ## @brief 一条控制命令的控制对象取值(RxPDO 的对象名为键)。力以 N 给出,写入力偏置 0x2102(0x6071 是额定力的
278
+ ## 千分比,10 kN 额定力下分辨率只有 10 N),0x6071 为 0。USB、CAN、SIL 与 EtherCAT 的驱动都由此打包。
279
+ def control_values(controlword, mode=0, motor_rpm=0.0, position_um=0, velocity_um_s=0, force_n=0.0, stiffness_n_mm=0.0,
280
+ damping_n_s_mm=0.0):
281
+ return {"controlword": controlword, "modes_of_operation": mode, "target_position_um": round(position_um),
282
+ "target_velocity_um_s": round(velocity_um_s), "target_force_permille": 0, "force_offset_n": force_n,
283
+ "target_motor_speed_rpm": motor_rpm, "impedance_stiffness_n_mm": stiffness_n_mm,
284
+ "impedance_damping_n_s_mm": damping_n_s_mm}
285
+
286
+
287
+ ## @brief 运动中止:设备进入 Fault,或持续收不到新的反馈。工具已按停机顺序收尾。
288
+ class DriveAborted(RuntimeError):
289
+ pass
290
+
291
+
292
+ ## @brief 运动中发现控制属主是其他通道:本工具的命令已被设备丢弃,工具停止发送,不对其他属主的会话发停机命令。
293
+ class ControlLost(DriveAborted):
294
+ pass
295
+
296
+
297
+ ## @brief 用户停止或发起运动的页面离开:由运动循环在下一个周期抛出,按停机顺序收尾(与 Ctrl-C 相同)。
298
+ class Cancelled(DriveAborted):
299
+ pass
300
+
301
+
302
+ ## @brief 运动开始前不能取得控制权(驱动正在运行、有待确认的故障或保护、其他通道在线持有控制权)。
303
+ ## 工具没有改变设备状态:至多经 SDO 把 0x6060 写为其当前值。
304
+ class ControlRefused(RuntimeError):
305
+ pass
306
+
307
+
308
+ ## @brief 运动类子命令的 --ack(见 Device.acquire):设备处于 Fault 或有锁存的保护时,由本工具发送故障复位;缺省拒绝运行,
309
+ ## 不替其他会话确认保护。
310
+ def add_ack(parser):
311
+ parser.add_argument("--ack", action="store_true",
312
+ help="设备处于 Fault 或有锁存的保护(statusword 位 7)时,查明原因后由本工具发送故障复位")
313
+
314
+
315
+ ## @brief 收尾后无法确认设备已断电(没有反馈或仍在运行):设备状态未知,按失联反应(0x6007)处理。
316
+ class DriveStateUnknown(RuntimeError):
317
+ pass
318
+
319
+
320
+ ## @brief SDO 中止。
321
+ class SdoAbort(RuntimeError):
322
+ def __init__(self, code, context="", request=None):
323
+ super().__init__(code)
324
+ self.code = code
325
+ self.request = request
326
+ self.diagnostic = decode_sdo_abort(code)
327
+ if request is not None:
328
+ self.diagnostic["request"] = request
329
+ if context:
330
+ self.diagnostic["context"] = context
331
+
332
+ def __str__(self):
333
+ from .output import render_diagnostic
334
+ return render_diagnostic(self.diagnostic)
335
+
336
+
337
+ ## @brief 对象字典客户端:快速 SDO 与控制命令(USB 过程数据帧、CAN 默认 PDO)。
338
+ class Device:
339
+ report = staticmethod(print)
340
+ # 读到身份后:型号表中没有的产品码记在这里,写入一律拒绝(见 adopt_identity)。
341
+ unknown_product = None
342
+
343
+ def __init__(self, link, od=None):
344
+ self.link = link
345
+ self.od = od or odmod.ObjectDictionary()
346
+ # acquire() 之后、motion() 结束之前为真:本通道已取得控制权;reset 为使能前是否先发故障复位(--ack)。
347
+ self.held = False
348
+ self.reset = False
349
+
350
+ ## @brief 匹配单次 SDO 应答;整个事务共用截止时间,超时不自动重发。
351
+ def _sdo_exchange(self, request, deadline, *, address=None, segment=False):
352
+ index, sub = address or struct.unpack_from("<HB", request, 1)
353
+ expected_address = struct.pack("<HB", index, sub)
354
+ with _bounded_io(self.link, deadline):
355
+ _remaining(deadline)
356
+ self.link.drain()
357
+ _remaining(deadline)
358
+ self.link.send(COB_SDO_RX, request)
359
+ while (remaining := deadline - time.monotonic()) > 0:
360
+ resp = self.link.receive(COB_SDO_TX, remaining)
361
+ if resp is None:
362
+ break
363
+ _remaining(deadline)
364
+ if len(resp) != 8:
365
+ continue
366
+ if resp[0] == 0x80:
367
+ if resp[1:4] != expected_address:
368
+ continue
369
+ operation = "read" if segment or request[0] == 0x40 else "write"
370
+ detail = {"operation": operation, "index": index, "subindex": sub}
371
+ raise SdoAbort(struct.unpack_from("<I", resp, 4)[0], request=detail)
372
+ if segment:
373
+ if resp[0] & 0xE0 == 0:
374
+ return resp
375
+ elif resp[1:4] == expected_address:
376
+ if request[0] == 0x40 and resp[0] & 0xE0 == 0x40:
377
+ return resp
378
+ if request[0] != 0x40 and resp[0] == 0x60:
379
+ return resp
380
+ hint = ";一直无应答时核对固件与 ehatool 是否同一次构建(ehatool --version、0x100A)" if isinstance(self.link, StreamLink) else ""
381
+ raise TimeoutError(f"SDO {odmod.format_address(index, sub)} 无应答(是否已执行未知){hint}")
382
+
383
+ def sdo(self, request, timeout=0.2, *, deadline=None):
384
+ end = time.monotonic() + timeout
385
+ if deadline is not None:
386
+ end = min(end, deadline)
387
+ return self._sdo_exchange(request, end)
388
+
389
+ def read(self, obj, timeout=0.2, *, deadline=None):
390
+ if isinstance(obj, str):
391
+ obj = self.od.lookup(obj)
392
+ resp = self.sdo(struct.pack("<BHB4x", 0x40, obj["index"], obj["sub"]), timeout, deadline=deadline)
393
+ expected = 0x43 | ((4 - odmod.size(obj)) << 2)
394
+ if resp[0] != expected:
395
+ raise RuntimeError(MESSAGES["sdo_numeric_type"].format(address=odmod.format_address(obj["index"], obj["sub"])))
396
+ return odmod.unpack(obj, resp, 4)
397
+
398
+ def read_identity(self, timeout=1.0, *, deadline=None, warn=None):
399
+ end = time.monotonic() + timeout
400
+ if deadline is not None:
401
+ end = min(end, deadline)
402
+ identity = {name: self.read(name, deadline=end)
403
+ for name in ("vendor_id", "product_code", "revision", "serial_number")}
404
+ self.adopt_identity(identity, warn)
405
+ return identity
406
+
407
+ ## @brief 按设备身份选型号:字典换成该型号可见的对象;产品码不在型号表中时保留原字典、记下原始身份,之后拒绝写入。
408
+ ## 构造时给出的字典(例如 --model)与设备不符时以设备为准,warn 收到一句提示。
409
+ def adopt_identity(self, identity, warn=None):
410
+ try:
411
+ od = self.od.for_identity(identity["vendor_id"], identity["product_code"])
412
+ except odmod.UnknownProduct as error:
413
+ self.unknown_product = error
414
+ return None
415
+ self.unknown_product = None
416
+ if warn is not None and self.od.model is not None and od is not self.od:
417
+ warn(f"--model {self.od.model['name']} 与设备身份不符,按设备的型号 {od.model['name']} 使用对象字典")
418
+ self.od = od
419
+ return od.model
420
+
421
+ ## @brief 有界的 CiA301 字符串上传;数值读取仍按对象类型检查快速上传宽度。
422
+ def sdo_upload(self, index, sub=0, timeout=1.0, *, deadline=None, max_size=4096):
423
+ end = time.monotonic() + timeout
424
+ if deadline is not None:
425
+ end = min(end, deadline)
426
+ request = struct.pack("<BHB4x", 0x40, index, sub)
427
+ response = self._sdo_exchange(request, end)
428
+ command = response[0]
429
+ if command & 0x02:
430
+ if command not in (0x42, 0x43, 0x47, 0x4B, 0x4F):
431
+ raise RuntimeError(MESSAGES["sdo_expedited_command"])
432
+ size = 4 - ((command >> 2) & 3) if command & 1 else 4
433
+ if size > max_size:
434
+ raise RuntimeError(MESSAGES["sdo_upload_limit"])
435
+ return response[4:4 + size]
436
+ if command not in (0x40, 0x41):
437
+ raise RuntimeError(MESSAGES["sdo_segment_command"])
438
+ announced = struct.unpack_from("<I", response, 4)[0] if command & 1 else None
439
+ if announced is not None and announced > max_size:
440
+ raise RuntimeError(MESSAGES["sdo_upload_limit"])
441
+ data = bytearray()
442
+ toggle = 0
443
+ while True:
444
+ request = bytes([0x60 | toggle << 4]) + bytes(7)
445
+ response = self._sdo_exchange(request, end, address=(index, sub), segment=True)
446
+ command = response[0]
447
+ unused = (command >> 1) & 7
448
+ if (command >> 4) & 1 != toggle or (not command & 1 and unused):
449
+ raise RuntimeError(MESSAGES["sdo_segment_toggle"])
450
+ data.extend(response[1:8 - unused])
451
+ if len(data) > max_size or announced is not None and len(data) > announced:
452
+ raise RuntimeError(MESSAGES["sdo_segment_limit"])
453
+ if command & 1:
454
+ if announced is not None and len(data) != announced:
455
+ raise RuntimeError(MESSAGES["sdo_segment_size"])
456
+ return bytes(data)
457
+ toggle ^= 1
458
+
459
+ def read_string(self, index, sub=0, timeout=1.0, *, deadline=None, max_size=4096):
460
+ return self.sdo_upload(index, sub, timeout, deadline=deadline, max_size=max_size).decode("utf-8", errors="replace")
461
+
462
+ ## @brief 写一个对象;timeout 缺省按对象取(保存与恢复出厂较长),运动中的调用方可给更短的等待以免拖慢控制节拍。
463
+ def write(self, obj, value, timeout=None):
464
+ if self.unknown_product is not None:
465
+ raise self.unknown_product
466
+ if isinstance(obj, str):
467
+ obj = self.od.lookup(obj)
468
+ if isinstance(value, str):
469
+ value = float(value) if obj["type"] == "f32" else int(value, 0)
470
+ # 保存与恢复出厂(0x1010/0x1011)在设备上擦写 Flash,应答晚于普通 SDO;超时后不重发(重发会再擦一次)。
471
+ if timeout is None and obj["index"] in (0x1010, 0x1011):
472
+ timeout = STORE_TIMEOUT_S
473
+ self._write(obj, value, timeout)
474
+
475
+ def _write(self, obj, value, timeout):
476
+ n = odmod.size(obj)
477
+ payload = odmod.pack(obj, value).ljust(4, b"\x00")
478
+ request = struct.pack("<BHB", 0x23 | ((4 - n) << 2), obj["index"], obj["sub"]) + payload
479
+ self.sdo(request, 0.2 if timeout is None else timeout)
480
+
481
+ ## @brief 开发者模式(0x2009)是否开启。
482
+ def developer(self):
483
+ return self.read("developer_mode") == DEVELOPER_SIGNATURE
484
+
485
+ ## @brief 本通道在 0x2005 中的编号:CAN 为 2,USB 为 3。
486
+ def channel(self):
487
+ return 2 if isinstance(self.link, CanLink) else 3
488
+
489
+ ## @brief 0x2005 的显示文字,例如 "CAN(在线)"。
490
+ @staticmethod
491
+ def owner_text(owner):
492
+ if owner & 0x7F == 0:
493
+ return "无"
494
+ return f"{CHANNEL_NAMES.get(owner & 0x7F, owner & 0x7F)}({'已失联' if owner & OWNER_LOST else '在线'})"
495
+
496
+ ## @brief 控制权在其他在线通道时给出一句说明(属主在线时本通道的控制数据被拒或丢弃),否则为空串。
497
+ ## 读取超时时也为空串:它只用于补充已有的错误说明,不掩盖原错误。
498
+ def holder_note(self):
499
+ try:
500
+ owner = self.read("control_owner")
501
+ except TimeoutError:
502
+ return ""
503
+ channel = owner & 0x7F
504
+ if channel in (0, self.channel()) or owner & OWNER_LOST:
505
+ return ""
506
+ return f"控制权在 {self.owner_text(owner)},须等它停发或失联后才能接管(ehatool info 查看)"
507
+
508
+ ## @brief 取权前只读检查:运行中或未确认的故障/锁存保护抛出 ControlRefused;返回取权后是否需要故障复位。
509
+ def _check_acquire(self, ack, confirm="加 --ack"):
510
+ sw = self.read("statusword")
511
+ state = state_name(sw)
512
+ if state in RUNNING:
513
+ raise ControlRefused(f"驱动正在运行({state},控制属主 {self.owner_text(self.read('control_owner'))}),"
514
+ "工具不接管运行中的驱动;先由当前主机停止")
515
+ faulted = state in ("Fault", "FaultReactionActive")
516
+ if (faulted or sw & SW_LATCHED) and not ack:
517
+ raise ControlRefused(f"设备{'处于 Fault' if faulted else '有锁存的保护'}(0x603F = 0x{self.read('error_code'):04X});"
518
+ f"查明原因后{confirm},由本工具发送故障复位")
519
+ return bool(faulted or sw & SW_LATCHED)
520
+
521
+ ## @brief 运动前取得控制权:在任何副作用(开发者模式、仿真参数、故障复位、使能)之前调用,按设备的受理裁定判断,
522
+ ## 不以先读到的 0x2005 为准。
523
+ ## 1. 只读:驱动在运行即拒绝,不论属主是谁、是否失联(工具不接管运行中的驱动);Fault 或位 7 锁存时没有 ack 即拒绝,
524
+ ## 不替其他会话确认保护。
525
+ ## 2. 经 SDO 把 0x6060 写为当前值:属主为其他在线通道时设备当场以 0x08000022 拒绝;写当前值不改变模式。
526
+ ## 3. 写入在下一个驱动周期提交:在 OWNER_CONFIRM_S 内轮询 0x2005,直到本通道在线。
527
+ ## 不能取得时抛出 ControlRefused。
528
+ def acquire(self, ack=False):
529
+ reset = self._check_acquire(ack)
530
+ if isinstance(self.link, CanLink):
531
+ self.can_preflight()
532
+ mode = self.read("modes_of_operation")
533
+ try:
534
+ self.write("modes_of_operation", mode)
535
+ except SdoAbort as error:
536
+ if error.code != ABORT_DEVICE_STATE:
537
+ raise
538
+ try:
539
+ note = self.holder_note()
540
+ except Exception:
541
+ # 补充诊断失败时保留原始写入中止。
542
+ note = ""
543
+ message = f"写入 modes_of_operation(0x6060:00)以取得控制权被拒绝\n{error}"
544
+ if note:
545
+ message += f"\n{note}"
546
+ raise ControlRefused(message) from None
547
+ end = time.monotonic() + OWNER_CONFIRM_S
548
+ while (owner := self.read("control_owner")) != self.channel():
549
+ if time.monotonic() > end:
550
+ raise ControlRefused(f"写入已受理,但控制属主仍为 {self.owner_text(owner)}")
551
+ time.sleep(0.002)
552
+ self.held, self.reset = True, reset
553
+
554
+ ## @brief CAN 上取得控制权之前的检查(只读,不发控制数据)。0x2005 只区分通道,同一总线上的另一台主机与本工具同为
555
+ ## "CAN",所以另外:
556
+ ## - 0x1016:01 已配置主机心跳时拒绝:本工具不发心跳,接管后经一个超时即被判失联;也不冒充那个主机节点;
557
+ ## - 本工具只按默认 PDO 收发:通信参数或映射与默认不符时拒绝,报出差异,不复位、不覆盖主站的配置;
558
+ ## - 侦听 2 × 0x2000:其间总线上有发往本节点 RPDO 或 SDO 服务器的帧,说明另一台主机仍在发送,拒绝。
559
+ def can_preflight(self):
560
+ node = self.link.node
561
+ heartbeat = self.read("host_heartbeat")
562
+ if heartbeat:
563
+ raise ControlRefused(f"0x1016:01 已配置主机心跳(节点 {heartbeat >> 16 & 0x7F},超时 {heartbeat & 0xFFFF} ms),"
564
+ "本工具不发心跳,接管后会被判失联;确认该主机离线后把 0x1016:01 写为 0")
565
+ mismatch = self.can_pdo_mismatch()
566
+ if mismatch:
567
+ raise ControlRefused("CAN PDO 与默认配置不符(ehatool 只按默认 PDO 收发,复位设备即恢复默认):" + ";".join(mismatch))
568
+ ids = {RPDO_COB[n] | node for n in range(len(RPDO_COB))} | {COB_SDO_RX | node}
569
+ heard = self.link.listen(2 * self.read("command_timeout_ms") / 1000, ids)
570
+ if heard:
571
+ raise ControlRefused(f"总线上另有主机在向节点 {node} 发送({'、'.join(f'0x{i:03X}' for i in sorted(heard))});"
572
+ "先让它停发或 NMT Stop 再接入")
573
+
574
+ ## @brief 设备当前的 CAN PDO 与默认配置(od/eha_od.toml 的 [canopen])的差异,每项一句;一致时为空列表。
575
+ ## 核对 COB-ID(含节点号与有效位)、传输类型须为事件驱动(254、255;同步型 RPDO 要等 SYNC,本工具不发)、TPDO 事件
576
+ ## 定时器须在 1 ms 到 CAN_FEEDBACK_S 之间、映射项的对象、子索引、位长与顺序。
577
+ def can_pdo_mismatch(self):
578
+ node, out = self.link.node, []
579
+
580
+ def raw(index, sub, kind="u32"):
581
+ return self.read({"index": index, "sub": sub, "type": kind})
582
+
583
+ for kind, comm, mapping, cobs in (("rpdo", 0x1400, 0x1600, RPDO_COB), ("tpdo", 0x1800, 0x1A00, TPDO_COB)):
584
+ for n, (names, _) in enumerate(self.od.canopen_pdos(kind)):
585
+ label = f"{kind.upper()}{n + 1}"
586
+ cob = raw(comm + n, 1)
587
+ if cob != cobs[n] | node:
588
+ out.append(f"{label} COB-ID 为 0x{cob:08X},默认 0x{cobs[n] | node:03X}")
589
+ transmission = raw(comm + n, 2, "u8")
590
+ if transmission not in (254, 255):
591
+ out.append(f"{label} 传输类型为 {transmission},须为 254 或 255")
592
+ if kind == "tpdo":
593
+ timer = raw(comm + n, 5, "u16")
594
+ if not 0 < timer < CAN_FEEDBACK_S * 1000:
595
+ out.append(f"{label} 事件定时器为 {timer} ms,须在 1–{CAN_FEEDBACK_S * 1000 - 1:.0f} ms")
596
+ want = [(o["index"] << 16) | (o["sub"] << 8) | 8 * odmod.size(o) for o in map(self.od.by_name.get, names)]
597
+ got = [raw(mapping + n, sub) for sub in range(1, raw(mapping + n, 0, "u8") + 1)]
598
+ if got != want:
599
+ out.append(f"{label} 映射为 [{', '.join(f'0x{v:08X}' for v in got)}],"
600
+ f"默认 [{', '.join(f'0x{v:08X}' for v in want)}]")
601
+ return out
602
+
603
+ ## @brief 属主是其他通道时抛出 ControlLost;否则返回 0x2005 的值(本通道、本通道已失联或无属主)。
604
+ def check_owner_channel(self):
605
+ owner = self.read("control_owner")
606
+ if owner & 0x7F not in (0, self.channel()):
607
+ raise ControlLost(f"控制属主为 {self.owner_text(owner)},本工具的命令已被丢弃;停止发送,设备状态由当前属主决定")
608
+ return owner
609
+
610
+ ## @brief 确认本通道是在线属主。属主是其他通道时抛出 ControlLost;本通道已失联或无属主时抛出 DriveAborted,由调用方
611
+ ## 照常停机(本通道再送来数据即恢复在线,停机命令仍会生效)。
612
+ def check_owner(self):
613
+ if self.check_owner_channel() != self.channel():
614
+ raise DriveAborted("本通道不是在线属主(命令间隔超过 0x2000 或未被受理),按停机顺序收尾")
615
+
616
+ ## @brief 进入或退出开发者模式并读回;只在驱动未运行时被接受,否则抛出 SdoAbort(0x08000022)。
617
+ def set_developer(self, on):
618
+ self.write("developer_mode", DEVELOPER_SIGNATURE if on else 0)
619
+ return self.developer()
620
+
621
+ ## @brief 开发操作(模式 -2、仿真外力)期间处于开发者模式:未开启时进入并打印一行提示,结束时由它退出。
622
+ ## 退出被拒绝(驱动仍在运行)时只打印提示,不掩盖原本的结果;复位后设备总是回到用户模式。
623
+ @contextlib.contextmanager
624
+ def developer_session(self, reason):
625
+ entered = not self.developer()
626
+ if entered:
627
+ self.set_developer(True)
628
+ self.report(f"已进入开发者模式({reason}),结束时退出")
629
+ try:
630
+ yield
631
+ finally:
632
+ if entered:
633
+ try:
634
+ self.set_developer(False)
635
+ except (SdoAbort, TimeoutError) as error:
636
+ self.report(f"退出开发者模式失败:{error};驱动停止后执行 ehatool dev off,或复位")
637
+
638
+ ## @brief 发送一条控制命令(字段见 control_values)并等待反馈;超时返回 None。反馈以对象名为键,另加 "state"。
639
+ ## USB 用过程数据帧(EtherCAT 的 RxPDO/TxPDO 映像);CAN 用默认 RPDO/TPDO。
640
+ def command(self, controlword, mode=0, motor_rpm=0.0, **fields):
641
+ if self.unknown_product is not None:
642
+ raise self.unknown_product
643
+ budget = getattr(self, "live_timeout", None)
644
+ with _bounded_io(self.link, time.monotonic() + budget if budget is not None else None):
645
+ fb = self.link.command(self.od, control_values(controlword, mode, motor_rpm, **fields))
646
+ if fb is None:
647
+ return None
648
+ fb["state"] = state_name(fb["statusword"])
649
+ return fb
650
+
651
+ ## @brief 发一次控制命令并要求反馈有效:设备进入 Fault 时抛出 DriveAborted;没有反馈时返回 None,由调用方按
652
+ ## 新鲜度判断(见 Motion)。
653
+ def command_checked(self, controlword, mode=0, **fields):
654
+ fb = self.command(controlword, mode, **fields)
655
+ if fb is not None and fb["state"] in ("Fault", "FaultReactionActive"):
656
+ raise DriveAborted(f"设备进入 {fb['state']},故障 0x{fb['error_code']:04X}")
657
+ return fb
658
+
659
+ ## @brief 停机:快停直到收到静止(|转速| < 5 rpm)或已断电的新反馈(最多 stop_s),再断电直到确认
660
+ ## SwitchOnDisabled 或 Fault(最多 0.5 s)。返回最后的反馈;无法确认已断电时抛出 DriveStateUnknown。
661
+ def stop(self, mode=0, fields=None, stop_s=2.0, period=0.01):
662
+ period = min(period, getattr(self, "live_timeout", None) or period)
663
+ fields = fields or {}
664
+ off = ("SwitchOnDisabled", "Fault", "NotReadyToSwitchOn")
665
+ fb, end = None, time.monotonic() + stop_s
666
+ while time.monotonic() < end:
667
+ fb = self.command(CW_QUICK_STOP, mode, **fields) or fb
668
+ if fb is not None and (fb["state"] in off or abs(fb["motor_speed_rpm"]) < 5.0):
669
+ break
670
+ time.sleep(period)
671
+ last, end = None, time.monotonic() + 0.5
672
+ while time.monotonic() < end:
673
+ last = self.command(CW_DISABLE_VOLTAGE, mode, **fields)
674
+ if last is not None and last["state"] in off:
675
+ return last
676
+ time.sleep(period)
677
+ raise DriveStateUnknown("收尾后未确认设备已断电(" + (f"最后状态 {last['state']}" if last else "没有反馈") +
678
+ "),设备按失联反应 0x6007 处理")
679
+
680
+ ## @brief 运动会话:先取得控制权(acquire(),调用方已取得时跳过),按 CiA402 顺序使能,确认 OperationEnabled、模式显示
681
+ ## 与请求一致、本通道仍是在线属主后才进入会话;退出时(正常、异常、Ctrl-C)按 stop() 的顺序收尾。会话中用 step()
682
+ ## 发送命令:Fault 或连续 stale_s 没有反馈即抛出 DriveAborted,属主变为其他通道时抛出 ControlLost(不发停机命令)。
683
+ ## 收尾失败与原始异常同时存在时保留原始异常,收尾结果另行打印。
684
+ @contextlib.contextmanager
685
+ def motion(self, mode, fields=None, stale_s=0.2, period=0.01, ack=False):
686
+ if not self.held:
687
+ self.acquire(ack)
688
+ session = Motion(self, mode, stale_s)
689
+ period = min(period, getattr(self, "live_timeout", None) or period)
690
+ fields = fields or {}
691
+ try:
692
+ with self.stopped_on_error(mode, fields):
693
+ for cw in ((CW_FAULT_RESET,) if self.reset else ()) + (CW_DISABLE_VOLTAGE, CW_SHUTDOWN):
694
+ self.command(cw, mode, **fields)
695
+ time.sleep(period)
696
+ fb, end = None, time.monotonic() + 0.5
697
+ while time.monotonic() < end:
698
+ fb = self.command(CW_ENABLE, mode, **fields) or fb
699
+ if fb is not None and fb["state"] == "OperationEnabled" and fb["modes_of_operation_display"] == mode:
700
+ break
701
+ time.sleep(period)
702
+ if fb is None or fb["state"] != "OperationEnabled" or fb["modes_of_operation_display"] != mode:
703
+ self.check_owner_channel()
704
+ shown = f"{fb['state']},模式显示 {fb['modes_of_operation_display']}" if fb else "没有反馈"
705
+ raise DriveAborted(f"使能失败:{shown}")
706
+ # 驱动未运行时 EtherCAT 进入 OP 即取得控制权,状态与模式相同也可能是它使能的:再确认一次属主。
707
+ self.check_owner()
708
+ session.fresh()
709
+ yield session
710
+ fb = self.stop(mode, session.last_fields or fields)
711
+ self.report(f"已停机:{fb['state']}")
712
+ finally:
713
+ self.held = self.reset = False
714
+
715
+ ## @brief 其中的代码异常退出(含 Ctrl-C)时按 stop() 的顺序停机,再抛出原来的异常;停机结果另行打印,不掩盖它。
716
+ ## 控制权已在其他通道(ControlLost)时不发停机命令:设备只执行属主的数据,停机命令既无效,也不该替属主作主。
717
+ @contextlib.contextmanager
718
+ def stopped_on_error(self, mode=0, fields=None):
719
+ try:
720
+ yield
721
+ except ControlLost:
722
+ raise
723
+ except BaseException:
724
+ try:
725
+ self.report(f"已停机:{self.stop(mode, fields)['state']}")
726
+ except DriveStateUnknown as error:
727
+ self.report(str(error))
728
+ except Exception as error: # 链路本身出错时停机也做不了:如实报告,保留原异常
729
+ self.report(f"停机失败:{error};设备按失联反应 0x6007 处理")
730
+ raise
731
+
732
+
733
+ ## @brief 运动会话中的命令发送、反馈新鲜度与属主复核。
734
+ class Motion:
735
+ def __init__(self, dev, mode, stale_s):
736
+ self.dev, self.mode, self.stale_s = dev, mode, stale_s
737
+ self.last_fields = None
738
+ self.fresh()
739
+
740
+ def fresh(self):
741
+ self._fresh_at = time.monotonic()
742
+ self._owner_at = self._fresh_at + OWNER_RECHECK_S
743
+
744
+ ## @brief 发送 Enable operation 与目标;返回反馈(可能为 None)。驱动离开 OperationEnabled(保护保持、失联、故障)
745
+ ## 或连续 stale_s 没有反馈时抛出 DriveAborted;每 OWNER_RECHECK_S 经 SDO 复核一次属主。设备会话启用 defer_owner_check 时
746
+ ## 只标记 owner_check_due,由同一线程的循环间隙优先复核,避免在发送步骤里叠加页面 SDO 请求。
747
+ def step(self, **fields):
748
+ self.last_fields = fields
749
+ fb = self.dev.command_checked(CW_ENABLE, self.mode, **fields)
750
+ now = time.monotonic()
751
+ if fb is not None:
752
+ if fb["state"] != "OperationEnabled":
753
+ self.dev.check_owner_channel()
754
+ raise DriveAborted(f"驱动离开运行:{fb['state']},故障 0x{fb['error_code']:04X}")
755
+ self._fresh_at = now
756
+ elif now - self._fresh_at > self.stale_s:
757
+ raise DriveAborted(f"{self.stale_s * 1000:.0f} ms 没有收到反馈")
758
+ if now >= self._owner_at:
759
+ if getattr(self.dev, "defer_owner_check", False):
760
+ self.dev.owner_check_due = True
761
+ else:
762
+ self.dev.check_owner()
763
+ self._owner_at = now + OWNER_RECHECK_S
764
+ return fb
765
+
766
+
767
+ ## @brief 试验驱动对 Device 的对象访问;主机链路与 SIL 的计时、使能和过程数据交换由各自驱动负责。
768
+ class _DeviceDriver:
769
+ def sdo_read(self, obj):
770
+ return self.dev.read(obj)
771
+
772
+ def sdo_write(self, obj, value):
773
+ self.dev.write(obj, value)
774
+
775
+ def developer(self):
776
+ return self.dev.developer()
777
+
778
+ def set_developer(self, on):
779
+ self.dev.set_developer(on)
780
+
781
+ def position_mm(self):
782
+ return self.dev.read("position_actual_um") / 1000
783
+
784
+
785
+ ## @brief 试验驱动(experiment.py):USB 或 CAN 上的 Device。时间取主机时间(time_source = host),约 200 Hz 发送;
786
+ ## prepare 取得控制权(Device.acquire),session 即 Device.motion(使能、新鲜度、属主复核与收尾)。
787
+ class LinkDriver(_DeviceDriver):
788
+ time_source = "host"
789
+ period_s = 0.005
790
+
791
+ def __init__(self, dev):
792
+ self.dev, self.od, self.stats = dev, dev.od, None
793
+ self.report = getattr(dev, "report", print)
794
+
795
+ def prepare(self, ack=False):
796
+ self.dev.acquire(ack)
797
+
798
+ @contextlib.contextmanager
799
+ def session(self, mode, fields):
800
+ with self.dev.motion(mode, fields) as motion:
801
+ yield _LinkSession(motion, min(self.period_s, getattr(self.dev, "live_timeout", None) or self.period_s))
802
+
803
+
804
+ class _LinkSession:
805
+ def __init__(self, motion, period_s):
806
+ self.motion, self.period_s = motion, period_s
807
+
808
+ def exchange(self, **fields):
809
+ fb = self.motion.step(**fields)
810
+ time.sleep(self.period_s)
811
+ return (time.monotonic(), fb) if fb is not None else None