1#  Copyright (C) 2023 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
15import logging
16import time
17
18from bluetooth_test import bluetooth_base_test
19from utilities.main_utils import common_main
20from utilities.crystalball_metrics_utils import export_to_crystalball
21
22ITERATIONS_PARAM_NAME = 'iterations'
23DEFAULT_ITERATIONS = 10
24DEFAULT_ITERATION_DELAY_S = 2
25
26class BTPerformancePairingTest(bluetooth_base_test.BluetoothBaseTest):
27    """Test Class for Bluetooth Pairing Test."""
28
29    def setup_class(self):
30        super().setup_class()
31        self.iterations = DEFAULT_ITERATIONS
32        self.iteration_delay = DEFAULT_ITERATION_DELAY_S
33        if ITERATIONS_PARAM_NAME in self.user_params:
34            self.iterations = self.user_params[ITERATIONS_PARAM_NAME]
35        else:
36            logging.info(f'{ITERATIONS_PARAM_NAME} is not in testbed config. Using default value')
37        logging.info(f'Setup {self.__class__.__name__} with {ITERATIONS_PARAM_NAME} = {self.iterations} and iteration delay = {self.iteration_delay}')
38
39    def test_pairing(self):
40        """Test for pairing/unpairing a HU with a bluetooth device"""
41        pairing_success_count = 0
42        for i in range(1, self.iterations + 1):
43            logging.info(f'Pairing iteration {i}')
44            try:
45                self.bt_utils.pair_primary_to_secondary()
46                pairing_success_count += 1
47            except:
48                logging.error(f'Failed to pair devices on iteration {i}')
49            self.bt_utils.unpair()
50            time.sleep(self.iteration_delay)
51        success_rate = pairing_success_count / self.iterations
52        metrics = {'success_rate': success_rate}
53        export_to_crystalball(metrics, self.log_path, self.current_test_info.name)
54
55if __name__ == '__main__':
56    common_main()
57