Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 2 additions & 117 deletions docs/examples/example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -494,122 +494,7 @@
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"### Custom Modular Arm Example\n",
"The following is an example of how to implement a custom modular arm. For further instructions, read the detailed `Sensor` example above. Our custom Arm will be extremely simple. Please note that the minimum set of endpoints you need to implement for an arm are `GetKinematics`, `GetJointPositions`, and `MoveToJointPositions`.\n",
"\n",
"This arm example contains a minimal kinematics model. For a full model, take a look [here](https://github.com/viamrobotics/viam-python-sdk/blob/main/examples/complex_module/src/arm/my_arm_kinematics.json).\n",
"\n",
"Subclassing the `Arm` component and implementing the required functions:\n",
"```python\n",
"# modular-arm/src/my_modular_arm.py\n",
"import asyncio\n",
"import os\n",
"from typing import Any, ClassVar, Dict, List, Mapping, Optional, Tuple, Union\n",
"from typing_extensions import Self\n",
"\n",
"from viam.components.arm import Arm, JointPositions, KinematicsFileFormat, Pose\n",
"from viam.module.module import Module\n",
"from viam.operations import run_with_operation\n",
"from viam.proto.app.robot import ComponentConfig\n",
"from viam.proto.common import Mesh, ResourceName\n",
"from viam.proto.component.arm import MoveOptions\n",
"from viam.resource.base import ResourceBase\n",
"from viam.resource.registry import Registry, ResourceCreatorRegistration\n",
"from viam.resource.types import Model, ModelFamily\n",
"\n",
"\n",
"class MyModularArm(Arm):\n",
" # Subclass the Viam Arm component and implement the required functions\n",
" MODEL: ClassVar[Model] = Model(ModelFamily(\"viam\", \"arm\"), \"my-arm\")\n",
"\n",
" def __init__(self, name: str):\n",
" # Starting joint positions\n",
" self.joint_positions = JointPositions(values=[0, 0, 0, 0, 0, 0])\n",
"\n",
"\n",
" # Minimal working kinematics\n",
" self.kinematics = json.dumps(\n",
" {\n",
" \"name\": \"MyArm\",\n",
" \"links\": [{\"id\": \"base\", \"parent\": \"world\", \"translation\": {\"x\": 0, \"y\": 0, \"z\": 0}}],\n",
" \"joints\": [\n",
" {\"id\": \"waist\", \"type\": \"revolute\", \"parent\": \"base\", \"axis\": {\"x\": 0, \"y\": 0, \"z\": 1}, \"max\": 359, \"min\": -359}\n",
" ],\n",
" }\n",
" ).encode(\"utf-8\")\n",
" super().__init__(name)\n",
"\n",
" @classmethod\n",
" def new(cls, config: ComponentConfig, dependencies: Mapping[ResourceName, ResourceBase]) -> Self:\n",
" arm = cls(config.name)\n",
" return arm\n",
"\n",
" async def get_end_position(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Pose:\n",
" raise NotImplementedError()\n",
"\n",
" async def move_to_position(self, pose: Pose, extra: Optional[Dict[str, Any]] = None, **kwargs):\n",
" raise NotImplementedError()\n",
"\n",
" async def get_joint_positions(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> JointPositions:\n",
" return self.joint_positions\n",
"\n",
" @run_with_operation\n",
" async def move_to_joint_positions(self, positions: JointPositions, extra: Optional[Dict[str, Any]] = None, **kwargs):\n",
" operation = self.get_operation(kwargs)\n",
"\n",
" self.is_stopped = False\n",
"\n",
" # Simulate the length of time it takes for the arm to move to its new joint position\n",
" for x in range(10):\n",
" await asyncio.sleep(1)\n",
"\n",
" # Check if the operation is cancelled and, if it is, stop the arm's motion\n",
" if await operation.is_cancelled():\n",
" await self.stop()\n",
" break\n",
"\n",
" self.joint_positions = positions\n",
" self.is_stopped = True\n",
"\n",
" async def move_through_joint_positions(\n",
" self,\n",
" positions: List[JointPositions],\n",
" options: Optional[MoveOptions] = None,\n",
" extra: Optional[Dict[str, Any]] = None,\n",
" **kwargs,\n",
" ):\n",
" for position in positions:\n",
" self.joint_positions = position\n",
"\n",
" async def get_3d_models(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, Mesh]:\n",
" raise NotImplementedError()\n",
"\n",
" async def stop(self, extra: Optional[Dict[str, Any]] = None, **kwargs):\n",
" self.is_stopped = True\n",
"\n",
" async def is_moving(self) -> bool:\n",
" return not self.is_stopped\n",
"\n",
" async def get_kinematics(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Union[Tuple[KinematicsFileFormat.ValueType, bytes], Tuple[KinematicsFileFormat.ValueType, bytes, Mapping[str, Mesh]]]:\n",
" return KinematicsFileFormat.KINEMATICS_FILE_FORMAT_SVA, self.kinematics\n",
"\n",
"async def main():\n",
" \"\"\"This function creates and starts a new module, after adding all desired resource model.\n",
" Resource creators must be registered to the resource registry before the module adds the resource model.\n",
" \"\"\"\n",
" Registry.register_resource_creator(Arm.SUBTYPE, MyModularArm.MODEL, ResourceCreatorRegistration(MyModularArm.new))\n",
" module = Module.from_args()\n",
" module.add_model_from_registry(Arm.SUBTYPE, MyModularArm.MODEL)\n",
" await module.start()\n",
"\n",
"\n",
"if __name__ == \"__main__\":\n",
" asyncio.run(main())\n",
"```\n",
"\n",
"Lastly, make the module executable and configure the module on your robot."
]
"source": "### Custom Modular Arm Example\nThe following is an example of how to implement a custom modular arm. For further instructions, read the detailed `Sensor` example above. Our custom Arm will be extremely simple. Please note that the minimum set of endpoints you need to implement for an arm are `GetKinematics`, `GetJointPositions`, and `MoveToJointPositions`.\n\nThis arm example contains a minimal kinematics model. For a full model, take a look [here](https://github.com/viamrobotics/viam-python-sdk/blob/main/examples/complex_module/src/arm/my_arm_kinematics.json).\n\nSubclassing the `Arm` component and implementing the required functions:\n```python\n# modular-arm/src/my_modular_arm.py\nimport asyncio\nimport os\nfrom typing import Any, ClassVar, Dict, List, Mapping, Optional, Tuple, Union\nfrom typing_extensions import Self\n\nfrom viam.components.arm import Arm, JointPositions, KinematicsFileFormat, Pose\nfrom viam.module.module import Module\nfrom viam.operations import run_with_operation\nfrom viam.proto.app.robot import ComponentConfig\nfrom viam.proto.common import Mesh, ResourceName\nfrom viam.proto.component.arm import MoveOptions\nfrom viam.resource.base import ResourceBase\nfrom viam.resource.registry import Registry, ResourceCreatorRegistration\nfrom viam.resource.types import Model, ModelFamily\n\n\nclass MyModularArm(Arm):\n # Subclass the Viam Arm component and implement the required functions\n MODEL: ClassVar[Model] = Model(ModelFamily(\"viam\", \"arm\"), \"my-arm\")\n\n def __init__(self, name: str):\n # Starting joint positions\n self.joint_positions = JointPositions(values=[0, 0, 0, 0, 0, 0])\n\n\n # Minimal working kinematics\n self.kinematics = json.dumps(\n {\n \"name\": \"MyArm\",\n \"links\": [{\"id\": \"base\", \"parent\": \"world\", \"translation\": {\"x\": 0, \"y\": 0, \"z\": 0}}],\n \"joints\": [\n {\"id\": \"waist\", \"type\": \"revolute\", \"parent\": \"base\", \"axis\": {\"x\": 0, \"y\": 0, \"z\": 1}, \"max\": 359, \"min\": -359}\n ],\n }\n ).encode(\"utf-8\")\n super().__init__(name)\n\n @classmethod\n def new(cls, config: ComponentConfig, dependencies: Mapping[ResourceName, ResourceBase]) -> Self:\n arm = cls(config.name)\n return arm\n\n async def get_end_position(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Pose:\n raise NotImplementedError()\n\n async def move_to_position(self, pose: Pose, extra: Optional[Dict[str, Any]] = None, **kwargs):\n raise NotImplementedError()\n\n async def get_joint_positions(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> JointPositions:\n return self.joint_positions\n\n @run_with_operation\n async def move_to_joint_positions(self, positions: JointPositions, extra: Optional[Dict[str, Any]] = None, **kwargs):\n operation = self.get_operation(kwargs)\n\n self.is_stopped = False\n\n # Simulate the length of time it takes for the arm to move to its new joint position\n for x in range(10):\n await asyncio.sleep(1)\n\n # Check if the operation is cancelled and, if it is, stop the arm's motion\n if await operation.is_cancelled():\n await self.stop()\n break\n\n self.joint_positions = positions\n self.is_stopped = True\n\n async def move_through_joint_positions(\n self,\n positions: List[JointPositions],\n options: Optional[MoveOptions] = None,\n extra: Optional[Dict[str, Any]] = None,\n **kwargs,\n ):\n for position in positions:\n self.joint_positions = position\n\n async def get_3d_models(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, Mesh]:\n raise NotImplementedError()\n\n async def stop(self, extra: Optional[Dict[str, Any]] = None, **kwargs):\n self.is_stopped = True\n\n async def is_moving(self) -> bool:\n return not self.is_stopped\n\n async def get_kinematics(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Union[Tuple[KinematicsFileFormat.ValueType, bytes], Tuple[KinematicsFileFormat.ValueType, bytes, Mapping[str, Mesh]]]:\n return KinematicsFileFormat.KINEMATICS_FILE_FORMAT_SVA, self.kinematics\n\n async def set_manual_mode(self, manual_mode: bool, enabled_for: int = 0, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs):\n pass\n\n async def get_manual_mode(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> bool:\n return False\n\n async def get_properties(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> Arm.Properties:\n return Arm.Properties()\n\nasync def main():\n \"\"\"This function creates and starts a new module, after adding all desired resource model.\n Resource creators must be registered to the resource registry before the module adds the resource model.\n \"\"\"\n Registry.register_resource_creator(Arm.SUBTYPE, MyModularArm.MODEL, ResourceCreatorRegistration(MyModularArm.new))\n module = Module.from_args()\n module.add_model_from_registry(Arm.SUBTYPE, MyModularArm.MODEL)\n await module.start()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n```\n\nLastly, make the module executable and configure the module on your robot."
},
{
"attachments": {},
Expand Down Expand Up @@ -1445,4 +1330,4 @@
},
"nbformat": 4,
"nbformat_minor": 4
}
}
9 changes: 9 additions & 0 deletions docs/examples/my_cool_arm.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,15 @@ async def get_kinematics(
) -> Union[Tuple[KinematicsFileFormat.ValueType, bytes], Tuple[KinematicsFileFormat.ValueType, bytes, Mapping[str, Mesh]]]:
return KinematicsFileFormat.KINEMATICS_FILE_FORMAT_SVA, self.kinematics

