dobotkit 0.1.0__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.
@@ -0,0 +1,364 @@
1
+ """Sensor-feedback navigation primitives for the Magician GO.
2
+
3
+ The GO's built-in closed-loop commands (``rotate``/``move_dist``/``arc_*``/
4
+ ``increment_closed_loop``) HANG on this chassis: the firmware queues them with
5
+ ``isWaitForFinish`` and the completion callback never arrives, so the call
6
+ blocks until its (~7-day) timeout. Continuous velocity control (``move``), on
7
+ the other hand, works reliably. This module therefore builds its *own* closed
8
+ loop out of continuous ``move`` plus odometer/IMU feedback, stopping the car
9
+ the moment a target is reached.
10
+
11
+ :class:`PreciseMover` mirrors the proven reference implementation
12
+ (``magiciango_go/precise_move.py``): straight-line / strafe / in-place-turn
13
+ primitives that drive at a capped, near-target-decelerated speed until the
14
+ measured travel (or turn) reaches the target, then stop.
15
+
16
+ Heading-source rule (research doc §2.3 / §3.5): **"how far have I turned"** (the
17
+ rotation amount measured inside :meth:`PreciseMover.turn_degrees`) is read from
18
+ the **IMU yaw** delta — a power-on-referenced absolute angle whose *relative*
19
+ change is stable and responsive over a short turn, and it needs no mat-frame
20
+ zero. (For absolute mat *heading* you would instead zero the odometer yaw with
21
+ :meth:`MagicianGO.set_odometer`; the two references must not be mixed.)
22
+
23
+ Safety (research doc §8 — a past open-loop test drove into a wall and tripped
24
+ the power, so this matters):
25
+
26
+ * Every control loop has an **absolute wall-clock timeout**
27
+ (:func:`time.monotonic`); it can never spin forever even if the target is
28
+ never reached (``timed_out=True`` in the result).
29
+ * Each motion checks :meth:`MagicianGO.clearance_ok` for the intended direction
30
+ *before* moving; if blocked it aborts immediately (``aborted=True`` plus a
31
+ ``reason``).
32
+ * Every code path — normal finish, timeout, or exception — ends in
33
+ ``emergency_stop`` (via a ``try/finally``).
34
+ * Commanded speed is conservatively capped (``max_speed``) and floored near the
35
+ target (``min_speed``) so a crawl still actually stops.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import time
40
+ from typing import Any, Dict
41
+
42
+ from dobotkit.exceptions import DobotError
43
+ from dobotkit.go.geometry import clamp_speed, yaw_delta
44
+
45
+ __all__ = ["NavigationAborted", "PreciseMover"]
46
+
47
+
48
+ class NavigationAborted(DobotError, RuntimeError):
49
+ """Raised (opt-in via ``raise_on_abort=True``) when a motion aborts/times out.
50
+
51
+ By default the motion primitives report failure only inside their result
52
+ dict (``aborted``/``timed_out``), which beginner code routinely forgets to
53
+ check. Passing ``raise_on_abort=True`` makes failure loud instead. The full
54
+ result dict is available as :attr:`result`.
55
+
56
+ Inherits :class:`~dobotkit.exceptions.DobotError` so downstream consumers
57
+ with ``except DobotError`` handlers (e.g. GUI controllers that must never
58
+ let device errors reach the UI thread) catch it without changes.
59
+ """
60
+
61
+ def __init__(self, result: Dict[str, Any]) -> None:
62
+ super().__init__(
63
+ f"motion aborted/timed out: {result.get('reason', 'timed out')} "
64
+ f"(target={result.get('target')}, achieved={result.get('achieved')})"
65
+ )
66
+ self.result = result
67
+
68
+
69
+ def _finish(result: Dict[str, Any], raise_on_abort: bool) -> Dict[str, Any]:
70
+ """Return ``result``, or raise :class:`NavigationAborted` when opted in."""
71
+ if raise_on_abort and (result.get("aborted") or result.get("timed_out")):
72
+ raise NavigationAborted(result)
73
+ return result
74
+
75
+ #: Control-loop period (seconds) between successive sensor read + move commands.
76
+ LOOP_DT: float = 0.05
77
+
78
+ #: Final fraction of the move/turn over which speed is proportionally tapered
79
+ #: down toward ``min_speed`` to limit overshoot near the target.
80
+ SLOW_BAND: float = 0.30
81
+
82
+ #: Stall guard (hardware incident 2026-07-03: the car pressed a wall for the
83
+ #: full timeout): if the measured progress advances less than ``STALL_EPS``
84
+ #: for ``STALL_WINDOW_S`` seconds while a velocity is commanded, the motion
85
+ #: aborts as a suspected collision instead of pushing until timeout.
86
+ STALL_WINDOW_S: float = 1.0
87
+ STALL_EPS_MM: float = 3.0 # translation progress epsilon (mm)
88
+ STALL_EPS_DEG: float = 2.0 # rotation progress epsilon (degrees)
89
+
90
+ #: Period (seconds) between mid-move clearance re-checks during travel.
91
+ RECHECK_S: float = 0.25
92
+
93
+ # Anything exposing the MagicianGO method surface used here (move/forward/spin/
94
+ # odometer/imu_angle/ultrasonic/clearance_ok/stop/emergency_stop/set_odometer).
95
+ GoLike = Any
96
+
97
+
98
+ class PreciseMover:
99
+ """Odometer/IMU-feedback closed-loop motion primitives over continuous ``move``.
100
+
101
+ Builds a software closed loop on top of the GO's reliable continuous
102
+ velocity control: command a velocity, sample the odometer (translation) or
103
+ IMU (rotation) each tick, and stop the instant the measured travel reaches
104
+ the target. Speed is capped into ``[min_speed, max_speed]`` and tapered down
105
+ over the final :data:`SLOW_BAND` of the move to limit overshoot.
106
+
107
+ Args:
108
+ go: A :class:`~dobotkit.go.magiciango.MagicianGO` (or any object with the
109
+ same ``move``/``odometer``/``imu_angle``/``ultrasonic``/
110
+ ``clearance_ok``/``stop``/``emergency_stop`` surface).
111
+ max_speed: Absolute upper cap on commanded speed magnitude. Defaults to
112
+ ``30`` (the conservative safety cap from the reference).
113
+ min_speed: Lower floor on commanded speed magnitude near the target, so a
114
+ slowing crawl still moves enough to finish. Defaults to ``8``.
115
+ """
116
+
117
+ def __init__(self, go: GoLike, max_speed: float = 30, min_speed: float = 8) -> None:
118
+ self.go = go
119
+ self.max_speed = float(max_speed)
120
+ self.min_speed = float(min_speed)
121
+
122
+ # ---- internal helpers --------------------------------------------------
123
+
124
+ def _profiled_speed(self, remaining: float, total: float, base_speed: float) -> float:
125
+ """Commanded speed *magnitude* with ``remaining`` (absolute) left to go.
126
+
127
+ Over the final :data:`SLOW_BAND` fraction of the move the speed is
128
+ proportionally tapered toward ``min_speed`` (precision / overshoot
129
+ guard). The result is always clamped into ``[min_speed, max_speed]``.
130
+ """
131
+ base = min(abs(base_speed), self.max_speed)
132
+ band = max(abs(total) * SLOW_BAND, 1e-6)
133
+ if remaining < band:
134
+ scaled = base * (remaining / band)
135
+ return max(min(scaled, base), self.min_speed)
136
+ return max(base, self.min_speed)
137
+
138
+ def _settle_stop(self) -> None:
139
+ """Stop for sure: fire-and-forget ``emergency_stop``, then a confirming ``stop``.
140
+
141
+ ``emergency_stop`` is a no-wait notify, so a follow-up blocking ``stop``
142
+ confirms the car actually halted; if that confirming read fails the
143
+ emergency stop is re-fired.
144
+ """
145
+ self.go.emergency_stop()
146
+ try:
147
+ self.go.stop()
148
+ except Exception: # noqa: BLE001 -- any link error -> re-fire the safe stop
149
+ self.go.emergency_stop()
150
+
151
+ # ---- straight-line / strafe travel -------------------------------------
152
+
153
+ def goto_distance(
154
+ self,
155
+ distance_mm: float,
156
+ speed: float = 25,
157
+ axis: str = "x",
158
+ threshold: float = 20,
159
+ timeout_s: float = 8.0,
160
+ raise_on_abort: bool = False,
161
+ ) -> Dict[str, Any]:
162
+ """Travel ``|distance_mm|`` along ``axis`` then stop; the sign sets direction.
163
+
164
+ ``axis="x"`` is forward/back (``+`` forward); ``axis="y"`` is strafe
165
+ (``+`` left). The odometer is **not** reset — it stays in whatever
166
+ (mat/world) frame an outer caller (e.g. :class:`WaypointNav`) has zeroed
167
+ it to. Because the GO odometer is a world-frame, yaw-aware integral,
168
+ travel is measured as the straight-line displacement magnitude
169
+ ``hypot(dx, dy)`` from the start pose and the move stops once that
170
+ reaches ``|distance_mm|``. Speed tapers near the target. Safety, in
171
+ layers (the pre-check alone proved insufficient on hardware): the
172
+ intended direction is clearance-checked **before** moving, re-checked
173
+ every :data:`RECHECK_S` seconds **during** the move, and a stall guard
174
+ aborts if the odometer stops advancing for :data:`STALL_WINDOW_S`
175
+ seconds while a velocity is commanded (suspected collision).
176
+
177
+ .. note:: **Unit boundary.** This primitive works in **millimetres**
178
+ (odometer units); :class:`WaypointNav` works in **centimetres**
179
+ (mat/SDK units) and converts only at its own boundary. Speed units
180
+ are firmware-defined and unconfirmed — 8..30 is the practical range.
181
+
182
+ Args:
183
+ distance_mm: Signed target distance in **millimetres**.
184
+ speed: Base speed magnitude (capped into ``[min_speed, max_speed]``;
185
+ units unconfirmed, 8..30 practical).
186
+ axis: ``"x"`` (forward/back) or ``"y"`` (strafe left/right).
187
+ threshold: Minimum required clearance (cm) ahead before moving.
188
+ timeout_s: Absolute wall-clock safety timeout (seconds).
189
+ raise_on_abort: When ``True``, raise :class:`NavigationAborted`
190
+ instead of returning an ``aborted``/``timed_out`` result dict —
191
+ use this to make failures loud in beginner/teaching code.
192
+
193
+ Returns:
194
+ ``{target, achieved, error, axis, timed_out, aborted}``. When the
195
+ clearance check blocks the move, ``aborted`` is ``True`` and a
196
+ ``reason`` key is added; ``error = target - achieved``.
197
+ """
198
+ if axis not in ("x", "y"):
199
+ raise ValueError("axis must be 'x' or 'y'")
200
+
201
+ direction = 0.0 if distance_mm == 0 else (1.0 if distance_mm > 0 else -1.0)
202
+ base = clamp_speed(speed, self.min_speed, self.max_speed)
203
+ result: Dict[str, Any] = {
204
+ "target": float(distance_mm),
205
+ "achieved": 0.0,
206
+ "error": float(distance_mm),
207
+ "axis": axis,
208
+ "timed_out": False,
209
+ "aborted": False,
210
+ }
211
+
212
+ # Pre-check clearance in the intended direction of travel.
213
+ cx = direction * base if axis == "x" else 0.0
214
+ cy = direction * base if axis == "y" else 0.0
215
+ ok, info = self.go.clearance_ok(x=cx, y=cy, threshold=threshold)
216
+ if not ok:
217
+ result["aborted"] = True
218
+ result["reason"] = f"clearance blocked: {info}"
219
+ return _finish(result, raise_on_abort)
220
+
221
+ try:
222
+ start = self.go.odometer()
223
+ now = time.monotonic()
224
+ deadline = now + timeout_s
225
+ traveled = 0.0
226
+ # Stall guard state (hardware incident 2026-07-03: the car pressed
227
+ # into a wall for the full timeout because nothing watched progress).
228
+ best_progress = 0.0
229
+ progress_t = now
230
+ recheck_t = now
231
+ while True:
232
+ now = time.monotonic()
233
+ if now >= deadline:
234
+ result["timed_out"] = True
235
+ break
236
+ odo = self.go.odometer()
237
+ # World-frame odometer: progress = displacement magnitude from
238
+ # the start pose (direction-agnostic), re-signed by direction.
239
+ dist = (
240
+ (odo["x"] - start["x"]) ** 2 + (odo["y"] - start["y"]) ** 2
241
+ ) ** 0.5
242
+ traveled = direction * dist
243
+ remaining = abs(distance_mm) - abs(traveled)
244
+ if remaining <= 0:
245
+ break
246
+ # Stall guard: wheels commanded but odometer frozen -> the car
247
+ # is most likely pressing an obstacle (or wedged). Stop pushing.
248
+ if abs(traveled) > best_progress + STALL_EPS_MM:
249
+ best_progress = abs(traveled)
250
+ progress_t = now
251
+ elif now - progress_t >= STALL_WINDOW_S:
252
+ result["aborted"] = True
253
+ result["reason"] = (
254
+ f"stall: no odometer progress for {STALL_WINDOW_S:.1f}s "
255
+ f"while driving (collision?)"
256
+ )
257
+ break
258
+ # Mid-move clearance recheck: the pre-check alone cannot see an
259
+ # obstacle entering the path (or sensor offset error) once moving.
260
+ if now - recheck_t >= RECHECK_S:
261
+ recheck_t = now
262
+ ok, info = self.go.clearance_ok(x=cx, y=cy, threshold=threshold)
263
+ if not ok:
264
+ result["aborted"] = True
265
+ result["reason"] = f"clearance lost mid-move: {info}"
266
+ break
267
+ v = self._profiled_speed(remaining, distance_mm, base) * direction
268
+ if axis == "x":
269
+ self.go.move(x=v)
270
+ else:
271
+ self.go.move(y=v)
272
+ time.sleep(LOOP_DT)
273
+ result["achieved"] = float(traveled)
274
+ result["error"] = float(distance_mm) - float(traveled)
275
+ finally:
276
+ self._settle_stop()
277
+ return _finish(result, raise_on_abort)
278
+
279
+ # ---- in-place rotation -------------------------------------------------
280
+
281
+ def turn_degrees(
282
+ self,
283
+ deg: float,
284
+ speed: float = 25,
285
+ threshold: float = 20,
286
+ timeout_s: float = 8.0,
287
+ raise_on_abort: bool = False,
288
+ ) -> Dict[str, Any]:
289
+ """Turn in place by ``deg`` then stop; the sign sets direction (``r+`` = CCW).
290
+
291
+ Records the start IMU yaw and stops once the IMU yaw change (with +-180
292
+ wraparound handling) reaches ``|deg|``. The rotation amount is measured
293
+ from the **IMU** yaw delta (a stable *relative* change), distinct from
294
+ the odometer yaw used for absolute mat heading. All-around clearance is
295
+ checked before turning.
296
+
297
+ Args:
298
+ deg: Signed target turn in degrees (``+`` = CCW / left).
299
+ speed: Base angular speed magnitude (capped into ``[min, max]``;
300
+ units unconfirmed, 8..30 practical).
301
+ threshold: Minimum required clearance (cm) all around before turning.
302
+ timeout_s: Absolute wall-clock safety timeout (seconds).
303
+ raise_on_abort: When ``True``, raise :class:`NavigationAborted`
304
+ instead of returning an ``aborted``/``timed_out`` result dict.
305
+
306
+ Returns:
307
+ ``{target, achieved, error, timed_out, aborted}``. When the clearance
308
+ check blocks the turn, ``aborted`` is ``True`` and a ``reason`` key is
309
+ added; ``error = target - achieved``.
310
+ """
311
+ direction = 0.0 if deg == 0 else (1.0 if deg > 0 else -1.0)
312
+ base = clamp_speed(speed, self.min_speed, self.max_speed)
313
+ result: Dict[str, Any] = {
314
+ "target": float(deg),
315
+ "achieved": 0.0,
316
+ "error": float(deg),
317
+ "timed_out": False,
318
+ "aborted": False,
319
+ }
320
+
321
+ ok, info = self.go.clearance_ok(r=direction * base, threshold=threshold)
322
+ if not ok:
323
+ result["aborted"] = True
324
+ result["reason"] = f"clearance blocked: {info}"
325
+ return _finish(result, raise_on_abort)
326
+
327
+ try:
328
+ start_yaw = self.go.imu_angle()["yaw"]
329
+ now = time.monotonic()
330
+ deadline = now + timeout_s
331
+ turned = 0.0
332
+ best_progress = 0.0
333
+ progress_t = now
334
+ while True:
335
+ now = time.monotonic()
336
+ if now >= deadline:
337
+ result["timed_out"] = True
338
+ break
339
+ cur_yaw = self.go.imu_angle()["yaw"]
340
+ # Rotation amount = IMU yaw delta (current - start), +-180 wrapped.
341
+ turned = yaw_delta(cur_yaw, start_yaw)
342
+ remaining = abs(deg) - abs(turned)
343
+ if remaining <= 0:
344
+ break
345
+ # Stall guard: commanded to spin but the IMU is frozen -> the
346
+ # chassis is most likely wedged. Stop pushing.
347
+ if abs(turned) > best_progress + STALL_EPS_DEG:
348
+ best_progress = abs(turned)
349
+ progress_t = now
350
+ elif now - progress_t >= STALL_WINDOW_S:
351
+ result["aborted"] = True
352
+ result["reason"] = (
353
+ f"stall: no IMU progress for {STALL_WINDOW_S:.1f}s "
354
+ f"while turning (wedged?)"
355
+ )
356
+ break
357
+ v = self._profiled_speed(remaining, deg, base) * direction
358
+ self.go.move(r=v)
359
+ time.sleep(LOOP_DT)
360
+ result["achieved"] = float(turned)
361
+ result["error"] = float(deg) - float(turned)
362
+ finally:
363
+ self._settle_stop()
364
+ return _finish(result, raise_on_abort)
dobotkit/link.py ADDED
@@ -0,0 +1,209 @@
1
+ """Shared DobotLink client (arm + GO): synchronous JSON-RPC over ``ws://localhost:9090``.
2
+
3
+ Neither the Magician Lite arm nor the Magician GO is driven directly; Python
4
+ talks to the **DobotLink** desktop service over a WebSocket using JSON-RPC 2.0,
5
+ and DobotLink relays commands to the device over its COM port / wireless
6
+ dongle::
7
+
8
+ Python --(WebSocket JSON-RPC)--> DobotLink.exe --(COM/wireless)--> arm / GO
9
+
10
+ This client is a thin, blocking wrapper over the ``websockets`` *sync* API: one
11
+ request, then a read loop that returns the response whose ``id`` matches. It
12
+ depends only on ``websockets`` -- never on Dobot's DobotEDU/DobotRPC packages.
13
+
14
+ Method prefixing: only the ``dobotlink.`` namespace is added automatically.
15
+ A bare ``MagicianGO.GetBatteryVoltage`` becomes
16
+ ``dobotlink.MagicianGO.GetBatteryVoltage``, but the ``MagicianGO.`` /
17
+ ``MagicBox.`` / ``Magician.`` segment itself is left untouched -- callers using
18
+ the low-level ``call``/``notify`` must spell those namespaces themselves (the
19
+ high-level ``MagicianGO`` wrapper adds ``MagicianGO.`` and the arm's
20
+ ``ArmCommands`` adds ``Magician.`` for you).
21
+
22
+ A ``_ws_factory`` hook lets tests inject an in-memory socket double without
23
+ opening a real connection; in production it defaults to
24
+ ``websockets.sync.client.connect``.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import time
30
+ from typing import Any, Callable, Dict, Optional
31
+
32
+ from dobotkit.exceptions import DobotConnectionError, DobotLinkError, DobotTimeoutError
33
+
34
+ _PREFIX = "dobotlink."
35
+
36
+
37
+ def _default_ws_factory(url: str, *, open_timeout: float) -> Any:
38
+ """Open a real DobotLink WebSocket. Imported lazily so importing this module
39
+ (or ``dobotkit.go``) never pulls in ``websockets`` until a connection is made.
40
+ """
41
+ from websockets.sync.client import connect
42
+
43
+ return connect(url, open_timeout=open_timeout)
44
+
45
+
46
+ class DobotLinkClient:
47
+ """Blocking JSON-RPC 2.0 client for the DobotLink WebSocket service.
48
+
49
+ Args:
50
+ host: DobotLink host. Defaults to ``"localhost"``.
51
+ port: DobotLink WebSocket port. Defaults to ``9090``.
52
+ timeout: Seconds to wait both for the initial connection and for each
53
+ ``call`` response before raising. Defaults to ``10.0``.
54
+ _ws_factory: Test/advanced hook returning a connection object exposing
55
+ ``send(str)``, ``recv(timeout=...) -> str``, and ``close()``. When
56
+ ``None`` (default) a real ``websockets`` connection is opened.
57
+
58
+ Use as a context manager to guarantee the socket is closed::
59
+
60
+ with DobotLinkClient() as client:
61
+ client.call("MagicianGO.GetBatteryVoltage", portName="COM5")
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ host: str = "localhost",
67
+ port: int = 9090,
68
+ timeout: float = 10.0,
69
+ _ws_factory: Optional[Callable[..., Any]] = None,
70
+ ) -> None:
71
+ self._url = f"ws://{host}:{port}"
72
+ self._timeout = timeout
73
+ self._ws_factory = _ws_factory or _default_ws_factory
74
+ self._ws: Optional[Any] = None
75
+ self._id = 0
76
+
77
+ # ---- lifecycle ---------------------------------------------------------
78
+
79
+ def connect(self) -> "DobotLinkClient":
80
+ """Open the WebSocket (idempotent) and return ``self`` for chaining.
81
+
82
+ Raises:
83
+ DobotConnectionError: if the connection cannot be established
84
+ (most often because DobotLink.exe is not running).
85
+ """
86
+ if self._ws is None:
87
+ try:
88
+ self._ws = self._ws_factory(self._url, open_timeout=self._timeout)
89
+ except Exception as exc: # noqa: BLE001 - surfaced as a typed error
90
+ raise DobotConnectionError(
91
+ f"cannot connect to DobotLink at {self._url}. "
92
+ f"Is DobotLink.exe running? ({exc})"
93
+ ) from exc
94
+ return self
95
+
96
+ def close(self) -> None:
97
+ """Close the WebSocket if open. Safe to call more than once.
98
+
99
+ Note: this only closes the *socket* — it does **not** stop the car. A
100
+ GO driving at its last commanded velocity keeps driving. Safety
101
+ teardown (line-trace OFF + emergency stop) is the job of the
102
+ ``MagicianGO`` context manager; prefer ``with MagicianGO.open(...)``.
103
+ """
104
+ if self._ws is not None:
105
+ ws, self._ws = self._ws, None
106
+ ws.close()
107
+
108
+ def __enter__(self) -> "DobotLinkClient":
109
+ return self.connect()
110
+
111
+ def __exit__(self, *exc: object) -> None:
112
+ self.close()
113
+
114
+ # ---- RPC ---------------------------------------------------------------
115
+
116
+ def call(self, method: str, *, call_timeout: Optional[float] = None, **params: Any) -> Any:
117
+ """Send a JSON-RPC request and block for the matching response.
118
+
119
+ Args:
120
+ method: RPC method name. Auto-prefixed with ``dobotlink.`` unless it
121
+ already starts with it.
122
+ call_timeout: Override the client's default ``timeout`` for just this
123
+ call. Keyword-only so it never collides with an RPC param that
124
+ happens to be named ``timeout`` (e.g. ``SetWAITCmd``). When
125
+ ``None`` (default), the client's ``timeout`` is used.
126
+ **params: JSON-RPC ``params`` object.
127
+
128
+ Returns:
129
+ The ``result`` field of the matching response.
130
+
131
+ Raises:
132
+ DobotLinkError: if not connected, or if the response is a JSON-RPC
133
+ error.
134
+ DobotTimeoutError: if no matching response arrives within the
135
+ effective timeout (the device may be unresponsive or DobotLink
136
+ lost the link). The timeout is a **total deadline** for the
137
+ whole call, not a per-read budget — a stream of unrelated
138
+ notifications cannot extend the wait indefinitely.
139
+ """
140
+ ws = self._require_connection()
141
+ self._id += 1
142
+ request_id = self._id
143
+ payload: Dict[str, Any] = {
144
+ "jsonrpc": "2.0",
145
+ "id": request_id,
146
+ "method": self._full_method(method),
147
+ "params": params,
148
+ }
149
+ ws.send(json.dumps(payload))
150
+
151
+ eff = call_timeout if call_timeout is not None else self._timeout
152
+ deadline = time.monotonic() + eff
153
+ while True:
154
+ remaining = deadline - time.monotonic()
155
+ if remaining <= 0:
156
+ raise DobotTimeoutError(
157
+ f"timed out after {eff}s waiting for "
158
+ f"'{payload['method']}'. The device may be unresponsive or "
159
+ f"DobotLink lost the link."
160
+ )
161
+ try:
162
+ raw = ws.recv(timeout=remaining)
163
+ except TimeoutError as exc:
164
+ raise DobotTimeoutError(
165
+ f"timed out after {eff}s waiting for "
166
+ f"'{payload['method']}'. The device may be unresponsive or "
167
+ f"DobotLink lost the link."
168
+ ) from exc
169
+ message = json.loads(raw)
170
+ # Skip notifications and responses to other requests.
171
+ if message.get("id") != request_id:
172
+ continue
173
+ error = message.get("error")
174
+ if error is not None:
175
+ raise DobotLinkError(f"DobotLink error for '{payload['method']}': {error}")
176
+ return message.get("result")
177
+
178
+ def notify(self, method: str, **params: Any) -> None:
179
+ """Send a fire-and-forget JSON-RPC notification (no ``id``, no reply read).
180
+
181
+ Used for non-blocking commands such as emergency stop, where waiting on a
182
+ response is undesirable.
183
+
184
+ Args:
185
+ method: RPC method name. Auto-prefixed with ``dobotlink.`` unless it
186
+ already starts with it.
187
+ **params: JSON-RPC ``params`` object.
188
+
189
+ Raises:
190
+ DobotLinkError: if not connected.
191
+ """
192
+ ws = self._require_connection()
193
+ payload: Dict[str, Any] = {
194
+ "jsonrpc": "2.0",
195
+ "method": self._full_method(method),
196
+ "params": params,
197
+ }
198
+ ws.send(json.dumps(payload))
199
+
200
+ # ---- internals ---------------------------------------------------------
201
+
202
+ def _require_connection(self) -> Any:
203
+ if self._ws is None:
204
+ raise DobotLinkError("not connected; call connect() first")
205
+ return self._ws
206
+
207
+ @staticmethod
208
+ def _full_method(method: str) -> str:
209
+ return method if method.startswith(_PREFIX) else _PREFIX + method
dobotkit/py.typed ADDED
File without changes