Merge "Merge "Tweaking RSSI polling to import test timing" am: cde88b0133 am: 7df21e3c70 am: 1b39791e4a" into pi-dev
diff --git a/acts/framework/acts/base_test.py b/acts/framework/acts/base_test.py
index 3dc8797..d5b0db9 100755
--- a/acts/framework/acts/base_test.py
+++ b/acts/framework/acts/base_test.py
@@ -186,7 +186,6 @@
             self.log.warning(
                 'Unable to send BEGIN log command to all devices.')
             self.log.warning('Error: %s' % e)
-            pass
         return self.setup_test()
 
     def setup_test(self):
@@ -205,12 +204,14 @@
         """Proxy function to guarantee the base implementation of teardown_test
         is called.
         """
+        self.log.debug('Tearing down test %s' % test_name)
         try:
             # Write test end token to adb log if android device is attached.
             for ad in self.android_devices:
                 ad.droid.logV("%s END %s" % (TEST_CASE_TOKEN, test_name))
-        except:
-            pass
+        except Exception as e:
+            self.log.warning('Unable to send END log command to all devices.')
+            self.log.warning('Error: %s' % e)
         try:
             self.teardown_test()
         finally:
diff --git a/acts/framework/acts/test_utils/bt/bt_coc_test_utils.py b/acts/framework/acts/test_utils/bt/bt_coc_test_utils.py
index 3dbf60c..19e966b 100644
--- a/acts/framework/acts/test_utils/bt/bt_coc_test_utils.py
+++ b/acts/framework/acts/test_utils/bt/bt_coc_test_utils.py
@@ -20,11 +20,13 @@
 
 from acts.test_utils.bt.bt_constants import bt_default_timeout
 from acts.test_utils.bt.bt_constants import default_bluetooth_socket_timeout_ms
+from acts.test_utils.bt.bt_constants import default_le_connection_interval_ms
 from acts.test_utils.bt.bt_constants import default_le_data_length
 from acts.test_utils.bt.bt_constants import gatt_phy
 from acts.test_utils.bt.bt_constants import gatt_transport
 from acts.test_utils.bt.bt_constants import l2cap_coc_header_size
-from acts.test_utils.bt.bt_constants import le_connection_interval_time_step
+from acts.test_utils.bt.bt_constants import le_connection_event_time_step_ms
+from acts.test_utils.bt.bt_constants import le_connection_interval_time_step_ms
 from acts.test_utils.bt.bt_constants import le_default_supervision_timeout
 from acts.test_utils.bt.bt_test_utils import get_mac_address_of_generic_advertisement
 from acts.test_utils.bt.bt_gatt_utils import setup_gatt_connection
@@ -130,7 +132,9 @@
         secured_conn=False,
         le_connection_interval=0,
         le_tx_data_length=default_le_data_length,