async def set_manual_mode(self, manual_mode: bool, enabled_for: int = 0, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs):
pass

async def get_manual_mode(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> bool:
return False

async def get_properties(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> Arm.Properties:
return Arm.Properties()

async def close(self):
# This is a completely optional function to include. This will be called when the resource is removed from the config or the module
# is shutting down.
Expand Down
9 changes: 9 additions & 0 deletions examples/complex_module/src/arm/my_arm.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,15 @@ async def get_kinematics(self, extra: Optional[Dict[str, Any]] = None, **kwargs)
file_data = f.read()
return (KinematicsFileFormat.KINEMATICS_FILE_FORMAT_SVA, file_data)

async def set_manual_mode(self, manual_mode: bool, enabled_for: int = 0, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs):
pass

async def get_manual_mode(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> bool:
return False

async def get_properties(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> Arm.Properties:
return Arm.Properties()

async def close(self):
# This is a completely optional function to include. This will be called when the resource is removed from the config or the module
# is shutting down.
Expand Down
12 changes: 11 additions & 1 deletion examples/server/v1/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
Vector3,
Mesh,
)
from viam.proto.component.arm import JointPositions, MoveOptions
from viam.proto.component.arm import GetPropertiesResponse, JointPositions, MoveOptions
from viam.proto.component.encoder import PositionType
from viam.streams import StreamWithIterator
from viam.utils import SensorReading, ValueTypes
Expand All @@ -74,6 +74,7 @@ def __init__(self, name: str):
self.joint_positions = JointPositions(values=[0, 0, 0, 0, 0, 0])
self.is_stopped = True
self.kinematics = (KinematicsFileFormat.KINEMATICS_FILE_FORMAT_SVA, b"\x00\x01\x02", {})
self.manual_mode = False
super().__init__(name)

async def get_end_position(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Pose:
Expand Down Expand Up @@ -126,6 +127,15 @@ async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs)
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}

async def set_manual_mode(self, manual_mode: bool, enabled_for: int = 0, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.manual_mode = manual_mode

async def get_manual_mode(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> bool:
return self.manual_mode

async def get_properties(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Arm.Properties:
return GetPropertiesResponse(support_manual_mode=True, support_cartesian_commands=True)


class ExampleAudioOut(AudioOut):
def __init__(self, name: str):
Expand Down
84 changes: 83 additions & 1 deletion src/viam/components/arm/arm.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import abc
from typing import Any, Dict, Final, List, Mapping, Optional
from typing import Any, Dict, Final, List, Mapping, Optional, TypeAlias

from viam.components import KinematicsReturn
from viam.components.component_base import ComponentBase
from viam.proto.component.arm import GetPropertiesResponse
from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT

from . import JointPositions, Mesh, MoveOptions, Pose
Expand Down Expand Up @@ -31,6 +32,8 @@ class Arm(ComponentBase):
For more information, see `Arm component <https://docs.viam.com/dev/reference/apis/components/arm/>`_.
"""

Properties: "TypeAlias" = GetPropertiesResponse

API: Final = API(RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "arm") # pyright: ignore [reportIncompatibleVariableOverride]

@abc.abstractmethod
Expand Down Expand Up @@ -315,3 +318,82 @@ async def get_3d_models(
For more information, see `Arm component <https://docs.viam.com/dev/reference/apis/components/arm/#get3dmodels>`_.
"""
...

@abc.abstractmethod
async def set_manual_mode(
self,
manual_mode: bool,
enabled_for: int = 0,
*,
extra: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
**kwargs,
):
"""
Enter or exit software-enabled manual mode.

::

my_arm = Arm.from_robot(robot=machine, name="my_arm")

# Enter manual mode for 30 seconds.
await my_arm.set_manual_mode(manual_mode=True, enabled_for=30)

Args:
manual_mode (bool): ``True`` to enter manual mode, ``False`` to exit it.
enabled_for (int): How long to stay in manual mode, in seconds. ``0`` means no time limit.

For more information, see `Arm component <https://docs.viam.com/dev/reference/apis/components/arm/#setmanualmode>`_.
"""
...

@abc.abstractmethod
async def get_manual_mode(
self,
*,
extra: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
**kwargs,
) -> bool:
"""
Get whether the arm is currently in manual mode.

::

my_arm = Arm.from_robot(robot=machine, name="my_arm")

# Print if the arm is currently in manual mode.
print(await my_arm.get_manual_mode())

Returns:
bool: ``True`` if the arm is in manual mode.

For more information, see `Arm component <https://docs.viam.com/dev/reference/apis/components/arm/#getmanualmode>`_.
"""
...

@abc.abstractmethod
async def get_properties(
self,
*,
extra: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
**kwargs,
) -> Properties:
"""
Get the properties of the arm.

::

my_arm = Arm.from_robot(robot=machine, name="my_arm")

# Get the properties of the arm.
properties = await my_arm.get_properties()

Returns:
Properties: The arm's properties, including whether it supports software-enabled
manual mode and whether it supports direct cartesian commands (``move_to_position``).

For more information, see `Arm component <https://docs.viam.com/dev/reference/apis/components/arm/#getproperties>`_.
"""
...
Loading