aboutsummaryrefslogtreecommitdiff
path: root/mobly/controllers/android_device_lib/callback_handler_v2.py
blob: d1f9e8f75dea000d5821cfbd464fb204ccd6dd08 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# Copyright 2022 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The callback handler V2 module for Android Mobly Snippet Lib."""

from mobly.snippet import callback_handler_base
from mobly.snippet import errors

# The timeout error meesage when pulling events from the server
TIMEOUT_ERROR_MESSAGE = 'EventSnippetException: timeout.'


class CallbackHandlerV2(callback_handler_base.CallbackHandlerBase):
  """The callback handler V2 class for Android Mobly Snippet Lib."""

  def callEventWaitAndGetRpc(self, callback_id, event_name, timeout_sec):
    """Waits and returns an existing CallbackEvent for the specified identifier.

    This function calls snippet lib's eventWaitAndGet RPC.

    Args:
      callback_id: str, the callback identifier.
      event_name: str, the callback name.
      timeout_sec: float, the number of seconds to wait for the event.

    Returns:
      The event dictionary.

    Raises:
      errors.CallbackHandlerTimeoutError: The expected event does not occur
        within the time limit.
    """
    timeout_ms = int(timeout_sec * 1000)
    try:
      return self._event_client.eventWaitAndGet(
          callback_id, event_name, timeout_ms
      )
    except Exception as e:
      if TIMEOUT_ERROR_MESSAGE in str(e):
        raise errors.CallbackHandlerTimeoutError(
            self._device,
            (
                f'Timed out after waiting {timeout_sec}s for event '
                f'"{event_name}" triggered by {self._method_name} '
                f'({self.callback_id}).'
            ),
        ) from e
      raise

  def callEventGetAllRpc(self, callback_id, event_name):
    """Gets all existing events for the specified identifier without waiting.

    This function calls snippet lib's eventGetAll RPC.

    Args:
      callback_id: str, the callback identifier.
      event_name: str, the callback name.

    Returns:
      A list of event dictionaries.
    """
    return self._event_client.eventGetAll(callback_id, event_name)