|
| 1 | +from typing import Any, ClassVar, Mapping, Dict, List, Optional, cast, Sequence |
| 2 | + |
| 3 | +from typing_extensions import Self |
| 4 | + |
| 5 | +from viam.components.base import Base |
| 6 | +from viam.components.motor import Motor |
| 7 | +from viam.module.types import Reconfigurable |
| 8 | +from viam.proto.app.robot import ComponentConfig |
| 9 | +from viam.resource.base import ResourceBase |
| 10 | +from viam.proto.common import Geometry, Vector3, ResourceName |
| 11 | +from viam.resource.types import Model, ModelFamily |
| 12 | +from viam.utils import struct_to_dict |
| 13 | + |
| 14 | + |
| 15 | +class MyBase(Base, Reconfigurable): |
| 16 | + """ |
| 17 | + MyBase implements a base that only supports set_power (basic forward/back/turn controls), is_moving (check if in motion), and stop (stop |
| 18 | + all motion). |
| 19 | +
|
| 20 | + It inherits from the built-in resource subtype Base and conforms to the ``Reconfigurable`` protocol, which signifies that this component |
| 21 | + can be reconfigured. Additionally, it specifies a constructor function ``MyBase.new`` which conforms to the |
| 22 | + ``resource.types.ResourceCreator`` type required for all models. It also specifies a validator function `MyBase.validate_config` which |
| 23 | + conforms to the ``resource.types.Validator`` type and returns implicit dependencies for the model. |
| 24 | + """ |
| 25 | + |
| 26 | + # Subclass the Viam Base component and implement the required functions |
| 27 | + MODEL: ClassVar[Model] = Model(ModelFamily("acme", "demo"), "mybase") |
| 28 | + |
| 29 | + def __init__(self, name: str): |
| 30 | + super().__init__(name) |
| 31 | + |
| 32 | + # Constructor |
| 33 | + @classmethod |
| 34 | + def new(cls, config: ComponentConfig, dependencies: Mapping[ResourceName, ResourceBase]) -> Self: |
| 35 | + base = cls(config.name) |
| 36 | + base.reconfigure(config, dependencies) |
| 37 | + return base |
| 38 | + |
| 39 | + # Validates JSON Configuration |
| 40 | + @classmethod |
| 41 | + def validate_config(cls, config: ComponentConfig) -> Sequence[str]: |
| 42 | + attributes_dict = struct_to_dict(config.attributes) |
| 43 | + left_name = attributes_dict.get("left", "") |
| 44 | + assert isinstance(left_name, str) |
| 45 | + if left_name == "": |
| 46 | + raise Exception("A left attribute is required for a MyBase component.") |
| 47 | + |
| 48 | + right_name = attributes_dict.get("right", "") |
| 49 | + assert isinstance(right_name, str) |
| 50 | + if right_name == "": |
| 51 | + raise Exception("A right attribute is required for a MyBase component.") |
| 52 | + return [left_name, right_name] |
| 53 | + |
| 54 | + # Handles attribute reconfiguration |
| 55 | + def reconfigure(self, config: ComponentConfig, dependencies: Mapping[ResourceName, ResourceBase]): |
| 56 | + attributes_dict = struct_to_dict(config.attributes) |
| 57 | + left_name = attributes_dict.get("left") |
| 58 | + right_name = attributes_dict.get("right") |
| 59 | + |
| 60 | + assert isinstance(left_name, str) and isinstance(right_name, str) |
| 61 | + |
| 62 | + left_motor = dependencies[Motor.get_resource_name(left_name)] |
| 63 | + right_motor = dependencies[Motor.get_resource_name(right_name)] |
| 64 | + |
| 65 | + self.left = cast(Motor, left_motor) |
| 66 | + self.right = cast(Motor, right_motor) |
| 67 | + |
| 68 | + # Not implemented |
| 69 | + async def move_straight( |
| 70 | + self, |
| 71 | + distance: int, |
| 72 | + velocity: float, |
| 73 | + *, |
| 74 | + extra: Optional[Dict[str, Any]] = None, |
| 75 | + timeout: Optional[float] = None, |
| 76 | + **kwargs, |
| 77 | + ): |
| 78 | + raise NotImplementedError() |
| 79 | + |
| 80 | + # Not implemented |
| 81 | + async def spin( |
| 82 | + self, |
| 83 | + angle: float, |
| 84 | + velocity: float, |
| 85 | + *, |
| 86 | + extra: Optional[Dict[str, Any]] = None, |
| 87 | + timeout: Optional[float] = None, |
| 88 | + **kwargs, |
| 89 | + ): |
| 90 | + raise NotImplementedError() |
| 91 | + |
| 92 | + # Set the linear and angular velocity of the left and right motors on the base |
| 93 | + async def set_power( |
| 94 | + self, |
| 95 | + linear: Vector3, |
| 96 | + angular: Vector3, |
| 97 | + *, |
| 98 | + extra: Optional[Dict[str, Any]] = None, |
| 99 | + timeout: Optional[float] = None, |
| 100 | + **kwargs, |
| 101 | + ): |
| 102 | + # stop the base if absolute value of linear and angular velocity is less than 0.01 |
| 103 | + if abs(linear.y) < 0.01 and abs(angular.z) < 0.01: |
| 104 | + await self.stop(extra=extra, timeout=timeout) |
| 105 | + |
| 106 | + # use linear and angular velocity to calculate percentage of max power to pass to SetPower for left & right motors |
| 107 | + sum = abs(linear.y) + abs(angular.z) |
| 108 | + |
| 109 | + await self.left.set_power(power=((linear.y - angular.z) / sum), extra=extra, timeout=timeout) |
| 110 | + await self.right.set_power(power=((linear.y - angular.z) / sum), extra=extra, timeout=timeout) |
| 111 | + |
| 112 | + # Not implemented |
| 113 | + async def set_velocity( |
| 114 | + self, |
| 115 | + linear: Vector3, |
| 116 | + angular: Vector3, |
| 117 | + *, |
| 118 | + extra: Optional[Dict[str, Any]] = None, |
| 119 | + timeout: Optional[float] = None, |
| 120 | + **kwargs, |
| 121 | + ): |
| 122 | + raise NotImplementedError() |
| 123 | + |
| 124 | + # Stop the base from moving by stopping both motors |
| 125 | + async def stop( |
| 126 | + self, |
| 127 | + *, |
| 128 | + extra: Optional[Dict[str, Any]] = None, |
| 129 | + timeout: Optional[float] = None, |
| 130 | + **kwargs, |
| 131 | + ): |
| 132 | + await self.left.stop(extra=extra, timeout=timeout) |
| 133 | + await self.right.stop(extra=extra, timeout=timeout) |
| 134 | + |
| 135 | + # Check if either motor on the base is moving with motors' is_moving |
| 136 | + async def is_moving(self) -> bool: |
| 137 | + return await self.left.is_moving() or await self.right.is_moving() |
| 138 | + |
| 139 | + # Not implemented |
| 140 | + async def get_properties(self, *, timeout: Optional[float] | None = None, **kwargs) -> Base.Properties: |
| 141 | + raise NotImplementedError() |
| 142 | + |
| 143 | + # Not implemented |
| 144 | + async def get_geometries(self) -> List[Geometry]: |
| 145 | + raise NotImplementedError() |
0 commit comments