uc2canopen 0.1.4__tar.gz → 0.2.2__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.
@@ -0,0 +1,95 @@
1
+ # Changelog
2
+
3
+ All notable changes to `uc2canopen` are documented here. The format is based on
4
+ [Keep a Changelog](https://keepachangelog.com/), and this project adheres to
5
+ semantic versioning.
6
+
7
+ ## [0.2.0] — 2026-07-15
8
+
9
+ Sync with the openUC2 ESP32 firmware CANopen interface (`uc2_canopen_registry.yaml`
10
+ / `UC2_OD_Indices.h`). This release adds high-level controllers for every device
11
+ class the firmware now exposes and brings the Object Dictionary in `od.py` up to
12
+ date with the current registry.
13
+
14
+ ### Added — new device controllers on `UC2Client`
15
+
16
+ - **`uc2.galvo`** (`Galvo`) — galvo mirror scanner (OD `0x2600`):
17
+ - `set_position(x, y)` / `goto(...)` — absolute XY move (DAC counts) + `GOTO`.
18
+ - `raster_scan(...)` — full XY raster; mirrors the firmware
19
+ `DeviceRouter::handleGalvoAct` config path, including the reused transport
20
+ slots (`0x2607` → bidirectional, `0x2608` → line-settle samples) and the
21
+ `x_step`/`y_step = (max − min) // n` computation.
22
+ - `line_scan(...)` — single X-sweep line scan.
23
+ - `stop()`, `estop()`, `get_position()`, `get_status()` (decoded flag dict).
24
+ - Command-word (`CMD_*`) and camera-trigger (`TRIGGER_*`) constants.
25
+ - **`uc2.pid`** (`Pid`) — generic PID loop (OD `0x2700`): `set_setpoint`,
26
+ `set_gains(kp, ki, kd)`, `set_enabled`, `get_actual`.
27
+ - **`uc2.encoder`** (`Encoder`) — quadrature/AS5600 feedback (OD `0x2340`):
28
+ `get_position`, `get_velocity`, `set_zero`.
29
+ - **`uc2.digital`** (`DigitalIO`) — digital inputs/outputs (OD `0x2300`):
30
+ `read_input`, `write_output`.
31
+ - **`uc2.analog`** (`Analog`) — ADC in / DAC out (OD `0x2310`/`0x2320`):
32
+ `read_input`, `read_filtered`, `write_dac`.
33
+ - **`uc2.collision`** (`Collision`) — baseline-deviation collision detector on
34
+ the GPIO slave (OD `0x2330`): `configure`, `calibrate`, `get_mean`,
35
+ `get_sigma`, with `MODE_AUTO` / `MODE_MANUAL`.
36
+
37
+ ### Added — extensions to existing controllers
38
+
39
+ - `Motor`: `get_homing_status` / `wait_for_homed` (via new `HOMING_STATUS`
40
+ `0x2016`, also broadcast on TPDO1 byte 5), `set_soft_limits`,
41
+ `set_acceleration`, `configure_tmc`, `set_hardlimit`, `clear_hardlimit`, plus
42
+ `HOME_*` status constants.
43
+ - `Laser`: `get_max_value`, `set_pwm_frequency`, `set_pwm_resolution`,
44
+ `set_despeckle` (new `LASER_DESPECKLE_PERIOD` `0x2104` / `_AMPLITUDE` `0x2105`),
45
+ `get_safety_state`.
46
+ - `Led`: `set_mode`, `set_pattern`, `get_pixel_count`, plus `MODE_*` and
47
+ `PATTERN_*` constants.
48
+ - `State`: `get_cpu_temperature` (`0x2506`), `get_can_errors`,
49
+ `get_enabled_modules` (`0x2502`), and `set_node_id` (node provisioning via
50
+ `COMMANDED_NODE_ID` `0x250A`).
51
+
52
+ ### Added — Object Dictionary (`od.py`)
53
+
54
+ New index constants and expedited-SDO type entries mirroring the firmware:
55
+
56
+ - Homing: `HOMING_STATUS` (`0x2016`).
57
+ - Laser: `LASER_DESPECKLE_PERIOD` (`0x2104`), `LASER_DESPECKLE_AMPLITUDE` (`0x2105`).
58
+ - LED: `LED_LAYOUT_WIDTH` (`0x2204`), `LED_LAYOUT_HEIGHT` (`0x2205`),
59
+ `LED_SHAPE` (`0x2212`, DOMAIN).
60
+ - Collision: `COLLISION_REFERENCE`…`COLLISION_SIGMA` (`0x2330`–`0x2336`).
61
+ - I2C bridge: `I2C_COMMAND`…`I2C_RESP_LEN` (`0x2350`–`0x2354`; buffers are DOMAIN).
62
+ - System: `BUILD_TIMESTAMP` (`0x2508`), `MAC_ADDRESS` (`0x2509`),
63
+ `COMMANDED_NODE_ID` (`0x250A`); `CPU_TEMPERATURE` (`0x2506`) is now a real
64
+ packable entry.
65
+ - Galvo: `GALVO_POINTS_DATA` (`0x2610`, DOMAIN).
66
+ - Also added expedited type-table entries that were previously index-only:
67
+ encoder velocity/zero-offset, DAC output, analog filtered, digital
68
+ change-mask, joystick, `ENABLED_MODULES`, and the full PID block.
69
+
70
+ ### Changed
71
+
72
+ - `GALVO_CAMERA_TRIGGER` (`0x260F`) renamed to **`GALVO_CAMERA_TRIGGER_MODE`** to
73
+ match the firmware. The old name remains as a deprecated alias.
74
+ - TPDO1 listener now parses the optional 6th byte (per-axis homing status) and
75
+ stores it on `MotorState.homing_status`; older 5-byte frames still work.
76
+ - Package `__version__` corrected to track the packaged version (was stuck at
77
+ `0.1.0`); now `0.2.0`.
78
+ - New controller classes are exported from the top-level package
79
+ (`from uc2canopen import Galvo, Pid, Encoder, …`).
80
+
81
+ ### Notes / limitations
82
+
83
+ - DOMAIN entries (arbitrary galvo point lists `0x2610`, LED pixel/shape data,
84
+ raw-I2C buffers `0x2350`/`0x2353`, OTA) and STRING reads (`0x2500`, `0x2508`,
85
+ `0x2509`) require **segmented/block SDO transfer**, which the current
86
+ expedited-only `SdoClient` does not implement. Their index constants are
87
+ provided; the transport is a follow-up.
88
+ - `tests/test_new_features.py` validates the exact SDO traffic for every new
89
+ command against the firmware mapping, with no hardware required. An optional
90
+ live smoke test runs with `UC2_LIVE=1`.
91
+
92
+ ## [0.1.4] and earlier
93
+
94
+ Initial motor / laser / led / state controllers over CANopen SDO, with SocketCAN
95
+ (MCP2515 HAT) and Waveshare USB-CAN-A transports. See git history for details.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: uc2canopen
3
- Version: 0.1.4
3
+ Version: 0.2.2
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
@@ -169,9 +169,36 @@ uc2.laser.set_value(channel=0, pwm=512, node_id=NODE.LASER_0) # laser 50%
169
169
  uc2.led.fill(r=255, g=0, b=0, node_id=NODE.LED_0) # LEDs red
170
170
  print(f"Uptime: {uc2.state.get_uptime(NODE.MOT_X)}s")
171
171
 
172
+ # Galvo scanner: centre, raster scan, stop
173
+ uc2.galvo.set_position(2048, 2048, node_id=NODE.GALVO)
174
+ uc2.galvo.raster_scan(nx=128, ny=128, sample_period_us=2, node_id=NODE.GALVO)
175
+ uc2.galvo.stop(node_id=NODE.GALVO)
176
+
172
177
  uc2.close()
173
178
  ```
174
179
 
180
+ ### Device modules
181
+
182
+ `UC2Client` exposes one controller per firmware device class (all mirror the
183
+ CANopen Object Dictionary in `od.py`):
184
+
185
+ | Module | Highlights |
186
+ |---|---|
187
+ | `uc2.motor` | `move`, `home`/`wait_for_homed`, `get_homing_status`, `set_soft_limits`, `configure_tmc`, `set_hardlimit` |
188
+ | `uc2.laser` | `set_value`, `set_pwm_frequency`/`_resolution`, `set_despeckle`, `get_safety_state` |
189
+ | `uc2.led` | `fill`, `set_mode`, `set_pattern` (rainbow/fire/…), `set_brightness` |
190
+ | `uc2.galvo` | `set_position`/`goto`, `line_scan`, `raster_scan`, `stop`/`estop`, `get_status` |
191
+ | `uc2.pid` | `set_setpoint`, `set_gains`, `set_enabled`, `get_actual` |
192
+ | `uc2.encoder` | `get_position`, `get_velocity`, `set_zero` |
193
+ | `uc2.digital` | `read_input`, `write_output` |
194
+ | `uc2.analog` | `read_input`, `read_filtered`, `write_dac` |
195
+ | `uc2.collision` | `configure`, `calibrate`, `get_mean`, `get_sigma` |
196
+ | `uc2.state` | `get_uptime`, `get_cpu_temperature`, `get_enabled_modules`, `scan_nodes`, `set_node_id` |
197
+
198
+ See [`CHANGELOG.md`](CHANGELOG.md) for the full 0.2.0 feature list and
199
+ [`tests/test_new_features.py`](tests/test_new_features.py) for runnable examples
200
+ of every new command.
201
+
175
202
  ## 5. CLI
176
203
 
177
204
  The `uc2can` command also defaults to SocketCAN `can0`:
@@ -151,9 +151,36 @@ uc2.laser.set_value(channel=0, pwm=512, node_id=NODE.LASER_0) # laser 50%
151
151
  uc2.led.fill(r=255, g=0, b=0, node_id=NODE.LED_0) # LEDs red
152
152
  print(f"Uptime: {uc2.state.get_uptime(NODE.MOT_X)}s")
153
153
 
154
+ # Galvo scanner: centre, raster scan, stop
155
+ uc2.galvo.set_position(2048, 2048, node_id=NODE.GALVO)
156
+ uc2.galvo.raster_scan(nx=128, ny=128, sample_period_us=2, node_id=NODE.GALVO)
157
+ uc2.galvo.stop(node_id=NODE.GALVO)
158
+
154
159
  uc2.close()
155
160
  ```
156
161
 
162
+ ### Device modules
163
+
164
+ `UC2Client` exposes one controller per firmware device class (all mirror the
165
+ CANopen Object Dictionary in `od.py`):
166
+
167
+ | Module | Highlights |
168
+ |---|---|
169
+ | `uc2.motor` | `move`, `home`/`wait_for_homed`, `get_homing_status`, `set_soft_limits`, `configure_tmc`, `set_hardlimit` |
170
+ | `uc2.laser` | `set_value`, `set_pwm_frequency`/`_resolution`, `set_despeckle`, `get_safety_state` |
171
+ | `uc2.led` | `fill`, `set_mode`, `set_pattern` (rainbow/fire/…), `set_brightness` |
172
+ | `uc2.galvo` | `set_position`/`goto`, `line_scan`, `raster_scan`, `stop`/`estop`, `get_status` |
173
+ | `uc2.pid` | `set_setpoint`, `set_gains`, `set_enabled`, `get_actual` |
174
+ | `uc2.encoder` | `get_position`, `get_velocity`, `set_zero` |
175
+ | `uc2.digital` | `read_input`, `write_output` |
176
+ | `uc2.analog` | `read_input`, `read_filtered`, `write_dac` |
177
+ | `uc2.collision` | `configure`, `calibrate`, `get_mean`, `get_sigma` |
178
+ | `uc2.state` | `get_uptime`, `get_cpu_temperature`, `get_enabled_modules`, `scan_nodes`, `set_node_id` |
179
+
180
+ See [`CHANGELOG.md`](CHANGELOG.md) for the full 0.2.0 feature list and
181
+ [`tests/test_new_features.py`](tests/test_new_features.py) for runnable examples
182
+ of every new command.
183
+
157
184
  ## 5. CLI
158
185
 
159
186
  The `uc2can` command also defaults to SocketCAN `can0`:
@@ -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.1.4"
3
+ version = "0.2.2"
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
@@ -9,6 +9,7 @@ Quick start:
9
9
  uc2.motor.wait_for_idle(axis=0, node_id=NODE.MOT_X)
10
10
  uc2.laser.set_value(channel=0, pwm=512, node_id=NODE.LASER_0)
11
11
  uc2.led.fill(r=255, g=0, b=0, node_id=NODE.LED_0)
12
+ uc2.galvo.raster_scan(nx=128, ny=128, node_id=NODE.GALVO)
12
13
  uc2.close()
13
14
  """
14
15
 
@@ -18,13 +19,47 @@ import logging
18
19
  # discarded unless the application configures a handler.
19
20
  logging.getLogger(__name__).addHandler(logging.NullHandler())
20
21
 
21
- from .client import UC2Client
22
+ from .client import (
23
+ UC2Client,
24
+ Motor,
25
+ Laser,
26
+ Led,
27
+ Galvo,
28
+ Pid,
29
+ Encoder,
30
+ DigitalIO,
31
+ Analog,
32
+ Collision,
33
+ State,
34
+ )
22
35
  from .od import OD, NODE
23
36
  from .sdo import SdoClient, SdoError
24
37
  from .waveshare_bus import WaveshareBus, find_waveshare_port
38
+ from .aio import (
39
+ AsyncUC2Client,
40
+ MotorUpdateEvent,
41
+ MotorDoneEvent,
42
+ HomingChangedEvent,
43
+ HeartbeatEvent,
44
+ )
25
45
 
26
46
  __all__ = [
47
+ "AsyncUC2Client",
48
+ "MotorUpdateEvent",
49
+ "MotorDoneEvent",
50
+ "HomingChangedEvent",
51
+ "HeartbeatEvent",
27
52
  "UC2Client",
53
+ "Motor",
54
+ "Laser",
55
+ "Led",
56
+ "Galvo",
57
+ "Pid",
58
+ "Encoder",
59
+ "DigitalIO",
60
+ "Analog",
61
+ "Collision",
62
+ "State",
28
63
  "OD",
29
64
  "NODE",
30
65
  "SdoClient",
@@ -33,4 +68,4 @@ __all__ = [
33
68
  "find_waveshare_port",
34
69
  ]
35
70
 
36
- __version__ = "0.1.0"
71
+ __version__ = "0.2.0"
@@ -0,0 +1,318 @@
1
+ """
2
+ Asyncio facade for uc2canopen.
3
+
4
+ Wraps the blocking `UC2Client` so it can be driven from asyncio applications
5
+ (e.g. the newswitch backend) without blocking the event loop. Every blocking
6
+ call is executed via `asyncio.to_thread`; asynchronous hardware events
7
+ (TPDO frames, heartbeats) arriving on the python-can notifier thread are
8
+ bridged onto the event loop and exposed as a typed async event stream.
9
+
10
+ This module is purely additive: the synchronous `UC2Client` API is unchanged
11
+ and remains the interface consumed by ImSwitch.
12
+
13
+ Usage:
14
+ from uc2canopen.aio import AsyncUC2Client
15
+
16
+ uc2 = await AsyncUC2Client.create(channel="can0")
17
+ await uc2.move(axis=0, position=1000, speed=20000, node_id=11)
18
+ await uc2.wait_for_idle(axis=0, node_id=11)
19
+
20
+ async for event in uc2.events():
21
+ print(event)
22
+
23
+ await uc2.aclose()
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import asyncio
29
+ import logging
30
+ from dataclasses import dataclass
31
+ from typing import Any, AsyncIterator, Callable, Optional, Union
32
+
33
+ from .client import MotorState, NodeInfo, UC2Client
34
+
35
+ _log = logging.getLogger(__name__)
36
+
37
+ # Default per-subscriber queue size. When a slow consumer falls behind, the
38
+ # oldest events are dropped (position streams are idempotent snapshots).
39
+ _DEFAULT_QUEUE_SIZE = 1024
40
+
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Typed events
44
+ # ---------------------------------------------------------------------------
45
+
46
+ @dataclass(frozen=True)
47
+ class MotorUpdateEvent:
48
+ """Periodic motor snapshot from a TPDO1 frame."""
49
+
50
+ node_id: int
51
+ axis: int
52
+ position: int
53
+ running: bool
54
+ homing_status: int
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class MotorDoneEvent:
59
+ """A motor transitioned from running to stopped."""
60
+
61
+ node_id: int
62
+ axis: int
63
+ position: int
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class HomingChangedEvent:
68
+ """The homing phase of an axis changed (0=idle, 1=homing, 2=done, 3=timeout)."""
69
+
70
+ node_id: int
71
+ axis: int
72
+ status: int
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class HeartbeatEvent:
77
+ """A CANopen heartbeat was received from a node."""
78
+
79
+ node_id: int
80
+ nmt_state: int
81
+
82
+
83
+ CanEvent = Union[MotorUpdateEvent, MotorDoneEvent, HomingChangedEvent, HeartbeatEvent]
84
+
85
+
86
+ # ---------------------------------------------------------------------------
87
+ # Async client
88
+ # ---------------------------------------------------------------------------
89
+
90
+ class AsyncUC2Client:
91
+ """Asyncio wrapper around the blocking `UC2Client`.
92
+
93
+ Construct with `await AsyncUC2Client.create(...)` (same kwargs as
94
+ `UC2Client`). The underlying sync client is available as `.sync` for
95
+ anything not wrapped explicitly; `await client.call(fn, ...)` runs any
96
+ blocking callable off-loop.
97
+ """
98
+
99
+ def __init__(self, client: UC2Client, loop: Optional[asyncio.AbstractEventLoop] = None):
100
+ self._client = client
101
+ self._loop = loop or asyncio.get_running_loop()
102
+ self._queues: list[asyncio.Queue[CanEvent]] = []
103
+ self._motion_waiters: dict[tuple[int, int], list[asyncio.Future[int]]] = {}
104
+ self._closed = False
105
+
106
+ listener = client._listener
107
+ listener.on_motor_update(self._on_motor_update)
108
+ listener.on_motor_done(self._on_motor_done)
109
+ listener.on_homing_changed(self._on_homing_changed)
110
+ listener.on_heartbeat(self._on_heartbeat)
111
+
112
+ @classmethod
113
+ async def create(cls, **kwargs: Any) -> "AsyncUC2Client":
114
+ """Open the CAN bus off-loop and return a ready async client.
115
+
116
+ Accepts the same keyword arguments as `UC2Client` (port, bitrate,
117
+ interface, channel, sdo_timeout, ...).
118
+ """
119
+ loop = asyncio.get_running_loop()
120
+ client = await asyncio.to_thread(UC2Client, **kwargs)
121
+ return cls(client, loop=loop)
122
+
123
+ # -- plumbing -----------------------------------------------------------
124
+
125
+ @property
126
+ def sync(self) -> UC2Client:
127
+ """The wrapped synchronous client (full uc2canopen API surface)."""
128
+ return self._client
129
+
130
+ async def call(self, fn: Callable[..., Any], /, *args: Any, **kwargs: Any) -> Any:
131
+ """Run any blocking callable (e.g. `client.sync.motor.get_position`) off-loop."""
132
+ return await asyncio.to_thread(fn, *args, **kwargs)
133
+
134
+ async def aclose(self) -> None:
135
+ """Shut down the notifier and close the CAN bus."""
136
+ self._closed = True
137
+ await asyncio.to_thread(self._client.close)
138
+
139
+ async def __aenter__(self) -> "AsyncUC2Client":
140
+ return self
141
+
142
+ async def __aexit__(self, *args: Any) -> None:
143
+ await self.aclose()
144
+
145
+ # -- event bridge (notifier thread -> event loop) ------------------------
146
+
147
+ def _publish(self, event: CanEvent) -> None:
148
+ """Thread-safe: schedule fan-out of an event onto the loop."""
149
+ if self._closed:
150
+ return
151
+ try:
152
+ self._loop.call_soon_threadsafe(self._publish_on_loop, event)
153
+ except RuntimeError:
154
+ # Event loop already closed during shutdown.
155
+ pass
156
+
157
+ def _publish_on_loop(self, event: CanEvent) -> None:
158
+ for queue in list(self._queues):
159
+ if queue.full():
160
+ try:
161
+ queue.get_nowait() # drop oldest
162
+ except asyncio.QueueEmpty:
163
+ pass
164
+ queue.put_nowait(event)
165
+ if isinstance(event, MotorDoneEvent):
166
+ waiters = self._motion_waiters.pop((event.node_id, event.axis), [])
167
+ for fut in waiters:
168
+ if not fut.done():
169
+ fut.set_result(event.position)
170
+
171
+ def _on_motor_update(self, node_id: int, axis: int, state: MotorState) -> None:
172
+ self._publish(MotorUpdateEvent(
173
+ node_id=node_id, axis=axis, position=state.position,
174
+ running=state.running, homing_status=state.homing_status,
175
+ ))
176
+
177
+ def _on_motor_done(self, node_id: int, axis: int, position: int) -> None:
178
+ self._publish(MotorDoneEvent(node_id=node_id, axis=axis, position=position))
179
+
180
+ def _on_homing_changed(self, node_id: int, axis: int, status: int) -> None:
181
+ self._publish(HomingChangedEvent(node_id=node_id, axis=axis, status=status))
182
+
183
+ def _on_heartbeat(self, node_id: int, info: NodeInfo) -> None:
184
+ self._publish(HeartbeatEvent(node_id=node_id, nmt_state=info.nmt_state))
185
+
186
+ async def events(self, queue_size: int = _DEFAULT_QUEUE_SIZE) -> AsyncIterator[CanEvent]:
187
+ """Yield typed hardware events as they arrive.
188
+
189
+ Multiple consumers may iterate concurrently; each gets its own queue.
190
+ The oldest events are dropped if a consumer falls behind.
191
+ """
192
+ queue: asyncio.Queue[CanEvent] = asyncio.Queue(maxsize=queue_size)
193
+ self._queues.append(queue)
194
+ try:
195
+ while True:
196
+ yield await queue.get()
197
+ finally:
198
+ self._queues.remove(queue)
199
+
200
+ # -- motor ---------------------------------------------------------------
201
+
202
+ async def move(self, axis: int = 0, position: int = 0, speed: int = 20000,
203
+ acceleration: int = 0, is_absolute: bool = False,
204
+ is_forever: bool = False, node_id: Optional[int] = None) -> None:
205
+ """Start a motor move (see `Motor.move`). Returns once the command is issued."""
206
+ await asyncio.to_thread(
207
+ self._client.motor.move, axis=axis, position=position, speed=speed,
208
+ acceleration=acceleration, is_absolute=is_absolute,
209
+ is_forever=is_forever, node_id=node_id,
210
+ )
211
+
212
+ async def move_and_wait(self, axis: int = 0, position: int = 0, speed: int = 20000,
213
+ acceleration: int = 0, is_absolute: bool = False,
214
+ node_id: Optional[int] = None,
215
+ timeout: float = 60.0) -> int:
216
+ """Start a move and wait (event-driven) until the motor stops.
217
+
218
+ Returns the final position. Falls back to polled `wait_for_idle` if no
219
+ TPDO done-event arrives within `timeout`. On cancellation the motor is
220
+ stopped before the CancelledError propagates.
221
+ """
222
+ nid = node_id if node_id is not None else self._client.motor.default_node
223
+ fut: asyncio.Future[int] = self._loop.create_future()
224
+ self._motion_waiters.setdefault((nid, axis), []).append(fut)
225
+ try:
226
+ await self.move(axis=axis, position=position, speed=speed,
227
+ acceleration=acceleration, is_absolute=is_absolute,
228
+ node_id=nid)
229
+ try:
230
+ return await asyncio.wait_for(fut, timeout=timeout)
231
+ except asyncio.TimeoutError:
232
+ _log.warning("No TPDO done-event within %.1fs; falling back to polling", timeout)
233
+ await asyncio.to_thread(self._client.motor.wait_for_idle, axis, nid, 5.0)
234
+ return await self.get_position(axis=axis, node_id=nid)
235
+ except asyncio.CancelledError:
236
+ await asyncio.shield(self.stop(axis=axis, node_id=nid))
237
+ raise
238
+ finally:
239
+ waiters = self._motion_waiters.get((nid, axis))
240
+ if waiters and fut in waiters:
241
+ waiters.remove(fut)
242
+
243
+ async def stop(self, axis: int = 0, node_id: Optional[int] = None) -> None:
244
+ """Stop a motor axis."""
245
+ await asyncio.to_thread(self._client.motor.stop, axis, node_id)
246
+
247
+ async def get_position(self, axis: int = 0, node_id: Optional[int] = None) -> int:
248
+ """Read a motor position (TPDO cache preferred, SDO fallback)."""
249
+ return await asyncio.to_thread(self._client.motor.get_position, axis, node_id)
250
+
251
+ async def is_running(self, axis: int = 0, node_id: Optional[int] = None) -> bool:
252
+ """Check whether a motor axis is currently running."""
253
+ return await asyncio.to_thread(self._client.motor.is_running, axis, node_id)
254
+
255
+ async def home(self, axis: int = 0, speed: int = 15000, direction: int = -1,
256
+ timeout_ms: int = 20000, node_id: Optional[int] = None) -> None:
257
+ """Start homing for an axis (see `Motor.home`)."""
258
+ await asyncio.to_thread(self._client.motor.home, axis, speed, direction,
259
+ timeout_ms, node_id)
260
+
261
+ async def home_and_wait(self, axis: int = 0, speed: int = 15000, direction: int = -1,
262
+ timeout_ms: int = 20000, node_id: Optional[int] = None,
263
+ timeout: float = 30.0) -> bool:
264
+ """Home an axis and wait for completion. Returns True if homed."""
265
+ await self.home(axis=axis, speed=speed, direction=direction,
266
+ timeout_ms=timeout_ms, node_id=node_id)
267
+ return await asyncio.to_thread(self._client.motor.wait_for_homed, axis,
268
+ node_id, timeout)
269
+
270
+ # -- laser / led ----------------------------------------------------------
271
+
272
+ async def laser_set(self, channel: int = 0, pwm: int = 0,
273
+ node_id: Optional[int] = None) -> None:
274
+ """Set a laser channel PWM value."""
275
+ await asyncio.to_thread(self._client.laser.set_value, channel, pwm, node_id)
276
+
277
+ async def laser_get(self, channel: int = 0, node_id: Optional[int] = None) -> int:
278
+ """Read back a laser channel PWM value."""
279
+ return await asyncio.to_thread(self._client.laser.get_value, channel, node_id)
280
+
281
+ async def led_fill(self, r: int = 0, g: int = 0, b: int = 0,
282
+ node_id: Optional[int] = None) -> None:
283
+ """Fill the LED array with a uniform colour."""
284
+ await asyncio.to_thread(self._client.led.fill, r, g, b, node_id)
285
+
286
+ async def led_off(self, node_id: Optional[int] = None) -> None:
287
+ """Turn the LED array off."""
288
+ await asyncio.to_thread(self._client.led.off, node_id)
289
+
290
+ # -- galvo ----------------------------------------------------------------
291
+
292
+ async def galvo_goto(self, x: int, y: int, node_id: Optional[int] = None) -> None:
293
+ """Move the galvo to an absolute XY position (DAC counts)."""
294
+ await asyncio.to_thread(self._client.galvo.set_position, x, y, node_id)
295
+
296
+ async def galvo_raster_scan(self, node_id: Optional[int] = None, **kwargs: Any) -> None:
297
+ """Configure and start a raster scan (see `Galvo.raster_scan` for kwargs)."""
298
+ await asyncio.to_thread(
299
+ lambda: self._client.galvo.raster_scan(node_id=node_id, **kwargs)
300
+ )
301
+
302
+ async def galvo_stop(self, node_id: Optional[int] = None) -> None:
303
+ """Stop any active galvo scan / motion."""
304
+ await asyncio.to_thread(self._client.galvo.stop, node_id)
305
+
306
+ async def galvo_status(self, node_id: Optional[int] = None) -> dict:
307
+ """Read and decode the galvo status word."""
308
+ return await asyncio.to_thread(self._client.galvo.get_status, node_id)
309
+
310
+ # -- system ---------------------------------------------------------------
311
+
312
+ async def scan_nodes(self, timeout: float = 3.0) -> list[int]:
313
+ """Passively scan for online nodes (heartbeats/TPDOs) for `timeout` seconds."""
314
+ return await asyncio.to_thread(self._client.state.scan_nodes, timeout)
315
+
316
+ async def reboot(self, node_id: int) -> None:
317
+ """Reboot a slave node."""
318
+ await asyncio.to_thread(self._client.state.reboot, node_id)