|
| 1 | +# Copyright 2021 Open Source Robotics Foundation, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Module for OnActionEventBase class.""" |
| 16 | + |
| 17 | +import collections.abc |
| 18 | +from typing import Callable |
| 19 | +from typing import List # noqa |
| 20 | +from typing import Optional |
| 21 | +from typing import Text |
| 22 | +from typing import Type |
| 23 | +from typing import TYPE_CHECKING |
| 24 | +from typing import Union |
| 25 | + |
| 26 | +from ..event import Event |
| 27 | +from ..event_handler import BaseEventHandler |
| 28 | +from ..launch_context import LaunchContext |
| 29 | +from ..launch_description_entity import LaunchDescriptionEntity |
| 30 | +from ..some_actions_type import SomeActionsType |
| 31 | + |
| 32 | +if TYPE_CHECKING: |
| 33 | + from ..action import Action # noqa: F401 |
| 34 | + |
| 35 | + |
| 36 | +class OnActionEventBase(BaseEventHandler): |
| 37 | + """Base event handler for events that have a source action.""" |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + *, |
| 42 | + action_matcher: Optional[Union[Callable[['Action'], bool], 'Action']], |
| 43 | + on_event: Union[ |
| 44 | + SomeActionsType, |
| 45 | + Callable[[Event, LaunchContext], Optional[SomeActionsType]] |
| 46 | + ], |
| 47 | + target_event_cls: Type[Event], |
| 48 | + target_action_cls: Type['Action'], |
| 49 | + **kwargs |
| 50 | + ) -> None: |
| 51 | + """ |
| 52 | + Construct a `OnActionEventBase` instance. |
| 53 | +
|
| 54 | + :param action_matcher: `ExecuteProcess` instance or callable to filter events |
| 55 | + from which proces/processes to handle. |
| 56 | + :param on_event: Action to be done to handle the event. |
| 57 | + :param target_event_cls: A subclass of `Event`, indicating which events |
| 58 | + should be handled. |
| 59 | + :param target_action_cls: A subclass of `Action`, indicating which kind of action can |
| 60 | + generate the event. |
| 61 | + """ |
| 62 | + if not issubclass(target_event_cls, Event): |
| 63 | + raise TypeError("'target_event_cls' must be a subclass of 'Event'") |
| 64 | + if ( |
| 65 | + not isinstance(action_matcher, (target_action_cls, type(None))) |
| 66 | + and not callable(action_matcher) |
| 67 | + ): |
| 68 | + raise TypeError( |
| 69 | + f"action_matcher must be an '{target_action_cls.__name__}' instance or a callable" |
| 70 | + ) |
| 71 | + self.__target_action_cls = target_action_cls |
| 72 | + self.__target_event_cls = target_event_cls |
| 73 | + self.__action_matcher = action_matcher |
| 74 | + |
| 75 | + def event_matcher(event): |
| 76 | + if not isinstance(event, target_event_cls): |
| 77 | + return False |
| 78 | + if callable(action_matcher): |
| 79 | + return action_matcher(event.action) |
| 80 | + if isinstance(action_matcher, target_action_cls): |
| 81 | + return event.action is action_matcher |
| 82 | + assert action_matcher is None |
| 83 | + return True |
| 84 | + super().__init__(matcher=event_matcher, **kwargs) |
| 85 | + self.__actions_on_event: List[LaunchDescriptionEntity] = [] |
| 86 | + # TODO(wjwwood) check that it is not only callable, but also a callable that matches |
| 87 | + # the correct signature for a handler in this case |
| 88 | + if callable(on_event): |
| 89 | + # Then on_exit is a function or lambda, so we can just call it, but |
| 90 | + # we don't put anything in self.__actions_on_event because we cannot |
| 91 | + # know what the function will return. |
| 92 | + self.__on_event = on_event |
| 93 | + else: |
| 94 | + # Otherwise, setup self.__actions_on_event |
| 95 | + if isinstance(on_event, collections.abc.Iterable): |
| 96 | + for entity in on_event: |
| 97 | + if not isinstance(entity, LaunchDescriptionEntity): |
| 98 | + raise TypeError( |
| 99 | + "expected all items in 'on_event' iterable to be of type " |
| 100 | + "'LaunchDescriptionEntity' but got '{}'".format(type(entity))) |
| 101 | + self.__actions_on_event = list(on_event) # Outside list is to ensure type is List |
| 102 | + else: |
| 103 | + self.__actions_on_event = [on_event] |
| 104 | + |
| 105 | + def handle(self, event: Event, context: LaunchContext) -> Optional[SomeActionsType]: |
| 106 | + """Handle the given event.""" |
| 107 | + super().handle(event, context) |
| 108 | + |
| 109 | + if self.__actions_on_event: |
| 110 | + return self.__actions_on_event |
| 111 | + return self.__on_event(event, context) |
| 112 | + |
| 113 | + @property |
| 114 | + def handler_description(self) -> Text: |
| 115 | + """Return the string description of the handler.""" |
| 116 | + # TODO(jacobperron): revisit how to describe known actions that are passed in. |
| 117 | + # It would be nice if the parent class could output their description |
| 118 | + # via the 'entities' property. |
| 119 | + if self.__actions_on_event: |
| 120 | + return '<actions>' |
| 121 | + return '{}'.format(self.__on_event) |
| 122 | + |
| 123 | + @property |
| 124 | + def matcher_description(self) -> Text: |
| 125 | + """Return the string description of the matcher.""" |
| 126 | + if self.__action_matcher is None: |
| 127 | + return f'event == {self.__target_event_cls.__name__}' |
| 128 | + return ( |
| 129 | + f'event == {self.__target_event_cls.__name__} and' |
| 130 | + f' {self.__target_action_cls.__name__}(event.action)' |
| 131 | + ) |
0 commit comments