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.
- dobotkit/__init__.py +112 -0
- dobotkit/_version.py +1 -0
- dobotkit/arm/__init__.py +46 -0
- dobotkit/arm/commands/__init__.py +21 -0
- dobotkit/arm/commands/_base.py +19 -0
- dobotkit/arm/commands/connection.py +32 -0
- dobotkit/arm/commands/effector_io.py +114 -0
- dobotkit/arm/commands/motion.py +60 -0
- dobotkit/arm/commands/sensors.py +38 -0
- dobotkit/arm/groups.py +162 -0
- dobotkit/arm/magicianlite.py +203 -0
- dobotkit/enums.py +69 -0
- dobotkit/exceptions.py +36 -0
- dobotkit/go/__init__.py +56 -0
- dobotkit/go/geometry.py +105 -0
- dobotkit/go/groups.py +164 -0
- dobotkit/go/magiciango.py +511 -0
- dobotkit/go/navigation.py +364 -0
- dobotkit/link.py +209 -0
- dobotkit/py.typed +0 -0
- dobotkit-0.1.0.dist-info/METADATA +322 -0
- dobotkit-0.1.0.dist-info/RECORD +24 -0
- dobotkit-0.1.0.dist-info/WHEEL +4 -0
- dobotkit-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""High-level Magician Lite arm over DobotLink.
|
|
2
|
+
|
|
3
|
+
:class:`MagicianLite` is the ergonomic, intent-revealing front door to the
|
|
4
|
+
DobotLink-mediated Magician Lite arm. It wraps a
|
|
5
|
+
:class:`~dobotkit.arm.commands.ArmCommands` (which speaks the DobotLink
|
|
6
|
+
JSON-RPC surface through a :class:`~dobotkit.link.DobotLinkClient`) and
|
|
7
|
+
exposes the everyday operations directly -- connect, home, move,
|
|
8
|
+
pick-and-place -- plus the effector/sensor/IO
|
|
9
|
+
:mod:`~dobotkit.arm.groups` facades.
|
|
10
|
+
|
|
11
|
+
Design highlights
|
|
12
|
+
------------------
|
|
13
|
+
* **Queued motion.** Motion commands are always queued on-device;
|
|
14
|
+
``connect()`` clears and starts the queue so anything sent afterwards
|
|
15
|
+
actually executes. ``wait=True`` sends ``isWaitForFinish=true`` (matching
|
|
16
|
+
DobotLab) so DobotLink itself blocks until the move physically completes --
|
|
17
|
+
there is no client-side polling.
|
|
18
|
+
* **Safe teardown.** Used as a context manager, ``__exit__`` always stops
|
|
19
|
+
the queue and disconnects -- even if the ``with`` body raised -- and
|
|
20
|
+
never suppresses the original exception.
|
|
21
|
+
* **``port="auto"``.** Resolves to the first port DobotLink's
|
|
22
|
+
``SearchDobot`` reports, at :meth:`connect` time.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
from typing import Any, Optional, Tuple
|
|
27
|
+
|
|
28
|
+
from dobotkit.arm.commands import ArmCommands
|
|
29
|
+
from dobotkit.arm.groups import EffectorGroup, IOGroup, SensorGroup
|
|
30
|
+
from dobotkit.enums import PTPMode
|
|
31
|
+
from dobotkit.exceptions import DobotConnectionError
|
|
32
|
+
|
|
33
|
+
__all__ = ["MagicianLite"]
|
|
34
|
+
|
|
35
|
+
# A 3-component Cartesian waypoint (x, y, z).
|
|
36
|
+
Point = Tuple[float, float, float]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MagicianLite:
|
|
40
|
+
"""Ergonomic high-level control of a Dobot Magician Lite arm via DobotLink."""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
port: str = "auto",
|
|
45
|
+
*,
|
|
46
|
+
host: str = "localhost",
|
|
47
|
+
ws_port: int = 9090,
|
|
48
|
+
timeout: float = 10.0,
|
|
49
|
+
auto_connect: bool = True,
|
|
50
|
+
_client: Optional[Any] = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
"""Create a MagicianLite.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
port: DobotLink port name (e.g. ``"COM3"``). The special value
|
|
56
|
+
``"auto"`` resolves to the first port reported by
|
|
57
|
+
:meth:`~dobotkit.arm.commands.ArmCommands.search` when
|
|
58
|
+
:meth:`connect` runs.
|
|
59
|
+
host: DobotLink WebSocket host.
|
|
60
|
+
ws_port: DobotLink WebSocket port.
|
|
61
|
+
timeout: Seconds to wait for the DobotLink connection and each RPC
|
|
62
|
+
response.
|
|
63
|
+
auto_connect: When ``True`` (default), :meth:`connect` is called
|
|
64
|
+
during construction.
|
|
65
|
+
_client: Test/advanced seam -- inject a ready (or fake)
|
|
66
|
+
DobotLink client instead of opening a real
|
|
67
|
+
:class:`~dobotkit.link.DobotLinkClient`.
|
|
68
|
+
"""
|
|
69
|
+
self._owns_client = _client is None
|
|
70
|
+
if _client is None:
|
|
71
|
+
from dobotkit.link import DobotLinkClient
|
|
72
|
+
|
|
73
|
+
_client = DobotLinkClient(host=host, port=ws_port, timeout=timeout).connect()
|
|
74
|
+
self._client = _client
|
|
75
|
+
self._port = port
|
|
76
|
+
self.cmds = ArmCommands(_client, port if port != "auto" else "")
|
|
77
|
+
self.effector = EffectorGroup(self.cmds)
|
|
78
|
+
self.sensors = SensorGroup(self.cmds)
|
|
79
|
+
self.io = IOGroup(self.cmds)
|
|
80
|
+
|
|
81
|
+
if auto_connect:
|
|
82
|
+
self.connect()
|
|
83
|
+
|
|
84
|
+
# -- lifecycle -----------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
def connect(self) -> None:
|
|
87
|
+
"""Resolve ``port="auto"``, connect the arm, and start its command queue."""
|
|
88
|
+
if self._port == "auto":
|
|
89
|
+
ports = self.cmds.search() or []
|
|
90
|
+
if not ports:
|
|
91
|
+
raise DobotConnectionError("no Dobot ports found via DobotLink")
|
|
92
|
+
self.cmds.port_name = ports[0]["portName"]
|
|
93
|
+
self.cmds.connect()
|
|
94
|
+
self.cmds.queue_clear()
|
|
95
|
+
self.cmds.queue_start()
|
|
96
|
+
|
|
97
|
+
def disconnect(self) -> None:
|
|
98
|
+
"""Disconnect the arm and, if this instance owns it, close the client."""
|
|
99
|
+
try:
|
|
100
|
+
self.cmds.disconnect()
|
|
101
|
+
finally:
|
|
102
|
+
if self._owns_client:
|
|
103
|
+
self._client.close()
|
|
104
|
+
|
|
105
|
+
def __enter__(self) -> "MagicianLite":
|
|
106
|
+
return self
|
|
107
|
+
|
|
108
|
+
def __exit__(self, *exc: object) -> None:
|
|
109
|
+
"""Stop the queue and disconnect, always; never suppress an exception."""
|
|
110
|
+
try:
|
|
111
|
+
self.cmds.queue_stop()
|
|
112
|
+
except Exception: # pragma: no cover - teardown must not mask body errors
|
|
113
|
+
pass
|
|
114
|
+
try:
|
|
115
|
+
self.disconnect()
|
|
116
|
+
except Exception: # pragma: no cover - teardown must not mask body errors
|
|
117
|
+
pass
|
|
118
|
+
|
|
119
|
+
# -- pose / speed ------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
def get_pose(self) -> Any:
|
|
122
|
+
"""Read the current Cartesian + joint pose."""
|
|
123
|
+
return self.cmds.get_pose()
|
|
124
|
+
|
|
125
|
+
def set_speed(self, velocity: float, acceleration: float) -> None:
|
|
126
|
+
"""Set the PTP velocity / acceleration for Cartesian moves."""
|
|
127
|
+
self.cmds.set_ptp_common_params(velocity, acceleration)
|
|
128
|
+
self.cmds.set_ptp_coordinate_params(velocity, acceleration)
|
|
129
|
+
|
|
130
|
+
# -- homing --------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
def home(
|
|
133
|
+
self, x: float = 200, y: float = 0, z: float = 0, r: float = 0, *, wait: bool = True
|
|
134
|
+
) -> Optional[int]:
|
|
135
|
+
"""Run the homing routine, targeting the given pose.
|
|
136
|
+
|
|
137
|
+
When ``wait`` is True (default), ``isWaitForFinish=true`` is sent so
|
|
138
|
+
DobotLink itself blocks until homing physically completes.
|
|
139
|
+
"""
|
|
140
|
+
self.cmds.set_home_params(x, y, z, r, queued=True)
|
|
141
|
+
return self.cmds.set_home_cmd(queued=True, wait_finish=wait)
|
|
142
|
+
|
|
143
|
+
# -- moves -----------------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
def move_to(
|
|
146
|
+
self, x: float, y: float, z: float, r: float = 0, *,
|
|
147
|
+
mode: int = PTPMode.MOVL_XYZ, wait: bool = False,
|
|
148
|
+
) -> Optional[int]:
|
|
149
|
+
"""Move to an absolute Cartesian pose (defaults to a straight-line move).
|
|
150
|
+
|
|
151
|
+
When ``wait`` is True, ``isWaitForFinish=true`` is sent so DobotLink
|
|
152
|
+
itself blocks until the move physically completes; when False
|
|
153
|
+
(default), the move is only queued and this returns immediately.
|
|
154
|
+
"""
|
|
155
|
+
return self.cmds.set_ptp_cmd(mode, x, y, z, r, queued=True, wait_finish=wait)
|
|
156
|
+
|
|
157
|
+
def move_relative(
|
|
158
|
+
self, dx: float = 0, dy: float = 0, dz: float = 0, dr: float = 0, *, wait: bool = False
|
|
159
|
+
) -> Optional[int]:
|
|
160
|
+
"""Move by a relative Cartesian offset (straight-line increment)."""
|
|
161
|
+
return self.cmds.set_ptp_cmd(
|
|
162
|
+
PTPMode.MOVL_XYZ_INC, dx, dy, dz, dr, queued=True, wait_finish=wait
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# -- effector aliases --------------------------------------------------
|
|
166
|
+
|
|
167
|
+
def suck(self, on: bool) -> Optional[int]:
|
|
168
|
+
"""Turn the suction cup on (grab) or off (release)."""
|
|
169
|
+
return self.effector.suck(bool(on))
|
|
170
|
+
|
|
171
|
+
def grip(self, on: bool) -> Optional[int]:
|
|
172
|
+
"""Close the gripper (``on=True``) or open it."""
|
|
173
|
+
return self.effector.grip(bool(on))
|
|
174
|
+
|
|
175
|
+
# -- pick and place --------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
def pick_and_place(
|
|
178
|
+
self, src: Point, dst: Point, z_safe: float, settle_ms: int = 200
|
|
179
|
+
) -> None:
|
|
180
|
+
"""Pick an object at ``src`` and place it at ``dst``.
|
|
181
|
+
|
|
182
|
+
The classic eight-step cycle, all queued so it runs as one program:
|
|
183
|
+
travel above the source at ``z_safe``, descend to the source, turn
|
|
184
|
+
the suction cup ON and settle, lift back to ``z_safe``, travel above
|
|
185
|
+
the destination, descend, turn the suction cup OFF and settle, lift
|
|
186
|
+
back to ``z_safe``. Each move sends ``isWaitForFinish=true`` so
|
|
187
|
+
DobotLink blocks until it physically completes before the next step is
|
|
188
|
+
sent -- the steps execute sequentially without overlap, and the call
|
|
189
|
+
blocks until the final move completes.
|
|
190
|
+
"""
|
|
191
|
+
sx, sy, sz = src
|
|
192
|
+
dx, dy, dz = dst
|
|
193
|
+
m = PTPMode.MOVL_XYZ
|
|
194
|
+
self.cmds.set_ptp_cmd(m, sx, sy, z_safe, 0, wait_finish=True)
|
|
195
|
+
self.cmds.set_ptp_cmd(m, sx, sy, sz, 0, wait_finish=True)
|
|
196
|
+
self.cmds.set_suction_cup(True, True)
|
|
197
|
+
self.cmds.set_wait_cmd(settle_ms)
|
|
198
|
+
self.cmds.set_ptp_cmd(m, sx, sy, z_safe, 0, wait_finish=True)
|
|
199
|
+
self.cmds.set_ptp_cmd(m, dx, dy, z_safe, 0, wait_finish=True)
|
|
200
|
+
self.cmds.set_ptp_cmd(m, dx, dy, dz, 0, wait_finish=True)
|
|
201
|
+
self.cmds.set_suction_cup(True, False)
|
|
202
|
+
self.cmds.set_wait_cmd(settle_ms)
|
|
203
|
+
self.cmds.set_ptp_cmd(m, dx, dy, z_safe, 0, wait_finish=True)
|
dobotkit/enums.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""All enumerations used across dobotkit."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from enum import IntEnum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PTPMode(IntEnum):
|
|
7
|
+
JUMP_XYZ = 0
|
|
8
|
+
MOVJ_XYZ = 1
|
|
9
|
+
MOVL_XYZ = 2
|
|
10
|
+
JUMP_ANGLE = 3
|
|
11
|
+
MOVJ_ANGLE = 4
|
|
12
|
+
MOVL_ANGLE = 5
|
|
13
|
+
MOVJ_ANGLE_INC = 6
|
|
14
|
+
MOVL_XYZ_INC = 7
|
|
15
|
+
MOVJ_XYZ_INC = 8
|
|
16
|
+
JUMP_MOVL_XYZ = 9
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class JOGMode(IntEnum):
|
|
20
|
+
"""SetJOGCmd `cmd` values. 0 = idle/stop; 1..8 = axis +/-; 9..10 = L-axis +/-."""
|
|
21
|
+
IDLE = 0
|
|
22
|
+
AP_DOWN = 1
|
|
23
|
+
AN_DOWN = 2
|
|
24
|
+
BP_DOWN = 3
|
|
25
|
+
BN_DOWN = 4
|
|
26
|
+
CP_DOWN = 5
|
|
27
|
+
CN_DOWN = 6
|
|
28
|
+
DP_DOWN = 7
|
|
29
|
+
DN_DOWN = 8
|
|
30
|
+
LP_DOWN = 9
|
|
31
|
+
LN_DOWN = 10
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ContinuousPathMode(IntEnum):
|
|
35
|
+
RELATIVE = 0
|
|
36
|
+
ABSOLUTE = 1
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class GPIOType(IntEnum):
|
|
40
|
+
DUMMY = 0
|
|
41
|
+
DO = 1
|
|
42
|
+
PWM = 2
|
|
43
|
+
DI = 3
|
|
44
|
+
ADC = 4
|
|
45
|
+
DIPU = 5
|
|
46
|
+
DIPD = 6
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class EndEffectorType(IntEnum):
|
|
50
|
+
NONE = 0
|
|
51
|
+
SUCTION_CUP = 1
|
|
52
|
+
GRIPPER = 2
|
|
53
|
+
LASER = 3
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ColorPort(IntEnum):
|
|
57
|
+
GP1 = 0
|
|
58
|
+
GP2 = 1
|
|
59
|
+
GP4 = 2
|
|
60
|
+
GP5 = 3
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class LEDChannel(IntEnum):
|
|
64
|
+
"""GO RGB LED channel; SetLightRGB `number`."""
|
|
65
|
+
LED_1 = 1
|
|
66
|
+
LED_2 = 2
|
|
67
|
+
LED_3 = 3
|
|
68
|
+
LED_4 = 4
|
|
69
|
+
LED_ALL = 5
|
dobotkit/exceptions.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Exception hierarchy shared across all dobotkit devices."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from typing import Sequence
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class DobotError(Exception):
|
|
7
|
+
"""Base class for all dobotkit errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DobotConnectionError(DobotError):
|
|
11
|
+
"""Connection failed: device not found, port occupied, or disconnected."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DobotTimeoutError(DobotError):
|
|
15
|
+
"""A response or motion-completion wait exceeded its timeout."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DobotProtocolError(DobotError):
|
|
19
|
+
"""Malformed frame, bad checksum, or undecodable payload."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DobotValueError(DobotError):
|
|
23
|
+
"""An argument was out of range or otherwise invalid."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DobotLinkError(DobotError):
|
|
27
|
+
"""GO only: DobotLink not running, or an RPC returned an error response."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class DobotAlarmError(DobotError):
|
|
31
|
+
"""The arm reported one or more active alarms."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, codes: Sequence[int], message: str = "") -> None:
|
|
34
|
+
self.codes = list(codes)
|
|
35
|
+
text = message or f"active alarms: {self.codes}"
|
|
36
|
+
super().__init__(text)
|
dobotkit/go/__init__.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""dobotkit.go -- Magician GO control over the DobotLink WebSocket (JSON-RPC).
|
|
2
|
+
|
|
3
|
+
This subpackage wraps the DobotLink ``MagicianGO.*`` RPC surface and layers
|
|
4
|
+
sensor-feedback navigation on top of it. It talks to ``ws://localhost:9090``
|
|
5
|
+
via the ``websockets`` library; nothing here touches the arm's serial stack.
|
|
6
|
+
|
|
7
|
+
Exported names:
|
|
8
|
+
|
|
9
|
+
* :class:`~dobotkit.link.DobotLinkClient` -- the WebSocket JSON-RPC client
|
|
10
|
+
(shared with the arm stack).
|
|
11
|
+
* :class:`~dobotkit.go.magiciango.MagicianGO` -- the high-level GO wrapper
|
|
12
|
+
(continuous drive, native sensors, MagicBox sensors/IO, LED/buzzer, alarms).
|
|
13
|
+
* :class:`~dobotkit.go.navigation.PreciseMover` -- sensor-feedback closed-loop
|
|
14
|
+
motion (drive an exact distance / turn an exact angle).
|
|
15
|
+
|
|
16
|
+
Names are resolved through a module-level :func:`__getattr__` (PEP 562) so that
|
|
17
|
+
merely importing :mod:`dobotkit.go` stays light (no ``websockets`` import, no
|
|
18
|
+
socket); the dependency is pulled in only when one of these classes is first
|
|
19
|
+
accessed. A program controlling only the arm never imports the GO stack.
|
|
20
|
+
"""
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from typing import TYPE_CHECKING, Any
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING: # pragma: no cover - for type checkers only, not imported at runtime
|
|
26
|
+
from dobotkit.link import DobotLinkClient
|
|
27
|
+
from .magiciango import MagicianGO
|
|
28
|
+
from .navigation import NavigationAborted, PreciseMover
|
|
29
|
+
|
|
30
|
+
# Public name -> (submodule, attribute). Deferred to first access so importing
|
|
31
|
+
# this subpackage never eagerly imports ``websockets``.
|
|
32
|
+
_LAZY = {
|
|
33
|
+
"DobotLinkClient": ("dobotkit.link", "DobotLinkClient"),
|
|
34
|
+
"MagicianGO": ("dobotkit.go.magiciango", "MagicianGO"),
|
|
35
|
+
"NavigationAborted": ("dobotkit.go.navigation", "NavigationAborted"),
|
|
36
|
+
"PreciseMover": ("dobotkit.go.navigation", "PreciseMover"),
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
__all__ = ["DobotLinkClient", "MagicianGO", "NavigationAborted", "PreciseMover"]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def __getattr__(name: str) -> Any:
|
|
43
|
+
"""Lazily resolve the GO classes on first access (PEP 562)."""
|
|
44
|
+
target = _LAZY.get(name)
|
|
45
|
+
if target is not None:
|
|
46
|
+
import importlib
|
|
47
|
+
|
|
48
|
+
module_name, attr = target
|
|
49
|
+
value = getattr(importlib.import_module(module_name), attr)
|
|
50
|
+
globals()[name] = value # cache so repeat access skips the import machinery
|
|
51
|
+
return value
|
|
52
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def __dir__() -> "list[str]":
|
|
56
|
+
return sorted(set(globals()) | set(__all__))
|
dobotkit/go/geometry.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Pure geometry/units helpers for Magician GO navigation.
|
|
2
|
+
|
|
3
|
+
Every function here is side-effect-free and hardware-independent: they are the
|
|
4
|
+
testable numeric core that ``PreciseMover`` and ``WaypointNav`` build on.
|
|
5
|
+
|
|
6
|
+
Angle / coordinate conventions (matching the GO research doc, section 2.3):
|
|
7
|
+
|
|
8
|
+
* ``0deg`` points along ``+X``; angles increase **counter-clockwise** (CCW),
|
|
9
|
+
so ``+90deg`` points along ``+Y``. This matches ``atan2(dy, dx)`` and the
|
|
10
|
+
GO's ``r+`` = CCW (left-turn) command convention.
|
|
11
|
+
* Signed angle deltas are normalized to the half-open range ``(-180, 180]``:
|
|
12
|
+
a half turn always resolves to ``+180``, never ``-180``.
|
|
13
|
+
|
|
14
|
+
Unit convention: mat/world coordinates are centimetres (matching the SDK's
|
|
15
|
+
position values), while the closed-loop motion primitives work in millimetres.
|
|
16
|
+
The ``cm_to_mm`` / ``mm_to_cm`` helpers are the only place that conversion
|
|
17
|
+
happens.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import math
|
|
22
|
+
|
|
23
|
+
from dobotkit.exceptions import DobotValueError
|
|
24
|
+
|
|
25
|
+
__all__ = ["yaw_delta", "bearing", "clamp_speed", "cm_to_mm", "mm_to_cm", "MM_PER_CM"]
|
|
26
|
+
|
|
27
|
+
#: Millimetres per centimetre — the mat(cm) <-> primitive(mm) scale factor.
|
|
28
|
+
MM_PER_CM: float = 10.0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def yaw_delta(a: float, b: float) -> float:
|
|
32
|
+
"""Return the signed shortest angle ``a - b`` in degrees.
|
|
33
|
+
|
|
34
|
+
The result is normalized to the half-open range ``(-180, 180]``, so the
|
|
35
|
+
+-180 wraparound is handled and a half turn resolves to ``+180`` (never
|
|
36
|
+
``-180``). Inputs need not be normalized; accumulated +-360 offsets give the
|
|
37
|
+
same answer.
|
|
38
|
+
|
|
39
|
+
Examples::
|
|
40
|
+
|
|
41
|
+
yaw_delta(170, -170) -> -20.0 # not 340
|
|
42
|
+
yaw_delta(-170, 170) -> 20.0
|
|
43
|
+
yaw_delta(90, 0) -> 90.0
|
|
44
|
+
yaw_delta(180, 0) -> 180.0
|
|
45
|
+
"""
|
|
46
|
+
d = (a - b) % 360.0
|
|
47
|
+
if d > 180.0:
|
|
48
|
+
d -= 360.0
|
|
49
|
+
return d
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def bearing(dx: float, dy: float) -> float:
|
|
53
|
+
"""Return the direction of the vector ``(dx, dy)`` in degrees.
|
|
54
|
+
|
|
55
|
+
``0deg`` = ``+X`` and angles increase counter-clockwise, so ``+90deg`` =
|
|
56
|
+
``+Y`` and ``-90deg`` = ``-Y``. The result lies in ``(-180, 180]``. The zero
|
|
57
|
+
vector yields ``0.0``.
|
|
58
|
+
|
|
59
|
+
Examples::
|
|
60
|
+
|
|
61
|
+
bearing(1, 0) -> 0.0
|
|
62
|
+
bearing(0, 1) -> 90.0
|
|
63
|
+
bearing(5, 5) -> 45.0
|
|
64
|
+
"""
|
|
65
|
+
return math.degrees(math.atan2(dy, dx))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def clamp_speed(v: float, lo: float, hi: float) -> float:
|
|
69
|
+
"""Clamp the *magnitude* of ``v`` into ``[lo, hi]`` while keeping its sign.
|
|
70
|
+
|
|
71
|
+
``lo``/``hi`` are non-negative magnitude bounds. A magnitude above ``hi`` is
|
|
72
|
+
capped to ``hi``; a non-zero magnitude below ``lo`` is raised to ``lo`` (so a
|
|
73
|
+
crawling command still actually moves). An exact ``0`` is returned unchanged
|
|
74
|
+
so a commanded stop stays a stop.
|
|
75
|
+
|
|
76
|
+
Examples::
|
|
77
|
+
|
|
78
|
+
clamp_speed(-50, 8, 30) -> -30.0
|
|
79
|
+
clamp_speed(3, 8, 30) -> 8.0
|
|
80
|
+
clamp_speed(0, 8, 30) -> 0.0
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
DobotValueError: if ``lo > hi`` or either bound is negative.
|
|
84
|
+
"""
|
|
85
|
+
if lo < 0 or hi < 0:
|
|
86
|
+
raise DobotValueError(f"speed bounds must be non-negative: lo={lo}, hi={hi}")
|
|
87
|
+
if lo > hi:
|
|
88
|
+
raise DobotValueError(f"speed lower bound {lo} exceeds upper bound {hi}")
|
|
89
|
+
if v == 0:
|
|
90
|
+
return 0.0
|
|
91
|
+
sign = 1.0 if v > 0 else -1.0
|
|
92
|
+
mag = abs(v)
|
|
93
|
+
mag = min(mag, hi)
|
|
94
|
+
mag = max(mag, lo)
|
|
95
|
+
return sign * mag
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def cm_to_mm(cm: float) -> float:
|
|
99
|
+
"""Convert centimetres to millimetres (``cm * 10``)."""
|
|
100
|
+
return float(cm) * MM_PER_CM
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def mm_to_cm(mm: float) -> float:
|
|
104
|
+
"""Convert millimetres to centimetres (``mm / 10``)."""
|
|
105
|
+
return float(mm) / MM_PER_CM
|
dobotkit/go/groups.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""MagicBox peripheral facades for the Magician GO.
|
|
2
|
+
|
|
3
|
+
The GO carries the same **MagicBox** peripheral hub as the arm, but its sensor
|
|
4
|
+
reads are issued on the DobotLink ``MagicBox.*`` JSON-RPC namespace (not
|
|
5
|
+
``MagicianGO.*``). The two namespaces coexist on a single connection: connect
|
|
6
|
+
the car once with ``MagicianGO.ConnectDobot`` and these ``MagicBox.*`` reads
|
|
7
|
+
work alongside the native drive/battery/ultrasonic calls (hardware-verified
|
|
8
|
+
2026-07-16). There is **no** separate ``MagicBox.ConnectDobot`` step — issuing
|
|
9
|
+
one actually knocks the GO chassis offline, so this module never does it.
|
|
10
|
+
|
|
11
|
+
Two addressing schemes, straight from the official DobotLab apiBook
|
|
12
|
+
(``magicbox.get_ad`` / ``get_di`` / ``set_port`` vs the sensor blocks):
|
|
13
|
+
|
|
14
|
+
* **ADC / DI / DO / PWM** address a raw **EIO pin (1..26)** -- e.g. the test
|
|
15
|
+
unit's rotary potentiometer on Grove connector 4 reads on EIO pin **22**.
|
|
16
|
+
``set_port(port, io_func=4)`` selects ADC before reading (``4`` = ADC).
|
|
17
|
+
* **color / infrared / Seeed** address the labelled **Grove connector (1..6)**.
|
|
18
|
+
|
|
19
|
+
Every read here is *guarded* (see :func:`_guard`): a missing MagicBox or
|
|
20
|
+
peripheral answers with :class:`~dobotkit.exceptions.DobotTimeoutError` /
|
|
21
|
+
:class:`~dobotkit.exceptions.DobotProtocolError`, which is caught and degraded
|
|
22
|
+
to ``None`` + a ``RuntimeWarning`` so teaching/beginner code keeps running. A
|
|
23
|
+
genuine connection error (DobotLink down / GO not connected) still raises.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import warnings
|
|
28
|
+
from typing import Any, Callable, Optional, TypeVar
|
|
29
|
+
|
|
30
|
+
from dobotkit.enums import GPIOType
|
|
31
|
+
from dobotkit.exceptions import DobotProtocolError, DobotTimeoutError
|
|
32
|
+
|
|
33
|
+
__all__ = ["GoSensorGroup", "GoIOGroup"]
|
|
34
|
+
|
|
35
|
+
_T = TypeVar("_T")
|
|
36
|
+
|
|
37
|
+
# A connected ``DobotLinkClient`` (or any object exposing ``call``).
|
|
38
|
+
ClientLike = Any
|
|
39
|
+
|
|
40
|
+
#: Warning emitted when a MagicBox-routed peripheral read gets no response.
|
|
41
|
+
#: Bilingual so it reads in both the Korean teaching materials and English docs.
|
|
42
|
+
_UNAVAILABLE = (
|
|
43
|
+
"주변장치 응답이 없습니다 — 매직박스/센서 연결을 확인하세요 "
|
|
44
|
+
"(no peripheral response; check the MagicBox and its device)"
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _guard(call: Callable[[], _T]) -> Optional[_T]:
|
|
49
|
+
"""Run a MagicBox-routed peripheral read, degrading to ``None`` if absent."""
|
|
50
|
+
try:
|
|
51
|
+
return call()
|
|
52
|
+
except (DobotTimeoutError, DobotProtocolError):
|
|
53
|
+
warnings.warn(_UNAVAILABLE, RuntimeWarning, stacklevel=3)
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class _MagicBoxBase:
|
|
58
|
+
"""Base holding the client + port; issues ``MagicBox.*`` RPCs for the GO.
|
|
59
|
+
|
|
60
|
+
The car is connected via ``MagicianGO.ConnectDobot`` elsewhere; these calls
|
|
61
|
+
ride the same open port using the ``MagicBox.*`` namespace and the GO's
|
|
62
|
+
``portName``.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(self, client: ClientLike, port_name: str) -> None:
|
|
66
|
+
self._client = client
|
|
67
|
+
self.port_name = port_name
|
|
68
|
+
|
|
69
|
+
def _mb(self, func: str, **params: Any) -> Any:
|
|
70
|
+
"""Issue ``MagicBox.<func>`` with the GO's ``portName``."""
|
|
71
|
+
params["portName"] = self.port_name
|
|
72
|
+
return self._client.call(f"MagicBox.{func}", **params)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class GoSensorGroup(_MagicBoxBase):
|
|
76
|
+
"""Ergonomic MagicBox sensor reads for the GO (all guarded -> ``None``).
|
|
77
|
+
|
|
78
|
+
``adc``/``di`` take an **EIO pin (1..26)**; ``color``/``infrared``/
|
|
79
|
+
``distance``/``temp``/``light``/``rgb`` take a **Grove connector (1..6)**.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def adc(self, eio: int) -> Optional[int]:
|
|
83
|
+
"""Select ADC mode on **EIO pin** ``eio`` (1..26) and read its analog value.
|
|
84
|
+
|
|
85
|
+
Example: the test unit's potentiometer on Grove connector 4 is EIO pin
|
|
86
|
+
``22`` -> ``go.sensors.adc(22)``.
|
|
87
|
+
"""
|
|
88
|
+
def _read() -> int:
|
|
89
|
+
self._mb("SetIOMultiplexing", port=int(eio), multiplex=int(GPIOType.ADC))
|
|
90
|
+
return int(self._mb("GetIOADC", port=int(eio))["value"])
|
|
91
|
+
|
|
92
|
+
return _guard(_read)
|
|
93
|
+
|
|
94
|
+
def di(self, eio: int) -> Optional[int]:
|
|
95
|
+
"""Read the digital-input level (0/1) of **EIO pin** ``eio`` (1..26)."""
|
|
96
|
+
def _read() -> int:
|
|
97
|
+
return int(self._mb("GetIODI", port=int(eio)).get("level", 0))
|
|
98
|
+
|
|
99
|
+
return _guard(_read)
|
|
100
|
+
|
|
101
|
+
def color(self, port: int) -> Optional[Any]:
|
|
102
|
+
"""Enable and read the color sensor on **Grove connector** ``port`` (1..6).
|
|
103
|
+
|
|
104
|
+
Returns ``{"red", "green", "blue"}``.
|
|
105
|
+
"""
|
|
106
|
+
def _read() -> Any:
|
|
107
|
+
self._mb("SetColorSensor", enable=1, colorPort=int(port), version=1)
|
|
108
|
+
return self._mb("GetColorSensor")
|
|
109
|
+
|
|
110
|
+
return _guard(_read)
|
|
111
|
+
|
|
112
|
+
def infrared(self, port: int) -> Optional[Any]:
|
|
113
|
+
"""Enable and read the infrared (photoelectric) sensor on Grove ``port``.
|
|
114
|
+
|
|
115
|
+
Returns ``{"status": 0|1}`` (1 = object detected).
|
|
116
|
+
"""
|
|
117
|
+
def _read() -> Any:
|
|
118
|
+
self._mb("SetInfraredSensor", enable=1, infraredPort=int(port), version=1)
|
|
119
|
+
return self._mb("GetInfraredSensor", infraredPort=int(port))
|
|
120
|
+
|
|
121
|
+
return _guard(_read)
|
|
122
|
+
|
|
123
|
+
def distance(self, port: int) -> Optional[Any]:
|
|
124
|
+
"""Read the Seeed distance sensor on **Grove connector** ``port`` (1..6)."""
|
|
125
|
+
return _guard(lambda: self._mb("GetSeeedDistanceSensor", port=int(port)))
|
|
126
|
+
|
|
127
|
+
def temp(self, port: int) -> Optional[Any]:
|
|
128
|
+
"""Read the Seeed temperature/humidity sensor on Grove ``port`` (1..6)."""
|
|
129
|
+
return _guard(lambda: self._mb("GetSeeedTempSensor", port=int(port)))
|
|
130
|
+
|
|
131
|
+
def light(self, port: int) -> Optional[Any]:
|
|
132
|
+
"""Read the Seeed light sensor on **Grove connector** ``port`` (1..6)."""
|
|
133
|
+
return _guard(lambda: self._mb("GetSeeedLightSensor", port=int(port)))
|
|
134
|
+
|
|
135
|
+
def rgb(self, port: int, value: float) -> Optional[Any]:
|
|
136
|
+
"""Set the Seeed RGB LED on Grove ``port`` (1..6) to ``value``."""
|
|
137
|
+
return _guard(lambda: self._mb("SetSeeedRGBLed", port=int(port), rgb=float(value)))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class GoIOGroup(_MagicBoxBase):
|
|
141
|
+
"""Ergonomic MagicBox digital/analog I/O for the GO, addressed by **EIO pin** (1..26)."""
|
|
142
|
+
|
|
143
|
+
def set_do(self, eio: int, level: int) -> Any:
|
|
144
|
+
"""Set the digital-output level (0/1) of **EIO pin** ``eio`` (1..26)."""
|
|
145
|
+
return self._mb("SetIODO", port=int(eio), level=int(level))
|
|
146
|
+
|
|
147
|
+
def get_di(self, eio: int) -> Optional[int]:
|
|
148
|
+
"""Read the digital-input level (0/1) of **EIO pin** ``eio`` (1..26)."""
|
|
149
|
+
def _read() -> int:
|
|
150
|
+
return int(self._mb("GetIODI", port=int(eio)).get("level", 0))
|
|
151
|
+
|
|
152
|
+
return _guard(_read)
|
|
153
|
+
|
|
154
|
+
def get_adc(self, eio: int) -> Optional[int]:
|
|
155
|
+
"""Read the ADC value of **EIO pin** ``eio`` (1..26)."""
|
|
156
|
+
return _guard(lambda: int(self._mb("GetIOADC", port=int(eio))["value"]))
|
|
157
|
+
|
|
158
|
+
def set_pwm(self, eio: int, frequency: float, duty: float) -> Any:
|
|
159
|
+
"""Configure PWM (frequency Hz, duty % 0..100) on **EIO pin** ``eio``."""
|
|
160
|
+
return self._mb("SetIOPWM", port=int(eio), frequency=float(frequency), dutyCycle=float(duty))
|
|
161
|
+
|
|
162
|
+
def set_multiplexing(self, eio: int, multiplex: int) -> Any:
|
|
163
|
+
"""Assign a multiplex function (see :class:`~dobotkit.enums.GPIOType`) to EIO ``eio``."""
|
|
164
|
+
return self._mb("SetIOMultiplexing", port=int(eio), multiplex=int(multiplex))
|