uc2canopen 0.2.2__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
1
  Metadata-Version: 2.5
2
2
  Name: uc2canopen
3
- Version: 0.2.2
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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "uc2canopen"
3
- version = "0.2.2"
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" }
@@ -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
@@ -1013,6 +1083,15 @@ class UC2Client:
1013
1083
  # Expose the raw bus for advanced use
1014
1084
  self.bus = self._bus
1015
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
+
1016
1095
  def close(self):
1017
1096
  """Shut down the notifier and close the CAN bus."""
1018
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,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
File without changes
File without changes