dobot-usb 0.2.0a3__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.
dobot_usb/__init__.py ADDED
@@ -0,0 +1,54 @@
1
+ """Small high-level interface for classic DOBOT Magician robots."""
2
+
3
+ from .client import Dobot
4
+ from .commands import CommandSpec
5
+ from .discovery import discover
6
+ from .errors import (
7
+ CommandInvalidated,
8
+ ConnectionError,
9
+ DobotError,
10
+ ExecutionTimeout,
11
+ OutcomeUnknown,
12
+ ProtocolError,
13
+ RequestTimeout,
14
+ RobotAlarmError,
15
+ UnsupportedCommand,
16
+ )
17
+ from .execution import CommandHandle, ExecutionState
18
+ from .models import DeviceInfo, Point, PortInfo, Pose, Status, ToolState
19
+ from .motion import PTPMode
20
+ from .paths import Bounds, Path, Preview
21
+ from .pen import PenCheckpoint, PenReport, pen_path
22
+ from .tools import LaserNotArmed
23
+
24
+ __version__ = "0.2.0a3"
25
+ __all__ = [
26
+ "Dobot",
27
+ "discover",
28
+ "DobotError",
29
+ "ConnectionError",
30
+ "ProtocolError",
31
+ "RequestTimeout",
32
+ "UnsupportedCommand",
33
+ "DeviceInfo",
34
+ "PortInfo",
35
+ "Pose",
36
+ "Status",
37
+ "ToolState",
38
+ "Point",
39
+ "PTPMode",
40
+ "Path",
41
+ "Bounds",
42
+ "Preview",
43
+ "pen_path",
44
+ "PenCheckpoint",
45
+ "PenReport",
46
+ "CommandSpec",
47
+ "CommandHandle",
48
+ "ExecutionState",
49
+ "ExecutionTimeout",
50
+ "CommandInvalidated",
51
+ "RobotAlarmError",
52
+ "OutcomeUnknown",
53
+ "LaserNotArmed",
54
+ ]
dobot_usb/backend.py ADDED
@@ -0,0 +1,65 @@
1
+ """Connect pure command schemas to the session-aware executor."""
2
+
3
+ from collections.abc import Callable
4
+
5
+ from .commands import COMMANDS, CommandSpec
6
+ from .errors import ProtocolError, UnsupportedCommand
7
+ from .execution import CommandExecutor, CommandHandle
8
+ from .validation import options
9
+
10
+ QUEUE_LIFECYCLE = {"queue_start", "queue_stop", "queue_force_stop", "queue_clear"}
11
+
12
+
13
+ class CommandBackend:
14
+ def __init__(self, executor: CommandExecutor, require_motion_ready: Callable[[], None]) -> None:
15
+ self.executor = executor
16
+ self._require_motion_ready = require_motion_ready
17
+
18
+ @staticmethod
19
+ def spec(name: str) -> CommandSpec:
20
+ if not isinstance(name, str) or name not in COMMANDS:
21
+ raise UnsupportedCommand(f"Unknown command name: {name!r}", stage="not_sent")
22
+ return COMMANDS[name]
23
+
24
+ def read(self, name: str, /, **params: object) -> dict[str, object]:
25
+ spec = self.spec(name)
26
+ packet = spec.encode_get(**params)
27
+ data = self.executor.read(spec.command, packet)
28
+ reply = spec.decode(data)
29
+ # EIO GETs echo the port. A different port is an unrelated reply.
30
+ if "address" in params and reply["address"] != params["address"]:
31
+ self.executor.close()
32
+ raise ProtocolError(
33
+ f"{name} requested EIO {params['address']} but received EIO {reply['address']}",
34
+ command=spec.command,
35
+ )
36
+ return reply
37
+
38
+ def write(
39
+ self,
40
+ name: str,
41
+ /,
42
+ *,
43
+ wait: bool = True,
44
+ timeout: float = 30.0,
45
+ queued: bool | None = None,
46
+ **params: object,
47
+ ) -> CommandHandle:
48
+ options(wait, timeout)
49
+ spec = self.spec(name)
50
+ packet = spec.encode_set(**params)
51
+ if queued is not None and type(queued) is not bool:
52
+ raise ValueError("queued must be bool or None")
53
+ queue = spec.default_queued if queued is None else queued
54
+ if queue and not spec.queueable:
55
+ raise UnsupportedCommand(f"{name} cannot be queued", stage="not_sent")
56
+ if name in QUEUE_LIFECYCLE:
57
+ raise UnsupportedCommand("Use robot.queue lifecycle methods", stage="not_sent")
58
+ with self.executor.sequence():
59
+ if name == "ptp_with_l":
60
+ self._require_motion_ready()
61
+ # An immediate SET has an ACK, no observable execution index. Do not turn
62
+ # the normal convenience call into an invented completion claim.
63
+ return self.executor.submit(
64
+ spec.command, packet, queued=queue, wait=wait if queue else False, timeout=timeout
65
+ )
dobot_usb/cli.py ADDED
@@ -0,0 +1,54 @@
1
+ """Read-only diagnostics for the classic Magician."""
2
+
3
+ import argparse
4
+ import json
5
+ from dataclasses import asdict
6
+
7
+ from .client import Dobot
8
+ from .commands import COMMANDS
9
+ from .discovery import discover
10
+ from .errors import DobotError
11
+
12
+
13
+ def main(argv: list[str] | None = None) -> int:
14
+ parser = argparse.ArgumentParser(description="Dobot Kit diagnostics")
15
+ sub = parser.add_subparsers(dest="command", required=True)
16
+ sub.add_parser("ports", help="enumerate candidate ports without opening them")
17
+ sub.add_parser("commands", help="list implemented protocol operations and known gaps")
18
+ status = sub.add_parser("status", help="read device version, pose and alarms")
19
+ status.add_argument(
20
+ "--port", required=True, help="explicit port released by other applications"
21
+ )
22
+ status.add_argument("--timeout", type=float, default=1.0, help="per-query deadline in seconds")
23
+ args = parser.parse_args(argv)
24
+ try:
25
+ if args.command == "commands":
26
+ print(
27
+ json.dumps(
28
+ [
29
+ {
30
+ "name": s.name,
31
+ "id": s.command,
32
+ "section": s.section,
33
+ "get": s.get_supported,
34
+ "set": s.set_supported,
35
+ "queueable": s.queueable,
36
+ "limitation": s.unsupported_reason,
37
+ }
38
+ for s in COMMANDS.values()
39
+ ],
40
+ ensure_ascii=False,
41
+ indent=2,
42
+ )
43
+ )
44
+ return 0
45
+ if args.command == "ports":
46
+ print(json.dumps([asdict(p) for p in discover()], ensure_ascii=False, indent=2))
47
+ return 0
48
+ with Dobot.connect(args.port, timeout=args.timeout, read_only=True) as bot:
49
+ state = asdict(bot.status())
50
+ state["device"]["firmware_raw"] = state["device"]["firmware_raw"].hex()
51
+ print(json.dumps(state, ensure_ascii=False, indent=2))
52
+ except (DobotError, ValueError) as exc:
53
+ parser.exit(1, f"dobot: {exc}\n")
54
+ return 0
dobot_usb/client.py ADDED
@@ -0,0 +1,263 @@
1
+ """Small synchronous query API for the classic Magician."""
2
+
3
+ import math
4
+ import struct
5
+ from types import TracebackType
6
+ from typing import cast
7
+
8
+ from .backend import CommandBackend
9
+ from .commands import COMMANDS, CommandSpec
10
+ from .conveyor import Conveyor
11
+ from .errors import ConnectionError, ProtocolError, RobotAlarmError, UnsupportedCommand
12
+ from .execution import CommandExecutor, CommandHandle
13
+ from .models import DeviceInfo, Point, Pose, Status, ToolState
14
+ from .motion import Motion
15
+ from .pen import Pen
16
+ from .peripherals import IO, Motors, Network, Rail, Sensors, Settings, Teaching
17
+ from .queue import Queue
18
+ from .tools import Laser, Tool
19
+ from .transfer import GripperHead, SuctionHead
20
+ from .transport import BOOTSTRAP_QUERIES, SerialTransport, Transport
21
+ from .validation import options
22
+
23
+
24
+ class Advanced:
25
+ """Named, validated protocol operations and legacy raw bootstrap queries."""
26
+
27
+ def __init__(self, backend: CommandBackend, queue: Queue) -> None:
28
+ self._backend = backend
29
+ self._queue = queue
30
+
31
+ def read(self, command: int) -> bytes:
32
+ """Return unparsed query bytes for an explicitly supported command ID."""
33
+ if type(command) is not int or command not in BOOTSTRAP_QUERIES:
34
+ raise UnsupportedCommand(f"Query command {command!r} is not enabled in this release")
35
+ return self._backend.executor.read(command)
36
+
37
+ def get(self, name: str, **params: object) -> dict[str, object]:
38
+ """Read a named command, validating addressed queries and reply fields."""
39
+ return self._backend.read(name, **params)
40
+
41
+ def set(
42
+ self,
43
+ name: str,
44
+ /,
45
+ *,
46
+ wait: bool = True,
47
+ timeout: float = 30.0,
48
+ queued: bool | None = None,
49
+ **params: object,
50
+ ) -> CommandHandle | None:
51
+ """Write a named command. Queue lifecycle operations invalidate old receipts."""
52
+ options(wait, timeout)
53
+ lifecycle = {
54
+ "queue_start": lambda: self._queue.start(timeout=timeout),
55
+ "queue_stop": lambda: self._queue.pause(timeout=timeout),
56
+ "queue_force_stop": lambda: self._queue.stop(clear=False, timeout=timeout),
57
+ "queue_clear": lambda: self._queue.clear(timeout=timeout),
58
+ }
59
+ spec = self.describe(name)
60
+ if name in lifecycle:
61
+ spec.encode_set(**params)
62
+ if queued is not None and (type(queued) is not bool or queued):
63
+ raise ValueError("Queue lifecycle commands cannot be queued")
64
+ lifecycle[name]()
65
+ return None
66
+ return self._backend.write(name, wait=wait, timeout=timeout, queued=queued, **params)
67
+
68
+ def describe(self, name: str) -> CommandSpec:
69
+ try:
70
+ return COMMANDS[name]
71
+ except (KeyError, TypeError) as exc:
72
+ raise UnsupportedCommand(f"Unknown command: {name!r}", stage="not_sent") from exc
73
+
74
+ @property
75
+ def commands(self) -> tuple[str, ...]:
76
+ return tuple(COMMANDS)
77
+
78
+
79
+ class Dobot:
80
+ """A classic Magician connected through a protocol transport.
81
+
82
+ Construction with a custom Transport does not perform a handshake. Use connect() for
83
+ a serial connection. Neither path sends motion or changes controller state.
84
+ """
85
+
86
+ def __init__(self, transport: Transport) -> None:
87
+ self._transport = transport
88
+ self._executor = CommandExecutor(transport)
89
+ self._backend = CommandBackend(self._executor, self._ready)
90
+ self.suction = SuctionHead(self._backend, self)
91
+ self.gripper = GripperHead(self._backend, self)
92
+ self.laser = Laser(self._backend, is_session_active=lambda: not self._executor.closed)
93
+ self.pen = Pen(self)
94
+ self.tool = Tool(self._backend)
95
+ self.io = IO(self._backend)
96
+ self.motors = Motors(self._backend)
97
+ self.conveyor = Conveyor(self._backend)
98
+ self.sensors = Sensors(self._backend)
99
+ self.rail = Rail(self._backend)
100
+ self.teaching = Teaching(self._backend)
101
+ self.settings = Settings(self._backend)
102
+ self.network = Network(self._backend)
103
+ self.queue = Queue(self._backend, on_invalidate=self.laser.invalidate)
104
+ self.advanced = Advanced(self._backend, self.queue)
105
+ self.motion = Motion(
106
+ self._backend,
107
+ self.pose,
108
+ self._executor.synchronize,
109
+ self._ready,
110
+ sequence=self._executor.sequence,
111
+ )
112
+
113
+ @classmethod
114
+ def connect(cls, port: str, *, timeout: float = 1.0, read_only: bool = False) -> "Dobot":
115
+ """Open an explicit port and verify version/pose/alarms using queries only.
116
+
117
+ The port must be released by DobotStudio, DobotLink or the existing local panel.
118
+ The handshake checks reply shapes, not cryptographic identity or tool presence.
119
+ """
120
+ if type(read_only) is not bool:
121
+ raise ValueError("read_only must be bool")
122
+ bot = cls(SerialTransport(port, timeout=timeout, allow_writes=not read_only))
123
+ try:
124
+ bot.status()
125
+ except BaseException:
126
+ bot.close()
127
+ raise
128
+ return bot
129
+
130
+ def _ready(self) -> None:
131
+ alarms = self.alarms()
132
+ if alarms:
133
+ raise RobotAlarmError(
134
+ "Controller alarms active before motion", alarms=alarms, stage="not_sent"
135
+ )
136
+
137
+ def move_to(
138
+ self,
139
+ x: float | Point | Pose,
140
+ y: float | None = None,
141
+ z: float | None = None,
142
+ r: float | None = None,
143
+ *,
144
+ path: str = "linear",
145
+ wait: bool = True,
146
+ timeout: float = 30.0,
147
+ ) -> CommandHandle:
148
+ """Move to XYZ or a saved Point/Pose, including its tool rotation."""
149
+ return self.motion.move_to(x, y, z, r, path=path, wait=wait, timeout=timeout)
150
+
151
+ def move_by(
152
+ self,
153
+ *,
154
+ x: float = 0,
155
+ y: float = 0,
156
+ z: float = 0,
157
+ r: float = 0,
158
+ path: str = "linear",
159
+ wait: bool = True,
160
+ timeout: float = 30.0,
161
+ ) -> CommandHandle:
162
+ return self.motion.move_by(x=x, y=y, z=z, r=r, path=path, wait=wait, timeout=timeout)
163
+
164
+ def move_joints(
165
+ self,
166
+ j1: float,
167
+ j2: float,
168
+ j3: float,
169
+ j4: float,
170
+ *,
171
+ relative: bool = False,
172
+ wait: bool = True,
173
+ timeout: float = 30.0,
174
+ ) -> CommandHandle:
175
+ return self.motion.move_joints(
176
+ j1, j2, j3, j4, relative=relative, wait=wait, timeout=timeout
177
+ )
178
+
179
+ def home(self, *, wait: bool = True, timeout: float = 60.0) -> CommandHandle:
180
+ return self.motion.home(wait=wait, timeout=timeout)
181
+
182
+ def speed(
183
+ self,
184
+ *,
185
+ mm_s: float,
186
+ mm_s2: float,
187
+ deg_s: float | None = None,
188
+ deg_s2: float | None = None,
189
+ ) -> CommandHandle:
190
+ return self.motion.speed(mm_s=mm_s, mm_s2=mm_s2, deg_s=deg_s, deg_s2=deg_s2)
191
+
192
+ def stop(self, *, clear: bool = True, timeout: float = 30.0) -> None:
193
+ self.queue.stop(clear=clear, timeout=timeout)
194
+
195
+ def pose(self) -> Pose:
196
+ data = self.advanced.read(10)
197
+ if len(data) != 32:
198
+ raise ProtocolError(f"Pose must contain 32 bytes, got {len(data)}")
199
+ x, y, z, r, j1, j2, j3, j4 = struct.unpack("<8f", data)
200
+ if not all(math.isfinite(v) for v in (x, y, z, r, j1, j2, j3, j4)):
201
+ raise ProtocolError("Pose contains a non-finite value")
202
+ return Pose(x, y, z, r, (j1, j2, j3, j4))
203
+
204
+ def alarms(self) -> tuple[int, ...]:
205
+ data = self.advanced.read(20)
206
+ if len(data) != 16:
207
+ raise ProtocolError(f"Alarm state must contain 16 bytes, got {len(data)}")
208
+ return tuple(
209
+ i * 8 + bit for i, byte in enumerate(data) for bit in range(8) if byte >> bit & 1
210
+ )
211
+
212
+ def device_info(self) -> DeviceInfo:
213
+ data = self.advanced.read(2)
214
+ # V1.1.5 specifies 3 bytes. Magician 3.7.0 and 4.0.3 also use 14-byte replies.
215
+ # Preserve all extended fields without guessing their meaning.
216
+ if len(data) not in (3, 14):
217
+ raise ProtocolError(f"Unsupported firmware version reply length: {len(data)}")
218
+ return DeviceInfo(
219
+ firmware=".".join(str(v) for v in data[:3]),
220
+ firmware_raw=data,
221
+ serial_number=cast(str | None, self.advanced.get("device_sn")["serial_number"]),
222
+ name=cast(str | None, self.advanced.get("device_name")["name"]),
223
+ )
224
+
225
+ def status(self) -> Status:
226
+ """Read identity, pose and alarms in sequence; does not probe attached tools."""
227
+ return Status(self.device_info(), self.pose(), self.alarms())
228
+
229
+ def tool_state(self, tool: str) -> ToolState:
230
+ """Read controller outputs, not physical tool presence or grasp success."""
231
+ commands = {"laser": 61, "suction": 62, "gripper": 63}
232
+ if tool not in commands:
233
+ raise ValueError("tool must be 'laser', 'suction' or 'gripper'")
234
+ data = self.advanced.read(commands[tool])
235
+ if len(data) != 2 or any(v not in (0, 1) for v in data):
236
+ raise ProtocolError("Tool state must contain two boolean bytes")
237
+ return ToolState(bool(data[0]), bool(data[1]))
238
+
239
+ def queue_index(self) -> int:
240
+ """Read controller execution index; this alone does not prove task completion."""
241
+ data = self.advanced.read(246)
242
+ if len(data) != 8:
243
+ raise ProtocolError(f"Queue index must contain 8 bytes, got {len(data)}")
244
+ return int(struct.unpack("<Q", data)[0])
245
+
246
+ def close(self) -> None:
247
+ """Release the connection; does not stop motion owned by another program."""
248
+ self.laser.invalidate()
249
+ self._executor.close()
250
+
251
+ def __enter__(self) -> "Dobot":
252
+ return self
253
+
254
+ def __exit__(
255
+ self,
256
+ exc_type: type[BaseException] | None,
257
+ exc: BaseException | None,
258
+ traceback: TracebackType | None,
259
+ ) -> None:
260
+ self.close()
261
+
262
+
263
+ __all__ = ["Advanced", "Dobot", "ConnectionError"]