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,511 @@
1
+ """High-level Magician GO control layered on a connected ``DobotLinkClient``.
2
+
3
+ ``MagicianGO`` is a thin, typed facade over the DobotLink ``MagicianGO.*``
4
+ JSON-RPC surface. Every method (except :meth:`search`) issues
5
+ ``client.call("MagicianGO.<Func>", portName=self.port_name, **params)`` via the
6
+ private :meth:`_call` helper; :meth:`emergency_stop` is the lone command that
7
+ uses ``client.notify`` so that stopping the car never blocks on a response.
8
+
9
+ **Drive model — continuous velocity only.** Motion is commanded as a velocity
10
+ vector (:meth:`move`, plus the :meth:`forward`/:meth:`backward`/:meth:`strafe`/
11
+ :meth:`spin` helpers and the bounded :meth:`drive_for` pulse): the car drives at
12
+ the commanded velocity until told to stop. This is the trusted, hardware-proven
13
+ path. For *precise* closed-loop motion (drive an exact distance, turn an exact
14
+ angle) build a loop out of continuous :meth:`move` plus sensor feedback with
15
+ :class:`dobotkit.go.navigation.PreciseMover` — the firmware's own queued
16
+ closed-loop commands are not exposed here because they can hang on this chassis.
17
+
18
+ **MagicBox peripherals.** The GO carries the same MagicBox hub as the arm; its
19
+ sensor/IO reads live on the ``MagicBox.*`` namespace and are exposed through the
20
+ :attr:`sensors` and :attr:`io` groups (see :mod:`dobotkit.go.groups`). They
21
+ coexist with the native drive/sensor calls on a single ``MagicianGO`` connection
22
+ (hardware-verified 2026-07-16).
23
+
24
+ Safety workflow: after :meth:`connect_robot` always verify the link with a read
25
+ such as :meth:`battery` (use :meth:`connect` which does this for you); check
26
+ :meth:`clearance_ok` before driving; wrap motion in ``try/finally`` ending in
27
+ :meth:`emergency_stop`.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import math
32
+ import time
33
+ from typing import Any, Dict, Optional, Tuple, Union, cast
34
+
35
+ from dobotkit.enums import LEDChannel
36
+ from dobotkit.go.groups import GoIOGroup, GoSensorGroup
37
+
38
+ #: Hard cap (magnitude) applied to every continuous-velocity component. Speed
39
+ #: units are firmware-defined and unconfirmed; 8..30 is the empirically safe
40
+ #: range on this chassis, so nothing larger is ever put on the wire.
41
+ SPEED_CAP: float = 30.0
42
+
43
+ #: The ultrasonic sensors clamp at this ceiling (hardware-measured): readings
44
+ #: of 40 mean "40 cm **or more**".
45
+ ULTRA_MAX_CM: float = 40.0
46
+
47
+ _ULTRA_KEYS: Tuple[str, str, str, str] = ("front", "back", "left", "right")
48
+
49
+
50
+ def _cap(value: float) -> float:
51
+ """Clamp a velocity component's magnitude to the :data:`SPEED_CAP` safety cap.
52
+
53
+ Non-finite input (NaN/inf from broken control math) maps to **0.0** — an
54
+ undefined velocity must refuse to move, never drive. Naive
55
+ ``max(min(...))`` clamping would turn NaN into +SPEED_CAP (full speed)
56
+ because NaN comparisons are always False.
57
+ """
58
+ v = float(value)
59
+ if not math.isfinite(v):
60
+ return 0.0
61
+ return max(-SPEED_CAP, min(SPEED_CAP, v))
62
+
63
+
64
+ # String aliases accepted by :meth:`rgb` ``number``, mapping to firmware LED ids.
65
+ _LED_NAMES: Dict[str, int] = {
66
+ "LED_1": 1,
67
+ "LED_2": 2,
68
+ "LED_3": 3,
69
+ "LED_4": 4,
70
+ "LED_ALL": 5,
71
+ }
72
+
73
+ # A connected ``DobotLinkClient`` (or any object exposing ``call``/``notify``).
74
+ ClientLike = Any
75
+ # Accepted forms for the RGB LED channel selector.
76
+ LedSelector = Union[LEDChannel, int, str]
77
+
78
+
79
+ class MagicianGO:
80
+ """Ergonomic, typed wrapper over the DobotLink ``MagicianGO.*`` RPC surface.
81
+
82
+ Args:
83
+ client: A connected :class:`~dobotkit.link.DobotLinkClient` (or any
84
+ object exposing ``call(method, **params)`` and
85
+ ``notify(method, **params)``).
86
+ port_name: The COM port DobotLink uses to reach the GO. Defaults to
87
+ ``"COM5"``. Sent as ``portName`` on every call except
88
+ :meth:`search`.
89
+
90
+ Attributes:
91
+ sensors: :class:`~dobotkit.go.groups.GoSensorGroup` — MagicBox sensor
92
+ reads (ADC/DI by EIO pin; color/infrared/Seeed by Grove connector),
93
+ guarded so a missing peripheral degrades to ``None``.
94
+ io: :class:`~dobotkit.go.groups.GoIOGroup` — MagicBox digital/analog I/O
95
+ addressed by EIO pin (1..26).
96
+ """
97
+
98
+ def __init__(self, client: ClientLike, port_name: str = "COM5") -> None:
99
+ self._client = client
100
+ self.port_name = port_name
101
+ self._owns_client = False # True only when built via :meth:`open`
102
+ #: Connection lifecycle flag: ``True`` after a successful
103
+ #: :meth:`connect_robot`/:meth:`connect`, ``False`` initially and after
104
+ #: :meth:`disconnect_robot` or context-manager exit. Consumers (e.g.
105
+ #: GUI controllers) read this to gate device features.
106
+ self.connected: bool = False
107
+ #: MagicBox peripheral sensor reads (guarded -> ``None`` if absent).
108
+ self.sensors = GoSensorGroup(client, port_name)
109
+ #: MagicBox digital/analog I/O, addressed by EIO pin.
110
+ self.io = GoIOGroup(client, port_name)
111
+
112
+ # ---- lifecycle ----------------------------------------------------------
113
+
114
+ @classmethod
115
+ def open(
116
+ cls,
117
+ port_name: str = "COM5",
118
+ host: str = "localhost",
119
+ port: int = 9090,
120
+ timeout: float = 10.0,
121
+ ) -> "MagicianGO":
122
+ """One-line entry point: connect DobotLink, wrap it, verify the GO link.
123
+
124
+ Equivalent to ``DobotLinkClient(host, port, timeout).connect()`` +
125
+ ``MagicianGO(client, port_name)`` + :meth:`connect` (which includes the
126
+ battery link-verification read). The returned instance *owns* its
127
+ client, so using it as a context manager closes the socket too::
128
+
129
+ with MagicianGO.open(port_name="COM5") as go:
130
+ go.forward(15)
131
+ ...
132
+ # <- emergency stop + confirming stop + socket closed, even on error
133
+ """
134
+ from dobotkit.link import DobotLinkClient
135
+
136
+ client = DobotLinkClient(host=host, port=port, timeout=timeout).connect()
137
+ go = cls(client, port_name=port_name)
138
+ go._owns_client = True
139
+ try:
140
+ go.connect()
141
+ except Exception:
142
+ client.close()
143
+ raise
144
+ return go
145
+
146
+ def __enter__(self) -> "MagicianGO":
147
+ return self
148
+
149
+ def __exit__(self, *exc: object) -> None:
150
+ """Best-effort safety teardown so a crashed script never leaves the car driving.
151
+
152
+ 1. :meth:`emergency_stop` **first** — a fire-and-forget notify that can
153
+ never block, so the car stops instantly even when the link is hung.
154
+ 2. :meth:`stop` — a confirming blocking ``SetMoveSpeed(0)``; if it fails
155
+ the emergency stop is re-fired.
156
+
157
+ Teardown errors are swallowed — they must never mask the original
158
+ exception. When this instance was created via :meth:`open` the owned
159
+ client socket is closed as the final step.
160
+ """
161
+ try:
162
+ self.emergency_stop()
163
+ except Exception: # noqa: BLE001 - teardown must never raise
164
+ pass
165
+ try:
166
+ self.stop()
167
+ except Exception: # noqa: BLE001 - any link error -> re-fire safe stop
168
+ try:
169
+ self.emergency_stop()
170
+ except Exception: # noqa: BLE001 - teardown must never raise
171
+ pass
172
+ self.connected = False # the session is over either way
173
+ if self._owns_client:
174
+ try:
175
+ self._client.close()
176
+ except Exception: # noqa: BLE001 - teardown must never raise
177
+ pass
178
+
179
+ # ---- internals ---------------------------------------------------------
180
+
181
+ def _call(self, func: str, **params: Any) -> Any:
182
+ """Issue ``MagicianGO.<func>`` with ``portName`` and block for the result."""
183
+ params["portName"] = self.port_name
184
+ return self._client.call(f"MagicianGO.{func}", **params)
185
+
186
+ # ---- connection --------------------------------------------------------
187
+
188
+ def search(self) -> Any:
189
+ """Search for connectable GO units (``MagicianGO.SearchDobot``).
190
+
191
+ Unlike every other method this sends **no** ``portName`` (it runs before
192
+ a port is chosen). The DobotLink response is returned verbatim; its exact
193
+ structure is firmware-defined and not normalised here.
194
+ """
195
+ return self._client.call("MagicianGO.SearchDobot")
196
+
197
+ def connect_robot(self) -> Any:
198
+ """Tell DobotLink to connect to the GO on :attr:`port_name`.
199
+
200
+ Required before any command. Sets :attr:`connected` on success. Note:
201
+ the handshake can report a *false* success — always follow it with a
202
+ real read (:meth:`battery`) to verify the link, or simply use
203
+ :meth:`connect` (which resets :attr:`connected` if verification fails).
204
+ """
205
+ result = self._call("ConnectDobot")
206
+ self.connected = True
207
+ return result
208
+
209
+ def disconnect_robot(self) -> Any:
210
+ """Disconnect DobotLink from the GO (``MagicianGO.DisconnectDobot``)."""
211
+ self.connected = False
212
+ return self._call("DisconnectDobot")
213
+
214
+ def connect(self, verify: bool = True) -> Any:
215
+ """Connect to the GO and (by default) verify the link.
216
+
217
+ Calls :meth:`connect_robot`, then — unless ``verify`` is ``False`` —
218
+ calls :meth:`battery` so a dead power/wireless link surfaces immediately
219
+ (a hung/timed-out read) rather than silently after a false-success
220
+ handshake.
221
+
222
+ Args:
223
+ verify: When ``True`` (default), perform the battery read-back and
224
+ return its result. When ``False``, only connect and return the
225
+ ``connect_robot`` result.
226
+
227
+ Returns:
228
+ The :meth:`battery` reading when ``verify`` is ``True``, else the
229
+ :meth:`connect_robot` result.
230
+ """
231
+ result = self.connect_robot()
232
+ if verify:
233
+ try:
234
+ return self.battery()
235
+ except Exception:
236
+ # Handshake succeeded but the link is dead (false success) —
237
+ # the device is NOT usable, so don't report it as connected.
238
+ self.connected = False
239
+ raise
240
+ return result
241
+
242
+ # ---- continuous drive (trusted) ----------------------------------------
243
+
244
+ def move(self, x: float = 0, y: float = 0, r: float = 0) -> Any:
245
+ """Set a continuous velocity vector (``SetMoveSpeed``).
246
+
247
+ Drives **until told to stop** — prefer :meth:`drive_for` when a bounded
248
+ pulse is all you need. Convention: ``x+`` forward, ``y+`` strafe left,
249
+ ``r+`` rotate CCW (left). Each component's magnitude is clamped to
250
+ :data:`SPEED_CAP` (±30); speed units are firmware-defined and
251
+ unconfirmed — 8..30 is the practical range on this chassis.
252
+ """
253
+ return self._call("SetMoveSpeed", x=_cap(x), y=_cap(y), r=_cap(r))
254
+
255
+ def forward(self, speed: float) -> Any:
256
+ """Drive forward at ``speed`` (= ``move(x=speed)``)."""
257
+ return self.move(x=speed)
258
+
259
+ def backward(self, speed: float) -> Any:
260
+ """Drive backward at ``speed`` (= ``move(x=-speed)``)."""
261
+ return self.move(x=-speed)
262
+
263
+ def strafe(self, speed: float) -> Any:
264
+ """Strafe left (+) / right (-) at ``speed`` (= ``move(y=speed)``)."""
265
+ return self.move(y=speed)
266
+
267
+ def spin(self, speed: float) -> Any:
268
+ """Rotate in place at ``speed`` (``+`` = CCW; = ``move(r=speed)``)."""
269
+ return self.move(r=speed)
270
+
271
+ def stop(self) -> Any:
272
+ """Stop driving (= ``move(0, 0, 0)``; waits for the response)."""
273
+ return self.move(0, 0, 0)
274
+
275
+ def drive_for(
276
+ self, x: float = 0, y: float = 0, r: float = 0, seconds: float = 0.5
277
+ ) -> None:
278
+ """Dead-man drive: :meth:`move` for ``seconds`` (clamped to 5 s), then stop.
279
+
280
+ The safe, bounded alternative to a bare :meth:`move` — even if the
281
+ caller is interrupted mid-pulse, the ``finally`` still stops the car
282
+ (fire-and-forget :meth:`emergency_stop`, then a confirming
283
+ :meth:`stop`; if that confirming read fails the emergency stop is
284
+ re-fired).
285
+ """
286
+ duration = max(0.0, min(5.0, float(seconds)))
287
+ try:
288
+ self.move(x=x, y=y, r=r)
289
+ time.sleep(duration)
290
+ finally:
291
+ # Teardown must never raise (e.g. replace an in-flight
292
+ # KeyboardInterrupt with a socket error) — same convention as
293
+ # __exit__. Every stop attempt is individually guarded.
294
+ try:
295
+ self.emergency_stop()
296
+ except Exception: # noqa: BLE001 - teardown must never raise
297
+ pass
298
+ try:
299
+ self.stop()
300
+ except Exception: # noqa: BLE001 - any link error -> re-fire safe stop
301
+ try:
302
+ self.emergency_stop()
303
+ except Exception: # noqa: BLE001 - teardown must never raise
304
+ pass
305
+
306
+ def emergency_stop(self) -> None:
307
+ """Stop immediately via ``notify`` — never blocks, never times out.
308
+
309
+ Sends ``SetMoveSpeed(x=0, y=0, r=0)`` as a fire-and-forget JSON-RPC
310
+ notification, so it is safe to call from a ``finally`` block or an
311
+ interrupt path even if the link is degraded.
312
+ """
313
+ self._client.notify(
314
+ "MagicianGO.SetMoveSpeed", portName=self.port_name, x=0, y=0, r=0
315
+ )
316
+
317
+ # ---- safety ------------------------------------------------------------
318
+
319
+ def clearance_ok(
320
+ self, x: float = 0, y: float = 0, r: float = 0, threshold: float = 20
321
+ ) -> Tuple[bool, Union[Dict[str, float], str]]:
322
+ """Check ultrasonic clearance in the intended direction of travel.
323
+
324
+ Reads :meth:`ultrasonic` and verifies the relevant sensor(s) report at
325
+ least ``threshold`` cm of clearance for the requested motion:
326
+
327
+ * ``x > 0`` -> front, ``x < 0`` -> back.
328
+ * ``y != 0`` -> both sides (min of left/right).
329
+ * ``r != 0`` -> all four directions (in-place rotation sweeps a circle).
330
+
331
+ Args:
332
+ x: Intended forward/backward velocity sign (only sign matters).
333
+ y: Intended strafe velocity sign (only sign matters).
334
+ r: Intended rotation velocity (any non-zero requires all-around clearance).
335
+ threshold: Minimum acceptable distance in cm. Defaults to ``20``.
336
+
337
+ Returns:
338
+ ``(True, distances)`` where ``distances`` is the ultrasonic dict when
339
+ clear, otherwise ``(False, reason)`` with a human-readable reason
340
+ string naming the blocked direction. A malformed ultrasonic read
341
+ (``None``) is itself a blocking reason — unknown means stop.
342
+ """
343
+ u = self.ultrasonic()
344
+ if u is None:
345
+ return False, "ultrasonic read invalid (unknown -> stop)"
346
+ if x > 0 and u["front"] < threshold:
347
+ return False, f"front={u['front']}<{threshold}"
348
+ if x < 0 and u["back"] < threshold:
349
+ return False, f"back={u['back']}<{threshold}"
350
+ if y != 0 and min(u["left"], u["right"]) < threshold:
351
+ return False, f"side min={min(u['left'], u['right'])}<{threshold}"
352
+ if r != 0 and min(u.values()) < threshold:
353
+ return False, f"around min={min(u.values())}<{threshold}"
354
+ return True, u
355
+
356
+ # ---- output: LED / buzzer ----------------------------------------------
357
+
358
+ def rgb(
359
+ self,
360
+ number: LedSelector,
361
+ effect: int,
362
+ r: int,
363
+ g: int,
364
+ b: int,
365
+ cycle: int,
366
+ counts: int,
367
+ ) -> Any:
368
+ """Set an RGB LED (``SetLightRGB``).
369
+
370
+ Hardware-verified (2026-07-03): with ``cycle=0, counts=0`` the LEDs
371
+ stay dim/dark regardless of ``effect`` — send ``cycle=1, counts>=1``
372
+ (or more) for a visible light. ``effect=0`` turns off; effects 1..3
373
+ all light up (3 is what DobotLab's own quick-test sends).
374
+
375
+ Args:
376
+ number: LED channel — a :class:`~dobotkit.enums.LEDChannel`, an int
377
+ ``1..5`` (``5`` = all), or a string name
378
+ (``"LED_1"``..``"LED_4"``, ``"LED_ALL"``).
379
+ effect: ``0`` = off; ``1..3`` = lit (mode enum, DobotLab uses 3).
380
+ r: Red ``0..255``.
381
+ g: Green ``0..255``.
382
+ b: Blue ``0..255``.
383
+ cycle: Blink period (use ``1`` — ``0`` renders dark, measured).
384
+ counts: Blink count (use ``>=1`` — ``0`` renders dark, measured).
385
+ """
386
+ if isinstance(number, str):
387
+ number = _LED_NAMES[number]
388
+ else:
389
+ number = int(number) # LEDChannel or int -> plain int on the wire
390
+ return self._call(
391
+ "SetLightRGB", number=number, effect=effect, r=r, g=g, b=b, cycle=cycle, counts=counts
392
+ )
393
+
394
+ def buzzer(self, index: int = 5, tone: int = 0, beat: int = 0) -> Any:
395
+ """Sound the buzzer (``SetBuzzerSound``).
396
+
397
+ Hardware-verified (2026-07-03): ``index=5, tone=0, beat=0`` — the
398
+ exact combo DobotLab's own beep uses — produces a clean beep. Other
399
+ combos (e.g. ``index=1, tone=5, beat=1``) produce a rattling buzz or
400
+ nothing; full range semantics remain firmware-defined.
401
+ """
402
+ return self._call("SetBuzzerSound", index=index, tone=tone, beat=beat)
403
+
404
+ # ---- sensors (read-only, motors idle) ----------------------------------
405
+
406
+ def ultrasonic(self) -> Optional[Dict[str, float]]:
407
+ """Read the four ultrasonic distances in cm, validated (``GetUltrasoundData``).
408
+
409
+ Returns ``{front, back, left, right}`` with every value clamped to the
410
+ hardware's measured :data:`ULTRA_MAX_CM` (40 cm) ceiling — a reading of
411
+ 40 means "40 cm **or more**". Returns ``None`` when the response is
412
+ malformed: missing keys, non-numeric, or ``<= 0`` sentinel values from
413
+ an absent/failed sensor. Callers must treat ``None`` as
414
+ "unknown -> stop" (as :meth:`clearance_ok` does). Use
415
+ :meth:`ultrasonic_raw` for the untouched firmware response.
416
+ """
417
+ raw = self.ultrasonic_raw()
418
+ if not isinstance(raw, dict):
419
+ return None
420
+ out: Dict[str, float] = {}
421
+ for key in _ULTRA_KEYS:
422
+ value = raw.get(key)
423
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
424
+ return None
425
+ v = float(value)
426
+ # NaN would sail through <=0 (NaN comparisons are False) and then
427
+ # defeat clearance_ok the same way — require a finite positive value.
428
+ if not math.isfinite(v) or v <= 0:
429
+ return None
430
+ out[key] = min(v, ULTRA_MAX_CM)
431
+ return out
432
+
433
+ def ultrasonic_raw(self) -> Any:
434
+ """Raw ``GetUltrasoundData`` response, unvalidated (advanced/diagnostic use)."""
435
+ return self._call("GetUltrasoundData")
436
+
437
+ def odometer(self) -> Dict[str, float]:
438
+ """Read accumulated world-frame pose (``GetSpeedometer``).
439
+
440
+ Returns ``{x, y, yaw}`` — position nominally in mm, yaw in degrees
441
+ (zeroed by :meth:`set_odometer`). Note the firmware spelling
442
+ ``Speedometer``.
443
+
444
+ .. caution::
445
+ The mm scale is **suspect** (2026-07-03 measurement: a drive whose
446
+ odometer counted ~110 covered roughly 370-470 real millimetres —
447
+ a 3-4x undercount). Treat odometer distances as *relative* progress
448
+ until the scale is calibrated with a ruler on your chassis.
449
+ """
450
+ return cast(Dict[str, float], self._call("GetSpeedometer"))
451
+
452
+ def set_odometer(self, x: float, y: float, yaw: float) -> Any:
453
+ """Force the odometer pose (``SetSpeedometer``) — used to zero coordinates."""
454
+ return self._call("SetSpeedometer", x=x, y=y, yaw=yaw)
455
+
456
+ def battery(self) -> Dict[str, float]:
457
+ """Read battery voltage/percentage (``GetBatteryVoltage``).
458
+
459
+ Returns ``{powerVoltage, powerPercentage}``. Commonly used as the
460
+ link-verification read after :meth:`connect_robot`.
461
+ """
462
+ return cast(Dict[str, float], self._call("GetBatteryVoltage"))
463
+
464
+ def imu_angle(self) -> Dict[str, float]:
465
+ """Read the IMU angle (``GetImuAngle``).
466
+
467
+ Returns ``{yaw, ...}`` — an absolute angle referenced to power-on (not
468
+ affected by :meth:`set_odometer`).
469
+ """
470
+ return cast(Dict[str, float], self._call("GetImuAngle"))
471
+
472
+ # ---- diagnostics / alarms ----------------------------------------------
473
+
474
+ def get_alarm_info(self) -> Any:
475
+ """Read the active alarm/warning list (``GetAlarmInfo``).
476
+
477
+ Returns the firmware result verbatim — expected shape is
478
+ ``{"warning": [...]}`` per the plugin protocol table — read it
479
+ defensively.
480
+ """
481
+ return self._call("GetAlarmInfo")
482
+
483
+ def clean_alarm_info(self) -> Any:
484
+ """Clear the active alarms (``CleanAlarmInfo``)."""
485
+ return self._call("CleanAlarmInfo")
486
+
487
+ def running_state(self) -> Any:
488
+ """Read the running state (``GetRunningState``); shape ``{"runningState": int}`` — read defensively."""
489
+ return self._call("GetRunningState")
490
+
491
+ def stall_protection(self) -> Any:
492
+ """Read the stall-protection flag (``GetStallProtection``); ``{"isHappened": int}``."""
493
+ return self._call("GetStallProtection")
494
+
495
+ def off_ground(self) -> Any:
496
+ """Read the wheels-off-ground flag (``GetOffGround``); ``{"isHappened": int}``."""
497
+ return self._call("GetOffGround")
498
+
499
+ # ---- MagicBox status ----------------------------------------------------
500
+ #
501
+ # Despite their names these are regular ``MagicianGO.*`` methods; the actual
502
+ # MagicBox sensor/IO reads live on the ``MagicBox.*`` namespace via the
503
+ # :attr:`sensors` / :attr:`io` groups.
504
+
505
+ def magic_box_mode(self) -> Any:
506
+ """Read the MagicBox mode (``MagicianGO.GetMagicBoxMode``); ``{"mode": int}``."""
507
+ return self._call("GetMagicBoxMode")
508
+
509
+ def magic_box_num(self) -> Any:
510
+ """Read the attached-MagicBox count/id (``MagicianGO.GetMagicBoxNum``); read defensively."""
511
+ return self._call("GetMagicBoxNum")