• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2022 Google 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"""The callback handler V2 module for Android Mobly Snippet Lib."""
15
16from mobly.snippet import callback_handler_base
17from mobly.snippet import errors
18
19# The timeout error meesage when pulling events from the server
20TIMEOUT_ERROR_MESSAGE = 'EventSnippetException: timeout.'
21
22
23class CallbackHandlerV2(callback_handler_base.CallbackHandlerBase):
24  """The callback handler V2 class for Android Mobly Snippet Lib."""
25
26  def callEventWaitAndGetRpc(self, callback_id, event_name, timeout_sec):
27    """Waits and returns an existing CallbackEvent for the specified identifier.
28
29    This function calls snippet lib's eventWaitAndGet RPC.
30
31    Args:
32      callback_id: str, the callback identifier.
33      event_name: str, the callback name.
34      timeout_sec: float, the number of seconds to wait for the event.
35
36    Returns:
37      The event dictionary.
38
39    Raises:
40      errors.CallbackHandlerTimeoutError: The expected event does not occur
41        within the time limit.
42    """
43    timeout_ms = int(timeout_sec * 1000)
44    try:
45      return self._event_client.eventWaitAndGet(
46          callback_id, event_name, timeout_ms
47      )
48    except Exception as e:
49      if TIMEOUT_ERROR_MESSAGE in str(e):
50        raise errors.CallbackHandlerTimeoutError(
51            self._device,
52            (
53                f'Timed out after waiting {timeout_sec}s for event '
54                f'"{event_name}" triggered by {self._method_name} '
55                f'({self.callback_id}).'
56            ),
57        ) from e
58      raise
59
60  def callEventGetAllRpc(self, callback_id, event_name):
61    """Gets all existing events for the specified identifier without waiting.
62
63    This function calls snippet lib's eventGetAll RPC.
64
65    Args:
66      callback_id: str, the callback identifier.
67      event_name: str, the callback name.
68
69    Returns:
70      A list of event dictionaries.
71    """
72    return self._event_client.eventGetAll(callback_id, event_name)
73