uc2canopen 0.2.1__tar.gz → 0.2.3__tar.gz

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.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: uc2canopen
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Python CANopen master for openUC2 microscope hardware — control motors, lasers, LEDs, galvos directly over CAN bus (SocketCAN MCP2515 HAT or Waveshare USB-CAN-A adapter)
5
5
  Project-URL: Homepage, https://github.com/openUC2/uc2-esp32
6
6
  Project-URL: Documentation, https://openuc2.github.io
@@ -265,7 +265,7 @@ def sniff(serial_port: str, can_bitrate: int, serial_baudrate: int = 2_000_000):
265
265
 
266
266
  if __name__ == "__main__":
267
267
  #SERIAL_PORT = "/dev/cu.wchusbserial110" # Waveshare USB-CAN-A port
268
- SERIAL_PORT = "/dev/cu.usbserial-110"
268
+ SERIAL_PORT = "/dev/cu.usbserial-10"
269
269
  CAN_BITRATE = 500_000 # Must match the CAN network
270
270
  SERIAL_BAUDRATE = 2_000_000 # Waveshare default
271
271
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "uc2canopen"
3
- version = "0.2.1"
3
+ version = "0.2.3"
4
4
  description = "Python CANopen master for openUC2 microscope hardware — control motors, lasers, LEDs, galvos directly over CAN bus (SocketCAN MCP2515 HAT or Waveshare USB-CAN-A adapter)"
5
5
  readme = "README.md"
6
6
  license = { text = "MIT" }
@@ -19,6 +19,8 @@ Usage:
19
19
 
20
20
  # Waveshare USB-CAN-A adapter instead:
21
21
  python src/motor_demo.py --interface waveshare --port /dev/ttyUSB0 --motor-node 11
