1#!/usr/bin/env python3.4 2# 3# Copyright (C) 2017 The Android Open Source Project 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); you may not 6# use this file except in compliance with the License. You may obtain a copy of 7# the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14# License for the specific language governing permissions and limitations under 15# the License. 16 17""" 18This test script leverages the relay_lib to pair different BT devices. This 19script will be invoked from Tradefed test. The test will first setup pairing 20between BT device and DUT and wait for signal (through socket) from tradefed 21to power down the BT device 22""" 23 24import logging 25import socket 26import sys 27import time 28 29from acts import base_test 30 31class SetupBTPairingTest(base_test.BaseTestClass): 32 33 def __init__(self, controllers): 34 base_test.BaseTestClass.__init__(self, controllers) 35 36 def select_device_by_mac_address(self, mac_address): 37 for device in self.relay_devices: 38 if device.mac_address == mac_address: 39 return device 40 return self.relay_devices[0] 41 42 def setup_test(self): 43 self.bt_device = self.select_device_by_mac_address(self.user_params["mac_address"]) 44 45 def wait_for_test_completion(self): 46 port = int(self.user_params["socket_port"]) 47 timeout = float(self.user_params["socket_timeout_secs"]) 48 49 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 50 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 51 52 server_address = ('localhost', port) 53 logging.info("Starting server socket on localhost port %s", port) 54 sock.bind(('localhost', port)) 55 sock.settimeout(timeout) 56 sock.listen(1) 57 logging.info("Waiting for client socket connection") 58 try: 59 connection, client_address = sock.accept() 60 except socket.timeout: 61 logging.error("Did not receive signal. Shutting down AP") 62 except socket.error: 63 logging.error("Socket connection errored out. Shutting down AP") 64 finally: 65 if connection is not None: 66 connection.close() 67 if sock is not None: 68 sock.shutdown(socket.SHUT_RDWR) 69 sock.close() 70 71 72 def enable_pairing_mode(self): 73 self.bt_device.setup() 74 self.bt_device.power_on() 75 # Wait for a moment between pushing buttons 76 time.sleep(2) 77 self.bt_device.enter_pairing_mode() 78 79 def test_bt_pairing(self): 80 req_params = [ 81 "RelayDevice", "socket_port", "socket_timeout_secs" 82 ] 83 opt_params = [] 84 self.unpack_userparams( 85 req_param_names=req_params, opt_param_names=opt_params) 86 # Setup BT pairing mode 87 self.enable_pairing_mode() 88 # BT pairing mode is turned on 89 self.wait_for_test_completion() 90 91 def teardown_test(self): 92 self.bt_device.power_off() 93 self.bt_device.clean_up() 94