a2a-robots 0.1.1__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.
- a2a_robots/__init__.py +32 -0
- a2a_robots/adapter.py +152 -0
- a2a_robots/backend.py +57 -0
- a2a_robots/controller.py +212 -0
- a2a_robots/fake.py +98 -0
- a2a_robots/limits.py +68 -0
- a2a_robots/planning.py +69 -0
- a2a_robots/skills.py +156 -0
- a2a_robots/testing.py +208 -0
- a2a_robots-0.1.1.dist-info/METADATA +171 -0
- a2a_robots-0.1.1.dist-info/RECORD +13 -0
- a2a_robots-0.1.1.dist-info/WHEEL +4 -0
- a2a_robots-0.1.1.dist-info/licenses/LICENSE +201 -0
a2a_robots/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Expose robots as A2A agents with task-level skills and adapter-enforced safety limits."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.1"
|
|
4
|
+
|
|
5
|
+
from .adapter import SAFETY_LIMITS_EXTENSION, RobotAdapter, serve_robot
|
|
6
|
+
from .backend import HandState, MotionOutcome, RobotBackend
|
|
7
|
+
from .controller import RobotController, SkillCancelled, StopError
|
|
8
|
+
from .fake import FakeBackend
|
|
9
|
+
from .limits import SafetyLimits, Workspace
|
|
10
|
+
from .skills import FailureCode, Pose, RequestError, Skill, SkillRequest, SkillResult
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"SAFETY_LIMITS_EXTENSION",
|
|
14
|
+
"FailureCode",
|
|
15
|
+
"FakeBackend",
|
|
16
|
+
"HandState",
|
|
17
|
+
"MotionOutcome",
|
|
18
|
+
"Pose",
|
|
19
|
+
"RequestError",
|
|
20
|
+
"RobotAdapter",
|
|
21
|
+
"RobotBackend",
|
|
22
|
+
"RobotController",
|
|
23
|
+
"SafetyLimits",
|
|
24
|
+
"Skill",
|
|
25
|
+
"SkillRequest",
|
|
26
|
+
"SkillCancelled",
|
|
27
|
+
"SkillResult",
|
|
28
|
+
"StopError",
|
|
29
|
+
"Workspace",
|
|
30
|
+
"__version__",
|
|
31
|
+
"serve_robot",
|
|
32
|
+
]
|
a2a_robots/adapter.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""A2A adapter that exposes one robot through a2a-adapter."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from a2a.types import Part
|
|
9
|
+
from a2a_adapter import AdapterMetadata, BaseA2AAdapter, CancelledByAdapterError, serve_agent
|
|
10
|
+
from google.protobuf import json_format, struct_pb2
|
|
11
|
+
|
|
12
|
+
from .backend import RobotBackend
|
|
13
|
+
from .controller import RobotController, SkillCancelled
|
|
14
|
+
from .limits import SafetyLimits
|
|
15
|
+
from .skills import RequestError, parse_request
|
|
16
|
+
|
|
17
|
+
JSON = "application/json"
|
|
18
|
+
_EXAMPLE_POSE = {
|
|
19
|
+
"frame": "world",
|
|
20
|
+
"units": "m",
|
|
21
|
+
"position": [0.30, -0.20, 0.15],
|
|
22
|
+
"orientation": {"quaternion": [1, 0, 0, 0]},
|
|
23
|
+
}
|
|
24
|
+
_EXAMPLE_RESULT = (
|
|
25
|
+
'{"skill": "%s", "success": true, "failure_code": null, "detail": null, '
|
|
26
|
+
'"final_pose": {"right": {...}}, "contact": {"right": {...}}, "held": {"right": false}}'
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
SAFETY_LIMITS_EXTENSION = "https://github.com/hybroai/a2a-robots/extensions/safety-limits/v1"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _skill(skill_id: str, description: str, args: dict[str, Any]) -> dict[str, Any]:
|
|
34
|
+
request = json.dumps({"skill": skill_id, "args": args})
|
|
35
|
+
return {
|
|
36
|
+
"id": skill_id,
|
|
37
|
+
"name": skill_id,
|
|
38
|
+
"description": f"{description} Request: {request} Response: {_EXAMPLE_RESULT % skill_id}",
|
|
39
|
+
"tags": ["robot"],
|
|
40
|
+
"examples": [request],
|
|
41
|
+
"input_modes": [JSON, "text/plain"],
|
|
42
|
+
"output_modes": [JSON, "text/plain"],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
SKILLS = [
|
|
47
|
+
_skill("observe", "Read the pose, contact and held state of every hand. Always allowed.", {}),
|
|
48
|
+
_skill(
|
|
49
|
+
"move_to",
|
|
50
|
+
"Move a hand to a pose. frame, units and orientation are required; "
|
|
51
|
+
"a move larger than the step limit, or a target outside the workspace box, "
|
|
52
|
+
"is refused before anything moves. The limits are in the agent card's "
|
|
53
|
+
"safety-limits extension.",
|
|
54
|
+
{"hand": "right", "pose": _EXAMPLE_POSE},
|
|
55
|
+
),
|
|
56
|
+
_skill("open", "Open a hand.", {"hand": "right"}),
|
|
57
|
+
_skill(
|
|
58
|
+
"close", "Close a hand; held reports whether it is holding something.", {"hand": "right"}
|
|
59
|
+
),
|
|
60
|
+
_skill("stop", "Stop all motion now and freeze every hand. Always allowed.", {}),
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _limits_extension(limits: SafetyLimits) -> dict[str, Any]:
|
|
65
|
+
"""A data-only A2A extension that states the limits the adapter enforces."""
|
|
66
|
+
workspace = limits.workspace
|
|
67
|
+
return {
|
|
68
|
+
"uri": SAFETY_LIMITS_EXTENSION,
|
|
69
|
+
"description": "Safety limits this robot enforces before anything moves.",
|
|
70
|
+
"required": False,
|
|
71
|
+
"params": {
|
|
72
|
+
"frame": workspace.frame,
|
|
73
|
+
"workspace": {"min_xyz": list(workspace.min_xyz), "max_xyz": list(workspace.max_xyz)},
|
|
74
|
+
"max_step_m": limits.max_step_m,
|
|
75
|
+
"max_step_rad": limits.max_step_rad,
|
|
76
|
+
"skill_timeout_s": limits.skill_timeout_s,
|
|
77
|
+
"stop_timeout_s": limits.stop_timeout_s,
|
|
78
|
+
},
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class RobotAdapter(BaseA2AAdapter):
|
|
83
|
+
"""Accepts ``{"skill": ..., "args": {...}}`` as a JSON text part or a data part.
|
|
84
|
+
|
|
85
|
+
Every reply carries the same result twice: as JSON text, for clients that
|
|
86
|
+
only read text, and as an ``application/json`` data part.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
def __init__(
|
|
90
|
+
self,
|
|
91
|
+
backend: RobotBackend,
|
|
92
|
+
limits: SafetyLimits,
|
|
93
|
+
*,
|
|
94
|
+
name: str = "Robot",
|
|
95
|
+
description: str = "Task-level robot skills over A2A.",
|
|
96
|
+
) -> None:
|
|
97
|
+
self.controller = RobotController(backend, limits)
|
|
98
|
+
self._name = name
|
|
99
|
+
self._description = description
|
|
100
|
+
|
|
101
|
+
async def invoke(self, user_input: str, context_id: str | None = None, **kwargs: Any):
|
|
102
|
+
context = kwargs.get("context")
|
|
103
|
+
payload = _request_payload(user_input, context)
|
|
104
|
+
request = parse_request(payload, self.controller.backend.hands)
|
|
105
|
+
try:
|
|
106
|
+
result = await self.controller.run(request, getattr(context, "task_id", None))
|
|
107
|
+
except SkillCancelled as e:
|
|
108
|
+
# cancel() already stopped the robot; the task is reported canceled.
|
|
109
|
+
raise CancelledByAdapterError(str(e)) from None
|
|
110
|
+
data = struct_pb2.Value()
|
|
111
|
+
json_format.ParseDict(result.to_dict(), data)
|
|
112
|
+
return [Part(text=result.to_json()), Part(data=data, media_type=JSON)]
|
|
113
|
+
|
|
114
|
+
async def cancel(self, context_id: str | None = None, **kwargs: Any) -> None:
|
|
115
|
+
"""Return once the robot has stopped and the hands are frozen. Raises
|
|
116
|
+
``StopError`` if it did not stop in time, so the task fails instead of
|
|
117
|
+
being reported canceled."""
|
|
118
|
+
context = kwargs.get("context")
|
|
119
|
+
await self.controller.cancel(getattr(context, "task_id", None))
|
|
120
|
+
|
|
121
|
+
async def close(self) -> None:
|
|
122
|
+
await self.controller.aclose()
|
|
123
|
+
|
|
124
|
+
def get_metadata(self) -> AdapterMetadata:
|
|
125
|
+
return AdapterMetadata(
|
|
126
|
+
name=self._name,
|
|
127
|
+
description=self._description,
|
|
128
|
+
skills=SKILLS,
|
|
129
|
+
extensions=[_limits_extension(self.controller.limits)],
|
|
130
|
+
input_modes=[JSON, "text/plain"],
|
|
131
|
+
output_modes=[JSON, "text/plain"],
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _request_payload(user_input: str, context: Any) -> Any:
|
|
136
|
+
message = getattr(context, "message", None)
|
|
137
|
+
data_parts = [p for p in getattr(message, "parts", []) if p.WhichOneof("content") == "data"]
|
|
138
|
+
if len(data_parts) > 1:
|
|
139
|
+
raise RequestError("send one skill request per message")
|
|
140
|
+
if data_parts:
|
|
141
|
+
return json_format.MessageToDict(data_parts[0].data)
|
|
142
|
+
try:
|
|
143
|
+
return json.loads(user_input)
|
|
144
|
+
except json.JSONDecodeError:
|
|
145
|
+
raise RequestError('send the request as JSON: {"skill": ..., "args": {...}}') from None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def serve_robot(
|
|
149
|
+
adapter: RobotAdapter, *, host: str = "127.0.0.1", port: int = 9100, **kwargs: Any
|
|
150
|
+
) -> None:
|
|
151
|
+
"""Serve on loopback by default: anyone who can reach the server can move the robot."""
|
|
152
|
+
serve_agent(adapter, host=host, port=port, **kwargs)
|
a2a_robots/backend.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""The interface a robot implements to be driven by ``RobotAdapter``.
|
|
2
|
+
|
|
3
|
+
Backend methods are synchronous and run in a worker thread, because simulator
|
|
4
|
+
steps and vendor SDK calls block. Cancelling the asyncio task cannot interrupt
|
|
5
|
+
them, so every motion method must poll ``stop`` at each control step and return
|
|
6
|
+
promptly once it is set, leaving the hand where it is.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import threading
|
|
12
|
+
from abc import ABC, abstractmethod
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
|
|
15
|
+
from .skills import FailureCode, Pose
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(slots=True)
|
|
19
|
+
class HandState:
|
|
20
|
+
pose: Pose
|
|
21
|
+
contact: dict[str, float] = field(default_factory=dict)
|
|
22
|
+
held: bool = False
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class MotionOutcome:
|
|
27
|
+
"""What a motion call did. ``failure_code`` is None on success."""
|
|
28
|
+
|
|
29
|
+
failure_code: FailureCode | None = None
|
|
30
|
+
detail: str | None = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class RobotBackend(ABC):
|
|
34
|
+
@property
|
|
35
|
+
@abstractmethod
|
|
36
|
+
def hands(self) -> frozenset[str]: ...
|
|
37
|
+
|
|
38
|
+
@abstractmethod
|
|
39
|
+
def observe(self) -> dict[str, HandState]:
|
|
40
|
+
"""Current state of every hand. Must be safe to call during motion."""
|
|
41
|
+
|
|
42
|
+
@abstractmethod
|
|
43
|
+
def move_to(self, hand: str, target: Pose, stop: threading.Event) -> MotionOutcome: ...
|
|
44
|
+
|
|
45
|
+
@abstractmethod
|
|
46
|
+
def open(self, hand: str, stop: threading.Event) -> MotionOutcome: ...
|
|
47
|
+
|
|
48
|
+
@abstractmethod
|
|
49
|
+
def close(self, hand: str, stop: threading.Event) -> MotionOutcome: ...
|
|
50
|
+
|
|
51
|
+
@abstractmethod
|
|
52
|
+
def hold(self) -> None:
|
|
53
|
+
"""Freeze every hand at its current pose."""
|
|
54
|
+
|
|
55
|
+
@abstractmethod
|
|
56
|
+
def shutdown(self) -> None:
|
|
57
|
+
"""Release the robot or simulator. Called once, after motion has stopped."""
|
a2a_robots/controller.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Runs skills on one robot: busy flag, preemption, timeouts, results.
|
|
2
|
+
|
|
3
|
+
One controller owns one backend, so every chat served by the process shares
|
|
4
|
+
the same busy flag and two chats cannot move the same robot at once.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import contextlib
|
|
11
|
+
import functools
|
|
12
|
+
import logging
|
|
13
|
+
import threading
|
|
14
|
+
|
|
15
|
+
from a2a_adapter import UserFacingError
|
|
16
|
+
|
|
17
|
+
from .backend import MotionOutcome, RobotBackend
|
|
18
|
+
from .limits import SafetyLimits
|
|
19
|
+
from .skills import FailureCode, Pose, RequestError, Skill, SkillRequest, SkillResult
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class StopError(UserFacingError):
|
|
25
|
+
"""The backend did not stop in time, so the robot may still be moving."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SkillCancelled(Exception):
|
|
29
|
+
"""The motion was stopped by ``cancel`` for its own task."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class RobotController:
|
|
33
|
+
def __init__(self, backend: RobotBackend, limits: SafetyLimits) -> None:
|
|
34
|
+
self.backend = backend
|
|
35
|
+
self.limits = limits
|
|
36
|
+
self._stop = threading.Event()
|
|
37
|
+
self._busy_task: str | None = None
|
|
38
|
+
self._stopping = 0
|
|
39
|
+
self._worker: asyncio.Future[MotionOutcome] | None = None
|
|
40
|
+
self._cancelled: set[str] = set()
|
|
41
|
+
# Target of each hand's last successful move. A backend stops within its
|
|
42
|
+
# settle tolerance, so the next step is measured from here instead of
|
|
43
|
+
# the observed pose. Cleared by anything that may leave the hand elsewhere.
|
|
44
|
+
self._commanded: dict[str, Pose] = {}
|
|
45
|
+
|
|
46
|
+
async def run(self, request: SkillRequest, task_id: str | None) -> SkillResult:
|
|
47
|
+
if request.skill is Skill.OBSERVE:
|
|
48
|
+
return await self._result(request.skill)
|
|
49
|
+
if request.skill is Skill.STOP:
|
|
50
|
+
await self.stop()
|
|
51
|
+
return await self._result(request.skill)
|
|
52
|
+
return await self._run_motion(request, task_id)
|
|
53
|
+
|
|
54
|
+
async def stop(self) -> None:
|
|
55
|
+
"""Stop any motion now and freeze every hand where it is.
|
|
56
|
+
|
|
57
|
+
No motion can start until the hands are frozen, including in the gap
|
|
58
|
+
after a stopped motion releases the busy flag and before ``hold`` ends.
|
|
59
|
+
Raises ``StopError`` if the motion does not stop within
|
|
60
|
+
``stop_timeout_s``; the hands are still told to hold.
|
|
61
|
+
"""
|
|
62
|
+
self._stopping += 1
|
|
63
|
+
try:
|
|
64
|
+
self._stop.set()
|
|
65
|
+
stopped = await self._wait_for_worker()
|
|
66
|
+
await asyncio.to_thread(self.backend.hold)
|
|
67
|
+
self._commanded.clear()
|
|
68
|
+
finally:
|
|
69
|
+
self._stopping -= 1
|
|
70
|
+
if not stopped:
|
|
71
|
+
raise StopError(
|
|
72
|
+
f"the robot did not stop within {self.limits.stop_timeout_s} s; "
|
|
73
|
+
"it may still be moving"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
async def cancel(self, task_id: str | None) -> None:
|
|
77
|
+
"""Stop the motion started by ``task_id``, if it is the one running, and
|
|
78
|
+
return once the hands are frozen. That run then raises ``SkillCancelled``.
|
|
79
|
+
Raises ``StopError`` if the robot did not stop in time."""
|
|
80
|
+
# A run without a task id is stored as "", so None matches it here.
|
|
81
|
+
key = task_id or ""
|
|
82
|
+
if key != self._busy_task:
|
|
83
|
+
return
|
|
84
|
+
self._cancelled.add(key) # before the await, so the run sees it
|
|
85
|
+
await self.stop()
|
|
86
|
+
|
|
87
|
+
async def aclose(self) -> None:
|
|
88
|
+
try:
|
|
89
|
+
await self.stop()
|
|
90
|
+
finally:
|
|
91
|
+
await asyncio.to_thread(self.backend.shutdown)
|
|
92
|
+
|
|
93
|
+
async def _run_motion(self, request: SkillRequest, task_id: str | None) -> SkillResult:
|
|
94
|
+
if request.pose is not None and request.pose.frame != self.limits.workspace.frame:
|
|
95
|
+
raise RequestError(f'pose.frame must be "{self.limits.workspace.frame}"')
|
|
96
|
+
# No await between this check and claiming the flag, so it is atomic on the loop.
|
|
97
|
+
if self._stopping:
|
|
98
|
+
return await self._result(request.skill, FailureCode.BUSY, "the robot is stopping")
|
|
99
|
+
if self._busy_task is not None:
|
|
100
|
+
return await self._result(
|
|
101
|
+
request.skill, FailureCode.BUSY, "another skill is running on this robot"
|
|
102
|
+
)
|
|
103
|
+
if self._worker is not None and not self._worker.done():
|
|
104
|
+
return await self._result(
|
|
105
|
+
request.skill, FailureCode.BUSY, "the last motion has not stopped"
|
|
106
|
+
)
|
|
107
|
+
key = self._busy_task = task_id or ""
|
|
108
|
+
self._stop.clear()
|
|
109
|
+
try:
|
|
110
|
+
if request.skill is Skill.MOVE_TO:
|
|
111
|
+
assert request.hand is not None and request.pose is not None
|
|
112
|
+
states = await asyncio.to_thread(self.backend.observe)
|
|
113
|
+
current = self._commanded.get(request.hand, states[request.hand].pose)
|
|
114
|
+
refusal = self.limits.check_move(current, request.pose)
|
|
115
|
+
if refusal is not None:
|
|
116
|
+
return await self._result(request.skill, *refusal, limits=True)
|
|
117
|
+
call = functools.partial(
|
|
118
|
+
self.backend.move_to, request.hand, request.pose, self._stop
|
|
119
|
+
)
|
|
120
|
+
elif request.skill is Skill.OPEN:
|
|
121
|
+
call = functools.partial(self.backend.open, request.hand, self._stop)
|
|
122
|
+
else:
|
|
123
|
+
call = functools.partial(self.backend.close, request.hand, self._stop)
|
|
124
|
+
self._commanded.pop(request.hand, None)
|
|
125
|
+
try:
|
|
126
|
+
outcome = await self._run_worker(call)
|
|
127
|
+
except StopError:
|
|
128
|
+
if key not in self._cancelled:
|
|
129
|
+
raise
|
|
130
|
+
# A timeout during a cancel; cancel() reports the failed stop.
|
|
131
|
+
if key in self._cancelled:
|
|
132
|
+
await self._motion_ended()
|
|
133
|
+
raise SkillCancelled(f"{request.skill} was cancelled")
|
|
134
|
+
if (
|
|
135
|
+
request.skill is Skill.MOVE_TO
|
|
136
|
+
and outcome.failure_code is None
|
|
137
|
+
and not self._stop.is_set()
|
|
138
|
+
):
|
|
139
|
+
self._commanded[request.hand] = request.pose
|
|
140
|
+
return await self._result(request.skill, outcome.failure_code, outcome.detail)
|
|
141
|
+
finally:
|
|
142
|
+
self._busy_task = None
|
|
143
|
+
self._cancelled.discard(key)
|
|
144
|
+
|
|
145
|
+
async def _run_worker(self, call: functools.partial[MotionOutcome]) -> MotionOutcome:
|
|
146
|
+
self._worker = asyncio.ensure_future(asyncio.to_thread(call))
|
|
147
|
+
try:
|
|
148
|
+
return await asyncio.wait_for(asyncio.shield(self._worker), self.limits.skill_timeout_s)
|
|
149
|
+
except TimeoutError:
|
|
150
|
+
await self.stop()
|
|
151
|
+
return MotionOutcome(
|
|
152
|
+
FailureCode.TIMEOUT, f"skill exceeded {self.limits.skill_timeout_s} s"
|
|
153
|
+
)
|
|
154
|
+
except asyncio.CancelledError:
|
|
155
|
+
# tasks/cancel cancels this coroutine, not the thread: stop the hand too.
|
|
156
|
+
# A stop that times out is reported by cancel(), not here.
|
|
157
|
+
with contextlib.suppress(StopError):
|
|
158
|
+
await asyncio.shield(self.stop())
|
|
159
|
+
raise
|
|
160
|
+
except Exception:
|
|
161
|
+
# The backend failed mid-motion: freeze the hands before reporting it.
|
|
162
|
+
try:
|
|
163
|
+
await self.stop()
|
|
164
|
+
except Exception:
|
|
165
|
+
logger.exception("Could not freeze the robot after a backend error")
|
|
166
|
+
raise
|
|
167
|
+
|
|
168
|
+
async def _motion_ended(self) -> None:
|
|
169
|
+
"""Wait, without a bound, for the motion thread to end.
|
|
170
|
+
|
|
171
|
+
When ``cancel`` fails, a2a-adapter reports the task canceled if the run
|
|
172
|
+
has already ended, so a cancelled run must not end before the robot
|
|
173
|
+
stops. The executor waits a bounded time and then fails the task, and
|
|
174
|
+
cancelling this wait ends the run.
|
|
175
|
+
"""
|
|
176
|
+
worker = self._worker
|
|
177
|
+
if worker is not None:
|
|
178
|
+
with contextlib.suppress(Exception):
|
|
179
|
+
await asyncio.shield(worker)
|
|
180
|
+
|
|
181
|
+
async def _wait_for_worker(self) -> bool:
|
|
182
|
+
"""Wait for the motion thread to end; False if it is still running."""
|
|
183
|
+
worker = self._worker
|
|
184
|
+
if worker is None or worker.done():
|
|
185
|
+
return True
|
|
186
|
+
try:
|
|
187
|
+
await asyncio.wait_for(asyncio.shield(worker), self.limits.stop_timeout_s)
|
|
188
|
+
except TimeoutError:
|
|
189
|
+
return False
|
|
190
|
+
except Exception:
|
|
191
|
+
pass # the motion's own error is reported by its run
|
|
192
|
+
return True
|
|
193
|
+
|
|
194
|
+
async def _result(
|
|
195
|
+
self,
|
|
196
|
+
skill: Skill,
|
|
197
|
+
failure_code: FailureCode | None = None,
|
|
198
|
+
detail: str | None = None,
|
|
199
|
+
*,
|
|
200
|
+
limits: bool = False,
|
|
201
|
+
) -> SkillResult:
|
|
202
|
+
states = await asyncio.to_thread(self.backend.observe)
|
|
203
|
+
return SkillResult(
|
|
204
|
+
skill=skill,
|
|
205
|
+
success=failure_code is None,
|
|
206
|
+
failure_code=failure_code,
|
|
207
|
+
detail=detail,
|
|
208
|
+
final_pose={hand: s.pose.to_dict() for hand, s in states.items()},
|
|
209
|
+
contact={hand: dict(s.contact) for hand, s in states.items()},
|
|
210
|
+
held={hand: s.held for hand, s in states.items()},
|
|
211
|
+
limits=self.limits.as_dict() if limits else None,
|
|
212
|
+
)
|
a2a_robots/fake.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""In-memory robot for tests and examples. Moves in timed steps so stop,
|
|
2
|
+
cancel and timeouts can be exercised without hardware."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import threading
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
|
|
9
|
+
from .backend import HandState, MotionOutcome, RobotBackend
|
|
10
|
+
from .skills import FailureCode, Pose
|
|
11
|
+
|
|
12
|
+
_IDENTITY = (1.0, 0.0, 0.0, 0.0)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class FakeBackend(RobotBackend):
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
*,
|
|
19
|
+
hands: Iterable[str] = ("left", "right"),
|
|
20
|
+
frame: str = "world",
|
|
21
|
+
steps: int = 10,
|
|
22
|
+
step_time_s: float = 0.01,
|
|
23
|
+
reachable_objects: Iterable[str] = (),
|
|
24
|
+
slipping: Iterable[str] = (),
|
|
25
|
+
) -> None:
|
|
26
|
+
"""``reachable_objects`` names hands with an object to grasp;
|
|
27
|
+
``slipping`` names hands whose grasp slips."""
|
|
28
|
+
names = tuple(hands)
|
|
29
|
+
self._hands = frozenset(names)
|
|
30
|
+
self._steps = steps
|
|
31
|
+
self._step_time_s = step_time_s
|
|
32
|
+
self._reachable = frozenset(reachable_objects)
|
|
33
|
+
self._slipping = frozenset(slipping)
|
|
34
|
+
self._lock = threading.Lock()
|
|
35
|
+
self._state = {
|
|
36
|
+
hand: HandState(Pose(frame, (0.3, 0.2 * (i - 0.5), 0.1), _IDENTITY))
|
|
37
|
+
for i, hand in enumerate(names)
|
|
38
|
+
}
|
|
39
|
+
self.hold_calls = 0
|
|
40
|
+
self.shut_down = False
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def hands(self) -> frozenset[str]:
|
|
44
|
+
return self._hands
|
|
45
|
+
|
|
46
|
+
def observe(self) -> dict[str, HandState]:
|
|
47
|
+
with self._lock:
|
|
48
|
+
return {h: HandState(s.pose, dict(s.contact), s.held) for h, s in self._state.items()}
|
|
49
|
+
|
|
50
|
+
def move_to(self, hand: str, target: Pose, stop: threading.Event) -> MotionOutcome:
|
|
51
|
+
start = self._state[hand].pose
|
|
52
|
+
for i in range(1, self._steps + 1):
|
|
53
|
+
if not self._step(stop):
|
|
54
|
+
return MotionOutcome(FailureCode.STOPPED, "stopped before reaching the target")
|
|
55
|
+
t = i / self._steps
|
|
56
|
+
position = tuple(
|
|
57
|
+
a + (b - a) * t for a, b in zip(start.position, target.position, strict=True)
|
|
58
|
+
)
|
|
59
|
+
orientation = start.orientation if t < 1 else target.orientation
|
|
60
|
+
with self._lock:
|
|
61
|
+
self._state[hand].pose = Pose(target.frame, position, orientation)
|
|
62
|
+
return MotionOutcome()
|
|
63
|
+
|
|
64
|
+
def open(self, hand: str, stop: threading.Event) -> MotionOutcome:
|
|
65
|
+
for _ in range(self._steps):
|
|
66
|
+
if not self._step(stop):
|
|
67
|
+
return MotionOutcome(FailureCode.STOPPED, "stopped while opening")
|
|
68
|
+
with self._lock:
|
|
69
|
+
self._state[hand].held = False
|
|
70
|
+
self._state[hand].contact = {}
|
|
71
|
+
return MotionOutcome()
|
|
72
|
+
|
|
73
|
+
def close(self, hand: str, stop: threading.Event) -> MotionOutcome:
|
|
74
|
+
for _ in range(self._steps):
|
|
75
|
+
if not self._step(stop):
|
|
76
|
+
return MotionOutcome(FailureCode.STOPPED, "stopped while closing")
|
|
77
|
+
with self._lock:
|
|
78
|
+
state = self._state[hand]
|
|
79
|
+
if hand in self._reachable and hand not in self._slipping:
|
|
80
|
+
state.held = True
|
|
81
|
+
state.contact = {"thumb": 1.0, "index": 1.0}
|
|
82
|
+
return MotionOutcome()
|
|
83
|
+
state.held = False
|
|
84
|
+
state.contact = {}
|
|
85
|
+
if hand in self._slipping:
|
|
86
|
+
return MotionOutcome(FailureCode.SLIPPED, "object slipped during the grasp")
|
|
87
|
+
return MotionOutcome()
|
|
88
|
+
|
|
89
|
+
def hold(self) -> None:
|
|
90
|
+
with self._lock:
|
|
91
|
+
self.hold_calls += 1
|
|
92
|
+
|
|
93
|
+
def shutdown(self) -> None:
|
|
94
|
+
self.shut_down = True
|
|
95
|
+
|
|
96
|
+
def _step(self, stop: threading.Event) -> bool:
|
|
97
|
+
"""Wait one control step; False when stop was requested."""
|
|
98
|
+
return not stop.wait(self._step_time_s)
|
a2a_robots/limits.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Safety limits checked before anything moves.
|
|
2
|
+
|
|
3
|
+
Only the target pose is checked, not the path to it. That is acceptable in
|
|
4
|
+
simulation; real hardware also needs the robot's own path and collision checks.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from .skills import FailureCode, Pose
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class Workspace:
|
|
17
|
+
"""Axis-aligned box, in metres, in ``frame``."""
|
|
18
|
+
|
|
19
|
+
frame: str
|
|
20
|
+
min_xyz: tuple[float, float, float]
|
|
21
|
+
max_xyz: tuple[float, float, float]
|
|
22
|
+
|
|
23
|
+
def contains(self, position: tuple[float, float, float]) -> bool:
|
|
24
|
+
return all(
|
|
25
|
+
lo <= v <= hi for v, lo, hi in zip(position, self.min_xyz, self.max_xyz, strict=True)
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True, slots=True)
|
|
30
|
+
class SafetyLimits:
|
|
31
|
+
workspace: Workspace
|
|
32
|
+
max_step_m: float = 0.01
|
|
33
|
+
max_step_rad: float = 0.05
|
|
34
|
+
skill_timeout_s: float = 10.0
|
|
35
|
+
# How long a stop may take before the robot is reported as possibly still moving.
|
|
36
|
+
stop_timeout_s: float = 2.0
|
|
37
|
+
|
|
38
|
+
def as_dict(self) -> dict[str, float]:
|
|
39
|
+
return {"max_step_m": self.max_step_m, "max_step_rad": self.max_step_rad}
|
|
40
|
+
|
|
41
|
+
def check_move(self, current: Pose, target: Pose) -> tuple[FailureCode, str] | None:
|
|
42
|
+
"""Return why ``target`` is refused, or None when it may run unchanged.
|
|
43
|
+
|
|
44
|
+
Both poses must already be in ``workspace.frame``.
|
|
45
|
+
"""
|
|
46
|
+
if not self.workspace.contains(target.position):
|
|
47
|
+
return FailureCode.OUT_OF_WORKSPACE, "target position is outside the workspace box"
|
|
48
|
+
distance = math.dist(current.position, target.position)
|
|
49
|
+
if distance > self.max_step_m:
|
|
50
|
+
return (
|
|
51
|
+
FailureCode.STEP_TOO_LARGE,
|
|
52
|
+
f"move of {distance:.4f} m exceeds max_step_m {self.max_step_m}",
|
|
53
|
+
)
|
|
54
|
+
angle = rotation_angle(current.orientation, target.orientation)
|
|
55
|
+
if angle > self.max_step_rad:
|
|
56
|
+
return (
|
|
57
|
+
FailureCode.STEP_TOO_LARGE,
|
|
58
|
+
f"rotation of {angle:.4f} rad exceeds max_step_rad {self.max_step_rad}",
|
|
59
|
+
)
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def rotation_angle(
|
|
64
|
+
a: tuple[float, float, float, float], b: tuple[float, float, float, float]
|
|
65
|
+
) -> float:
|
|
66
|
+
"""Smallest angle in radians between two unit quaternions."""
|
|
67
|
+
dot = abs(sum(x * y for x, y in zip(a, b, strict=True)))
|
|
68
|
+
return 2.0 * math.acos(min(1.0, dot))
|
a2a_robots/planning.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""The planning layer between a skill and joint-level control.
|
|
2
|
+
|
|
3
|
+
A planner turns a pose target into a joint trajectory: one position target per
|
|
4
|
+
control step for the joints that carry the hand (a floating base in simulation,
|
|
5
|
+
an arm on a real robot). The backend streams those targets to the robot and
|
|
6
|
+
checks the stop flag between them. Collision checking belongs to the planner,
|
|
7
|
+
because only it knows the scene.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from abc import ABC, abstractmethod
|
|
14
|
+
from collections.abc import Mapping, Sequence
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
|
|
17
|
+
from .skills import FailureCode, Pose
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class JointTrajectory:
|
|
22
|
+
"""Position targets for ``joints``, one per control step of ``dt`` seconds.
|
|
23
|
+
|
|
24
|
+
The last point is the goal.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
joints: tuple[str, ...]
|
|
28
|
+
points: tuple[tuple[float, ...], ...]
|
|
29
|
+
dt: float
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class PlanError(Exception):
|
|
33
|
+
"""No safe trajectory exists. Becomes a completed skill with ``success: false``."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, failure_code: FailureCode, detail: str) -> None:
|
|
36
|
+
super().__init__(detail)
|
|
37
|
+
self.failure_code = failure_code
|
|
38
|
+
self.detail = detail
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Planner(ABC):
|
|
42
|
+
@abstractmethod
|
|
43
|
+
def plan(
|
|
44
|
+
self, hand: str, start: Mapping[str, float], target: Pose, dt: float
|
|
45
|
+
) -> JointTrajectory:
|
|
46
|
+
"""Plan from the joint positions ``start`` to a configuration that puts
|
|
47
|
+
``hand`` at ``target``. Raise ``PlanError`` when there is none."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def interpolate(
|
|
51
|
+
start: Sequence[float], goal: Sequence[float], max_speeds: Sequence[float], dt: float
|
|
52
|
+
) -> list[tuple[float, ...]]:
|
|
53
|
+
"""Points from ``start`` (excluded) to ``goal`` (included), one per ``dt``.
|
|
54
|
+
|
|
55
|
+
Uses a smooth (minimum-jerk) time scaling that starts and ends at rest; the
|
|
56
|
+
duration is chosen so no joint exceeds its entry in ``max_speeds``.
|
|
57
|
+
"""
|
|
58
|
+
# Minimum-jerk peak speed is 1.875 times the average speed.
|
|
59
|
+
duration = max(
|
|
60
|
+
(1.875 * abs(b - a) / v for a, b, v in zip(start, goal, max_speeds, strict=True)),
|
|
61
|
+
default=0.0,
|
|
62
|
+
)
|
|
63
|
+
steps = max(1, math.ceil(duration / dt - 1e-9))
|
|
64
|
+
points = []
|
|
65
|
+
for i in range(1, steps + 1):
|
|
66
|
+
s = i / steps
|
|
67
|
+
blend = s**3 * (10 - 15 * s + 6 * s**2)
|
|
68
|
+
points.append(tuple(a + (b - a) * blend for a, b in zip(start, goal, strict=True)))
|
|
69
|
+
return points
|