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(callback_id, event_name, 46 timeout_ms) 47 except Exception as e: 48 if TIMEOUT_ERROR_MESSAGE in str(e): 49 raise errors.CallbackHandlerTimeoutError( 50 self._device, (f'Timed out after waiting {timeout_sec}s for event ' 51 f'"{event_name}" triggered by {self._method_name} ' 52 f'({self.callback_id}).')) from e 53 raise 54 55 def callEventGetAllRpc(self, callback_id, event_name): 56 """Gets all existing events for the specified identifier without waiting. 57 58 This function calls snippet lib's eventGetAll RPC. 59 60 Args: 61 callback_id: str, the callback identifier. 62 event_name: str, the callback name. 63 64 Returns: 65 A list of event dictionaries. 66 """ 67 return self._event_client.eventGetAll(callback_id, event_name) 68