-        accept_timeout_ms=default_bluetooth_socket_timeout_ms):
+        accept_timeout_ms=default_bluetooth_socket_timeout_ms,
+        le_min_ce_len=0,
+        le_max_ce_len=0):
     """Sets up the CoC connection between two Android devices.
 
     Args:
@@ -171,9 +175,11 @@
     # Adjust the Connection Interval (if necessary)
     bluetooth_gatt_1 = -1
     gatt_callback_1 = -1
-    if (le_connection_interval != 0) and is_ble:
+    gatt_connected = False
+    if is_ble and (le_connection_interval != 0 or le_min_ce_len != 0 or le_max_ce_len != 0):
         client_ad.log.info(
-            "Adjusting connection interval={}".format(le_connection_interval))
+            "Adjusting connection interval={}, le_min_ce_len={}, le_max_ce_len={}"
+            .format(le_connection_interval, le_min_ce_len, le_max_ce_len))
         try:
             bluetooth_gatt_1, gatt_callback_1 = setup_gatt_connection(
                 client_ad,
@@ -185,11 +191,20 @@
             client_ad.log.error(err)
             return False, None, None
         client_ad.log.info("setup_gatt_connection returns success")
-        minInterval = le_connection_interval / le_connection_interval_time_step
-        maxInterval = le_connection_interval / le_connection_interval_time_step
+        if (le_connection_interval != 0):
+            minInterval = le_connection_interval / le_connection_interval_time_step_ms
+            maxInterval = le_connection_interval / le_connection_interval_time_step_ms
+        else:
+            minInterval = default_le_connection_interval_ms / le_connection_interval_time_step_ms
+            maxInterval = default_le_connection_interval_ms / le_connection_interval_time_step_ms
+        if (le_min_ce_len != 0):
+            le_min_ce_len = le_min_ce_len / le_connection_event_time_step_ms
+        if (le_max_ce_len != 0):
+            le_max_ce_len = le_max_ce_len / le_connection_event_time_step_ms
+
         return_status = client_ad.droid.gattClientRequestLeConnectionParameters(
             bluetooth_gatt_1, minInterval, maxInterval, 0,
-            le_default_supervision_timeout, 0, 0)
+            le_default_supervision_timeout, le_min_ce_len, le_max_ce_len)
         if not return_status:
             client_ad.log.error(
                 "gattClientRequestLeConnectionParameters returns failure")
@@ -197,6 +212,7 @@
         client_ad.log.info(
             "gattClientRequestLeConnectionParameters returns success. Interval={}"
             .format(minInterval))
+        gatt_connected = True
         # For now, we will only test with 1 Mbit Phy.
         # TODO: Add explicit tests with 2 MBit Phy.
         client_ad.droid.gattClientSetPreferredPhy(
@@ -238,14 +254,27 @@
         server_ad.log.info("Error CoC client_ad Connection Inactive")
         client_ad.log.info("Error CoC client_ad Connection Inactive")
 
-    # Get the conn_id
-    client_conn_id = client_ad.droid.bluetoothGetLastConnId()
-    server_conn_id = server_ad.droid.bluetoothGetLastConnId()
+    # Wait for the client to be ready
+    client_conn_id = None
+    while (client_conn_id == None):
+        client_conn_id = client_ad.droid.bluetoothGetLastConnId()
+        if (client_conn_id != None):
+            break
+        time.sleep(1)
+
+    # Wait for the server to be ready
+    server_conn_id = None
+    while (server_conn_id == None):
+        server_conn_id = server_ad.droid.bluetoothGetLastConnId()
+        if (server_conn_id != None):
+            break
+        time.sleep(1)
+
     client_ad.log.info(
         "orchestrate_coc_connection: client conn id={}, server conn id={}".
         format(client_conn_id, server_conn_id))
 
-    if (le_connection_interval != 0) and is_ble:
+    if gatt_connected:
         disconnect_gatt_connection(client_ad, bluetooth_gatt_1,
                                    gatt_callback_1)
         client_ad.droid.gattClientClose(bluetooth_gatt_1)
diff --git a/acts/framework/acts/test_utils/bt/bt_constants.py b/acts/framework/acts/test_utils/bt/bt_constants.py
index bda16a6..20f68dd 100644
--- a/acts/framework/acts/test_utils/bt/bt_constants.py
+++ b/acts/framework/acts/test_utils/bt/bt_constants.py
@@ -32,9 +32,11 @@
 l2cap_max_inactivity_delay_after_disconnect = 5
 
 # LE specifications related constants
-le_connection_interval_time_step = 1.25
+le_connection_interval_time_step_ms = 1.25
 le_default_supervision_timeout = 2000
 default_le_data_length = 23
+default_le_connection_interval_ms = 30
+le_connection_event_time_step_ms = 0.625
 
 # Headers of LE L2CAP Connection-oriented Channels. See section 3.4, Vol 3, Part A, Version 5.0.
 l2cap_header_size = 4
diff --git a/acts/framework/acts/test_utils/bt/bt_contacts_utils.py b/acts/framework/acts/test_utils/bt/bt_contacts_utils.py
index ccebdbf..91d37cc 100644
--- a/acts/framework/acts/test_utils/bt/bt_contacts_utils.py
+++ b/acts/framework/acts/test_utils/bt/bt_contacts_utils.py
@@ -1,4 +1,4 @@
-#/usr/bin/env python3.4
+# /usr/bin/env python3.4
 #
 # Copyright (C) 2016 The Android Open Source Project
 #
@@ -24,7 +24,7 @@
 import re
 import random
 import string
-
+from time import sleep
 from acts.utils import exe_cmd
 import queue
 
@@ -283,6 +283,10 @@
     phone_phonebook_path = "{}{}".format(STORAGE_PATH, vcf_file)
     device.adb.push("{} {}".format(local_phonebook_path, phone_phonebook_path))
     device.droid.importVcf("file://{}{}".format(STORAGE_PATH, vcf_file))
+    # keyevent to allow contacts import from vcf file
+    sleep(1)
+    for key in ["ENTER", "DPAD_RIGHT", "ENTER"]:
+        device.adb.shell("input keyevent KEYCODE_{}".format(key))
     if wait_for_phone_number_update_complete(device, number_count):
         return number_count
     else:
@@ -299,6 +303,15 @@
     return True
 
 
+def delete_vcf_files(device):
+    """Deletes all files with .vcf extension
+    """
+    files = device.adb.shell("ls {}".format(STORAGE_PATH))
+    for file_name in files.split():
+        if ".vcf" in file_name:
+            device.adb.shell("rm -f {}{}".format(STORAGE_PATH, file_name))
+
+
 def erase_contacts(device):
     """Erase all contacts out of devices contact database.
     """
@@ -379,8 +392,8 @@
         for i in range(len(pse_call_log)):
             # Compare the phone number
             if normalize_phonenumber(pse_call_log[i][
-                    "number"]) != normalize_phonenumber(pce_call_log[i][
-                        "number"]):
+                                         "number"]) != normalize_phonenumber(pce_call_log[i][
+                                                                                 "number"]):
                 log.warning("Call Log numbers differ")
                 call_logs_match = False
 
@@ -391,7 +404,7 @@
 
             # Compare time to truncated second.
             if int(pse_call_log[i]["date"]) // 1000 != int(pce_call_log[i][
-                    "date"]) // 1000:
+                                                               "date"]) // 1000:
                 log.warning("Call log times don't match, check timezone.")
                 call_logs_match = False
 
diff --git a/acts/tests/google/ble/conn_oriented_chan/BleCoc2ConnTest.py b/acts/tests/google/ble/conn_oriented_chan/BleCoc2ConnTest.py
index a477672..bff59e7 100644
--- a/acts/tests/google/ble/conn_oriented_chan/BleCoc2ConnTest.py
+++ b/acts/tests/google/ble/conn_oriented_chan/BleCoc2ConnTest.py
@@ -27,8 +27,10 @@
 from acts.test_utils.bt.bt_coc_test_utils import orchestrate_coc_connection
 from acts.test_utils.bt.bt_coc_test_utils import do_multi_connection_throughput
 from acts.test_utils.bt.bt_constants import default_le_data_length
+from acts.test_utils.bt.bt_constants import default_bluetooth_socket_timeout_ms
 from acts.test_utils.bt.bt_constants import l2cap_coc_header_size
 from acts.test_utils.bt.bt_constants import l2cap_max_inactivity_delay_after_disconnect
+from acts.test_utils.bt.bt_constants import le_connection_event_time_step_ms
 from acts.test_utils.bt.bt_test_utils import clear_bonded_devices
 from acts.test_utils.bt.bt_test_utils import kill_bluetooth_process
 from acts.test_utils.bt.bt_test_utils import reset_bluetooth
@@ -56,12 +58,22 @@
         # Give sufficient time for the physical LE link to be disconnected.
         time.sleep(l2cap_max_inactivity_delay_after_disconnect)
 
+    # This utility function calculates the max and min connection event (ce) time.
+    # The formula is that the min/max ce time should be less than half the connection
+    # interval and must be multiples of the le_connection_event_time_step.
+    def _calc_min_max_ce_time(self, le_connection_interval):
+        conn_event_time_steps = int((le_connection_interval/2)/le_connection_event_time_step_ms)
+        conn_event_time_steps -= 1
+        return (le_connection_event_time_step_ms * conn_event_time_steps)
+
     def _run_coc_connection_throughput_2_conn(
             self,
             is_secured,
             buffer_size,
             le_connection_interval=0,
-            le_tx_data_length=default_le_data_length):
+            le_tx_data_length=default_le_data_length,
+            min_ce_len=0,
+            max_ce_len=0):
 
         # The num_iterations is that number of repetitions of each
         # set of buffers r/w.
@@ -70,8 +82,6 @@
         # buffer_size is the number of bytes per L2CAP data buffer.
         num_iterations = 10
         number_buffers = 100
-        # Note: A 117 octets buffer size would fix nicely to a 123 bytes Data Length
-        buffer_size = 117
 
         # Make sure at least 3 phones are setup
         if len(self.android_devices) <= 2:
@@ -81,17 +91,19 @@
 
         self.log.info(
             "_run_coc_connection_throughput_2_conn: is_secured={}, Interval={}, buffer_size={}, "
-            "le_tx_data_length={}".format(is_secured, le_connection_interval,
-                                          buffer_size, le_tx_data_length))
+            "le_tx_data_length={}, min_ce_len={}".format(is_secured, le_connection_interval,
+                                          buffer_size, le_tx_data_length, min_ce_len))
         status, client_conn_id1, server_conn_id1 = orchestrate_coc_connection(
             self.client_ad, self.server_ad, True, is_secured,
-            le_connection_interval, le_tx_data_length)
+            le_connection_interval, le_tx_data_length, default_bluetooth_socket_timeout_ms,
+            min_ce_len, max_ce_len)
         if not status:
             return False
 
         status, client_conn_id2, server_conn_id2 = orchestrate_coc_connection(
             self.client_ad, self.server2_ad, True, is_secured,
-            le_connection_interval, le_tx_data_length)
+            le_connection_interval, le_tx_data_length, default_bluetooth_socket_timeout_ms,
+            min_ce_len, max_ce_len)
         if not status:
             return False
 
@@ -223,8 +235,11 @@
         le_connection_interval = 10
         buffer_size = 60
         le_tx_data_length = buffer_size + l2cap_coc_header_size
+
         status = self._run_coc_connection_throughput_2_conn(
-            is_secured, buffer_size, le_connection_interval, le_tx_data_length)
+            is_secured, buffer_size, le_connection_interval, le_tx_data_length,
+            self._calc_min_max_ce_time(le_connection_interval),
+            self._calc_min_max_ce_time(le_connection_interval))
         return status
 
     @BluetoothBaseTest.bt_test_wrap
@@ -266,7 +281,9 @@
         buffer_size = 80
         le_tx_data_length = buffer_size + l2cap_coc_header_size
         status = self._run_coc_connection_throughput_2_conn(
-            is_secured, buffer_size, le_connection_interval, le_tx_data_length)
+            is_secured, buffer_size, le_connection_interval, le_tx_data_length,
+            self._calc_min_max_ce_time(le_connection_interval),
+            self._calc_min_max_ce_time(le_connection_interval))
         return status
 
     @BluetoothBaseTest.bt_test_wrap
@@ -308,7 +325,9 @@
         buffer_size = 120
         le_tx_data_length = buffer_size + l2cap_coc_header_size
         status = self._run_coc_connection_throughput_2_conn(
-            is_secured, buffer_size, le_connection_interval, le_tx_data_length)
+            is_secured, buffer_size, le_connection_interval, le_tx_data_length,
+            self._calc_min_max_ce_time(le_connection_interval),
+            self._calc_min_max_ce_time(le_connection_interval))
         return status
 
     @BluetoothBaseTest.bt_test_wrap
@@ -350,7 +369,9 @@
         buffer_size = 120
         le_tx_data_length = buffer_size + l2cap_coc_header_size
         status = self._run_coc_connection_throughput_2_conn(
-            is_secured, buffer_size, le_connection_interval, le_tx_data_length)
+            is_secured, buffer_size, le_connection_interval, le_tx_data_length,
+            self._calc_min_max_ce_time(le_connection_interval),
+            self._calc_min_max_ce_time(le_connection_interval))
         return status
 
     @BluetoothBaseTest.bt_test_wrap
@@ -392,7 +413,9 @@
         buffer_size = 180
         le_tx_data_length = buffer_size + l2cap_coc_header_size
         status = self._run_coc_connection_throughput_2_conn(
-            is_secured, buffer_size, le_connection_interval, le_tx_data_length)
+            is_secured, buffer_size, le_connection_interval, le_tx_data_length,
+            self._calc_min_max_ce_time(le_connection_interval),
+            self._calc_min_max_ce_time(le_connection_interval))
         return status
 
     @BluetoothBaseTest.bt_test_wrap
@@ -434,7 +457,9 @@
         buffer_size = 240
         le_tx_data_length = buffer_size + l2cap_coc_header_size
         status = self._run_coc_connection_throughput_2_conn(
-            is_secured, buffer_size, le_connection_interval, le_tx_data_length)
+            is_secured, buffer_size, le_connection_interval, le_tx_data_length,
+            self._calc_min_max_ce_time(le_connection_interval),
+            self._calc_min_max_ce_time(le_connection_interval))
         return status
 
     @BluetoothBaseTest.bt_test_wrap
@@ -476,5 +501,7 @@
         buffer_size = 240
         le_tx_data_length = buffer_size + l2cap_coc_header_size
         status = self._run_coc_connection_throughput_2_conn(
-            is_secured, buffer_size, le_connection_interval, le_tx_data_length)
+            is_secured, buffer_size, le_connection_interval, le_tx_data_length,
+            self._calc_min_max_ce_time(le_connection_interval),
+            self._calc_min_max_ce_time(le_connection_interval))
         return status
diff --git a/acts/tests/google/bt/car_bt/BtCarPbapTest.py b/acts/tests/google/bt/car_bt/BtCarPbapTest.py
index bc1b930..a3ae194 100644
--- a/acts/tests/google/bt/car_bt/BtCarPbapTest.py
+++ b/acts/tests/google/bt/car_bt/BtCarPbapTest.py
@@ -1,4 +1,4 @@
-#/usr/bin/env python3.4
+# /usr/bin/env python3.4
 #
 # Copyright (C) 2016 The Android Open Source Project
 #
@@ -55,12 +55,10 @@
             "android.permission.WRITE_CONTACTS",
             "android.permission.READ_EXTERNAL_STORAGE"
         ]
-        for permission in permissions_list:
-            self.pse.adb.shell(
-                "pm grant com.google.android.contacts {}".format(permission))
-        for permission in permissions_list:
-            self.pce.adb.shell("pm grant com.android.contacts {}".format(
-                permission))
+        for device in [self.pce, self.pse, self.pse2]:
+            for permission in permissions_list:
+                device.adb.shell(
+                    "pm grant com.google.android.contacts {}".format(permission))
 
         # Pair the devices.
         # This call may block until some specified timeout in bt_test_utils.py.
@@ -115,6 +113,9 @@
     def teardown_test(self):
         if not super(BtCarPbapTest, self).teardown_test():
             return False
+        for device in [self.pce, self.pse, self.pse2]:
+            bt_contacts_utils.delete_vcf_files(device)
+
         self.pce.droid.bluetoothPbapClientDisconnect(
             self.pse.droid.bluetoothGetLocalAddress())
         bt_contacts_utils.erase_contacts(self.pse)
@@ -214,6 +215,8 @@
                                                 PSE_CONTACTS_FILE, 100)
         phone_numbers_added = bt_contacts_utils.import_device_contacts_from_vcf(
             self.pse, self.contacts_destination_path, PSE_CONTACTS_FILE)
+
+        bt_test_utils.reset_bluetooth([self.pce])
         bt_test_utils.connect_pri_to_sec(
             self.pce, self.pse,
             set([BtEnum.BluetoothProfile.PBAP_CLIENT.value]))
@@ -249,6 +252,7 @@
                                                 PSE_CONTACTS_FILE, 100)
         phone_numbers_added = bt_contacts_utils.import_device_contacts_from_vcf(
             self.pse, self.contacts_destination_path, PSE_CONTACTS_FILE)
+        bt_test_utils.reset_bluetooth([self.pce])
         if not self.connect_and_verify(phone_numbers_added):
             return False
 
@@ -257,6 +261,7 @@
                                                 PSE_CONTACTS_FILE, 110, 2)
         phone_numbers_added = bt_contacts_utils.import_device_contacts_from_vcf(
             self.pse, self.contacts_destination_path, PSE_CONTACTS_FILE)
+        bt_test_utils.reset_bluetooth([self.pce])
         return self.connect_and_verify(phone_numbers_added)
 
     @test_tracker_info(uuid='bbe31bf5-51e8-4175-b266-1c7750e44f5b')
@@ -330,7 +335,7 @@
 
         phone_numbers_added = bt_contacts_utils.import_device_contacts_from_vcf(
             self.pse, self.contacts_destination_path, PSE_CONTACTS_FILE)
-
+        bt_test_utils.reset_bluetooth([self.pce])
         return self.connect_and_verify(phone_numbers_added)
 
     @test_tracker_info(uuid='2aa2bd00-86cc-4f39-a06a-90b17ea5b320')
@@ -432,13 +437,16 @@
 
         bt_contacts_utils.generate_contact_list(self.contacts_destination_path,
                                                 PSE1_CONTACTS_FILE, 100)
-        phone_numbers_added = bt_contacts_utils.import_device_contacts_from_vcf(
-            self.pse, self.contacts_destination_path, PSE1_CONTACTS_FILE)
+        phone_numbers_added = bt_contacts_utils.import_device_contacts_from_vcf(self.pse,
+                                                                                self.contacts_destination_path,
+                                                                                PSE1_CONTACTS_FILE)
         bt_contacts_utils.generate_contact_list(self.contacts_destination_path,
                                                 PSE2_CONTACTS_FILE, 100)
-        phone_numbers_added = bt_contacts_utils.import_device_contacts_from_vcf(
-            self.pse2, self.contacts_destination_path, PSE2_CONTACTS_FILE)
+        phone_numbers_added = bt_contacts_utils.import_device_contacts_from_vcf(self.pse2,
+                                                                                self.contacts_destination_path,
+                                                                                PSE2_CONTACTS_FILE)
 
+        bt_test_utils.reset_bluetooth([self.pce])
         self.pce.droid.bluetoothPbapClientDisconnect(
             self.pse.droid.bluetoothGetLocalAddress())
         self.pce.droid.bluetoothPbapClientDisconnect(
diff --git a/acts/tests/google/wifi/aware/stress/DataPathStressTest.py b/acts/tests/google/wifi/aware/stress/DataPathStressTest.py
index 9a862cb..529d884 100644
--- a/acts/tests/google/wifi/aware/stress/DataPathStressTest.py
+++ b/acts/tests/google/wifi/aware/stress/DataPathStressTest.py
@@ -75,6 +75,12 @@
             resp_dut.droid.wifiAwareCreateNetworkSpecifierOob(
                 resp_id, aconsts.DATA_PATH_RESPONDER, init_mac, None))
 
+        # Wait a minimal amount of time to let the Responder configure itself
+        # and be ready for the request. While calling it first may be sufficient
+        # there are no guarantees that a glitch may slow the Responder slightly
+        # enough to invert the setup order.
+        time.sleep(1)
+
         # Initiator: request network
         init_req_key = autils.request_network(
             init_dut,