|
| 1 | +from typing import Any, Mapping, Optional |
| 2 | + |
| 3 | +from grpclib import GRPCError, Status |
| 4 | +from grpclib.client import Channel |
| 5 | + |
| 6 | +from viam.proto.common import DoCommandRequest, DoCommandResponse |
| 7 | +from viam.proto.service.generic import GenericServiceStub |
| 8 | +from viam.resource.rpc_client_base import ReconfigurableResourceRPCClientBase |
| 9 | +from viam.utils import ValueTypes, dict_to_struct, struct_to_dict |
| 10 | + |
| 11 | +from .generic import Generic |
| 12 | + |
| 13 | + |
| 14 | +class GenericClient(Generic, ReconfigurableResourceRPCClientBase): |
| 15 | + """ |
| 16 | + gRPC client for the Generic service. |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self, name: str, channel: Channel): |
| 20 | + self.client = GenericServiceStub(channel) |
| 21 | + super().__init__(name) |
| 22 | + |
| 23 | + async def do_command( |
| 24 | + self, |
| 25 | + command: Mapping[str, Any], |
| 26 | + *, |
| 27 | + timeout: Optional[float] = None, |
| 28 | + **__, |
| 29 | + ) -> Mapping[str, Any]: |
| 30 | + request = DoCommandRequest(name=self.name, command=dict_to_struct(command)) |
| 31 | + try: |
| 32 | + response: DoCommandResponse = await self.client.DoCommand(request, timeout=timeout) |
| 33 | + except GRPCError as e: |
| 34 | + if e.status == Status.UNIMPLEMENTED: |
| 35 | + raise NotImplementedError() |
| 36 | + raise e |
| 37 | + |
| 38 | + return struct_to_dict(response.result) |
| 39 | + |
| 40 | + |
| 41 | +async def do_command( |
| 42 | + channel: Channel, name: str, command: Mapping[str, ValueTypes], *, timeout: Optional[float] = None |
| 43 | +) -> Mapping[str, ValueTypes]: |
| 44 | + """Convenience method to allow service clients to execute ``do_command`` functions |
| 45 | +
|
| 46 | + Args: |
| 47 | + channel (Channel): A gRPC channel |
| 48 | + name (str): The name of the component |
| 49 | + command (Dict[str, Any]): The command to execute |
| 50 | +
|
| 51 | + Returns: |
| 52 | + Dict[str, Any]: The result of the executed command |
| 53 | + """ |
| 54 | + client = GenericClient(name, channel) |
| 55 | + return await client.do_command(command, timeout=timeout) |
0 commit comments