22
+ python src/motor_demo.py --interface waveshare --port /dev/cu.usbserial-10 --motor-node 11
23
+ python src/motor_demo.py --interface waveshare --port /dev/cu.wchusbserial10 --motor-node 11
22
24
  """
23
25
 
24
26
  from __future__ import annotations
@@ -45,6 +45,8 @@ _log = logging.getLogger(__name__)
45
45
 
46
46
  # TPDO1 COB-ID base
47
47
  TPDO1_BASE = 0x180
48
+ TPDO3_BASE = 0x380 # strobed-sweep position latch: i32 position + u16 count
49
+ SYNC_COB_ID = 0x080
48
50
  HB_BASE = 0x700
49
51
 
50
52
 
@@ -88,6 +90,7 @@ class TpdoListener(can.Listener):
88
90
  self._update_callbacks: list[Callable] = [] # every TPDO1 frame
89
91
  self._homing_callbacks: list[Callable] = [] # homing_status transitions
90
92
  self._heartbeat_callbacks: list[Callable] = [] # every heartbeat frame
93
+ self._sync_position_callbacks: list[Callable] = [] # every TPDO3 latch frame
91
94
 
92
95
  # Kept for API compatibility — no thread to start/stop now; the owning
93
96
  # UC2Client manages a shared can.Notifier instead.
@@ -122,6 +125,13 @@ class TpdoListener(can.Listener):
122
125
  """Register callback(node_id, NodeInfo) fired on every heartbeat frame."""
123
126
  self._heartbeat_callbacks.append(callback)
124
127
 
128
+ def on_sync_position(self, callback: Callable[[int, int, int], None]):
129
+ """Register callback(node_id, position_steps, sync_count) for TPDO3 latch frames.
130
+
131
+ Motor nodes send one per received SYNC while their latch (OD 0x200E) is on.
132
+ """
133
+ self._sync_position_callbacks.append(callback)
134
+
125
135
  def on_message_received(self, msg: can.Message) -> None:
126
136
  cob = msg.arbitration_id
127
137
  fc = cob & 0x780
@@ -171,6 +181,15 @@ class TpdoListener(can.Listener):
171
181
  except Exception:
172
182
  pass
173
183
 
184
+ elif fc == TPDO3_BASE and node_id and len(msg.data) >= 6:
185
+ # TPDO3: i32 latched position + u16 sync count (strobed sweep)
186
+ pos, count = struct.unpack_from("<iH", msg.data, 0)
187
+ for cb in self._sync_position_callbacks:
188
+ try:
189
+ cb(node_id, pos, count)
190
+ except Exception:
191
+ pass
192
+
174
193
  elif fc == HB_BASE and len(msg.data) >= 1:
175
194
  info = NodeInfo(
176
195
  node_id=node_id,
@@ -233,6 +252,20 @@ class Motor:
233
252
  self._listener = listener
234
253
  self.default_node = default_node
235
254
 
255
+ def enable_sync_latch(self, axis: int = 0, enable: bool = True,
256
+ node_id: Optional[int] = None) -> bool:
257
+ """Latch this node's position on every SYNC and send it in TPDO3 (0x380 + node).
258
+
259
+ Enabling writes 0 first so the node restarts its count at 1 for the next
260
+ SYNC (it polls the object every millisecond).
261
+ """
262
+ nid = node_id or self.default_node
263
+ sub = axis + 1
264
+ if enable:
265
+ self._sdo.write_u8(nid, OD.MOTOR_SYNC_LATCH_ENABLE, sub, 0)
266
+ time.sleep(0.01)
267
+ return bool(self._sdo.write_u8(nid, OD.MOTOR_SYNC_LATCH_ENABLE, sub, 1 if enable else 0))
268
+
236
269
  def move(self, axis: int = 0, position: int = 0, speed: int = 20000,
237
270
  acceleration: int = 0, is_absolute: bool = False,
238
271
  is_forever: bool = False, node_id: Optional[int] = None):
@@ -443,6 +476,33 @@ class Laser:
443
476
  nid = node_id or self.default_node
444
477
  self._sdo.write_u8(nid, OD.LASER_PWM_RESOLUTION, channel + 1, bits & 0xFF)
445
478
 
479
+ def configure_strobe(self, channel: int = 0, enable: bool = True, delay_us: int = 0,
480
+ width_us: int = 20, node_id: Optional[int] = None) -> bool:
481
+ """Strobe this node channel: one flash per received SYNC, delay_us after it.
482
+
483
+ Delay and width are written before enable so the node never flashes with
484
+ stale values. The node applies the request from its main loop and writes
485
+ the outcome back (enable 0 when refused, clamped delay/width): read it with
486
+ get_strobe() a few tens of milliseconds later.
487
+ """
488
+ nid = node_id or self.default_node
489
+ sub = channel + 1
490
+ if enable:
491
+ self._sdo.write_u32(nid, OD.LASER_STROBE_DELAY_US, sub, int(delay_us))
492
+ self._sdo.write_u32(nid, OD.LASER_STROBE_WIDTH_US, sub, int(width_us))
493
+ return bool(self._sdo.write_u8(nid, OD.LASER_STROBE_ENABLE, sub, 1 if enable else 0))
494
+
495
+ def get_strobe(self, channel: int = 0, node_id: Optional[int] = None) -> dict:
496
+ """Read back {'enabled', 'delay_us', 'width_us', 'count'} of a strobe channel."""
497
+ nid = node_id or self.default_node
498
+ sub = channel + 1
499
+ return {
500
+ "enabled": bool(self._sdo.read_u8(nid, OD.LASER_STROBE_ENABLE, sub)),
501
+ "delay_us": self._sdo.read_u32(nid, OD.LASER_STROBE_DELAY_US, sub),
502
+ "width_us": self._sdo.read_u32(nid, OD.LASER_STROBE_WIDTH_US, sub),
503
+ "count": self._sdo.read_u32(nid, OD.LASER_STROBE_COUNT, sub),
504
+ }
505
+
446
506
  def set_despeckle(self, channel: int = 0, period_us: int = 0, amplitude: int = 0,
447
507
  node_id: Optional[int] = None):
448
508
  """Configure laser despeckle modulation. period_us=0 disables it."""
@@ -901,6 +961,16 @@ class State:
901
961
  def reset_node(self, node_id: int = 0):
902
962
  self.send_nmt(node_id, 0x81)
903
963
 
964
+ def send_sync(self):
965
+ """Send one CANopen SYNC (COB-ID 0x080, no data).
966
+
967
+ Bench tool for the strobed sweep: strobing illumination nodes flash and
968
+ latching motor nodes report their position on every SYNC. In a real
969
+ sweep the ESP32 master sends SYNC so the camera trigger is aligned.
970
+ """
971
+ msg = can.Message(arbitration_id=SYNC_COB_ID, data=b"", is_extended_id=False)
972
+ self._sdo.bus.send(msg)
973
+
904
974
 
905
975
  # ============================================================================
906
976
  # Main client — the public API
@@ -951,6 +1021,7 @@ class UC2Client:
951
1021
  interface: Optional[str] = None,
952
1022
  channel: Optional[str] = None,
953
1023
  log_level: int = logging.WARNING,
1024
+ debug: bool = False
954
1025
  ):
955
1026
  # Configure the package-wide logger so all sub-modules (sdo, waveshare_bus)
956
1027
  # honour the same level. The caller controls verbosity; we never install
@@ -1012,6 +1083,15 @@ class UC2Client:
1012
1083
  # Expose the raw bus for advanced use
1013
1084
  self.bus = self._bus
1014
1085
 
1086
+ # --- strobed sweep bench helpers ---------------------------------------
1087
+ def send_sync(self):
1088
+ """Send one CANopen SYNC (see State.send_sync)."""
1089
+ self.state.send_sync()
1090
+
1091
+ def on_sync_position(self, callback):
1092
+ """Register callback(node_id, position_steps, sync_count) for TPDO3 latch frames."""
1093
+ self._listener.on_sync_position(callback)
1094
+
1015
1095
  def close(self):
1016
1096
  """Shut down the notifier and close the CAN bus."""
1017
1097
  try:
@@ -37,6 +37,10 @@ class OD:
37
37
  MOTOR_MAX_POSITION = 0x2009 # I32[4] soft limit max
38
38
  MOTOR_JERK = 0x200A # U32[4]
39
39
  MOTOR_IS_FOREVER = 0x200B # U8[4] continuous move
40
+ # strobed sweep position latch (TPDO3 = 0x380 + node: i32 position + u16 count)
41
+ MOTOR_SYNC_POSITION = 0x200C # I32[4] steps latched at the last SYNC (ro)
42
+ MOTOR_SYNC_COUNT = 0x200D # U16[4] SYNCs latched since enable (ro)
43
+ MOTOR_SYNC_LATCH_ENABLE = 0x200E # U8[4] 1 = latch on SYNC + send TPDO3
40
44
 
41
45
  # ── Homing (0x2010-0x2016) ──
42
46
  HOMING_COMMAND = 0x2010 # U8[4] 1=start
@@ -70,6 +74,11 @@ class OD:
70
74
  LASER_DESPECKLE_PERIOD = 0x2104 # U32[4] us (0=off)
71
75
  LASER_DESPECKLE_AMPLITUDE = 0x2105 # U16[4]
72
76
  LASER_SAFETY_STATE = 0x2106 # U8
77
+ # strobed sweep flash: one flash per received SYNC
78
+ LASER_STROBE_ENABLE = 0x2107 # U8[4] 1 = strobe on (PWM detached)
79
+ LASER_STROBE_DELAY_US = 0x2108 # U32[4] SYNC-to-flash delay, µs
80
+ LASER_STROBE_WIDTH_US = 0x2109 # U32[4] flash width, µs
81
+ LASER_STROBE_COUNT = 0x210A # U32[4] flashes since enable (ro)
73
82
 
74
83
  # ── LED (0x2200-0x2221) ──
75
84
  # Note: 0x2210 and 0x2211 are DOMAIN/segmented — not expedited SDO.
@@ -232,6 +241,9 @@ _ENTRIES: list[ODEntry] = [
232
241
  ODEntry(0x2009, "motor_max_position", "i", 4, 4, True),
233
242
  ODEntry(0x200A, "motor_jerk", "I", 4, 4, True),
234
243
  ODEntry(0x200B, "motor_is_forever", "B", 1, 4, True),
244
+ ODEntry(0x200C, "motor_sync_position", "i", 4, 4, False),
245
+ ODEntry(0x200D, "motor_sync_count", "H", 2, 4, False),
246
+ ODEntry(0x200E, "motor_sync_latch_enable", "B", 1, 4, True),
235
247
  # homing (0x2010-0x2015)
236
248
  ODEntry(0x2010, "homing_command", "B", 1, 4, True),
237
249
  ODEntry(0x2011, "homing_speed", "I", 4, 4, True),
@@ -261,6 +273,10 @@ _ENTRIES: list[ODEntry] = [
261
273
  ODEntry(0x2104, "laser_despeckle_period", "I", 4, 4, True),
262
274
  ODEntry(0x2105, "laser_despeckle_amplitude","H", 2, 4, True),
263
275
  ODEntry(0x2106, "laser_safety_state", "B", 1, 0, False),
276
+ ODEntry(0x2107, "laser_strobe_enable", "B", 1, 4, True),
277
+ ODEntry(0x2108, "laser_strobe_delay_us", "I", 4, 4, True),
278
+ ODEntry(0x2109, "laser_strobe_width_us", "I", 4, 4, True),
279
+ ODEntry(0x210A, "laser_strobe_count", "I", 4, 4, False),
264
280
  # led (0x2200-0x2221); 0x2210/2211 are DOMAIN/multi-byte — handle separately
265
281
  ODEntry(0x2200, "led_array_mode", "B", 1, 0, True),
266
282
  ODEntry(0x2201, "led_brightness", "B", 1, 0, True),
@@ -0,0 +1,192 @@
1
+ """Tests for uc2canopen.aio — asyncio facade + TpdoListener event bridging.
2
+
3
+ Hardware-free: synthetic `can.Message` frames are pushed straight into a
4
+ `TpdoListener`, and a stub client stands in for the SDO side, so we can
5
+ assert the full event pipeline (TPDO/heartbeat -> typed async events) and
6
+ `move_and_wait`'s done-edge / cancellation semantics.
7
+
8
+ Run:
9
+ pytest tests/test_aio.py -v
10
+ # or, without pytest installed:
11
+ python tests/test_aio.py
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import asyncio
17
+ import struct
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
22
+
23
+ import can # noqa: E402
24
+
25
+ from uc2canopen.aio import ( # noqa: E402
26
+ AsyncUC2Client,
27
+ HeartbeatEvent,
28
+ HomingChangedEvent,
29
+ MotorDoneEvent,
30
+ MotorUpdateEvent,
31
+ )
32
+ from uc2canopen.client import TpdoListener # noqa: E402
33
+
34
+
35
+ def tpdo1_frame(node_id: int, position: int, running: bool, homing: int = 0) -> can.Message:
36
+ """Build a synthetic TPDO1 frame (i32 position + u8 status + u8 homing)."""
37
+ data = struct.pack("<i", position) + bytes([1 if running else 0, homing])
38
+ return can.Message(arbitration_id=0x180 + node_id, data=data, is_extended_id=False)
39
+
40
+
41
+ def heartbeat_frame(node_id: int, nmt_state: int = 0x05) -> can.Message:
42
+ """Build a synthetic heartbeat frame."""
43
+ return can.Message(arbitration_id=0x700 + node_id, data=bytes([nmt_state]), is_extended_id=False)
44
+
45
+
46
+ class StubMotor:
47
+ """Records move/stop calls; no I/O."""
48
+
49
+ default_node = 11
50
+
51
+ def __init__(self):
52
+ self.moves = []
53
+ self.stops = []
54
+
55
+ def move(self, **kwargs):
56
+ self.moves.append(kwargs)
57
+
58
+ def stop(self, axis=0, node_id=None):
59
+ self.stops.append((axis, node_id))
60
+
61
+ def wait_for_idle(self, axis=0, node_id=None, timeout=5.0):
62
+ return True
63
+
64
+ def get_position(self, axis=0, node_id=None):
65
+ return 0
66
+
67
+
68
+ class StubClient:
69
+ """Stands in for UC2Client: a real TpdoListener + recording motor."""
70
+
71
+ def __init__(self):
72
+ self._listener = TpdoListener(bus=None)
73
+ self.motor = StubMotor()
74
+
75
+ def close(self):
76
+ pass
77
+
78
+
79
+ def test_events_bridge_tpdo_and_heartbeat():
80
+ """TPDO1/heartbeat frames come out of events() as typed async events."""
81
+
82
+ async def scenario():
83
+ stub = StubClient()
84
+ client = AsyncUC2Client(stub) # type: ignore[arg-type]
85
+
86
+ received = []
87
+
88
+ async def collect():
89
+ # frame1 -> update; frame2 -> update + homing-change + done-edge;
90
+ # heartbeat -> 1. Five events total.
91
+ async for event in client.events():
92
+ received.append(event)
93
+ if len(received) >= 5:
94
+ return
95
+
96
+ collector = asyncio.create_task(collect())
97
+ await asyncio.sleep(0) # let the collector subscribe
98
+
99
+ listener = stub._listener
100
+ listener.on_message_received(tpdo1_frame(11, 100, running=True))
101
+ listener.on_message_received(tpdo1_frame(11, 500, running=False, homing=2))
102
+ listener.on_message_received(heartbeat_frame(12))
103
+ await asyncio.wait_for(collector, timeout=2.0)
104
+ return received
105
+
106
+ received = asyncio.run(scenario())
107
+
108
+ updates = [e for e in received if isinstance(e, MotorUpdateEvent)]
109
+ assert len(updates) == 2 and updates[0].position == 100 and updates[0].running
110
+ dones = [e for e in received if isinstance(e, MotorDoneEvent)]
111
+ assert len(dones) == 1 and dones[0].position == 500 and dones[0].node_id == 11
112
+ homings = [e for e in received if isinstance(e, HomingChangedEvent)]
113
+ assert len(homings) == 1 and homings[0].status == 2
114
+ beats = [e for e in received if isinstance(e, HeartbeatEvent)]
115
+ assert len(beats) == 1 and beats[0].node_id == 12
116
+
117
+
118
+ def test_move_and_wait_resolves_on_done_edge():
119
+ """move_and_wait returns the final position when the running->stopped edge arrives."""
120
+
121
+ async def scenario():
122
+ stub = StubClient()
123
+ client = AsyncUC2Client(stub) # type: ignore[arg-type]
124
+
125
+ async def inject_done():
126
+ await asyncio.sleep(0.05)
127
+ stub._listener.on_message_received(tpdo1_frame(11, 0, running=True))
128
+ stub._listener.on_message_received(tpdo1_frame(11, 1234, running=False))
129
+
130
+ injector = asyncio.create_task(inject_done())
131
+ final = await client.move_and_wait(axis=0, position=1234, node_id=11, timeout=2.0)
132
+ await injector
133
+ return final, stub.motor.moves
134
+
135
+ final, moves = asyncio.run(scenario())
136
+ assert final == 1234
137
+ assert len(moves) == 1 and moves[0]["position"] == 1234
138
+
139
+
140
+ def test_move_and_wait_stops_motor_on_cancellation():
141
+ """Cancelling a pending move sends a stop to the hardware."""
142
+
143
+ async def scenario():
144
+ stub = StubClient()
145
+ client = AsyncUC2Client(stub) # type: ignore[arg-type]
146
+
147
+ task = asyncio.create_task(
148
+ client.move_and_wait(axis=0, position=99, node_id=11, timeout=10.0)
149
+ )
150
+ await asyncio.sleep(0.05)
151
+ task.cancel()
152
+ try:
153
+ await task
154
+ except asyncio.CancelledError:
155
+ pass
156
+ return stub.motor.stops
157
+
158
+ stops = asyncio.run(scenario())
159
+ assert stops == [(0, 11)]
160
+
161
+
162
+ def test_callbacks_fire_outside_listener_lock():
163
+ """A callback may safely read back cached state (regression: lock deadlock)."""
164
+ listener = TpdoListener(bus=None)
165
+ seen = []
166
+
167
+ def callback(node_id, axis, state):
168
+ # This get_motor() call would deadlock if callbacks fired under the lock.
169
+ seen.append(listener.get_motor(node_id, axis))
170
+
171
+ listener.on_motor_update(callback)
172
+ listener.on_message_received(tpdo1_frame(11, 42, running=False))
173
+ assert len(seen) == 1 and seen[0].position == 42
174
+
175
+
176
+ def _main() -> int:
177
+ """Self-runner (no pytest needed)."""
178
+ failures = 0
179
+ for name, fn in sorted(globals().items()):
180
+ if name.startswith("test_") and callable(fn):
181
+ try:
182
+ fn()
183
+ print(f"PASS {name}")
184
+ except Exception as exc: # noqa: BLE001
185
+ failures += 1
186
+ print(f"FAIL {name}: {exc!r}")
187
+ print(f"{'OK' if not failures else 'FAILED'}")
188
+ return failures
189
+
190
+
191
+ if __name__ == "__main__":
192
+ raise SystemExit(_main())
@@ -0,0 +1,115 @@
1
+ """Strobed-sweep additions: OD constants, strobe/latch SDO sequences, SYNC frame, TPDO3 decode.
2
+
3
+ Runs without CAN hardware: `.venv/bin/python -m pytest tests/test_strobe.py`.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ import struct
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ import can
13
+ import pytest
14
+
15
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
16
+
17
+ from uc2canopen.od import OD, SDO_TYPES # noqa: E402
18
+ from uc2canopen.client import Laser, Motor, State, TpdoListener, SYNC_COB_ID # noqa: E402
19
+
20
+
21
+ class RecordingSdo:
22
+ def __init__(self, reads=None):
23
+ self.writes = []
24
+ self._reads = reads or {}
25
+ self.bus = RecordingBus()
26
+
27
+ def _w(self, kind, n, i, s, v):
28
+ self.writes.append((kind, n, i, s, v))
29
+ return True
30
+
31
+ def write_u8(self, n, i, s, v): return self._w("u8", n, i, s, v)
32
+ def write_u16(self, n, i, s, v): return self._w("u16", n, i, s, v)
33
+ def write_u32(self, n, i, s, v): return self._w("u32", n, i, s, v)
34
+ def read_u8(self, n, i, s): return self._reads.get((i, s), 0)
35
+ def read_u32(self, n, i, s): return self._reads.get((i, s), 0)
36
+
37
+
38
+ class RecordingBus:
39
+ def __init__(self):
40
+ self.sent = []
41
+
42
+ def send(self, msg):
43
+ self.sent.append(msg)
44
+
45
+
46
+ def test_constants_and_types():
47
+ assert (OD.MOTOR_SYNC_POSITION, OD.MOTOR_SYNC_COUNT, OD.MOTOR_SYNC_LATCH_ENABLE) == (0x200C, 0x200D, 0x200E)
48
+ assert (OD.LASER_STROBE_ENABLE, OD.LASER_STROBE_DELAY_US,
49
+ OD.LASER_STROBE_WIDTH_US, OD.LASER_STROBE_COUNT) == (0x2107, 0x2108, 0x2109, 0x210A)
50
+ assert SDO_TYPES[0x200C].fmt == "i" and SDO_TYPES[0x200D].fmt == "H"
51
+ assert SDO_TYPES[0x2108].fmt == "I" and SDO_TYPES[0x2107].fmt == "B"
52
+ assert not SDO_TYPES[0x210A].writable and SDO_TYPES[0x2109].writable
53
+
54
+
55
+ def test_constants_match_firmware_registry():
56
+ """od.py is hand-copied from uc2-ESP's generated indices; fail loudly on drift."""
57
+ fw = Path(__file__).resolve().parents[2] / "uc2-ESP" / "PYTHON" / "uc2_canopen" / "uc2_indices.py"
58
+ if not fw.exists():
59
+ pytest.skip("uc2-ESP checkout not next to this repo")
60
+ text = fw.read_text()
61
+ for name in ("MOTOR_SYNC_POSITION", "MOTOR_SYNC_COUNT", "MOTOR_SYNC_LATCH_ENABLE",
62
+ "LASER_STROBE_ENABLE", "LASER_STROBE_DELAY_US", "LASER_STROBE_WIDTH_US",
63
+ "LASER_STROBE_COUNT"):
64
+ m = re.search(rf"^\s*{name}\s*=\s*(0x[0-9A-Fa-f]+)", text, re.M)
65
+ assert m, f"{name} missing in firmware registry"
66
+ assert int(m.group(1), 16) == getattr(OD, name), name
67
+
68
+
69
+ def test_configure_strobe_writes_delay_width_then_enable():
70
+ sdo = RecordingSdo()
71
+ Laser(sdo, default_node=30).configure_strobe(channel=0, enable=True, delay_us=1200, width_us=20)
72
+ assert sdo.writes == [
73
+ ("u32", 30, 0x2108, 1, 1200),
74
+ ("u32", 30, 0x2109, 1, 20),
75
+ ("u8", 30, 0x2107, 1, 1),
76
+ ]
77
+ sdo.writes.clear()
78
+ Laser(sdo, default_node=30).configure_strobe(channel=0, enable=False)
79
+ assert sdo.writes == [("u8", 30, 0x2107, 1, 0)]
80
+
81
+
82
+ def test_get_strobe_reads_back():
83
+ sdo = RecordingSdo({(0x2107, 1): 1, (0x2108, 1): 1200, (0x2109, 1): 20, (0x210A, 1): 480})
84
+ assert Laser(sdo, default_node=30).get_strobe(0) == {
85
+ "enabled": True, "delay_us": 1200, "width_us": 20, "count": 480}
86
+
87
+
88
+ def test_enable_sync_latch_resets_then_enables():
89
+ sdo = RecordingSdo()
90
+ Motor(sdo, listener=None, default_node=11).enable_sync_latch(axis=0, enable=True)
91
+ assert sdo.writes == [("u8", 11, 0x200E, 1, 0), ("u8", 11, 0x200E, 1, 1)]
92
+ sdo.writes.clear()
93
+ Motor(sdo, listener=None, default_node=11).enable_sync_latch(axis=0, enable=False)
94
+ assert sdo.writes == [("u8", 11, 0x200E, 1, 0)]
95
+
96
+
97
+ def test_send_sync_frame():
98
+ sdo = RecordingSdo()
99
+ State(sdo, None).send_sync()
100
+ (msg,) = sdo.bus.sent
101
+ assert msg.arbitration_id == SYNC_COB_ID == 0x080
102
+ assert not msg.is_extended_id and len(msg.data) == 0
103
+
104
+
105
+ def test_tpdo3_decode():
106
+ listener = TpdoListener(bus=None)
107
+ got = []
108
+ listener.on_sync_position(lambda node, pos, count: got.append((node, pos, count)))
109
+ listener.on_message_received(can.Message(arbitration_id=0x380 + 11,
110
+ data=struct.pack("<iH", -123456, 17), is_extended_id=False))
111
+ # short frame and other function codes are ignored
112
+ listener.on_message_received(can.Message(arbitration_id=0x380 + 11, data=b"\x01\x02", is_extended_id=False))
113
+ listener.on_message_received(can.Message(arbitration_id=0x480 + 11,
114
+ data=struct.pack("<iH", 1, 1), is_extended_id=False))
115
+ assert got == [(11, -123456, 17)]
File without changes
File without changes
File without changes
File without changes