1# Copyright (C) 2022 The Android Open Source Project 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"""This is a shared library to help handling Mobly event waiting logic.""" 16 17import time 18from typing import Callable 19 20from mobly.controllers.android_device_lib import callback_handler 21from mobly.controllers.android_device_lib import snippet_event 22 23# Abbreviations for common use type 24CallbackHandler = callback_handler.CallbackHandler 25SnippetEvent = snippet_event.SnippetEvent 26 27# Type definition for the callback functions to make code formatted nicely 28OnReceivedCallback = Callable[[SnippetEvent, int], bool] 29OnWaitingCallback = Callable[[int], None] 30OnMissedCallback = Callable[[], None] 31 32 33def wait_callback_event(callback_event_handler: CallbackHandler, 34 event_name: str, timeout_seconds: int, 35 on_received: OnReceivedCallback, 36 on_waiting: OnWaitingCallback, 37 on_missed: OnMissedCallback) -> None: 38 """Waits until the matched event has been received or timeout. 39 40 Here we keep waitAndGet for event callback from EventSnippet. 41 We loop until over timeout_seconds instead of directly 42 waitAndGet(timeout=teardown_timeout_seconds). Because there is 43 MAX_TIMEOUT limitation in callback_handler of Mobly. 44 45 Args: 46 callback_event_handler: Mobly callback events handler. 47 event_name: the specific name of the event to wait. 48 timeout_seconds: the number of seconds to wait before giving up. 49 on_received: calls when event received, return false to keep waiting. 50 on_waiting: calls when waitAndGet timeout. 51 on_missed: calls when giving up. 52 """ 53 start_time = time.perf_counter() 54 deadline = start_time + timeout_seconds 55 while time.perf_counter() < deadline: 56 remaining_time_sec = min(callback_handler.DEFAULT_TIMEOUT, 57 deadline - time.perf_counter()) 58 try: 59 event = callback_event_handler.waitAndGet( 60 event_name, timeout=remaining_time_sec) 61 except callback_handler.TimeoutError: 62 elapsed_time = int(time.perf_counter() - start_time) 63 on_waiting(elapsed_time) 64 else: 65 elapsed_time = int(time.perf_counter() - start_time) 66 if on_received(event, elapsed_time): 67 break 68 else: 69 on_missed() 70