remotivelabs.topology.control

 1from .client import ControlClient
 2from .handler import Handler
 3from .request import ControlRequest
 4from .response import ControlResponse
 5
 6__all__ = [
 7    "ControlClient",
 8    "ControlRequest",
 9    "ControlResponse",
10    "Handler",
11]
class ControlClient:
23class ControlClient:
24    """
25    Client for sending control messages in a Remotive topology.
26
27    A ControlClient is used to send abstract or synthetic control messages that do not exist
28    in a real vehicle but are useful to manipulate or initialize models into a specific state.
29    """
30
31    def __init__(self, client: BrokerClient) -> None:
32        """
33        Control message client.
34
35        Args:
36            client: BrokerClient instance.
37
38        Note:
39            Start the instance using a context manager:
40            ```python
41            async with ControlClient(...) as client:
42                ...
43            ```
44        """
45        self._transport: TransportClientApi = TransportClient(client=client)
46
47    async def __aenter__(self) -> Self:
48        await self._transport.__aenter__()
49        return self
50
51    async def __aexit__(self, exc_type, exc_value, traceback) -> None:
52        await self._transport.__aexit__(exc_type, exc_value, traceback)
53
54    async def send(self, target_ecu: str, request: ControlRequest, timeout: float = 10.0, retries: int = 0) -> ControlResponse:
55        """
56        Send a control request to the target ECU, retrying on timeout.
57
58        Args:
59            target_ecu: The name of the target ECU.
60            request: The control message request.
61            timeout: Timeout per attempt in seconds.
62            retries: Number of retries on timeout. Defaults to 0.
63
64        Returns:
65            Control response.
66        """
67
68        data = control_request_fmt.dumps(request)
69        for attempt in range(retries + 1):
70            try:
71                _logger.debug(f"attempt {attempt + 1}: sending request {request}")
72                ret = await asyncio.wait_for(self._transport.send(data=data, target_ecu=target_ecu, timeout=timeout), timeout=timeout)
73                response = control_response_fmt.loads(ret)
74                _logger.debug(f"received response {response}")
75                return response
76            except asyncio.TimeoutError:
77                continue
78
79        raise asyncio.TimeoutError(f"Timeout sending {request} to '{target_ecu}'")

Client for sending control messages in a Remotive topology.

A ControlClient is used to send abstract or synthetic control messages that do not exist in a real vehicle but are useful to manipulate or initialize models into a specific state.

ControlClient(client: remotivelabs.broker.client.BrokerClient)
31    def __init__(self, client: BrokerClient) -> None:
32        """
33        Control message client.
34
35        Args:
36            client: BrokerClient instance.
37
38        Note:
39            Start the instance using a context manager:
40            ```python
41            async with ControlClient(...) as client:
42                ...
43            ```
44        """
45        self._transport: TransportClientApi = TransportClient(client=client)

Control message client.

Arguments:
  • client: BrokerClient instance.
Note:

Start the instance using a context manager:

async with ControlClient(...) as client:
    ...
async def send( self, target_ecu: str, request: ControlRequest, timeout: float = 10.0, retries: int = 0) -> ControlResponse:
54    async def send(self, target_ecu: str, request: ControlRequest, timeout: float = 10.0, retries: int = 0) -> ControlResponse:
55        """
56        Send a control request to the target ECU, retrying on timeout.
57
58        Args:
59            target_ecu: The name of the target ECU.
60            request: The control message request.
61            timeout: Timeout per attempt in seconds.
62            retries: Number of retries on timeout. Defaults to 0.
63
64        Returns:
65            Control response.
66        """
67
68        data = control_request_fmt.dumps(request)
69        for attempt in range(retries + 1):
70            try:
71                _logger.debug(f"attempt {attempt + 1}: sending request {request}")
72                ret = await asyncio.wait_for(self._transport.send(data=data, target_ecu=target_ecu, timeout=timeout), timeout=timeout)
73                response = control_response_fmt.loads(ret)
74                _logger.debug(f"received response {response}")
75                return response
76            except asyncio.TimeoutError:
77                continue
78
79        raise asyncio.TimeoutError(f"Timeout sending {request} to '{target_ecu}'")

Send a control request to the target ECU, retrying on timeout.

Arguments:
  • target_ecu: The name of the target ECU.
  • request: The control message request.
  • timeout: Timeout per attempt in seconds.
  • retries: Number of retries on timeout. Defaults to 0.
Returns:

Control response.

@dataclass
class ControlRequest:
12@dataclass
13class ControlRequest:
14    """
15    Message structure and serialization for control requests.
16    Attributes:
17        type: The type of control message.
18        argument (Any | None): Optional argument to the control message.
19            Must be JSON-serializable if provided.
20    """
21
22    type: str
23    argument: Any | None = None

Message structure and serialization for control requests.

Attributes:
  • type: The type of control message.
  • argument (Any | None): Optional argument to the control message. Must be JSON-serializable if provided.
ControlRequest(type: str, argument: typing.Any | None = None)
type: str
argument: typing.Any | None = None
@dataclass
class ControlResponse:
12@dataclass
13class ControlResponse:
14    """
15    Message structure and serialization for control responses.
16    """
17
18    status: str = "ok"
19    data: Any = None

Message structure and serialization for control responses.

ControlResponse(status: str = 'ok', data: Any = None)
status: str = 'ok'
data: Any = None
@runtime_checkable
class Handler(typing.Protocol):
21@runtime_checkable
22class Handler(Protocol):
23    """
24    A callable protocol for handling control messages asynchronously.
25
26    Implementations must define an async __call__ method that takes a
27    ControlRequest and returns a ControlResponse.
28    """
29
30    async def __call__(self, request: ControlRequest) -> ControlResponse:
31        pass

A callable protocol for handling control messages asynchronously.

Implementations must define an async __call__ method that takes a ControlRequest and returns a ControlResponse.

Handler(*args, **kwargs)
1945def _no_init_or_replace_init(self, *args, **kwargs):
1946    cls = type(self)
1947
1948    if cls._is_protocol:
1949        raise TypeError('Protocols cannot be instantiated')
1950
1951    # Already using a custom `__init__`. No need to calculate correct
1952    # `__init__` to call. This can lead to RecursionError. See bpo-45121.
1953    if cls.__init__ is not _no_init_or_replace_init:
1954        return
1955
1956    # Initially, `__init__` of a protocol subclass is set to `_no_init_or_replace_init`.
1957    # The first instantiation of the subclass will call `_no_init_or_replace_init` which
1958    # searches for a proper new `__init__` in the MRO. The new `__init__`
1959    # replaces the subclass' old `__init__` (ie `_no_init_or_replace_init`). Subsequent
1960    # instantiation of the protocol subclass will thus use the new
1961    # `__init__` and no longer call `_no_init_or_replace_init`.
1962    for base in cls.__mro__:
1963        init = base.__dict__.get('__init__', _no_init_or_replace_init)
1964        if init is not _no_init_or_replace_init:
1965            cls.__init__ = init
1966            break
1967    else:
1968        # should not happen
1969        cls.__init__ = object.__init__
1970
1971    cls.__init__(self, *args, **kwargs)