class AndroidUiTestVcMt(AndroidUiTest):
    """
    Android UI test mobile terminated voice call class.
    This use case will permit to launch UI test on DUT.
    The PHONE2 will be used in application framework level to make a voice call.
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        # Call Android UI test use case base Init function
        AndroidUiTest.__init__(self, tc_name, global_config)

        #
        self._phone_number = \
            str(self._device.get_phone_number())

        # Read callSetupTimeout from Device_Catalog.xml
        self._call_setup_time = \
            int(self._dut_config.get("callSetupTimeout"))

        # Get UECmdLayer
        self._phone2 = DeviceManager().get_device("PHONE2")
        if self._phone2 is not None:
            self._voice_call_api2 = self._phone2.get_uecmd("VoiceCall")

    def set_up(self):
        """
        Set up the test configuration
        """
        # Call Android UI test use case base Setup function
        verdict, msg = AndroidUiTest.set_up(self)
        if verdict != Global.SUCCESS:
            return verdict, msg

        # Check if we have the second phone available
        if self._phone2 is None:
            # We are using this multi UC with only one phone
            return Global.FAILURE, "Cannot run that use case with only one phone configured."

        # Boot the other phone (the DUT is already booted)

        if self._phone2.get_state() != "alive":
            # We are using this multi UC with an phone2 is not available
            return Global.FAILURE, "Ref phone not available (power off ?), please check your bench."

        if not self._phone2.is_available():
            self._phone2.connect_board()

        return Global.SUCCESS, "No error"

    def run_test(self):
        """
        Execute the test
        """
        self._logger.info("")
        self._logger.info("%s: RunTest", self._name)
        self._logger.info("")

        # Phone 2 : Release any previous call (Robustness)
        time.sleep(self._wait_btwn_cmd)
        self._voice_call_api2.release()

        # Phone2 : Dial without checking call state (Non Blocking)
        time.sleep(self._wait_btwn_cmd)
        self._voice_call_api2.dial(self._phone_number, False)

        # Phone1 : Call AndroidUiTest run test
        return AndroidUiTest.run_test(self)
示例#2
0
class LabWifiTetheringBase(LabWcdmaBase):
    """
    Lab Wifi Tethering base Test class.
    """
    _CHECK_CONNECTION_TIMEOUT = 20

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        LabWcdmaBase.__init__(self, tc_name, global_config)

        # Get host spot configuration according HOTSPOT_SSID
        self._hotspot_ssid = \
            str(self._tc_parameters.get_param_value("HOTSPOT_SSID"))

        # Get host spot configuration according HOTSPOT_SECURITY
        self._hotspot_security = \
            str(self._tc_parameters.get_param_value("HOTSPOT_SECURITY"))

        # Get host spot configuration according HOTSPOT_PASSWORD
        self._hotspot_passphrase = \
            str(self._tc_parameters.get_param_value("HOTSPOT_PASSWORD"))

        # Get UECmdLayer
        self._networking_api = self._device.get_uecmd("Networking")

        self._phone2 = DeviceManager().get_device("PHONE2")
        if self._phone2 is not None:
            self._networking_api2 = self._phone2.get_uecmd("Networking")

        # init original wifi power status for phone1
        self._original_wifi_power_status = 0

        # Set BT prerequisite (set ON, set OFF or nothing) for FIT BT/WIFI tests
        self._bt_fit_used, self._bt_wished_value = self._get_bt_fit_config()
        # Instantiate generic UECmd
        self._localconnectivity_api = self._device.get_uecmd(
            "LocalConnectivity")
        self._bt_initial_state = 'STATE_ON'

        # MAC Address of the STA device that will be connected to the softAP
        self._client_mac_address = ""

#------------------------------------------------------------------------------

    def set_up(self):
        """
        Initialize the test
        """
        # run setup inherit from LabWcdmaBase
        LabWcdmaBase.set_up(self)

        # Check if we have the second phone available
        if self._phone2 is None:
            return Global.FAILURE, "Cannot run that use case with only one phone configured."

        # Boot the other phone (the DUT is already booted)
        if not self._phone2.is_available():
            DeviceManager().boot_device("PHONE2")

        # If Bt to be (de-)activated for FIT tests
        if self._bt_fit_used:

            self._bt_initial_state = self._localconnectivity_api.get_bt_power_status(
            )

            # if Bt is not at the wished value, set it to the correct one.
            if self._bt_initial_state != self._bt_wished_value:
                self._localconnectivity_api.set_bt_power(self._bt_wished_value)
                time.sleep(self._wait_btwn_cmd)

        # store original wifi power status
        time.sleep(self._wait_btwn_cmd)
        self._original_wifi_power_status = \
            self._networking_api.get_wifi_power_status()

        # disable wifi for Phone1
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_power("off")

        # enable Portable wifi hotspot for Phone1
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_hotspot("on", self._hotspot_ssid,
                                              self._hotspot_security,
                                              self._hotspot_passphrase)

        # set wifi power on for Phone2
        time.sleep(self._wait_btwn_cmd)
        self._networking_api2.set_wifi_power("on")

        # Clear all data connections for Phone2
        time.sleep(self._wait_btwn_cmd)
        self._networking_api2.clean_all_data_connections()

        # scan wifi for Phone2
        time.sleep(self._wait_btwn_cmd)
        self._networking_api2.request_wifi_scan()

        # set passphrase for Phone2
        if self._hotspot_security in "WPA2-PSK":
            self._networking_api2.set_wificonfiguration(
                self._hotspot_ssid, self._hotspot_passphrase,
                self._hotspot_security)

        # connect hotspot from Phone1 for Phone2
        time.sleep(self._wait_btwn_cmd)
        self._networking_api2.wifi_connect(self._hotspot_ssid)

        # Retrieve the PHONE2 MAC address
        time.sleep(self._wait_btwn_cmd)
        self._client_mac_address = self._networking_api2.get_interface_mac_addr(
        )

        return Global.SUCCESS, "No errors"

#------------------------------------------------------------------------------

    def tear_down(self):
        """
        End and dispose the test
        """
        LabWcdmaBase.tear_down(self)

        status = Global.SUCCESS
        msg = "No error"

        # disconnect from hotspot for Phone2
        time.sleep(self._wait_btwn_cmd)
        self._networking_api2.\
            wifi_disconnect(self._hotspot_ssid)

        # set wifi power off for phone2
        time.sleep(self._wait_btwn_cmd)
        self._networking_api2.set_wifi_power("off")

        # disable Portable wifi hotspot for Phone1
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_hotspot("off")

        # restore original wifi power status
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_power(self._original_wifi_power_status)

        # If Bt to be (de-)activated for FIT tests
        if self._bt_fit_used:

            bt_final_status = self._localconnectivity_api.get_bt_power_status()

            # if Bt is not at the initial value, set it to the correct one.
            if bt_final_status != self._bt_initial_state:
                # restore Bt in initial state
                self._localconnectivity_api.set_bt_power(
                    self._bt_initial_state)
                time.sleep(self._wait_btwn_cmd)

        return status, msg

#------------------------------------------------------------------------------

    def _get_bt_fit_config(self):
        """
        Get BT configuration for FIT BT/WIFI tests

        :rtype: list of 2 elements (boolean, str)
        :return: true if BT/WIFI FIT is used, Bluetooth state ON or OFF for the test to be run
        """

        # Read WHILE_BLUETOOTH_ON parameter (named for retro-compatibility)
        # from test case xml file for FIT tests
        param_while_bt_on = \
            str(self._tc_parameters.get_param_value("WHILE_BLUETOOTH_ON"))

        if param_while_bt_on.lower() in ["1", "on", "true", "yes"]:
            bt_fit_used = True
            bt_wished_value = 'STATE_ON'
        elif param_while_bt_on.lower() in ["0", "off", "false", "no"]:
            bt_fit_used = True
            bt_wished_value = 'STATE_OFF'
        else:
            bt_fit_used = False
            bt_wished_value = 'STATE_OFF'

        return bt_fit_used, bt_wished_value
class LabAudioGlitchDetectionBase(UseCaseBase):
    """
    AudioComms Audio CSV Call class.
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        # Call UseCaseBase Init function
        UseCaseBase.__init__(self, tc_name, global_config)

        # Create Audio Analyzer instance
        self._audio_analyzer = self._em.get_audio_analyzer("AudioAnalyzer")

        # Check if IO card is used
        self._use_io_card = str_to_bool(
            global_config.campaignConfig.get("isIoCardUsed"))

        # Create Whs
        if self._use_io_card:
            self._wired_headset = self._em.get_wired_headset("WiredHeadset")

        # Initialization of the test type
        self._test_type = "glitchdetection"

        # Initialization of test result
        self._result_verdict = Global.FAILURE

        # Initialization of the verdict comment
        self._verdict_comment = "Audio Glitch detection test fail"

        # Initialization of _dut_bt_address
        self._dut_bt_address = "None"

        # Read registrationTimeout from Device_Catalog.xml
        self._registration_timeout = \
            int(self._dut_config.get("registrationTimeout"))

        # Read callSetupTimeout from Device_Catalog.xml
        self._call_setup_time = \
            int(self._dut_config.get("callSetupTimeout"))

        # Read call origin type from test case xml file (str)
        self._call_origin_type = \
            str(self._tc_parameters.get_param_value("CALL_ORIGIN_TYPE"))

        # Read accessories type from test case xml file (str)
        self._acc_type = \
            str(self._tc_parameters.get_param_value("ACC_TYPE"))

        # Call Stream Volume in percent
        self._call_stream_volume_dut = \
            int(self._tc_parameters.get_param_value("CALL_VOLUME_DUT"))

        # Call Stream Volume in percent
        self._call_stream_volume_ref = \
            int(self._tc_parameters.get_param_value("CALL_VOLUME_REF"))

        # Read call end type from test case xml file (str)
        self._call_end_type = \
            str(self._tc_parameters.get_param_value("CALL_END_TYPE"))

        # Read call type from test case xml file (str)
        self._call_type = str(self._tc_parameters.get_param_value("CALL_TYPE"))

        # Read test call direction type from test case xml file (str)
        self._signal_tested_direction = \
            str(self._tc_parameters.get_param_value("SIGNAL_TESTED_DIRECTION"))

        # Read duration type from test case xml file (int)
        if self._tc_parameters.get_param_value("DURATION"):
            self._call_duration = int(
                self._tc_parameters.get_param_value("DURATION"))
        else:
            # Call duration by default
            self._call_duration = 5

        # Read Audio Analyzer parameters from bench config xml file (str)
        self._audio_analyzer_node = global_config.benchConfig.\
            get_parameters("AudioAnalyzer")
        self._bt_remote_addr = self._audio_analyzer_node.get_param_value(
            "Bt_mac_addr")

        # Instantiate generic UECmd for voiceCall Ucs
        self._phonemodem_api = self._device.get_uecmd("Modem")
        self._system_api = self._device.get_uecmd("System")

        if self._acc_type.find("BLUETOOTH") != -1:
            # Get UECmdLayer
            self._bt_api = self._device.get_uecmd("LocalConnectivity")

        # Load instance of the PHONE2
        self._phone2 = DeviceManager().get_device("PHONE2")
        # Instantiate system UECmd for Phone2
        self._system_api2 = None

    def set_up(self):
        """
        Set up the test configuration
        """

        # Call UseCaseBase Setup function
        UseCaseBase.set_up(self)

        # Check if we have the second phone available
        if self._phone2 is not None:
            if not self._phone2.is_available():
                self._phone2.switch_on(simple_switch_mode=True)
            self._system_api2 = self._phone2.get_uecmd("System")
        else:
            # We are using this multi UC with only one phone
            error_msg = \
                "This test case requires two phones to be executed !"
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     error_msg)

        # Swap 2G 3G or 4G.
        if self._call_type == "2G":
            self._networking_api.set_preferred_network_type(
                PreferredNetwork.GSM_ONLY)
        elif self._call_type == "3G":
            self._networking_api.set_preferred_network_type(
                PreferredNetwork.WCDMA_ONLY)
        elif self._call_type == "4G":
            self._networking_api.set_preferred_network_type(
                PreferredNetwork.LTE_ONLY)
        else:
            if self._call_type not in "VOIP":
                msg = "wrong value of parameter CALL TYPE"
                self._logger.error(msg)
                raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                         msg)

        # Audio Analyzer Initialization
        if self._audio_analyzer.initialization(self._device.get_phone_model(),
                                               self._test_type) != 0:
            error_msg = \
                "Audio Analyzer Initialization Failed !"
            self._logger.error(error_msg)
            raise TestEquipmentException(
                TestEquipmentException.OPERATION_FAILED, error_msg)

        if self._acc_type.find("BLUETOOTH") != -1:
            # Get dut bt address
            self._dut_bt_address = self._bt_api.get_bt_adapter_address()

    def run_test(self):
        """
        Execute the test
        """
        # Call UseCaseBase run_test function
        UseCaseBase.run_test(self)

        # Connect Bluetooth device
        if self._acc_type.find("BLUETOOTH") != -1:
            if self._audio_analyzer.connect_bt(self._acc_type,
                                               self._dut_bt_address) != 0:
                error_msg = \
                    "Connect Bluetooth failed !"
                self._logger.error(error_msg)
                raise TestEquipmentException(
                    TestEquipmentException.OPERATION_FAILED, error_msg)

    def tear_down(self):
        """
        End and dispose the test
        """

        # Call UseCaseBase tear_down function
        UseCaseBase.tear_down(self)

        # Reset Voice Call Volume at 70%
        if self._system_api is not None:
            self._system_api.adjust_specified_stream_volume("VoiceCall", 70)
        if self._system_api2 is not None:
            self._system_api2.adjust_specified_stream_volume("VoiceCall", 70)

    def __compute_test_verdict__(self, audio_analyzer_result):
        """
        Compute the result verdict and the verdict comment

        :type audio_analyzer_result: int
        :param audio_analyzer_result: the audio analyzer return code return by run command
        """

        if audio_analyzer_result == 0:
            self._result_verdict = Global.SUCCESS
            self._verdict_comment = (
                "Audio Glitch detection test success: in %s with "
                "a %s call and %s accessories" %
                (self._signal_tested_direction, self._call_type,
                 self._acc_type))
        elif audio_analyzer_result == 1:
            self._result_verdict = Global.FAILURE
            self._verdict_comment = (
                "Audio Glitch detection test fail: Audio Analyzer quality audio "
                "problems detected in %s with a %s call and "
                "%s accessories" % (self._signal_tested_direction,
                                    self._call_type, self._acc_type))
        elif audio_analyzer_result == 2:
            self._result_verdict = Global.FAILURE
            self._verdict_comment = (
                "Audio Glitch detection test fail: No audio signal in %s with "
                "a %s call and %s accessories" %
                (self._signal_tested_direction, self._call_type,
                 self._acc_type))
        else:
            self._result_verdict = Global.BLOCKED
            self._verdict_comment = (
                "Audio Glitch detection test fail: Audio Analyzer problems detected "
                "in %s with a %s call and %s accessories" %
                (self._signal_tested_direction, self._call_type,
                 self._acc_type))
class LabAudioActivityBase(UseCaseBase):
    """
    AudioComms Audio CSV Call class.
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        # Call UseCaseBase Init function
        UseCaseBase.__init__(self, tc_name, global_config)

        # Create Audio Analyzer
        self._audio_analyzer = self._em.get_audio_analyzer("AudioAnalyzer")

        # Check if IO card is used
        self._use_io_card = str_to_bool(
            global_config.campaignConfig.get("isIoCardUsed"))

        # Create Whs
        if self._use_io_card:
            self._wired_headset = self._em.get_wired_headset("WiredHeadset")

        # Initialization of test result
        self._result_verdict = Global.BLOCKED

        # Initialization of the verdict comment
        self._verdict_comment = "Audio Quality test fail"

        # Initialization of _dut_bt_address
        self._dut_bt_address = "None"

        # Read registrationTimeout from Device_Catalog.xml
        self._registration_timeout = \
            int(self._dut_config.get("registrationTimeout"))

        # Read callSetupTimeout from Device_Catalog.xml
        self._call_setup_time = \
            int(self._dut_config.get("callSetupTimeout"))

        # Read call origin type from test case xml file (str)
        self._call_origin_type = \
            str(self._tc_parameters.get_param_value("CALL_ORIGIN_TYPE"))

        # Read accessories type from test case xml file (str)
        self._acc_type = \
            str(self._tc_parameters.get_param_value("ACC_TYPE"))

        # Call Stream Volume in percent
        self._call_stream_volume_dut = \
            int(self._tc_parameters.get_param_value("CALL_VOLUME_DUT"))

        # Call Stream Volume in percent
        self._call_stream_volume_ref = \
            int(self._tc_parameters.get_param_value("CALL_VOLUME_REF"))

        # Read call end type from test case xml file (str)
        self._call_end_type = \
            str(self._tc_parameters.get_param_value("CALL_END_TYPE"))

        # Read call type from test case xml file (str)
        self._call_type = str(self._tc_parameters.get_param_value("CALL_TYPE"))

        # Read test call direction type from test case xml file (str)
        self._signal_tested_direction = \
            str(self._tc_parameters.get_param_value("SIGNAL_TESTED_DIRECTION"))

        # Read duration type from test case xml file (int)
        if self._tc_parameters.get_param_value("DURATION"):
            self._call_duration = int(
                self._tc_parameters.get_param_value("DURATION"))
        else:
            # Call duration by default
            self._call_duration = 5

        # Read Audio Analyzer parameters from bench config xml file (str)
        self._audio_analyzer_node = global_config.benchConfig. \
            get_parameters("AudioAnalyzer")

        # Initialization of the test type
        if self._audio_analyzer_node.get_param_value("Model") in "APx585":
            self._test_type = "audioactivity"
        elif self._audio_analyzer_node.get_param_value("Model") in "RS_UPV":
            self._test_type = self._name
        else:
            error_msg = \
                "Audio Analyzer model not supported or incorrect"
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     error_msg)

        # Instantiate generic UECmd for voiceCall Ucs
        self._phonemodem_api = self._device.get_uecmd("Modem")
        self._networking_api = self._device.get_uecmd("Networking")
        self._system_api = self._device.get_uecmd("System")
        self._phonesystem_api = self._device.get_uecmd("PhoneSystem")
        self._voice_call_api = self._device.get_uecmd("VoiceCall")

        if self._acc_type.find("BLUETOOTH") != -1:
            # Get UECmdLayer
            self._bt_api = self._device.get_uecmd("LocalConnectivity")

            # Get BT device MAC address
            self._bt_remote_addr = self._audio_analyzer_node.get_param_value(
                "Bt_mac_addr")

        # Load instance of the PHONE2
        self._phone2 = DeviceManager().get_device("PHONE2")
        # Instantiate system UECmd for Phone2
        self._system_api2 = None

        # Time elapsed during voice call
        self._elapsed_time = 0

        self._is_network_simulator_used = False

        # Time to wait between 2 successive measurement
        self._wait_between_measure = 0

        if "NETWORK_SIMULATOR1" in global_config.benchConfig.get_parameters_name(
        ):
            self._is_network_simulator_used = True
            # Read CELLULAR_NETWORK parameters from BenchConfig.xml
            self._network = \
                global_config.benchConfig.get_parameters("CELLULAR_NETWORK")
            self._apn = self._network.get_param_value("APN")
            self._ssid = self._network.get_param_value("SSID")
            self._ns_node = global_config.benchConfig.get_parameters(
                "NETWORK_SIMULATOR1")
            self._ns = self._em.get_cellular_network_simulator(
                "NETWORK_SIMULATOR1")

            if "2G" in self._call_type:
                self._ns_cell = self._ns.get_cell_2g()
            elif "3G" in self._call_type:
                self._ns_cell = self._ns.get_cell_3g()
            elif "4G" in self._call_type:
                self._ns_cell = self._ns.get_cell_4g()
            else:
                msg = "Wrong value for parameter CALL_TYPE (Must be one of the following: 2G, 3G, 4G)"
                self._logger.error(msg)
                raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                         msg)

            self._analog_input_peak_level = self._ns_node.get_param_value(
                "AnalogInputPeakLevel")
            self._analog_output_peak_level = self._ns_node.get_param_value(
                "AnalogOutputPeakLevel")

            self._vc = self._ns_cell.get_voice_call()

            # Read call parameters from test case xml file
            self._cell_band = \
                int(self._tc_parameters.get_param_value("CELL_BAND", 1))

            self._codec = str(self._tc_parameters.get_param_value("CODEC"))

            # In case of long lasting call, update the waiting time between measurements
            if self._call_duration > 60:
                # Read time between 2 successive measurement
                self._wait_between_measure = int(
                    self._tc_parameters.get_param_value(
                        "WAIT_BETWEEN_MEASURE"))

    def set_up(self):
        """
        Set up the test configuration
        """

        # Call UseCaseBase Setup function
        UseCaseBase.set_up(self)

        # Check if we have the second phone available
        if self._phone2 is not None:
            if not self._phone2.is_available():
                self._phone2.switch_on(simple_switch_mode=True)
            self._system_api2 = self._phone2.get_uecmd("System")

        # Audio Analyzer Initialization
        if self._audio_analyzer.initialization(self._device.get_phone_model(),
                                               self._test_type) != 0:
            error_msg = \
                "Audio Analyzer Initialization Failed !"
            self._logger.error(error_msg)
            raise TestEquipmentException(
                TestEquipmentException.OPERATION_FAILED, error_msg)

        if self._acc_type.find("BLUETOOTH") != -1:
            # Get dut bt address
            self._dut_bt_address = self._bt_api.get_bt_adapter_address()

        if self._is_network_simulator_used:
            # Perform network configuration
            # Connect to equipment
            self._ns.init()

            # Perform a full preset
            self._ns.perform_full_preset()

            # Flight mode activation
            self._networking_api.set_flight_mode("on")

            # Set cell off
            self._ns_cell.set_cell_off()

            if self._call_type in "2G" or self._call_type in "3G":
                # Set the APN
                time.sleep(self._wait_btwn_cmd)
                self._logger.info("Setting APN " + str(self._apn) + "...")
                self._networking_api.set_apn(self._ssid, self._apn)

            elif self._call_type in "4G":
                self._logger.info("Setting APN for IMS " + str(self._apn) +
                                  " on protocol IPV4 ")
                # APN for AP centric
                self._networking_api.set_apn(self._ssid, self._apn, None, None,
                                             "IP", None, "default")
                # APN for BP centric
                self._networking_api.set_apn("ims", "ims", None, None, "IP",
                                             None, "ims", False, False)

                # Load cell configuration
                self._ns.load_cell_config("COMMON_LTE")
                self._ns.load_cell_config(self._cell_band)

                # Load IMS server configuration
                self._ns.load_cell_config("COMMON_IMS")

                self._ns_cell.set_ims_on()

                time.sleep(10)
            else:
                msg = "Wrong value for parameter CALL_TYPE (Must be one of the following: 2G, 3G, 4G)"
                self._logger.error(msg)
                raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                         msg)

            # Perform audio configuration
            self._vc.set_audio_codec(self._codec)
            self._vc.set_speech_configuration("AUDioboard")
            self._vc.calibrate_analog_audio_level(
                self._analog_input_peak_level, self._analog_output_peak_level)

            if self._call_type in "4G":
                # Set DAU on
                self._ns_cell.get_data().set_epc_on()
                self._ns_cell.set_ims_on()

            # Set Cell on
            self._ns_cell.set_cell_on()

            # Phone has to see the cell off!
            self._phonemodem_api.check_cdk_no_registration_bfor_timeout(
                self._registration_timeout)

            # Flight mode deactivation
            self._networking_api.set_flight_mode("off")

            time.sleep(self._wait_btwn_cmd)

            # Check registration state is connected using
            # registrationTimeout from Device_Catalog.xml
            self._logger.info("Check registration state is connected")
            self._phonemodem_api.check_cdk_registration_bfor_timeout(
                self._registration_timeout)

            if self._call_type in "4G":
                # Check IMS connection state
                self._ns_cell.get_data().check_ims_connection_state(
                    "REG", self._registration_timeout)

            time.sleep(self._wait_btwn_cmd)

        else:

            # Swap 2G 3G or 4G.
            if self._call_type == "2G":
                self._networking_api.set_preferred_network_type(
                    PreferredNetwork.GSM_ONLY)
            elif self._call_type == "3G":
                self._networking_api.set_preferred_network_type(
                    PreferredNetwork.WCDMA_ONLY)
            elif self._call_type == "4G":
                self._networking_api.set_preferred_network_type(
                    PreferredNetwork.LTE_ONLY)
            else:
                if self._call_type not in "VOIP":
                    msg = "wrong value of parameter CALL TYPE"
                    self._logger.error(msg)
                    raise AcsConfigException(
                        AcsConfigException.INVALID_PARAMETER, msg)

        # Connect Bluetooth device
        if self._acc_type.find("BLUETOOTH") != -1:
            if self._audio_analyzer.connect_bt(self._acc_type,
                                               self._dut_bt_address) != 0:
                error_msg = \
                    "Connect Bluetooth failed !"
                self._logger.error(error_msg)
                raise DeviceException(DeviceException.OPERATION_FAILED,
                                      error_msg)

    def tear_down(self):
        """
        End and dispose the test
        """

        # Call UseCaseBase tear_down function
        UseCaseBase.tear_down(self)

        # Reset Voice Call Volume at 70%
        if self._system_api is not None:
            self._system_api.adjust_specified_stream_volume("VoiceCall", 70)
        if self._system_api2 is not None:
            self._system_api2.adjust_specified_stream_volume("VoiceCall", 70)

    def __compute_test_verdict__(self, apx_result):
        """
        Compute the result verdict and the verdict comment

        :type apx_result: int
        :param apx_result: the apx585 return code return by run command
        """

        if (apx_result == 0):
            self._result_verdict = Global.SUCCESS
            self._verdict_comment = ("Audio Quality test success: in %s with "
                                     "a %s call and %s accessories" %
                                     (self._signal_tested_direction,
                                      self._call_type, self._acc_type))
        elif (apx_result == 1):
            self._result_verdict = Global.FAILURE
            self._verdict_comment = (
                "Audio Quality test fail: APx585 quality audio "
                "problems detected in %s with a %s call and "
                "%s accessories" % (self._signal_tested_direction,
                                    self._call_type, self._acc_type))
        elif (apx_result == 2):
            self._result_verdict = Global.FAILURE
            self._verdict_comment = (
                "Audio Quality test fail: No audio signal in %s with "
                "a %s call and %s accessories" %
                (self._signal_tested_direction, self._call_type,
                 self._acc_type))
        elif (apx_result == 3):
            self._result_verdict = Global.BLOCKED
            self._verdict_comment = (
                "Audio Quality test fail: Apx585 executable exception occurred"
            )
        else:
            self._result_verdict = Global.BLOCKED
            self._verdict_comment = (
                "Audio Quality test fail: APx585 problems detected "
                "in %s with a %s call and %s accessories" %
                (self._signal_tested_direction, self._call_type,
                 self._acc_type))

    def _get_elapsed_time(self, time_stamp_start, time_stamp_current):
        """
        Get elapsed time between 2 time stamps

        :type time_stamp_start: time.struct_time
        :param time_stamp_start: reference time stamp
        :type time_stamp_current: time.struct_time
        :param time_stamp_current: current time stamp
        """
        elapsed_time = [
            3600 * 24 * 12 * 365, 3600 * 24 * 12, 3600 * 24, 3600, 60, 1
        ]

        for i in range(len(time_stamp_start) - 3):
            elapsed_time[i] *= time_stamp_current[i] - time_stamp_start[i]

        return sum(elapsed_time)
class LiveWifiTetheringRememberedSsid(LiveWifiTetheringBase):
    """
    Live wifi Tethering ping.
    """
    def __init__(self, tc_name, global_config):  # pylint: disable=W0231
        """
        Constructor
        """
        # Call USECASE BASE Init function
        LiveWifiTetheringBase.__init__(self, tc_name, global_config)  # pylint: disable=W0233

        # Get host spot configuration according HOTSPOT_SSID_BASENAME
        self._hotspot_ssid_basename = \
            str(self._tc_parameters.get_param_value("HOTSPOT_SSID_BASENAME"))

        # Get host spot configuration according HOTSPOT_SECURITIES
        self._hotspot_securities = \
            str(self._tc_parameters.get_param_value("HOTSPOT_SECURITIES"))
        self._hotspot_securities = self._hotspot_securities.split("|")

        # Get UECmdLayer
        self._networking_api = self._device.get_uecmd("Networking")

        # Get PHONE2
        self._networking_api2 = None
        self._phone2 = DeviceManager().get_device("PHONE2")
        if self._phone2 is not None:
            self._networking_api2 = self._phone2.get_uecmd("Networking")

        # init original wifi power status for phone1
        self._original_wifi_power_status = 0
        # init original flight mode for phone1
        self._original_flight_mode = 0
        self._interface_ip = None

        self._hotspot_ext_interface = \
            str(self._dut_config.get("hotspotExtInterface"))

        # Read the number of pings to do
        self._nb_pings = self._tc_parameters.get_param_value("PACKET_COUNT")

        # Read the data size of a packet
        self._packet_size = self._tc_parameters.get_param_value("PACKET_SIZE")

        # Get target % of received packet for ping
        self._target_ping_packet_loss_rate = \
            float(self._tc_parameters.get_param_value("TARGET_PACKET_LOSS_RATE"))

        self._waiting_time = \
            int(self._tc_parameters.get_param_value("DELAY_AFTER_PING"))

        # Get the IP server to ping
        self._server_ip = self._tc_parameters.\
            get_param_value("SERVER_TO_PING")
        self._server_2_ping = None

        # Set BT prerequisite (set ON, set OFF or nothing) for FIT BT/WIFI tests
        self._bt_fit_used, self._bt_wished_value = LiveWifiTetheringBase._get_bt_fit_config(
            self)
        # Instantiate generic UECmd
        self._localconnectivity_api = self._device.get_uecmd(
            "LocalConnectivity")
        self._bt_initial_state = 'STATE_ON'

#------------------------------------------------------------------------------

    def set_up(self):
        """
        Initialize the test
        """
        UseCaseBase.set_up(self)

        # Check if we have second wifi interface or second phone available
        if self._networking_api2 is None:
            msg = "PHONE2 is required in BenchConfig"
            self._logger.error(msg)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg)

        # store original wifi power status
        time.sleep(self._wait_btwn_cmd)
        self._original_wifi_power_status = \
            self._networking_api.get_wifi_power_status()

        # store original flight mode
        time.sleep(self._wait_btwn_cmd)
        self._original_flight_mode = self._networking_api.get_flight_mode()

        # Enable/Disable flight mode
        if str_to_bool_ex(self._original_flight_mode) != str_to_bool_ex(
                self._flight_mode):
            time.sleep(self._wait_btwn_cmd)
            self._networking_api.set_flight_mode(self._flight_mode)

        # Enable Cellular Data connection
        if self._flight_mode == False and self._is_pdp_context_activated:
            time.sleep(self._wait_btwn_cmd)
            self._networking_api.activate_pdp_context()

        # disable wifi for Phone1
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_power("off")
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_hotspot("off")

        # Boot the other phone (the DUT is already booted)
        if self._phone2.get_state() != "alive" \
                or not self._phone2.is_available():
            DeviceManager().boot_device("PHONE2")

        # If Bt to be (de-)activated for FIT tests
        if self._bt_fit_used:

            self._bt_initial_state = self._localconnectivity_api.get_bt_power_status(
            )

            # if Bt is not at the wished value, set it to the correct one.
            if self._bt_initial_state != self._bt_wished_value:
                self._localconnectivity_api.set_bt_power(self._bt_wished_value)
                time.sleep(self._wait_btwn_cmd)

        # set wifi power on for Phone2
        time.sleep(self._wait_btwn_cmd)
        self._networking_api2.set_wifi_power("on")

        # disconnect all wifi for Phone2
        time.sleep(self._wait_btwn_cmd)
        self._networking_api2.wifi_remove_config("all")

        # Set networks as remembered SSIDs
        for security in self._hotspot_securities:

            # Build the SSID name
            ssid = self._hotspot_ssid_basename + "_" + security

            # set ssid for Phone2 as remembered network
            time.sleep(self._wait_btwn_cmd)
            self._networking_api2.set_wificonfiguration(
                ssid, self._hotspot_passphrase, security)

        # Need to restart Wifi interface to enable SSIDs
        self._networking_api2.set_wifi_power(0)
        time.sleep(self._wait_btwn_cmd)
        self._networking_api2.set_wifi_power(1)
        time.sleep(self._wait_btwn_cmd)
        self._networking_api2.set_wifi_sleep_policy(
            self._networking_api.WIFI_SLEEP_POLICY["NEVER"])

        return Global.SUCCESS, "No error"

#------------------------------------------------------------------------------

    def run_test(self):
        """
        Execute the test
        """
        UseCaseBase.run_test(self)

        self._error.Msg = ""
        self._error.Code = Global.SUCCESS

        for security in self._hotspot_securities:

            # Build the SSID name
            ssid = self._hotspot_ssid_basename + "_" + security

            # enable Portable wifi hotspot for Phone1
            time.sleep(self._wait_btwn_cmd)
            self._networking_api.set_wifi_hotspot("off")
            time.sleep(self._wait_btwn_cmd)
            self._networking_api.set_wifi_hotspot("on", ssid, security,
                                                  self._hotspot_passphrase)

            # Wait for the PHONE2 to auto connect
            self._logger.info("Waiting 60 sec for the connection to establish")
            time.sleep(60)
            self._networking_api2.check_connection_state(ssid)

            # Correct the IP server 2 ping if necessary, once
            if self._server_2_ping is None:
                if str(self._server_ip) in ["None", ""] or self._flight_mode:
                    # Get the IP of the softAP wifi interface
                    self._server_2_ping = self._networking_api.\
                        get_interface_ipv4_address(self._hotspot_ext_interface)

                    if str(self._server_ip) not in ["None", ""] \
                            and self._flight_mode:
                        # Display a warning because the given parameter
                        # cannot be used
                        self._logger.warning("IP server set as parameter " +
                                             "is ignored, as test is run " +
                                             "in flight mode. Using SoftAP" +
                                             " IP instead (%s)" %
                                             self._server_2_ping)
                else:
                    self._server_2_ping = self._server_ip

            # ping phone1 from phone2
            packet_loss = self._networking_api2.ping(self._server_2_ping,
                                                     self._packet_size,
                                                     self._nb_pings)

            msg = "[%s] Measured Packet Loss: %.0f%s (Target: %.0f%s) - " \
                % (security,
                  packet_loss.value,
                  packet_loss.units,
                  self._target_ping_packet_loss_rate,
                  packet_loss.units)
            self._logger.info(msg)
            self._error.Msg += msg

            # Compute verdict depending on % of packet loss
            if packet_loss.value > self._target_ping_packet_loss_rate:
                msg = "Ping packet loss is not acceptable [%s]" \
                    % str(packet_loss.value)
                self._logger.error(msg)
                raise DeviceException(DeviceException.OPERATION_FAILED, msg)

            if self._waiting_time > 0:
                self._logger.info("Waiting for %s sec" %
                                  str(self._waiting_time))
                time.sleep(self._waiting_time)

        return self._error.Code, self._error.Msg

    def tear_down(self):
        """
        End and dispose the test
        """
        LiveWifiTetheringBase.tear_down(self)

        if self._networking_api2 is not None:
            # disconnect from hotspot for Phone2
            time.sleep(self._wait_btwn_cmd)
            self._networking_api2.wifi_remove_config("all")

            # set wifi power off for phone2
            time.sleep(self._wait_btwn_cmd)
            self._networking_api2.set_wifi_power("off")

        # disable Portable wifi hotspot for Phone1
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_hotspot("off")

        return Global.SUCCESS, "No error"
class LabAudioQualityAccessoriesChangeBase(UseCaseBase):
    """
    AudioComms Audio CSV Call Accessories Change class.
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        # Call UseCaseBase Init function
        UseCaseBase.__init__(self, tc_name, global_config)

        # Create Audio Analyzer
        self._audio_analyzer = self._em.get_audio_analyzer("AudioAnalyzer")

        # Check if IO card is used
        self._use_io_card = str_to_bool(
            global_config.campaignConfig.get("isIoCardUsed"))

        # Create Whs
        if self._use_io_card:
            self._wired_headset = self._em.get_wired_headset("WiredHeadset")

        # Initialization of the test type
        self._test_type = "audioquality"

        # Initialization of accessories type
        self._acc_type = "None"
        self._previous_acc_type = "None"

        # Initialization of audio_analyzer_result saved
        self._audio_analyzer_result_save = 0
        self._audio_analyzer_result_ul = 0
        self._audio_analyzer_result_dl = 0

        # Initialization of failed transition saved
        self._failed_transition_audio_pb = ""
        self._failed_transition_no_audio = ""

        # Initialization of _dut_bt_address
        self._dut_bt_address = "None"

        # Initialization of test result
        self._result_verdict = Global.SUCCESS

        # Initialization of the verdict comment
        self._verdict_comment = "Audio Quality test fail"

        # Read registrationTimeout from Device_Catalog.xml
        self._registration_timeout = \
            int(self._dut_config.get("registrationTimeout"))

        # Read callSetupTimeout from Device_Catalog.xml
        self._call_setup_time = \
            int(self._dut_config.get("callSetupTimeout"))

        # Read call origin type from test case xml file (str)
        self._call_origin_type = str(
            self._tc_parameters.get_param_value("CALL_ORIGIN_TYPE"))

        # Read accessories list from test case xml file (str)
        self._acc_list = str(self._tc_parameters.get_param_value("ACC_LIST"))
        # Split the accessories list, accessories separated by ','
        self._acc_list = self._acc_list.strip('[] ')
        self._acc_list_split = self._acc_list.split(',')
        self._acc_list_split.reverse()

        # Read accessories active list from test case xml file (str)
        self._acc_active_list = str(
            self._tc_parameters.get_param_value("ACC_ACTIVE_LIST"))
        # Split the accessories active list, accessories separated by ','
        self._acc_active_list = self._acc_active_list.strip('[] ')
        self._acc_active_list_split = self._acc_active_list.split(',')
        self._acc_active_list_split.reverse()

        # Call Stream Volume in percent
        self._call_stream_volume_dut_list = \
            str(self._tc_parameters.get_param_value("CALL_VOLUME_DUT_LIST"))
        # Split the accessories list, accessories separated by ','
        self._call_stream_volume_dut_list = self._call_stream_volume_dut_list.strip(
            '[] ')
        self._call_volume_dut_list_split = self._call_stream_volume_dut_list.split(
            ',')
        self._call_volume_dut_list_split.reverse()

        # Call Stream Volume in percent
        self._call_stream_volume_ref_list = \
            str(self._tc_parameters.get_param_value("CALL_VOLUME_REF_LIST"))
        # Split the accessories list, accessories separated by ','
        self._call_stream_volume_ref_list = self._call_stream_volume_ref_list.strip(
            '[] ')
        self._call_volume_ref_list_split = self._call_stream_volume_ref_list.split(
            ',')
        self._call_volume_ref_list_split.reverse()

        # Read call end type from test case xml file (str)
        self._call_end_type = str(
            self._tc_parameters.get_param_value("CALL_END_TYPE"))

        # Read call type from test case xml file (str)
        self._call_type = str(self._tc_parameters.get_param_value("CALL_TYPE"))

        # Read test call direction type from test case xml file (s tring)
        self._signal_tested_direction = \
            str(self._tc_parameters.get_param_value("SIGNAL_TESTED_DIRECTION"))

        # Read duration type from test case xml file (int)
        if self._tc_parameters.get_param_value("DURATION"):
            self._call_duration = int(
                self._tc_parameters.get_param_value("DURATION"))
        else:
            # Call duration by default
            self._call_duration = 5

        # Read Audio Analyzer parameters from bench config xml file (str)
        self._audio_analyzer_node = global_config.benchConfig.\
            get_parameters("AudioAnalyzer")
        self._bt_remote_addr = self._audio_analyzer_node.get_param_value(
            "Bt_mac_addr")

        # Instantiate generic UECmd for voiceCall Ucs
        self._system_api = self._device.get_uecmd("System")
        self._networking_api = self._device.get_uecmd("Networking")

        # Bluetooth present in the list accessories
        if self._acc_list.count("BLUETOOTH") > 0:
            # Get UECmdLayer
            self._bt_api = self._device.get_uecmd("LocalConnectivity")

        # Load instance of the PHONE2
        self._phone2 = DeviceManager().get_device("PHONE2")
        self._system_api2 = None

        self._acc_swap_type = self._tc_parameters.get_param_value(
            "ACC_SWAP_TYPE", 'Default')

        # Copy of accessories list
        self._temp_acc_list_split = None

        # Copy of volume list / active accessory list
        self._temp_call_volume_dut_list_split = None
        self._temp_call_volume_ref_list_split = None
        self._temp_acc_active_list_split = None

    def set_up(self):
        """
        Set up the test configuration
        """

        # Call UseCaseBase Setup function
        UseCaseBase.set_up(self)

        # Check if we have the second phone available
        if self._phone2 is not None:
            if not self._phone2.is_available():
                self._phone2.switch_on(simple_switch_mode=True)
            self._system_api2 = self._phone2.get_uecmd("System")
        else:
            # We are using this multi UC with only one phone
            error_msg = \
                "This test case requires two phones to be executed !"
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     error_msg)

        # Swap 2G 3G or 4G.
        if self._call_type == "2G":
            self._networking_api.set_preferred_network_type(
                PreferredNetwork.GSM_ONLY)
        elif self._call_type == "3G":
            self._networking_api.set_preferred_network_type(
                PreferredNetwork.WCDMA_ONLY)
        elif self._call_type == "4G":
            self._networking_api.set_preferred_network_type(
                PreferredNetwork.LTE_ONLY)
        else:
            if self._call_type not in "VOIP":
                msg = "wrong value of parameter CALL TYPE"
                self._logger.error(msg)
                raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                         msg)

        # Audio Analyzer Initialization
        if self._audio_analyzer.initialization(self._device.get_phone_model(),
                                               self._test_type) != 0:
            error_msg = \
                "Audio Analyzer Initialization Failed !"
            self._logger.error(error_msg)
            raise TestEquipmentException(
                TestEquipmentException.OPERATION_FAILED, error_msg)

        if self._acc_list.count("BLUETOOTH") > 0:
            # Get dut bt address
            self._dut_bt_address = self._bt_api.get_bt_adapter_address()

            # Push the first Bluetooth accessories in first
            l_bluetooth_acc_position = 0
            for i in self._acc_list_split:
                if i.find("BLUETOOTH") != -1:
                    # Initialization of _acc_type with the bluetooth accessories
                    self._acc_type = i
                    self._acc_list_split.insert(len(self._acc_list_split), i)
                    self._acc_active_list_split.insert(
                        len(self._acc_active_list_split),
                        self._acc_active_list_split[l_bluetooth_acc_position])
                    self._call_volume_ref_list_split.insert(
                        len(self._call_volume_ref_list_split), self.
                        _call_volume_ref_list_split[l_bluetooth_acc_position])
                    self._call_volume_dut_list_split.insert(
                        len(self._call_volume_dut_list_split), self.
                        _call_volume_dut_list_split[l_bluetooth_acc_position])
                    break
                l_bluetooth_acc_position += 1

            # Connect Bluetooth device
            if self._audio_analyzer.connect_bt(self._acc_type,
                                               self._dut_bt_address) != 0:
                error_msg = \
                    "Connect Bluetooth failed !"
                self._logger.error(error_msg)
                raise DeviceException(DeviceException.OPERATION_FAILED,
                                      error_msg)

        return Global.SUCCESS, "No errors"

    def tear_down(self):
        """
        End and dispose the test
        """

        # Call UseCaseBase tear_down function
        UseCaseBase.tear_down(self)

        # Reset Voice Call Volume at 50%
        if self._system_api is not None:
            self._system_api.adjust_specified_stream_volume("VoiceCall", 70)
        if self._system_api2 is not None:
            self._system_api2.adjust_specified_stream_volume("VoiceCall", 70)

        return Global.SUCCESS, "No errors"

    def _compute_test_verdict_(self, audio_analyzer_result_ul,
                               audio_analyzer_result_dl):
        """
        Computes the test verdict for audio accessory change
        :type audio_analyzer_result_dl: int
        :param audio_analyzer_result_dl: result value for the DL audio test given by the audio analyzer
        :type audio_analyzer_result_ul: int
        :param audio_analyzer_result_ul: result value for the UL audio test given by the audio analyzer

        :return: None
        """

        if self._audio_analyzer_result_save == 3:
            self._result_verdict = Global.BLOCKED
        elif self._audio_analyzer_result_save == 2:
            if (audio_analyzer_result_ul == 3) or (audio_analyzer_result_dl
                                                   == 3):
                self._result_verdict = Global.BLOCKED
                self._failed_transition_no_audio = self._failed_transition_no_audio + ", " + \
                    self._previous_acc_type + " => " + self._acc_type
                self._audio_analyzer_result_save = 3
            elif (audio_analyzer_result_ul == 2) or (audio_analyzer_result_dl
                                                     == 2):
                self._result_verdict = Global.FAILURE
                self._failed_transition_no_audio = self._failed_transition_no_audio + ", " + \
                    self._previous_acc_type + " => " + self._acc_type
                self._audio_analyzer_result_save = 2
        elif self._audio_analyzer_result_save == 1:
            if (audio_analyzer_result_ul == 3) or (audio_analyzer_result_dl
                                                   == 3):
                self._result_verdict = Global.BLOCKED
                self._failed_transition_no_audio = self._failed_transition_no_audio + ", " + \
                    self._previous_acc_type + " => " + self._acc_type
                self._audio_analyzer_result_save = 3
            elif (audio_analyzer_result_ul == 2) or (audio_analyzer_result_dl
                                                     == 2):
                self._result_verdict = Global.FAILURE
                self._failed_transition_no_audio = self._failed_transition_no_audio + ", " + \
                    self._previous_acc_type + " => " + self._acc_type
                self._audio_analyzer_result_save = 2
            elif (audio_analyzer_result_ul == 1) or (audio_analyzer_result_dl
                                                     == 1):
                self._result_verdict = Global.FAILURE
                self._failed_transition_audio_pb = self._failed_transition_audio_pb + ", " + \
                    self._previous_acc_type + " => " + self._acc_type
        elif self._audio_analyzer_result_save == 0:
            if (audio_analyzer_result_ul == 3) or (audio_analyzer_result_dl
                                                   == 3):
                self._result_verdict = Global.BLOCKED
                self._failed_transition_no_audio = self._failed_transition_no_audio + ", " + \
                    self._previous_acc_type + " => " + self._acc_type
                self._audio_analyzer_result_save = 3
            elif (audio_analyzer_result_ul == 2) or (audio_analyzer_result_dl
                                                     == 2):
                self._result_verdict = Global.FAILURE
                self._failed_transition_no_audio = self._failed_transition_no_audio + ", " + \
                    self._previous_acc_type + " => " + self._acc_type
                self._audio_analyzer_result_save = 2
            elif (audio_analyzer_result_ul == 1) or (audio_analyzer_result_dl
                                                     == 1):
                self._result_verdict = Global.FAILURE
                self._failed_transition_audio_pb = self._failed_transition_audio_pb + ", " + \
                    self._previous_acc_type + " => " + self._acc_type
                self._audio_analyzer_result_save = 1
        else:
            self._audio_analyzer_result_save = 0
            self._result_verdict = Global.SUCCESS

        # Now, the verdict comment will be updated, according to the outcome of the audio test
        if self._audio_analyzer_result_save == 0:
            self._verdict_comment = (
                "Audio Quality test success: in %s with "
                "a %s call with %s accessories sequence" %
                (self._signal_tested_direction, self._call_type,
                 str(self._tc_parameters.get_param_value("ACC_LIST"))))
        elif self._audio_analyzer_result_save == 1:
            self._verdict_comment = (
                "Audio Quality test fail: Audio Analyzer quality audio "
                "problems detected in %s with a %s call with "
                "%s accessories sequence" %
                (self._signal_tested_direction, self._call_type,
                 self._failed_transition_audio_pb))
        elif self._audio_analyzer_result_save == 2:
            self._verdict_comment = (
                "Audio Quality test fail: No audio signal in %s with "
                "a %s call with %s accessories sequence" %
                (self._signal_tested_direction, self._call_type,
                 self._failed_transition_no_audio))
        elif self._audio_analyzer_result_save == 3:
            self._verdict_comment = (
                "Audio Quality test fail: Exception in executable in %s with "
                "a %s call with %s accessories sequence" %
                (self._signal_tested_direction, self._call_type,
                 self._failed_transition_no_audio))
        else:
            self._verdict_comment = (
                "Audio Quality test fail: Audio Analyzer problems detected "
                "in %s with a %s call" %
                (self._signal_tested_direction, self._call_type))
class LabAudioGlitchDetectionSwapCall(UseCaseBase):
    """
    AudioComms Audio Swap Call class.
    """
    def __compute_test_verdict__(self, audio_analyzer_result):

        if audio_analyzer_result == 0 and self._audio_analyzer_result_save == 0:
            self._result_verdict = Global.SUCCESS
        elif audio_analyzer_result == 1:
            # Update audio_analyser_result => error code 1 lower priority than error code 2
            if self._audio_analyzer_result_save == 0 or self._audio_analyzer_result_save == 3:
                self._audio_analyzer_result_save = 1
            # Save failed transition
            self._failed_transition_audio_pb = self._failed_transition_audio_pb + ", " + \
                self._previous_call_type_save + " => " + self._call_type_save
            self._result_verdict = Global.FAILURE
        elif audio_analyzer_result == 2:
            self._audio_analyzer_result_save = 2
            self._failed_transition_no_audio = self._failed_transition_no_audio + ", " + \
                self._previous_call_type_save + " => " + self._call_type_save
            self._result_verdict = Global.FAILURE
        elif audio_analyzer_result == 3:
            self._audio_analyzer_result_save = 3
            self._result_verdict = Global.FAILURE
            self._failed_transition_no_audio = self._failed_transition_no_audio + ", " + \
                self._previous_call_type_save + " => " + self._call_type_save
        else:
            if self._audio_analyzer_result_save == 0:
                self._audio_analyzer_result_save = 4
            self._result_verdict = Global.FAILURE

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        # Call UseCaseBase Init function
        UseCaseBase.__init__(self, tc_name, global_config)

        # Create Audio Analyser
        self._audio_analyzer = self._em.get_audio_analyzer("AudioAnalyzer")

        # Check if IO card is used
        self._use_io_card = str_to_bool(
            global_config.campaignConfig.get("isIoCardUsed"))

        # Create Whs
        if self._use_io_card:
            self._wired_headset = self._em.get_wired_headset("WiredHeadset")

        # Initialization of the test type
        self._test_type = "glitchdetectiononswap"

        # Initialization of test result
        self._result_verdict = Global.FAILURE

        # Initialization of the verdict comment
        self._verdict_comment = "Audio Quality test fail"

        # Initialization of _dut_bt_address
        self._dut_bt_address = "None"

        # Initialization of audio_analyser_result saved
        self._audio_analyzer_result_save = 0
        self._audio_analyzer_result_ul = 0
        self._audio_analyzer_result_dl = 0

        # delta volume for voip
        self._delta_voip_volume = 10

        # Initialization of failed transition saved
        self._failed_transition_audio_pb = ""
        self._failed_transition_no_audio = ""
        self._previous_call_type_save = ""
        self._call_type_save = ""

        self._phone_calling_list = []
        self._phone_receiving_list = []
        self._phone_releasing_list = []
        self._ui_api_phone_list = []
        self._calling_phone_number = []
        # List Saving
        self._saved_call_list = []
        self._saved_call_end_type_list = []
        self._saved_call_origin_type_list = []
        self._call_type_list_audio_analyser_run = []

        # Instantiate the instances for phone caller, receiver and releaser
        self._phone_calling = None
        self._phone_receiving = None

        # Read registrationTimeout from Device_Catalog.xml
        self._registration_timeout = \
            int(self._dut_config.get("registrationTimeout"))

        # Read callSetupTimeout from Device_Catalog.xml
        self._call_setup_time = \
            int(self._dut_config.get("callSetupTimeout"))

        # Read wifi parameters from bench config xml file (int)
        self._wifirouter = global_config.benchConfig.\
            get_parameters("WIFI_ACCESS_POINT")
        self._ssid = self._wifirouter.get_param_value("SSID")

        # Read accessories type from test case xml file (str)
        self._acc_type = \
            str(self._tc_parameters.get_param_value("ACC_TYPE"))

        # Read call type list from test case xml file (str)
        self._call_seq = str(
            self._tc_parameters.get_param_value("CALL_SEQUENCE"))
        # Split the call type list, call separated by ','
        self._call_seq = self._call_seq.strip('[] ')
        self._call_list = self._call_seq.split(',')
        self._call_list.reverse()

        # Read call origin list from test case xml file (str)
        self._call_origin_type = \
            str(self._tc_parameters.get_param_value("CALL_ORIGIN_TYPE_SEQUENCE"))
        # Split the call origin type list, call origin type separated by ','
        self._call_origin_type = self._call_origin_type.strip('[] ')
        self._call_origin_type_list = self._call_origin_type.split(',')
        self._call_origin_type_list.reverse()

        # Read call end type list from test case xml file (str)
        self._call_end_type = \
            str(self._tc_parameters.get_param_value("CALL_END_TYPE_SEQUENCE"))
        # Split the call end type list, call end type separated by ','
        self._call_end_type = self._call_end_type.strip('[] ')
        self._call_end_type_list = self._call_end_type.split(',')
        self._call_end_type_list.reverse()

        # Read call type from test case xml file (str)
        self._call_type = str(self._tc_parameters.get_param_value("CALL_TYPE"))

        # Call Stream Volume in percent
        self._call_stream_volume_dut = \
            int(self._tc_parameters.get_param_value("CALL_VOLUME_DUT"))

        # Call Stream Volume in percent
        self._call_stream_volume_ref = \
            int(self._tc_parameters.get_param_value("CALL_VOLUME_REF"))

        # Read duration type from test case xml file (int)
        if self._tc_parameters.get_param_value("DURATION"):
            self._call_duration = int(
                self._tc_parameters.get_param_value("DURATION"))
        else:
            # Call duration by default
            self._call_duration = 5

        # Read number of swap from test case xml file (int)
        self._number_of_swap = int(
            self._tc_parameters.get_param_value("SWAP_REPETITION"))

        # Read dut sip address from test case xml file (str)
        self._dut_sip_address = \
            str(self._tc_parameters.get_param_value("DUT_SIP_ADDRESS"))

        # Read ref phone sip address from test case xml file (str)
        self._peer_sip_address = \
            str(self._tc_parameters.get_param_value("PEER_SIP_ADDRESS"))

        # Read dut sip profile name from test case xml file (str)
        self._dut_sip_profile = \
            str(self._tc_parameters.get_param_value("DUT_SIP_PROFILE"))

        # Read ref phone sip profile name from test case xml file (str)
        self._peer_sip_profile = \
            str(self._tc_parameters.get_param_value("PEER_SIP_PROFILE"))

        # Read test call direction type from test case xml file (str)
        self._signal_tested_direction = \
            str(self._tc_parameters.get_param_value("SIGNAL_TESTED_DIRECTION"))

        # Read Audio Analyzer parameters from bench config xml file (str)
        self._audio_analyser = global_config.benchConfig.\
            get_parameters("AudioAnalyzer")
        self._bt_remote_addr = self._audio_analyser.get_param_value(
            "Bt_mac_addr")

        # Instantiate generic UECmd for voiceCall Ucs
        self._voice_call_api = self._device.get_uecmd("VoiceCall")
        self._phonesystem_api = self._device.get_uecmd("PhoneSystem")
        self._sip_call_api = self._device.get_uecmd("SipCall")
        self._phonemodem_api = self._device.get_uecmd("Modem")
        self._system_api = self._device.get_uecmd("System")
        self._networking_api = self._device.get_uecmd("Networking")
        self._ui_api = self._device.get_uecmd("Ui")
        self._ui_api.set_global_config(global_config)

        # Read Audio Analyzer parameters from bench config xml file (str)
        self._audio_analyser = global_config.benchConfig.get_parameters(
            "AudioAnalyzer")

        if self._acc_type.find("BLUETOOTH") != -1:
            # Get UECmdLayer
            self._bt_api = self._device.get_uecmd("LocalConnectivity")
            self._bt_remote_addr = self._audio_analyser.get_param_value(
                "Bt_mac_addr")

        # Load instance of the PHONE2
        self._phone2 = DeviceManager().get_device("PHONE2")
        # Instantiate system UECmd for Phone2
        self._system_api2 = None

        # Initialize UI object
        self._ui_api.init()

        # Connect the board
        self._device.connect_board()

        if self._phone2 is not None:
            if not self._phone2.is_available():
                self._phone2.switch_on(simple_switch_mode=True)
            self._voice_call_api2 = self._phone2.get_uecmd("VoiceCall")
            self._sip_call_api2 = self._phone2.get_uecmd("SipCall")
            self._ui_api2 = self._phone2.get_uecmd("Ui")
            self._ui_api2.set_global_config(global_config)
            self._system_api2 = self._phone2.get_uecmd("System")
            self._networking_api2 = self._phone2.get_uecmd("Networking")
            self._phonesystem_api2 = self._phone2.get_uecmd("PhoneSystem")
            self._ui_api2.init()
        else:
            error_msg = \
                "This test case requires two phones to be executed !"
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     error_msg)

    def set_up(self):
        """
        Set up the test configuration
        """
        # Call UseCaseBase Setup function
        UseCaseBase.set_up(self)

        # Check if we have the second phone available
        if self._phone2 is None:
            # We are using this multi UC with only one phone
            error_msg = \
                "This test case requires two phones to be executed !"
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     error_msg)

        self._phonesystem_api.wake_screen()
        # Swap 2G 3G or 4G.
        if self._call_type == "2G":
            self._networking_api.set_preferred_network_type(
                PreferredNetwork.GSM_ONLY)
        elif self._call_type == "3G":
            self._networking_api.set_preferred_network_type(
                PreferredNetwork.WCDMA_ONLY)
        elif self._call_type == "4G":
            self._networking_api.set_preferred_network_type(
                PreferredNetwork.LTE_ONLY)
        else:
            if self._call_type not in "VOIP":
                msg = "wrong value of parameter CALL TYPE"
                self._logger.error(msg)
                raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                         msg)

        # List Saving
        self._saved_call_list = list(self._call_list)
        self._saved_call_end_type_list = list(self._call_end_type_list)
        self._saved_call_origin_type_list = list(self._call_origin_type_list)

        # make list for call test type for audio_analyser
        l_temp_call_list = list(self._call_list)
        l_temp_call_list.reverse()
        self._call_type_list_audio_analyser_run = list(l_temp_call_list)
        num_of_swap_unpair = self._number_of_swap % 2
        i = self._number_of_swap
        while i > 1:
            self._call_type_list_audio_analyser_run += list(l_temp_call_list)
            i -= 1
        if num_of_swap_unpair > 0:
            # Grep last element of call list and insert at the top
            self._call_type_list_audio_analyser_run.insert(
                0, l_temp_call_list.pop())
        i = 1
        # Initialization of list for calling, receiving and releasing calls
        while len(self._saved_call_list) > 0:
            call_type = self._saved_call_list.pop()
            call_origin = self._saved_call_origin_type_list.pop()
            call_end = self._saved_call_end_type_list.pop()
            if call_origin == "MO":
                self._phone_calling_list.insert(i, self._voice_call_api)
                self._phone_receiving_list.insert(i, self._voice_call_api2)
                self._ui_api_phone_list.insert(i, self._ui_api2)
                if call_type == "2G" or call_type == "3G":
                    self._calling_phone_number.insert(
                        i, self._phone2.get_phone_number())
                elif call_type == "VOIP":
                    self._calling_phone_number.insert(i,
                                                      self._peer_sip_address)
                else:
                    error_msg = "This test case requires call type to be executed !"
                    self._logger.error(error_msg)
                    raise AcsConfigException(
                        AcsConfigException.INVALID_PARAMETER, error_msg)
            elif call_origin == "MT":
                self._phone_calling_list.insert(i, self._voice_call_api2)
                self._phone_receiving_list.insert(i, self._voice_call_api)
                self._ui_api_phone_list.insert(i, self._ui_api)
                if call_type == "2G" or call_type == "3G":
                    self._calling_phone_number.insert(
                        i, self._device.get_phone_number())
                elif call_type == "VOIP":
                    self._calling_phone_number.insert(i, self._dut_sip_address)
                else:
                    error_msg = "This test case requires call type to be executed !"
                    self._logger.error(error_msg)
                    raise AcsConfigException(
                        AcsConfigException.INVALID_PARAMETER, error_msg)
            else:
                error_msg = \
                    "This test case requires call originated type to be executed !"
                self._logger.error(error_msg)
                raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                         error_msg)

            if call_end == "NR":
                self._phone_releasing_list.insert(i, self._voice_call_api2)
            elif call_end == "MR":
                self._phone_releasing_list.insert(i, self._voice_call_api)
            else:
                error_msg = \
                    "This test case requires call end type to be executed !"
                self._logger.error(error_msg)
                raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                         error_msg)
            i += 1

        self._activate_wifi = False
        while len(self._saved_call_list) > 0:
            call_type = self._saved_call_list.pop()
            if call_type == "VOIP":
                self._activate_wifi = True
        if self._activate_wifi == True:
            if self._networking_api.get_wifi_power_status() == 0:
                # Turn Wifi interface ON
                self._networking_api.set_wifi_power("off")
                self._networking_api.set_wifi_power("on")
                # Configure the DUT
                self._networking_api.clean_all_data_connections()
                time.sleep(self._wait_btwn_cmd)
                # Connect to wifi using SSID parameter value for DUT
                self._networking_api.wifi_connect(self._ssid)
                time.sleep(self._wait_btwn_cmd)
            if self._networking_api2.get_wifi_power_status() == 0:
                self._networking_api2.set_wifi_power("off")
                self._networking_api2.set_wifi_power("on")
                self._networking_api2.clean_all_data_connections()
                time.sleep(self._wait_btwn_cmd)
                # Connect to wifi using SSID parameter value for Ref phone
                self._networking_api2.wifi_connect(self._ssid)
                time.sleep(self._wait_btwn_cmd)

        self._phonesystem_api.set_screen_timeout(900)
        self._phonesystem_api2.set_screen_timeout(900)

        # Audio Analyser Initialization
        if self._audio_analyzer.initialization(self._device.get_phone_model(),
                                               self._test_type) != 0:
            error_msg = "Audio Analyser Initialization Failed !"
            self._logger.error(error_msg)
            raise TestEquipmentException(
                TestEquipmentException.OPERATION_FAILED, error_msg)

        if self._acc_type.find("BLUETOOTH") != -1:
            self._dut_bt_address = self._bt_api.get_bt_adapter_address()

        self._sip_call_api.set_profile_sip_phone_app(self._dut_sip_profile)
        self._sip_call_api2.set_profile_sip_phone_app(self._peer_sip_profile)

        self._phone_calling_list.reverse()
        self._phone_receiving_list.reverse()
        self._phone_releasing_list.reverse()
        # self._calling_phone_number_list.reverse()
        self._ui_api_phone_list.reverse()
        self._calling_phone_number.reverse()

        # Release any previous call (Robustness)
        self._voice_call_api.release()
        self._voice_call_api2.release()

        return Global.SUCCESS, "No errors"

    def run_test(self):
        """
        Execute the test
        """
        # Call UseCaseBase run_test function
        UseCaseBase.run_test(self)

        if self._acc_type == "HEADSET":
            if self._use_io_card:
                self._wired_headset.unplug_headphone()
                self._wired_headset.plug_whs()
        elif self._acc_type == "HEADPHONE":
            if self._use_io_card:
                self._wired_headset.unplug_whs()
                self._wired_headset.plug_headphone()

        # Connect Bluetooth device
        if self._acc_type.find("BLUETOOTH") != -1:
            if self._audio_analyzer.connect_bt(self._acc_type,
                                               self._dut_bt_address) != 0:
                error_msg = \
                    "Connect Bluetooth failed !"
                self._logger.error(error_msg)
                raise DeviceException(DeviceException.OPERATION_FAILED,
                                      error_msg)

        self._phonesystem_api.display_off()
        self._phonesystem_api2.display_off()
        self._phonesystem_api.display_on()
        self._phonesystem_api2.display_on()
        # Unlock phones
        self._ui_api2.run_operation_set("phone_unlock")
        self._ui_api.run_operation_set("phone_unlock")

        l_audio_analyzer_result = 3
        l_call_type = self._call_list.pop()
        l_phone_calling = self._phone_calling_list.pop()
        l_phone_receiving = self._phone_receiving_list.pop()
        l_phone_ui = self._ui_api_phone_list.pop()
        self._call_type_save = l_call_type

        # Dial using PHONE_NUMBER parameter
        l_phone_calling.dial(self._calling_phone_number.pop(), False)
        time.sleep(self._wait_btwn_cmd)

        if l_call_type == "2G" or l_call_type == "3G":
            # Wait for state "active" before callSetupTimeout seconds
            l_phone_receiving.wait_for_state(
                self._uecmd_types.VOICE_CALL_STATE.INCOMING,
                self._call_setup_time)
            # Answer call
            l_phone_receiving.answer()

            # Phone1 & 2 : Check voice call is active
            l_phone_calling.wait_for_state(
                self._uecmd_types.VOICE_CALL_STATE.ACTIVE,
                self._call_setup_time)
            l_phone_receiving.wait_for_state(
                self._uecmd_types.VOICE_CALL_STATE.ACTIVE,
                self._call_setup_time)

        elif l_call_type == "VOIP":
            # Wait for state "active" before callSetupTimeout seconds
            l_phone_receiving.wait_for_audio_state(
                self._uecmd_types.AUDIO_STATE.RINGTONE, self._call_setup_time)
            # Answer call
            l_phone_ui.run_operation_set("call_answer")

            # Phone1 & 2 : Check voice call is active
            l_phone_calling.wait_for_audio_state(
                self._uecmd_types.AUDIO_STATE.IN_COMMUNICATION,
                self._call_setup_time)
            l_phone_receiving.wait_for_audio_state(
                self._uecmd_types.AUDIO_STATE.IN_COMMUNICATION,
                self._call_setup_time)

        # Configure Audio output to acc_type given with the test_case
        if self._acc_type == "EARPIECE":
            if self._use_io_card:
                self._wired_headset.unplug_headphone()
                self._wired_headset.unplug_whs()
        elif self._acc_type == "SPEAKER":
            # Switch to Speaker, nothing to do in Earpiece
            # Bluetooth already done with connect Bluetooth function above
            self._phonesystem_api.switch_audio_output(self._acc_type.lower())
            time.sleep(self._wait_btwn_cmd)

        # Voice call volume settings
        if self._acc_type.find("BLUETOOTH") == -1:
            # Set Voice Call Volume
            self._system_api.adjust_specified_stream_volume(
                "VoiceCall", self._call_stream_volume_dut)
        else:
            # Set Voice Call Volume
            self._system_api.adjust_specified_stream_volume(
                "Bluetooth", self._call_stream_volume_dut)

        self._system_api2.adjust_specified_stream_volume(
            "VoiceCall", self._call_stream_volume_ref)

        # WAIT FOR CALL DURATION
        self._logger.info("Wait for call duration: %s s..." %
                          str(self._call_duration))

        l_call_type = self._call_list.pop()
        l_phone_calling = self._phone_calling_list.pop()
        l_phone_receiving = self._phone_receiving_list.pop()
        l_phone_ui = self._ui_api_phone_list.pop()
        self._previous_call_type_save = self._call_type_save
        self._call_type_save = l_call_type
        # Dial using PHONE_NUMBER parameter
        l_phone_calling.dial(self._calling_phone_number.pop(), False)
        time.sleep(self._wait_btwn_cmd)

        if l_call_type == "2G" or l_call_type == "3G":
            # Wait for state "active" before callSetupTimeout seconds
            l_phone_receiving.wait_for_state(
                self._uecmd_types.VOICE_CALL_STATE.INCOMING,
                self._call_setup_time)
            # Answer call
            l_phone_receiving.answer()
            # Phone1 & 2 : Check voice call is active
            l_phone_calling.wait_for_state(
                self._uecmd_types.VOICE_CALL_STATE.ACTIVE,
                self._call_setup_time)
            l_phone_receiving.wait_for_state(
                self._uecmd_types.VOICE_CALL_STATE.ACTIVE,
                self._call_setup_time)
        else:
            # Answer call
            time.sleep(5)
            l_phone_ui.run_operation_set("call_answer")

            # Phone1 & 2 : Check voice call is active
            l_phone_calling.wait_for_audio_state(
                self._uecmd_types.AUDIO_STATE.IN_COMMUNICATION,
                self._call_setup_time)
            l_phone_receiving.wait_for_audio_state(
                self._uecmd_types.AUDIO_STATE.IN_COMMUNICATION,
                self._call_setup_time)

        self._call_type_list_audio_analyser_run.pop()

        while self._number_of_swap > 0:

            self._phonesystem_api2.wake_screen()
            time.sleep(self._wait_btwn_cmd)
            self._ui_api2.run_operation_set("swap_call")

            call_type_audio_analyzer = self._call_type_list_audio_analyser_run.pop(
            )
            if call_type_audio_analyzer == "VOIP":
                self._system_api2.adjust_specified_stream_volume(
                    "VoiceCall",
                    (self._call_stream_volume_ref + self._delta_voip_volume))
            else:
                self._system_api2.adjust_specified_stream_volume(
                    "VoiceCall", self._call_stream_volume_ref)

            self._phonesystem_api.wake_screen()
            time.sleep(self._wait_btwn_cmd)

            # Launch audio_quality test
            l_audio_analyzer_ready, l_audio_analyzer_process = self._audio_analyzer.glitch_detection_before_switch(
                self._test_type, self._device.get_phone_model(),
                call_type_audio_analyzer, self._acc_type,
                self._signal_tested_direction)

            if l_audio_analyzer_ready == 0:
                self._ui_api.run_operation_set("swap_call")

                l_audio_analyzer_result = self._audio_analyzer.glitch_detection_after_switch(
                    l_audio_analyzer_process)

            # Compute test verdict
            self.__compute_test_verdict__(l_audio_analyzer_result)

            self._previous_call_type_save = self._call_type_save
            self._call_type_save = call_type_audio_analyzer
            self._number_of_swap -= 1

        l_phone_releasing = self._phone_releasing_list.pop()
        # Hang up call
        l_phone_releasing.release(False)
        time.sleep(self._wait_btwn_cmd)

        l_phone_releasing = self._phone_releasing_list.pop()
        # Hang up call
        l_phone_releasing.release()

        # Phone1 & 2 : Check call is idle
        l_phone_calling.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.NOCALL, self._call_setup_time)
        l_phone_receiving.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.NOCALL, self._call_setup_time)

        if self._audio_analyzer_result_save == 0:
            self._verdict_comment = (
                "Audio Glitch detection test success with %s call sequence" %
                (str(self._tc_parameters.get_param_value("CALL_SEQUENCE"))))
        elif self._audio_analyzer_result_save == 1:
            self._verdict_comment = (
                "Audio Glitch detection test fail: Glitch "
                "problems detected in %s with "
                "%s call sequence" % (self._signal_tested_direction,
                                      self._failed_transition_audio_pb))
        elif self._audio_analyzer_result_save == 2:
            self._verdict_comment = (
                "Audio Glitch detection test fail: No audio signal in %s with "
                "%s call sequence" % (self._signal_tested_direction,
                                      self._failed_transition_no_audio))
        elif self._audio_analyzer_result_save == 3:
            self._verdict_comment = (
                "Audio Glitch detection test fail: Exception in executable "
                "in %s with %s call sequence" %
                (self._signal_tested_direction,
                 self._failed_transition_no_audio))
        else:
            self._verdict_comment = (
                "Audio Glitch detection test fail: Unknown problems detected "
                "with a %s call sequence" %
                (str(self._tc_parameters.get_param_value("CALL_SEQUENCE"))))

        return self._result_verdict, self._verdict_comment

    def tear_down(self):
        """
        End and dispose the test
        """

        # Call UseCaseBase tear_down function
        UseCaseBase.tear_down(self)

        if self._acc_type == "HEADSET":
            if self._use_io_card:
                self._wired_headset.unplug_whs()
        elif self._acc_type == "HEADPHONE":
            if self._use_io_card:
                self._wired_headset.unplug_headphone()

        # Release any previous call (Robustness)
        if self._voice_call_api is not None:
            self._voice_call_api.release(False)
        if self._voice_call_api2 is not None:
            self._voice_call_api2.release(False)

        self._sip_call_api.delete_profile_sip_phone_app()
        self._sip_call_api2.delete_profile_sip_phone_app()

        # Reset Voice Call Volume at 70%
        if self._system_api is not None:
            self._system_api.adjust_specified_stream_volume("VoiceCall", 70)
        if self._system_api2 is not None:
            self._system_api2.adjust_specified_stream_volume("VoiceCall", 70)

        # Disable Wifi connections
        if self._result_verdict != Global.SUCCESS:
            if self._networking_api is not None:
                self._networking_api.clean_all_data_connections()
                time.sleep(self._wait_btwn_cmd)
                self._networking_api.set_wifi_power("off")
            if self._networking_api2 is not None:
                self._networking_api2.clean_all_data_connections()
                time.sleep(self._wait_btwn_cmd)
                self._networking_api2.set_wifi_power("off")

        return Global.SUCCESS, "No errors"
class LiveWifiTetheringBase(UseCaseBase):
    """
    Live Wifi Tethering base Test class.
    """
    _CHECK_CONNECTION_TIMEOUT = 20

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        UseCaseBase.__init__(self, tc_name, global_config)

        # Get FTP server parameters
        self._wifi_server = global_config.benchConfig.get_parameters(
            "WIFI_SERVER")
        self._ftp_ip_address = self._wifi_server.get_param_value("IP")
        self._ftp_username = self._wifi_server.get_param_value("username")
        self._ftp_password = self._wifi_server.get_param_value("password")
        if self._wifi_server.has_parameter("ftp_path"):
            self._ftp_path = self._wifi_server.get_param_value("ftp_path")
        else:
            self._ftp_path = ""

        # Get host spot configuration according HOTSPOT_SSID
        self._hotspot_ssid = \
            str(self._tc_parameters.get_param_value("HOTSPOT_SSID"))

        # Get host spot configuration according HOTSPOT_SECURITY
        self._hotspot_security = \
            str(self._tc_parameters.get_param_value("HOTSPOT_SECURITY"))

        # Get host spot configuration according HOTSPOT_PASSWORD
        self._hotspot_passphrase = \
            str(self._tc_parameters.get_param_value("HOTSPOT_PASSWORD"))

        # Get host spot configuration according HOTSPOT_STANDARD
        self._hotspot_standard = \
            self._tc_parameters.get_param_value("HOTSPOT_STANDARD")

        # Get flight mode configuration according FLIGHT_MODE
        self._flight_mode = \
            str(self._tc_parameters.get_param_value("FLIGHT_MODE"))
        self._flight_mode = str_to_bool_ex(self._flight_mode)

        # Get Data connection mode
        self._is_pdp_context_activated = \
            str(self._tc_parameters.get_param_value("IS_PDP_CONTEXT_ACTIVATED"))
        self._is_pdp_context_activated = str_to_bool_ex(
            self._is_pdp_context_activated)
        # Default is True
        if self._is_pdp_context_activated == None:
            self._is_pdp_context_activated = True

        # Get the optional DUT wrong passphrase to test connection failure
        self._wrong_passphrase = self._tc_parameters. \
            get_param_value("WIFI_PASSPHRASE")

        # Get computer type
        self._computer = self._tc_parameters.get_param_value("COMPUTER")
        if self._computer == "":
            self._computer = None  # empty computer: use second DUT

        # Get UECmdLayer
        self._networking_api = self._device.get_uecmd("Networking")

        # Load computer equipment
        if self._computer is not None:
            self._computer = self._em.get_computer(self._computer)
            self._wifi_interface = self._computer.get_wifi_interface()
            if self._wifi_interface == "":
                self._wifi_interface = None
        else:
            self._wifi_interface = None

        # Get PHONE2
        self._phone2 = None
        self._networking_api2 = None
        if self._computer is None:
            self._phone2 = DeviceManager().get_device("PHONE2")
            if self._phone2 is not None:
                self._networking_api2 = self._phone2.get_uecmd("Networking")

        # init original wifi power status for phone1
        self._original_wifi_power_status = 0
        # init original flight mode for phone1
        self._original_flight_mode = 0
        self._interface_ip = None

        self._hotspot_ext_interface = \
            str(self._dut_config.get("hotspotExtInterface"))

        # Set BT prerequisite (set ON, set OFF or nothing) for FIT BT/WIFI tests
        self._bt_fit_used, self._bt_wished_value = self._get_bt_fit_config()
        # BT initial state
        self._bt_initial_state = 'STATE_ON'
        # Instantiate generic UECmd
        self._localconnectivity_api = self._device.get_uecmd(
            "LocalConnectivity")

        # MAC Address of the STA device that will be connected to the softAP
        self._client_mac_address = ""

#------------------------------------------------------------------------------

    def set_up(self):
        """
        Initialize the test
        """
        # pylint: disable=E1101
        # run setup inherit from UseCaseBase
        UseCaseBase.set_up(self)

        # Check if we have second wifi interface or second phone available
        if (self._computer is None or self._wifi_interface is None) \
                and self._phone2 is None:
            msg = "Cannot run that use case without a remote PC or with only one phone configured."
            self._logger.error(msg)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg)

        # If Bt to be (de-)activated for FIT tests
        if self._bt_fit_used:

            self._bt_initial_state = self._localconnectivity_api.get_bt_power_status(
            )

            # if Bt is not at the wished value, set it to the correct one.
            if self._bt_initial_state != self._bt_wished_value:
                self._localconnectivity_api.set_bt_power(self._bt_wished_value)
                time.sleep(self._wait_btwn_cmd)

        # store original wifi power status
        time.sleep(self._wait_btwn_cmd)
        self._original_wifi_power_status = \
            self._networking_api.get_wifi_power_status()

        # store original flight mode
        time.sleep(self._wait_btwn_cmd)
        self._original_flight_mode = self._networking_api.get_flight_mode()

        # Enable/Disable flight mode
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_flight_mode(self._flight_mode)

        # Enable Cellular Data connection
        if self._flight_mode == False and self._is_pdp_context_activated:
            time.sleep(self._wait_btwn_cmd)
            self._networking_api.activate_pdp_context()

        # disable wifi for Phone1
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_power("off")

        # enable Portable wifi hotspot for Phone1
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_hotspot("on", self._hotspot_ssid,
                                              self._hotspot_security,
                                              self._hotspot_passphrase)

        if self._wrong_passphrase in (None, "", "NONE", "None"):
            passphrase = self._hotspot_passphrase
            wrong_passphrase = False
        else:
            passphrase = self._wrong_passphrase
            wrong_passphrase = True

        if self._computer is not None:
            try:
                self._interface_ip = \
                    self._computer.wifi_connect(self._wifi_interface,
                                                self._hotspot_standard,
                                                self._hotspot_ssid,
                                                self._hotspot_security,
                                                passphrase)
                if wrong_passphrase:
                    msg = "Connection successful with wrong passphrase."
                    self._logger.error(msg)
                    raise TestEquipmentException(
                        TestEquipmentException.OPERATION_FAILED, msg)
            except TestEquipmentException as exc:
                # ignore the exception if the connection fails with a wrong passphrase
                if not wrong_passphrase:
                    raise
                elif not "Could not get IP address" in str(exc) \
                        and not "Could not associate device" in str(exc):
                    raise

            # Retrieve the MAC address of the COMPUTER
            time.sleep(self._wait_btwn_cmd)
            self._client_mac_address = self._computer.get_interface_mac_addr(
                self._wifi_interface)
            self._client_mac_address.lower()

        elif self._phone2 is not None:
            # Boot the other phone (the DUT is already booted)
            if not self._phone2.is_available():
                DeviceManager().boot_device("PHONE2")

            # set wifi power on for Phone2
            time.sleep(self._wait_btwn_cmd)
            self._networking_api2.set_wifi_power("on")

            # set auto connect state off for Phone2
            time.sleep(self._wait_btwn_cmd)
            self._networking_api2.\
                set_autoconnect_mode("all",
                                     self._uecmd_types.AUTO_CONNECT_STATE.off)

            # disconnect all wifi for Phone2
            time.sleep(self._wait_btwn_cmd)
            self._networking_api2.wifi_disconnect_all()

            # set passphrase for Phone2
            self._networking_api2.set_wificonfiguration(
                self._hotspot_ssid, passphrase, self._hotspot_security)

            # connect hotspot from Phone1 for Phone2
            time.sleep(self._wait_btwn_cmd)
            try:
                self._networking_api2.wifi_connect(self._hotspot_ssid)
                if wrong_passphrase:
                    msg = "Connection successful with wrong passphrase."
                    self._logger.error(msg)
                    raise DeviceException(DeviceException.OPERATION_FAILED,
                                          msg)
            except AcsBaseException as exc:
                # ignore the exception if the connection fails with a wrong passphrase
                if not wrong_passphrase:
                    raise
                elif not "timeout" in str(exc):
                    raise

            # Retrieve the MAC address of the PHONE2
            time.sleep(self._wait_btwn_cmd)
            self._client_mac_address = self._networking_api2.get_interface_mac_addr(
            ).lower()

        else:
            msg = "Cannot run that use case without a remote PC or with only one phone configured."
            self._logger.error(msg)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg)

        return Global.SUCCESS, "No error"

#------------------------------------------------------------------------------

    def tear_down(self):
        """
        End and dispose the test
        """
        UseCaseBase.tear_down(self)

        status = Global.SUCCESS
        msg = "No error"

        if self._computer is not None:
            self._computer.wifi_disconnect(self._wifi_interface)

        elif self._phone2 is not None:
            # disconnect from hotspot for Phone2
            time.sleep(self._wait_btwn_cmd)
            self._networking_api2.\
                wifi_disconnect(self._hotspot_ssid)

            time.sleep(self._wait_btwn_cmd)
            self._networking_api2.wifi_remove_config(self._hotspot_ssid)

            # set wifi power off for phone2
            time.sleep(self._wait_btwn_cmd)
            self._networking_api2.set_wifi_power("off")

        # disable Portable wifi hotspot for Phone1
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_hotspot("off")

        # restore original flight mode
        if str_to_bool_ex(self._original_flight_mode) != str_to_bool_ex(
                self._flight_mode):
            time.sleep(self._wait_btwn_cmd)
            self._networking_api.set_flight_mode(self._original_flight_mode)

        # restore original wifi power status
        time.sleep(self._wait_btwn_cmd)
        self._networking_api.set_wifi_power(self._original_wifi_power_status)

        # If Bt to be (de-)activated for FIT tests
        if self._bt_fit_used:

            bt_final_status = self._localconnectivity_api.get_bt_power_status()

            # if Bt is not at the initial value, set it to the correct one.
            if bt_final_status != self._bt_initial_state:
                # restore Bt in initial state
                self._localconnectivity_api.set_bt_power(
                    self._bt_initial_state)
                time.sleep(self._wait_btwn_cmd)

        return status, msg

#------------------------------------------------------------------------------

    def _get_bt_fit_config(self):
        """
        Get BT configuration for FIT BT/WIFI tests

        :rtype: list of 2 elements (boolean, str)
        :return: true if BT/WIFI FIT is used, Bluetooth state ON or OFF for the test to be run
        """

        # Read WHILE_BLUETOOTH_ON parameter (named for retro-compatibility)
        # from test case xml file for FIT tests
        param_while_bt_on = \
            str(self._tc_parameters.get_param_value("WHILE_BLUETOOTH_ON"))

        if param_while_bt_on.lower() in ["1", "on", "true", "yes"]:
            bt_fit_used = True
            bt_wished_value = 'STATE_ON'
        elif param_while_bt_on.lower() in ["0", "off", "false", "no"]:
            bt_fit_used = True
            bt_wished_value = 'STATE_OFF'
        else:
            bt_fit_used = False
            bt_wished_value = 'STATE_OFF'

        return bt_fit_used, bt_wished_value
class LiveLteImsVcDualBase(LiveLteImsReg):
    """
    This test case requires a Com4Innov cell to work.
    Because of this constraint some values that should
    have been given as parameters are actually hard-coded.
    That is to be changed if this test ever has to be
    executed in a different environment.
    """
    def __init__(self, tc_name, global_config):
        """
        Initializes this instance.
        """
        # Call inherited initializer
        LiveLteImsReg.__init__(self, tc_name, global_config)

        # Read the call direction parameter
        self._call_direction = str(
            self._tc_parameters.get_param_value("CALL_DIRECTION", "MO"))

        # Read the call release parameter
        self._call_release_direction = str(
            self._tc_parameters.get_param_value("CALL_RELEASE", "MR"))

        # Read the call type parameter
        self._call_type = self._tc_parameters.get_param_value("CALL_TYPE", "")

        # Retrieve call duration parameter
        self._callduration = \
            int(self._tc_parameters.get_param_value("CALL_DURATION", 15))

        # Read the parameter for call on hold/resume procedure
        self._check_on_hold_resume_procedure = str_to_bool(
            self._tc_parameters.get_param_value("CHECK_CALL_ON_HOLD_RESUME",
                                                "False"))

        # Read the call option parameter for remote party
        self._remote_party_action = \
            self._tc_parameters.get_param_value("REMOTE_PARTY_ACTION", "")

        # Initialize some attributes to store various phone numbers
        self._phone_no_main_dut = None
        self._phone_no_secondary_dut = None

        # Read the phone number parameter from TC's XML
        self._phone_number = self._tc_parameters.get_param_value(
            "PHONE_NUMBER")

        # If Phone number is not specified in TC XML, try to retrieve it from bench config
        if self._phone_number is None:
            # Retrieve the numbers for each phone used, from bench config file
            self._phone_no_main_dut = \
                self._retrive_parameter_bench_config(global_config, "PhoneNumberDut1")
            self._phone_no_secondary_dut = \
                self._retrive_parameter_bench_config(global_config, "PhoneNumberDut2")

        if self._ims_reg_operation == "CHECK_ONLY":
            self._perform_ims_registration = False
        else:
            self._perform_ims_registration = True

        # Read the ftp transfer parameter
        self._ftp_transfer = str_to_bool(
            self._tc_parameters.get_param_value("FTP_TRANSFER", "False"))

        if self._ftp_transfer is True:
            # Retrieve the parameters needed for FTP data transfer
            self._retrieve_ftp_parameters(global_config)
            # Instantiate the FTP UE commands for main device
            self._ftp_api = self._device.get_uecmd("Ftp")
        else:
            # Initialize the FTP parameters
            self._ftp_api = None
            self._server = None
            self._server_ip_v4_address = None
            self._server_ip_v6_address = None
            self._username = None
            self._password = None
            self._ftp_path = None
            self._ftp_direction = None
            self._ftp_filename = None
            self._dl_ftp_filename = None
            self._ftp_ip_version = None
            self._ip_address = None
            self._xfer_timeout = None

        # Read callSetupTimeout from Phone_Catalog.xml
        self._call_setup_time = \
            int(self._dut_config.get("callSetupTimeout"))

        # Instantiate UE categories for first device
        self._voice_call_api = self._device.get_uecmd("VoiceCall")
        self._networking_api = self._device.get_uecmd("Networking")
        self._file_system_api = self._device.get_uecmd("File")
        self._phone_system_api = self._device.get_uecmd("PhoneSystem")

        # Load instance of the PHONE2
        self._remote_phone = DeviceManager().get_device("PHONE2")
        self._remote_dut_config = DeviceManager().get_device_config("PHONE2")

        # Instantiate UE categories for second device
        if self._remote_phone is not None:
            self._voice_call_api2 = self._remote_phone.get_uecmd("VoiceCall")
            self._networking_api2 = self._remote_phone.get_uecmd("Networking")
            self._phone_system_api2 = self._remote_phone.get_uecmd(
                "PhoneSystem")
        else:
            self._voice_call_api2 = None
            self._networking_api2 = None
            self._phone_system_api2 = None

#------------------------------------------------------------------------------

    def set_up(self):
        """
        Initializes the test.
        """

        # Call the inherited set_up method
        # Ugly temporary solution before implementing something
        # better using test steps.
        if self._perform_ims_registration:
            # Call inherited setup method
            self._logger.info("Performing IMS registration step as requested.")
            LiveLteImsReg.set_up(self)
        else:
            # Call the base setup method in order to be
            # compliant with ACS framework
            self._logger.info(
                "Skipping IMS registration step (assumed to be done).")
            UseCaseBase.set_up(self)
            if self._perform_ims_registration is None:
                # But raise an exception
                message = "Invalid parameter value for IMS_REGISTRATION_OPERATION"
                raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                         message)
            # Simply perform a IMS registration check
            self._networking_api.check_ims_registration_before_timeout(10)

        # Check the call duration parameter
        if not self._callduration:
            message = "%s '%s' %s '%s'" % (
                "Invalid parameter value (or missing parameter)",
                str(self._callduration), "for parameter", "CALL_DURATION")
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)
        # We arbitrarily set a minimum allowed value for call duration
        if self._callduration < 15:
            message = "%s '%s' %s '%s'. %s." % (
                "Invalid parameter value ", str(
                    self._callduration), "for parameter", "CALL_DURATION",
                "The value should be set to 15 at the minimum")
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        # Check the call type parameter
        if self._call_type not in ("IR92", "IR94_AUDIO", "IR94_RX", "IR94_TX",
                                   "IR94_BIDIRECTIONAL"):
            message = "%s '%s' %s '%s'" % (
                "Invalid parameter value (or missing parameter)",
                str(self._call_type), "for parameter", "CALL_TYPE")
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        # Check the call type parameter
        if self._call_direction not in ("MO", "MT"):
            message = "%s '%s' %s '%s'" % (
                "Invalid parameter value (or missing parameter)",
                str(self._call_direction), "for parameter", "CALL_DIRECTION")
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        # Check the call type parameter
        if self._call_release_direction not in ("MR", "NR"):
            message = "%s '%s' %s '%s'" % ("Invalid parameter value",
                                           str(self._call_release_direction),
                                           "for parameter", "CALL_RELEASE")
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        # Check if we have the second phone available
        if self._remote_phone is None:
            # We are using this multi UC with only one phone
            message = \
                "This use case requires two phones to be executed !"
            self._logger.error(message)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     message)

        # Boot the other phone (the DUT is already booted)
        if not self._remote_phone.is_available():
            DeviceManager().boot_device("PHONE2")

        # Disable Flight Mode for the secondary DUT (robustness)
        self._networking_api2.set_flight_mode("off")

        # Set up is done correctly
        return (Global.SUCCESS, "No errors")

#------------------------------------------------------------------------------

    def run_test(self):
        """
        Runs the test.
        """
        # Call inherited run_test method which will ensure IMS registration
        # Ugly temporary solution before implementing something
        # better using test steps.
        if self._perform_ims_registration:
            LiveLteImsReg.run_test(self)
        else:
            UseCaseBase.run_test(self)

        # Check registration for secondary DUT
        self._check_registration_second_dut()

        # Release any previous call (Robustness)
        self._logger.info("Releasing any ongoing calls")
        self._voice_call_api.release()
        self._voice_call_api2.release()

        # Return the test result
        return (Global.SUCCESS, "No error.")

#------------------------------------------------------------------------------

    def tear_down(self):
        """
        Disposes this test.
        """
        # Call the inherited tear_down method
        # Ugly temporary solution before implementing something
        # better using test steps.
        if self._perform_ims_registration:
            LiveLteImsReg.tear_down(self)
        else:
            UseCaseBase.tear_down(self)

        # End of tear_down
        return (Global.SUCCESS, "No errors")

    def _retrieve_ftp_parameters(self, global_config):
        """
        Read and set the FTP parameters from bench config and TC's .XML files.
        """

        # Get FTP server parameters from bench config file
        self._server = \
            global_config.benchConfig.get_parameters("LAB_LTE_IMS_SERVER")
        self._server_ip_v4_address = self._server.get_param_value("IP4")
        self._server_ip_v6_address = self._server.get_param_value("IP6")
        self._username = self._server.get_param_value("username")
        self._password = self._server.get_param_value("password")
        if self._server.has_parameter("ftp_path"):
            self._ftp_path = self._server.get_param_value("ftp_path")
        else:
            self._ftp_path = ""

        # Read the the direction parameter name from TC's xml file
        self._ftp_direction = self._tc_parameters.get_param_value(
            "FTP_DIRECTION")
        # Read the ftp file name from TC's xml
        if self._ftp_direction == "DL":
            self._ftp_filename = os.path.join(
                self._ftp_path,
                self._tc_parameters.get_param_value("DL_FILENAME", ""))
            self._ftp_filename = self._ftp_filename.replace('\\', '/')
            self._dl_ftp_filename = None
        elif self._ftp_direction == "UL":
            # Read the UL_FILENAME value from TC's xml
            self._ftp_filename = os.path.join(
                self._ftp_path,
                self._tc_parameters.get_param_value("UL_FILENAME", ""))
            self._ftp_filename = self._ftp_filename.replace('\\', '/')
            self._dl_ftp_filename = None
        elif self._ftp_direction == "BOTH":
            self._dl_ftp_filename = os.path.join(
                self._ftp_path,
                self._tc_parameters.get_param_value("DL_FILENAME", ""))
            self._dl_ftp_filename = self._dl_ftp_filename.replace('\\', '/')
            # Read the UL_FILE value from TC's xml
            self._ftp_filename = os.path.join(
                self._ftp_path,
                self._tc_parameters.get_param_value("UL_FILENAME", ""))
            self._ftp_filename = self._ftp_filename.replace('\\', '/')

        # Read the the ip_version from TC's xml
        self._ftp_ip_version = self._tc_parameters.get_param_value(
            "FTP_IP_VERSION", "IPV4")

        # Selecting the IPV6 address of the FTP server, according to
        # the TC parameter value.
        if self._ftp_ip_version == "IPV6":
            if self._server_ip_v6_address is not None:
                # If Protocol is IPV6 use IPV6 address.
                log_msg = "Using IPV6 address to connect to the FTP server."
                self._logger.info(log_msg)
                self._ip_address = self._server_ip_v6_address
            else:
                # If IPV6 address is not present in the BenchConfig.
                msg = "The IPV6 parameter is missing from the Bench Config!"
                raise AcsConfigException(
                    AcsConfigException.INVALID_BENCH_CONFIG, msg)
        else:
            self._ip_address = self._server_ip_v4_address

        # Read the XFER_TIMEOUT from UseCase xml Parameter
        self._xfer_timeout = self._tc_parameters.get_param_value(
            "XFER_TIMEOUT")
        if self._xfer_timeout is not None and str(
                self._xfer_timeout).isdigit():
            self._xfer_timeout = int(self._xfer_timeout)
        else:
            self._xfer_timeout = None

    def _check_ftp_parameters(self):
        """
        Check the parameters related with FTP data transfer

        :raise AcsConfigException: in case any parameter is incorrect
        """

        # Check the call type parameter
        if self._ftp_direction not in ("DL", "UL", "BOTH"):
            message = "%s '%s' %s '%s'" % (
                "Invalid parameter value (or missing parameter)",
                str(self._ftp_direction), "for parameter", "FTP_DIRECTION")
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        if self._xfer_timeout is None:
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     "XFER_TIMEOUT should be int")

    def _check_registration_second_dut(self):
        """
        Check if secondary DUT is registered or not to NW

        :raise DeviceException: in case 2nd DUT not registered
        """
        in_service_status = ImsRegistrationStatus.in_service()
        reg_status = ImsRegistrationStatus(
            self._networking_api2.get_ims_registration_status())

        # If not registered
        if reg_status != in_service_status:
            self._logger.warning(
                "The secondary DUT is NOT registered! Airplane on/off will be performed!"
            )
            self._networking_api2.set_flight_mode("on")
            # Wait 10 seconds
            time.sleep(10)
            self._networking_api2.set_flight_mode("off")
            # Wait 10 seconds
            time.sleep(10)
            try:
                self._networking_api2.check_ims_registration_before_timeout(60)
            except DeviceException:
                message = "Secondary DUT still not registered after airplane on/off !"
                raise DeviceException(DeviceException.TIMEOUT_REACHED, message)
class LiveDualPhoneBTBase(LiveBTBase):

    """
    Live BT Test base class.
    """

    # Constants
    STR_PHONE_2 = "PHONE2"

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        LiveBTBase.__init__(self, tc_name, global_config)

        # Get PHONE2
        self._phone2 = DeviceManager().get_device(self.STR_PHONE_2)

        # Check if we have the second phone available
        if self._phone2 is not None:
            if not self._phone2.is_available():
                DeviceManager().boot_device(self.STR_PHONE_2)
            self._bt_api2 = self._phone2.get_uecmd("LocalConnectivity")

            # Get PHONE2 networking interface
            self._networking_api2 = self._phone2.get_uecmd("Networking")

            # Get BT device parameters
            self._dut2_config = DeviceManager().get_device_config(self.STR_PHONE_2)

        self._phone_system_api = self._device.get_uecmd("PhoneSystem")

        # Initialize phones address
        self._phone1_addr = ""
        self._phone2_addr = ""

        self._original_flight_mode2 = 0

#------------------------------------------------------------------------------

    def set_up(self):
        """
        Initialize the test
        """
        LiveBTBase.set_up(self)

        if self._phone2 is None:
            msg = "PHONE2 is not specified in the bench configuration"
            self._logger.error(msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG, msg)

        # Get original phone mode
        self._original_flight_mode2 = self._networking_api2.get_flight_mode()
        # Flight mode
        if self._use_flightmode != self._original_flight_mode2:
            self._networking_api2.set_flight_mode(self._use_flightmode)

        self._logger.info("Reset phone Bluetooth adapter")
        self._bt_api2.bt_reset_device()

        # Get phones address
        self._phone1_addr = self._bt_api.get_bt_adapter_address()
        self._phone2_addr = self._bt_api2.get_bt_adapter_address()

        return Global.SUCCESS, "No errors"

#------------------------------------------------------------------------------
    def tear_down(self):
        """
        End and dispose the test
        """
        LiveBTBase.tear_down(self)

        time.sleep(self._wait_btwn_cmd)

        # Recover to initial flight mode
        self._logger.info("Set PHONE2 to original flight mode")
        self._networking_api2.set_flight_mode(self._original_flight_mode2)
        time.sleep(self._wait_btwn_cmd)

        self._logger.info("Close phone 2 adapter devices")
        self._bt_api2.set_bt_power("off")
        time.sleep(self._wait_btwn_cmd)

        return Global.SUCCESS, "No errors"

    def _establish_bt_pairing(self, pairing_initiator):
        """
        Establish bluetooth pairing procedure

        :type pairing_initiator: String
        :param pairing_initiator: PHONE1 or PHONE2 the device that requests for pairing first
        """
        # Defines BT pairing roles
        if pairing_initiator == "PHONE2":
            paired_api = self._bt_api
            paired_addr = self._phone1_addr
            requester_api = self._bt_api2
            requester_addr = self._phone2_addr

        else:
            paired_api = self._bt_api2
            paired_addr = self._phone2_addr
            requester_api = self._bt_api
            requester_addr = self._phone1_addr

        establish_bt_pairing(requester_api, requester_addr,
                             paired_api, paired_addr,
                             self._wait_btwn_cmd)
示例#11
0
class LabAudioAPxCalibrationVOIP(UseCaseBase):
    """
    AudioComms calibration APx class.
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        # Call UseCaseBase Init function
        UseCaseBase.__init__(self, tc_name, global_config)

        # Create APx
        self._audio_analyzer = self._em.get_audio_analyzer("AudioAnalyzer")

        # Check if IO card is used
        self._use_io_card = str_to_bool(
            global_config.campaignConfig.get("isIoCardUsed"))

        # Create Whs
        if self._use_io_card:
            self._wired_headset = self._em.get_wired_headset("WiredHeadset")

        # Initialization of the test type
        self._test_type = "calibration"

        # Initialization of test result in uplink
        self._result_verdict_ul = Global.FAILURE
        # Initialization of test result in downlink
        self._result_verdict_dl = Global.FAILURE
        # Initialization of test result
        self._result_verdict_final = Global.FAILURE

        # Call Stream Volume
        self._call_stream_volume = 70

        # Initialization of the verdict comment
        self._verdict_comment = "APx Calibration fail"

        # Read registrationTimeout from Device_Catalog.xml
        self._registration_timeout = \
            int(self._dut_config.get("registrationTimeout"))

        # Read callSetupTimeout from Device_Catalog.xml
        self._call_setup_time = \
            int(self._dut_config.get("callSetupTimeout"))

        # Read accessories type from test case xml file (str)
        self._acc_type = str(self._tc_parameters.get_param_value("ACC_TYPE"))

        # Call Stream Volume in percent
        self._call_stream_volume_dut = \
            int(self._tc_parameters.get_param_value("CALL_VOLUME_DUT"))

        # Call Stream Volume in percent
        self._call_stream_volume_ref = \
            int(self._tc_parameters.get_param_value("CALL_VOLUME_REF"))

        # Read Audio Analyzer parameters from bench config xml file (str)
        self._audio_analyser = global_config.benchConfig.\
            get_parameters("AudioAnalyzer")
        self._bt_remote_addr = self._audio_analyser.get_param_value(
            "Bt_mac_addr")

        # Read dut sip address from test case xml file (str)
        self._dut_sip_address = \
            str(self._tc_parameters.get_param_value("DUT_SIP_ADDRESS"))

        # Read ref phone sip address from test case xml file (str)
        self._peer_sip_address = \
            str(self._tc_parameters.get_param_value("PEER_SIP_ADDRESS"))

        # Instantiate generic UECmd for voiceCall Ucs
        self._networking_api = self._device.get_uecmd("Networking")
        self._sip_call_api = self._device.get_uecmd("SipCall")
        self._phonesystem_api = self._device.get_uecmd("PhoneSystem")
        self._system_api = self._device.get_uecmd("System")

        if self._acc_type.find("BLUETOOTH") != -1:
            # Get UECmdLayer
            self._bt_api = self._device.get_uecmd("LocalConnectivity")
            # Get dut bt address
            self._dut_bt_address = self._bt_api.get_bt_adapter_address()
        else:
            self._dut_bt_address = "None"

        # Load instance of the PHONE2
        self._phone2 = DeviceManager().get_device("PHONE2")

        if self._phone2 is not None:
            if not self._phone2.is_available():
                self._phone2.switch_on(simple_switch_mode=True)
            self._voice_call_api2 = self._phone2.get_uecmd("VoiceCall")
            self._system_api2 = self._phone2.get_uecmd("System")

        # Instantiate the instances of member class variables
        self._sip_call_api2 = None
        self._networking_api2 = None
        self._phone_calling = None
        self._phone_receiving = None
        self._phone_releasing = None
        self._calling_phone_number = None

    def set_up(self):
        """
        Set up the test configuration
        """
        # Call UseCaseBase Setup function
        UseCaseBase.set_up(self)

        if self._phone2 is not None:
            self._networking_api2 = self._phone2.get_uecmd("Networking")
            self._sip_call_api2 = self._phone2.get_uecmd("SipCall")
        else:
            error_msg = \
                "This test case requires two phones to be executed !"
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     error_msg)

        # APx Initialization
        if self._audio_analyzer.initialization(self._device.get_phone_model(),
                                               self._test_type) != 0:
            error_msg = \
                "APX Initialization Failed !"
            self._logger.error(error_msg)
            raise TestEquipmentException(
                TestEquipmentException.OPERATION_FAILED, error_msg)

        # Setup phone type ( calling, receiving, releasing phone)
        self._phone_calling = self._sip_call_api
        self._phone_receiving = self._sip_call_api2
        self._calling_phone_number = self._peer_sip_address
        self._phone_releasing = self._sip_call_api2

        # Start Sip Service
        self._phone_calling.initialize_sipcall_module()
        self._phone_receiving.initialize_sipcall_module()

        # Setup Sip Account
        self._sip_call_api.initialize_local_profile(self._dut_sip_address)
        self._sip_call_api2.initialize_local_profile(self._peer_sip_address)

        return Global.SUCCESS, "No errors"

    def run_test(self):
        """
        Execute the test
        """
        # Call UseCaseBase run_test function
        UseCaseBase.run_test(self)

        self._phone_calling.wait_for_state(
            self._uecmd_types.SIP_CALL_STATE.READY_TO_CALL,
            self._call_setup_time)
        self._phone_receiving.wait_for_state(
            self._uecmd_types.SIP_CALL_STATE.READY_TO_CALL,
            self._call_setup_time)

        # Dial using PHONE_NUMBER parameter
        self._phone_calling.dial(self._calling_phone_number)

        self._phone_receiving.wait_for_state(
            self._uecmd_types.SIP_CALL_STATE.INCOMING_CALL,
            self._call_setup_time)

        self._phone_receiving.answer()
        # Phone1 & 2 : Check voice call is active
        self._phone_calling.wait_for_state(
            self._uecmd_types.SIP_CALL_STATE.IN_CALL, self._call_setup_time)
        self._phone_receiving.wait_for_state(
            self._uecmd_types.SIP_CALL_STATE.IN_CALL, self._call_setup_time)

        # Configure Audio output to acc_type given with the test_case except in Bluetooth test case
        if self._acc_type.find("BLUETOOTH") != -1:
            if self._audio_analyzer.connect_bt(self._acc_type,
                                               self._dut_bt_address) != 0:
                error_msg = \
                    "Connect Bluetooth failed !"
                self._logger.error(error_msg)
                raise DeviceException(DeviceException.OPERATION_FAILED,
                                      error_msg)

        # Configure Audio output to acc_type given with the test_case
        if self._acc_type == "EARPIECE":
            self._sip_call_api.switch_to_earpiece()
            if self._use_io_card:
                self._wired_headset.unplug_whs()
                self._wired_headset.unplug_headphone()
            time.sleep(self._wait_btwn_cmd)
        elif self._acc_type == "HEADSET":
            self._sip_call_api.switch_to_earpiece()
            if self._use_io_card:
                self._wired_headset.unplug_headphone()
                self._wired_headset.plug_whs()
            time.sleep(self._wait_btwn_cmd)
        elif self._acc_type == "HEADPHONE":
            self._sip_call_api.switch_to_earpiece()
            if self._use_io_card:
                self._wired_headset.unplug_whs()
                self._wired_headset.plug_headphone()
            time.sleep(self._wait_btwn_cmd)
        elif self._acc_type == "SPEAKER":
            self._sip_call_api.switch_to_speaker()
            time.sleep(self._wait_btwn_cmd)
        elif self._acc_type == "BLUETOOTHHSP" or self._acc_type == "BLUETOOTHHFP":
            self._sip_call_api.switch_to_bluetooth()
        elif self._acc_type == "BLUETOOTHA2DP":
            self._sip_call_api.switch_to_bluetooth()
        else:
            self._logger.error("Unknown accessories")
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     "Unknown accessories")

        time.sleep(self._wait_btwn_cmd)

        if self._acc_type.find("BLUETOOTH") == -1:
            # Set Voice Call Volume
            self._system_api.adjust_specified_stream_volume(
                "VoiceCall", self._call_stream_volume_dut)
        else:
            # Set Voice Call Volume
            self._system_api.adjust_specified_stream_volume(
                "Bluetooth", self._call_stream_volume_dut)

        self._system_api2.adjust_specified_stream_volume(
            "VoiceCall", self._call_stream_volume_ref)
        # Launch Apx Calibration test on Uplink
        apx_result = self._audio_analyzer.calibration(
            self._device.get_phone_model(), "VOIP", self._acc_type, "UL",
            self._dut_bt_address)

        if apx_result == 0:
            self._result_verdict_ul = Global.SUCCESS
            self._verdict_comment = "APx Calibration success in UL"
        else:
            self._result_verdict_ul = Global.FAILURE
            self._verdict_comment = "APx Calibration fail in UL"

        # Launch Apx Calibration test on Downlink
        apx_result = self._audio_analyzer.calibration(
            self._device.get_phone_model(), "VOIP", self._acc_type, "DL",
            self._dut_bt_address)

        if apx_result == 0:
            self._result_verdict_dl = Global.SUCCESS
            self._verdict_comment += " and APx Calibration success in DL"
        else:
            self._result_verdict_dl = Global.FAILURE
            self._verdict_comment += " and APx Calibration fail in DL"

        # Compute final verdict
        if self._result_verdict_ul == Global.FAILURE or \
           self._result_verdict_dl == Global.FAILURE:
            self._result_verdict_final = Global.FAILURE
        else:
            self._result_verdict_final = Global.SUCCESS

        # RELEASE THE CALL
        # Phone1 & 2 : Check call is still active
        self._phone_calling.wait_for_state(
            self._uecmd_types.SIP_CALL_STATE.IN_CALL, self._call_setup_time)
        self._phone_receiving.wait_for_state(
            self._uecmd_types.SIP_CALL_STATE.IN_CALL, self._call_setup_time)

        self._phone_releasing.release()

        self._phone_releasing.wait_for_state(
            self._uecmd_types.SIP_CALL_STATE.READY_TO_CALL,
            self._call_setup_time)
        self._phone_receiving.wait_for_state(
            self._uecmd_types.SIP_CALL_STATE.READY_TO_CALL,
            self._call_setup_time)

        return self._result_verdict_final, self._verdict_comment

    def tear_down(self):
        """
        End and dispose the test
        """

        # Call LabAudioQualityBase run_test function
        UseCaseBase.tear_down(self)

        if self._acc_type == "HEADSET":
            if self._use_io_card:
                self._wired_headset.unplug_whs()
        elif self._acc_type == "HEADPHONE":
            if self._use_io_card:
                self._wired_headset.unplug_headphone()

        # Stop Sip Service
        if self._sip_call_api is not None:
            self._sip_call_api.clean_sipcall_module()
        if self._sip_call_api2 is not None:
            self._sip_call_api2.clean_sipcall_module()

        return Global.SUCCESS, "No errors"
class LiveDualPhoneVcBase(UseCaseBase):
    """
    Live Voice Call base class.
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call init of use case base
        UseCaseBase.__init__(self, tc_name, global_config)

        # Get Test Cases Parameters
        self._callduration = \
            int(self._tc_parameters.get_param_value("CALL_DURATION"))

        # Read callSetupTimeout from Phone_Catalog.xml
        self._call_setup_time = \
            int(self._dut_config.get("callSetupTimeout"))

        # Get UECmdLayer
        self._voice_call_api = self._device.get_uecmd("VoiceCall")
        self._networking_api = self._device.get_uecmd("Networking")

        # Load instance of the PHONE2
        self._phone2 = DeviceManager().get_device("PHONE2")

        if self._phone2 is not None:
            self._voice_call_api2 = self._phone2.get_uecmd("VoiceCall")
            self._networking_api2 = self._phone2.get_uecmd("Networking")

        else:
            self._voice_call_api2 = None
            self._networking_api2 = None

        # Instantiate the instances for phone caller, receiver and releaser
        self._caller_phone = None
        self._receiver_phone = None
        self._releaser_phone = None

#------------------------------------------------------------------------------

    def set_up(self):
        """
        Initialize the test
        """
        # Call set_up of use case base
        UseCaseBase.set_up(self)

        # Check if we have the second phone available
        if self._phone2 is None:
            # We are using this multi UC with only one phone
            error_msg = \
                "This use case requires two phones to be executed !"
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     error_msg)

        # Boot the other phone (the DUT is already booted)
        if not self._phone2.is_available():
            DeviceManager().boot_device("PHONE2")

        # Disable flight mode
        self._networking_api.set_flight_mode("off")
        self._networking_api2.set_flight_mode("off")

        return Global.SUCCESS, "No errors"

#------------------------------------------------------------------------------

    def run_test(self):
        """
        Execute the test
        """
        # pylint: disable-msg=E1101
        # This to avoid pylint warnings due to enum class VOICE_CALL_STATE

        # Call init of use case base
        UseCaseBase.run_test(self)

        # Release any previous call (Robustness)
        time.sleep(self._wait_btwn_cmd)
        self._voice_call_api.release()
        self._voice_call_api2.release()

        # ESTABLISH THE CALL
        # Phone1 : Dial
        time.sleep(self._wait_btwn_cmd)
        self._caller_phone.dial(self._phone_number, False)

        # Phone2 : Wait for state incoming before callSetupTimeout seconds
        self._receiver_phone.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.INCOMING, self._call_setup_time)

        # Phone2 : Answer call
        self._receiver_phone.answer()

        # Phone1 & 2 : Check voice call is active
        self._voice_call_api.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.ACTIVE, self._call_setup_time)
        self._voice_call_api2.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.ACTIVE, self._call_setup_time)

        # WAIT FOR CALL DURATION
        self._logger.info("Wait for call duration: " +
                          str(self._callduration) + "s...")
        time.sleep(self._callduration)

        # RELEASE THE CALL
        # Phone1 & 2 : Check call is still active
        self._voice_call_api.check_state(
            self._uecmd_types.VOICE_CALL_STATE.ACTIVE)
        self._voice_call_api2.check_state(
            self._uecmd_types.VOICE_CALL_STATE.ACTIVE)

        # Phone1 : Release the call
        time.sleep(self._wait_btwn_cmd)
        self._releaser_phone.release()

        # Phone1 & 2 : Check call is idle
        self._voice_call_api.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.NOCALL, self._call_setup_time)
        self._voice_call_api2.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.NOCALL, self._call_setup_time)

        # pylint: enable=E1101
        return Global.SUCCESS, "No errors"
示例#13
0
class LabAudioAPxCalibrationCSV(UseCaseBase):
    """
    AudioComms calibration APx class.
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        # Call UseCaseBase Init function
        UseCaseBase.__init__(self, tc_name, global_config)

        # Create APx
        self._audio_analyzer = self._em.get_audio_analyzer("AudioAnalyzer")

        # Check if IO card is used
        self._use_io_card = str_to_bool(
            global_config.campaignConfig.get("isIoCardUsed"))

        # Create Whs
        if self._use_io_card:
            self._wired_headset = self._em.get_wired_headset("WiredHeadset")

        # Initialization of the test type
        self._test_type = "calibration"

        # Initialization of test result in uplink
        self._result_verdict_ul = Global.FAILURE
        # Initialization of test result in downlink
        self._result_verdict_dl = Global.FAILURE
        # Initialization of test result
        self._result_verdict_final = Global.FAILURE

        # Call Stream Volume
        self._call_stream_volume = 70

        # Initialization of the verdict comment
        self._verdict_comment = "APx Calibration fail"

        # Read registrationTimeout from Device_Catalog.xml
        self._registration_timeout = \
            int(self._dut_config.get("registrationTimeout"))

        # Read callSetupTimeout from Device_Catalog.xml
        self._call_setup_time = \
            int(self._dut_config.get("callSetupTimeout"))

        # Read accessories type from test case xml file (str)
        self._acc_type = str(self._tc_parameters.get_param_value("ACC_TYPE"))

        # Call Stream Volume in percent
        self._call_stream_volume_dut = \
            int(self._tc_parameters.get_param_value("CALL_VOLUME_DUT"))

        # Call Stream Volume in percent
        self._call_stream_volume_ref = \
            int(self._tc_parameters.get_param_value("CALL_VOLUME_REF"))

        # Read Audio Analyzer parameters from bench config xml file (str)
        self._audio_analyser = global_config.benchConfig.\
            get_parameters("AudioAnalyzer")
        self._bt_remote_addr = self._audio_analyser.get_param_value(
            "Bt_mac_addr")

        # Instantiate generic UECmd for voiceCall Ucs
        self._voice_call_api = self._device.get_uecmd("VoiceCall")
        self._phonesystem_api = self._device.get_uecmd("PhoneSystem")
        self._phonemodem_api = self._device.get_uecmd("Modem")
        self._system_api = self._device.get_uecmd("System")

        if self._acc_type.find("BLUETOOTH") != -1:
            # Get UECmdLayer
            self._bt_api = self._device.get_uecmd("LocalConnectivity")
            # Get dut bt address
            self._dut_bt_address = self._bt_api.get_bt_adapter_address()
        else:
            self._dut_bt_address = "None"

        # Load instance of the PHONE2
        self._phone2 = DeviceManager().get_device("PHONE2")

        if self._phone2 is not None:
            if not self._phone2.is_available():
                self._phone2.switch_on(simple_switch_mode=True)
            self._voice_call_api2 = self._phone2.get_uecmd("VoiceCall")
            self._system_api2 = self._phone2.get_uecmd("System")

        else:
            self._voice_call_api2 = None
            self._system_api2 = None

        # Setup phone type ( calling, receiving, releasing phone)
        self._phone_calling = self._voice_call_api
        self._phone_receiving = self._voice_call_api2
        self._calling_phone_number = self._phone2.get_phone_number()
        self._phone_releasing = self._voice_call_api2

    def set_up(self):
        """
        Set up the test configuration
        """
        # Call UseCaseBase Setup function
        UseCaseBase.set_up(self)

        # Check if we have the second phone available
        if self._phone2 is None:
            # We are using this multi UC with only one phone
            error_msg = \
                "This test case requires two phones to be executed !"
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     error_msg)

        # APx Initialization
        if self._audio_analyzer.initialization(self._device.get_phone_model(),
                                               self._test_type) != 0:
            error_msg = \
                "APX Initialization Failed !"
            self._logger.error(error_msg)
            raise TestEquipmentException(
                TestEquipmentException.OPERATION_FAILED, error_msg)

        # Release any previous call (Robustness)
        self._voice_call_api.release()
        self._voice_call_api2.release()

        return Global.SUCCESS, "No errors"

    def run_test(self):
        """
        Execute the test
        """
        # Call UseCaseBase run_test function
        UseCaseBase.run_test(self)

        if self._acc_type == "HEADSET":
            if self._use_io_card:
                self._wired_headset.unplug_headphone()
                self._wired_headset.plug_whs()
        elif self._acc_type == "HEADPHONE":
            if self._use_io_card:
                self._wired_headset.unplug_whs()
                self._wired_headset.plug_headphone()

        # Dial using PHONE_NUMBER parameter
        self._phone_calling.dial(self._calling_phone_number)
        time.sleep(self._wait_btwn_cmd)

        # Wait for state "active" before callSetupTimeout seconds
        self._phone_receiving.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.INCOMING, self._call_setup_time)

        # Answer call
        self._phone_receiving.answer()

        # Phone1 & 2 : Check voice call is active
        self._phone_calling.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.ACTIVE, self._call_setup_time)
        self._phone_receiving.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.ACTIVE, self._call_setup_time)

        # Configure Audio output to acc_type given with the test_case
        if self._acc_type == "EARPIECE":
            if self._use_io_card:
                self._wired_headset.unplug_whs()
                self._wired_headset.unplug_headphone()
        elif self._acc_type == "SPEAKER":
            # Switch to Speaker, nothing to do in Earpiece
            # Bluetooth already done with connect Bluetooth function above
            self._phonesystem_api.switch_audio_output(self._acc_type.lower())
            time.sleep(self._wait_btwn_cmd)
        elif self._acc_type.find("BLUETOOTH") != -1:
            if self._audio_analyzer.connect_bt(self._acc_type,
                                               self._dut_bt_address) != 0:
                error_msg = \
                    "Connect Bluetooth failed !"
                self._logger.error(error_msg)
                raise DeviceException(DeviceException.OPERATION_FAILED,
                                      error_msg)

        if self._acc_type.find("BLUETOOTH") == -1:
            # Set Voice Call Volume
            self._system_api.adjust_specified_stream_volume(
                "VoiceCall", self._call_stream_volume_dut)
        else:
            # Set Voice Call Volume
            self._system_api.adjust_specified_stream_volume(
                "Bluetooth", self._call_stream_volume_dut)

        self._system_api2.adjust_specified_stream_volume(
            "VoiceCall", self._call_stream_volume_ref)
        # Launch Apx Calibration test on Uplink
        apx_result = self._audio_analyzer.calibration(
            self._device.get_phone_model(), "3G", self._acc_type, "UL",
            self._dut_bt_address)

        if apx_result == 0:
            self._result_verdict_ul = Global.SUCCESS
            self._verdict_comment = "APx Calibration success in UL"
        else:
            self._result_verdict_ul = Global.FAILURE
            self._verdict_comment = "APx Calibration fail in UL"

        # Launch Apx Calibration test on Downlink
        apx_result = self._audio_analyzer.calibration(
            self._device.get_phone_model(), "3G", self._acc_type, "DL",
            self._dut_bt_address)

        if apx_result == 0:
            self._result_verdict_dl = Global.SUCCESS
            self._verdict_comment += " and APx Calibration success in DL"
        else:
            self._result_verdict_dl = Global.FAILURE
            self._verdict_comment += " and APx Calibration fail in DL"

        # Compute final verdict
        if self._result_verdict_ul == Global.FAILURE or \
           self._result_verdict_dl == Global.FAILURE:
            self._result_verdict_final = Global.FAILURE
        else:
            self._result_verdict_final = Global.SUCCESS

        # RELEASE THE CALL
        # Phone1 & 2 : Check call is still active
        self._phone_calling.check_state(
            self._uecmd_types.VOICE_CALL_STATE.ACTIVE)
        self._phone_receiving.check_state(
            self._uecmd_types.VOICE_CALL_STATE.ACTIVE)

        # Hang up call
        self._phone_releasing.release()

        # Phone1 & 2 : Check call is idle
        self._phone_calling.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.NOCALL, self._call_setup_time)
        self._phone_receiving.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.NOCALL, self._call_setup_time)

        return self._result_verdict_final, self._verdict_comment

    def tear_down(self):
        """
        End and dispose the test
        """
        # Call UseCaseBase tear_down function
        UseCaseBase.tear_down(self)

        if self._acc_type == "HEADSET":
            if self._use_io_card:
                self._wired_headset.unplug_whs()
        elif self._acc_type == "HEADPHONE":
            if self._use_io_card:
                self._wired_headset.unplug_headphone()

        # Release any previous call (Robustness)
        self._voice_call_api.release()
        self._voice_call_api2.release()

        # Reset Voice Call Volume at 70%
        if self._system_api is not None:
            self._system_api.adjust_specified_stream_volume("VoiceCall", 70)
        if self._system_api2 is not None:
            self._system_api2.adjust_specified_stream_volume("VoiceCall", 70)

        return Global.SUCCESS, "No errors"
class LiveSystemSleepResidencyMeasurement(SystemSleepBase):
    """
    Sleep mode residency measurement class.
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor

        :type tc_name: BaseConf
        :param tc_name: Configuration of the usecase

        :type global_config: Dictionary
        :param global_config: Global configuration of the campaign
        """

        # Call UseCase base constructor
        self._device = DeviceManager().get_device("PHONE1")

        self.__adbConnectionTimeout = self._device.get_config(
            "adbConnectTimeout", 30, float)
        self._device_uptime_begin = None
        self._sleep_duration = None

        # If the device was disconnected before due to an error
        # we must reconnect it explicitly at the beginning of the test
        # else some commands will not be executed and the test will be blocked
        self._system_api = self._device.get_uecmd("System")
        return_code = self._system_api.wait_for_device(
            self.__adbConnectionTimeout)
        if not return_code:
            time.sleep(30)

        if not self._device.is_available():
            self._device.connect_board()

        # Call SystemSleepBase base Init function
        SystemSleepBase.__init__(self, tc_name, global_config)

        self._report_tree = global_config.campaignConfig.get(
            "campaignReportTree")
        self._sysdebug_apis = self._device.get_uecmd("SysDebug")

        self._tc_name = os.path.basename(self.get_name())
        self._tc_date = ""
        attributes = {"id": self._tc_name, "date": self._tc_date}

        self.__results = PnPResults(self._report_tree,
                                    self._dut_config.get("Name"),
                                    self._failure_file, None, attributes)

    def run_test(self):
        """
        Execute the test
        """

        sysdbg_modules_config = self._tc_parameters.get_param_value(
            "SYSDEBUG_MODULES")
        self._sysdebug_apis.init(sysdbg_modules_config)

        sleep_parameter = self._tc_parameters.get_param_value("SLEEP_DURATION")
        if sleep_parameter is not None and sleep_parameter != "" and sleep_parameter.isdigit(
        ):
            self._sleep_duration = int(sleep_parameter)

        # Call live sleep use case base
        SystemSleepBase.run_test(self)

        self._tc_date = time.strftime("%Y-%m-%d %H:%M:%S")
        self.__results.update({"date": self._tc_date})

        while not self._sysdebug_apis.synchronize():
            time.sleep(10)

        adbConnectTimeout = self._device.get_config("adbConnectTimeout", 10,
                                                    float)
        usbReplugRetries = self._device.get_config("usbReplugRetries", 1, int)

        if self._io_card is not None:
            self._device.disconnect_board()
            self._sysdebug_apis.reset()  # will clear mid_pmu_states
            self._residency_api.clear(
                self._sleep_duration)  # will also clear mid_pmu_states
            # but this is needed to do the fetch on this instance
            self._io_card.usb_host_pc_connector(False)
            # Unplug wall charger only if it is AC_CHGR
            if self._device.get_default_wall_charger(
            ) == self._io_card.AC_CHGR:
                self._io_card.wall_charger_connector(False)

        # Update device uptime
        updated, self._device_uptime_begin = self._device._update_device_up_state(
            0)
        if not updated:
            self._device_uptime_begin = None

        if self._sleep_duration:
            self._logger.info(
                "Wait for %s s before measurement (sleep duration before %s)" %
                (str(self._sleep_duration), self._sleep_mode))
            time.sleep(self._sleep_duration)

        self._sysdebug_apis.start()
        self._logger.info("Wait for %s s to enter in %s" %
                          (str(self._duration), self._sleep_mode))
        time.sleep(self._duration)
        self._sysdebug_apis.stop()

        residency_spent = 0
        ret_code = None

        if self._io_card is not None:
            for cnt in range(0, usbReplugRetries + 1):
                self._logger.debug("Loop Iteration: %d" % cnt)
                # plug wall charger only if it is AC_CHGR
                if self._device.get_default_wall_charger(
                ) == self._io_card.AC_CHGR:
                    self._io_card.wall_charger_connector(True)
                self._io_card.usb_host_pc_connector(True)

                self._logger.debug("Wait for device %s seconds" %
                                   self.__adbConnectionTimeout)
                ret_code = self._system_api.wait_for_device(
                    self.__adbConnectionTimeout)
                self._logger.debug("Wait for device return code: %s" %
                                   ret_code)
                if not ret_code:
                    if cnt < usbReplugRetries:
                        self._logger.warning(
                            "timeout on wait-for-device, trying to unplug/replug (try %s/%s)"
                            % (str(cnt + 1), str(usbReplugRetries)))
                        self._io_card.usb_host_pc_connector(False)
                        # Unplug wall charger only if it is AC_CHGR
                        if self._device.get_default_wall_charger(
                        ) == self._io_card.AC_CHGR:
                            self._io_card.wall_charger_connector(False)
                        time.sleep(10)
                    continue

                residency_spent = self._residency_api.get_value(
                    "residency", self._sleep_mode_api.get_sleep_mode())
                self._sysdebug_apis.fetch()
                self._device.connect_board()
                self._logger.debug("device retrieved after %s tries" %
                                   str(cnt + 1))
                break

            if not ret_code:
                raise DeviceException(
                    DeviceException.OPERATION_FAILED,
                    "Could not retrieve the device after %s plug/unplug cycles"
                    % str(usbReplugRetries))

        if residency_spent is None:
            raise DeviceException(
                DeviceException.INVALID_PARAMETER,
                "There is no %s sleep mode for this device model" %
                self._sleep_mode_api.get_sleep_mode())

        # Get device uptime and raise an exception if the device rebooted
        if self._device_uptime_begin:
            updated, uptime = self._device._update_device_up_state(
                self._device_uptime_begin)
            if updated and not self._device.is_up:
                self._logger.warning(
                    "the device uptime was %s before the measurement, %s now !"
                    % (str(self._device_uptime_begin), str(uptime)))
                raise DeviceException(
                    DeviceException.OPERATION_FAILED,
                    "Device rebooted during the measurement")

        sysreport = self._sysdebug_apis.report()
        self.__results.append(sysreport)
        self.__results.write()

        return self._residency_verdict(residency_spent)
示例#15
0
class LiveDsdsFtMms(UseCaseBase):
    """
    Use Case Live SMS loopback class.
    """
    def __init__(self, tc_name, global_config):

        UseCaseBase.__init__(self, tc_name, global_config)

        self.awake = False
        self._test_timeout = 10
        self._call_setup_time = 15
        self.d = Device(self._device.retrieve_serial_number())
        self._registration_timeout = \
            int(self._dut_config.get("registrationTimeout"))

        self._phone_number = str(self._device.get_phone_number())

        self._repeat_count = 0
        repeat_count = self._tc_parameters.get_param_value("REPEAT_COUNT", "0")
        if repeat_count and repeat_count.isdigit():
            self._repeat_count = int(repeat_count)

        self._destination_number = \
            str(self._tc_parameters.get_param_value("DESTINATION_NUMBER"))
        # Retrieve the mms_type parameters.
        self._mms_type = self._tc_parameters.get_param_value("MMS_TYPE")

        # Retrieve the MMS subject.
        self._mms_subject = self._tc_parameters.get_param_value("MMS_SUBJECT")

        if self._mms_type == "text":
            self._attachment_file = None
        else:
            self._multimedia_path = self._device.multimedia_path
            # Retrieve the path of the MMS attachment.
            self._attachment_file = os.path.join(
                self._multimedia_path,
                self._tc_parameters.get_param_value("ATTACHED_FILE"))

        # Retrieve the time that the test should wait to receive the MMS.
        self._send_mms_timeout = \
            int(self._tc_parameters.get_param_value("SENT_MMS_TIMEOUT"))
        self._message=\
            str(self._tc_parameters.get_param_value("MESSAGE_CONTENT", ""))

        self._received_mms_timeout = \
            int(self._tc_parameters.get_param_value("RECEIVED_MMS_TIMEOUT"))
        self._test_timeout = 10
        self._phone = DeviceManager().get_device("PHONE1")

        self._phone2 = DeviceManager().get_device("PHONE2")

        self._phone_number2 = str(self._phone2.get_phone_number())
        self._default_sim = self._tc_parameters.get_param_value("DEFAULT_SIM")

        self._network_pref = self._tc_parameters.get_param_value(
            "PREFERRED_NETWORK_TYPE", None)
        if self._network_pref:
            self._network_pref = self._network_pref.upper()
        self._initial_pref_network = None
        #Parameter to download or upload
        self._direction = self._tc_parameters.get_param_value("DIRECTION")
        self._server_name = \
            self._tc_parameters.get_param_value("SERVER_NAME",
                                                "LAB_SERVER")
        self._callduration = \
             int(self._tc_parameters.get_param_value("CALL_DURATION"))

        # Get FTP server parameters
        self._server = \
            global_config.benchConfig.get_parameters(self._server_name)
        self._server_ip_address = self._server.get_param_value("IP")
        self._username = self._server.get_param_value("username")
        self._password = self._server.get_param_value("password")
        if self._server.has_parameter("ftp_path"):
            self._ftp_path = self._server.get_param_value("ftp_path")
        else:
            self._ftp_path = ""

        #The file need to download
        self._dlfilename = os.path.join(
            self._ftp_path, self._tc_parameters.get_param_value("DL_FILE", ""))
        #Max time for file transfer
        self._xfer_timeout = \
            int(self._tc_parameters.get_param_value("XFER_TIMEOUT"))

        # The base name of the file we download
        self._ftp_file_basename = self._tc_parameters.get_param_value(
            "BASENAME")
        self._system_api = self._device.get_uecmd("System")
        self._sms_api = self._device.get_uecmd("SmsMessaging")
        self._sms_api2 = self._phone2.get_uecmd("SmsMessaging")
        self._mms_api = self._device.get_uecmd("MmsMessaging")
        self._mms_api2 = self._phone2.get_uecmd("MmsMessaging")
        self._sms_api2 = self._phone2.get_uecmd("SmsMessaging")

        #self._voice_call_api2 = self._phone2.get_uecmd("VoiceCall")
        self._networking_api = self._device.get_uecmd("Networking")
        self._phone_system_api = self._device.get_uecmd("PhoneSystem")
        #self._phone_system_api2 = self._phone2.get_uecmd("PhoneSystem")
        self._ftp_api = self._device.get_uecmd("Ftp")
        self._modem_api = self._device.get_uecmd("Modem")
        self._phonesystem_api = self._device.get_uecmd("PhoneSystem")
        #self._phone_system_api2 = self._phone2.get_uecmd("PhoneSystem")

        self._networking_api = self._device.get_uecmd("Networking")
        #self._voice_call_api2 = self._phone2.get_uecmd("VoiceCall")
        #self._networking_api2 = self._phone2.get_uecmd("Networking")
        self._voicecall_api = self._phone.get_uecmd("VoiceCall")

        if self._phone2 is not None:
            self._voice_call_api2 = self._phone2.get_uecmd("VoiceCall")
            self._networking_api2 = self._phone2.get_uecmd("Networking")
            self._phone_system_api2 = self._phone2.get_uecmd("PhoneSystem")
#--------------------------------------------------------------------------------------

    def set_up(self):
        """
        Setup for the test case
        """

        # Call set_up of use case base
        UseCaseBase.set_up(self)

        # Check if we have the second phone available
        if self._phone2 is None:
            # We are using this multi UC with only one phone
            error_msg = \
                "This use case requires two phones to be executed !"
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     error_msg)

        # Boot the other phone (the DUT is already booted)
        if not self._phone2.is_available():
            DeviceManager().boot_device("PHONE2")
        if self._default_sim == "SIM2":
            #Setting the sim to Default
            (verdict, msg) = self._setDefaultSecondSim()
        else:
            (verdict, msg) = self._setDefaultSim()

        time.sleep(10)
        self._absolute_path_on_dut = "".join(
            [self._device.multimedia_path, self._ftp_file_basename])

        # Delete the FTP download file on the DUT
        self._delete_file_if_exists(self._absolute_path_on_dut)

        # Disable flight mode
        self._networking_api.set_flight_mode("off")
        time.sleep(self._wait_btwn_cmd)

        if self._mms_type.lower() == "picture":
            # Checks if the attachment file exist.
            self._phonesystem_api.check_file_exist(self._attachment_file)

        # Kill the messaging application.
        self._kill_messaging_app()

        time.sleep(self._wait_btwn_cmd)

        # There is a preferred network to set, backup initial, then set configured one
        if self._network_pref is not None:
            self._initial_pref_network = self._dut_config.get(
                "defaultPreferredNetwork")
            time.sleep(self._wait_btwn_cmd)

            if self._networking_api.is_preferred_network_type_valid(
                    self._network_pref):
                # Setting the DUT preferred network type to the one specified
                # in the TC.
                self._networking_api.set_preferred_network_type(
                    self._network_pref)
                time.sleep(self._wait_btwn_cmd)

                # Check the DUT is camped on a compatible network with the selected
                # preferred network.
                self._modem_api.check_rat_with_pref_network(
                    self._network_pref, self._registration_timeout)
                time.sleep(self._wait_btwn_cmd)
            else:
                raise AcsConfigException(
                    AcsConfigException.INVALID_PARAMETER,
                    "Unknown network type: %s" % self._network_pref)

        return verdict, msg
#--------------------------------------------------------------------------------------

    def run_test(self):
        """
        Execute the test
        """
        #Call UseCase base run function
        UseCaseBase.run_test(self)

        queue = Queue.Queue()
        #creating empty list to append the threads
        threads = []
        #creating empty list to append the return value from the threads
        result = []
        try:
            #creating thread object to trigger to the _ftpdownloads method
            thread_ftp = Thread(target=self._ftpdownload, args=[queue])
            thread_ftp.setName("Thread1")
            #to start the thread object
            thread_ftp.start()
            time.sleep(10)
            #creating thread object to trigger to the _smssendreceive method
            thread_mms = Thread(target=self._sendmms, args=[queue])
            thread_mms.setName("Thread2")
            #to start the thread object
            thread_mms.start()
        except Exception as inst:
            self._logger.info(inst)
            raise AcsConfigException(AcsConfigException.OPERATION_FAILED,
                                     "Exception: %s" % inst)
            return Global.FAILURE, "Error"

        #appending the thread object into the empty list
        threads.append(thread_ftp)
        #appending the thread object into the empty list
        threads.append(thread_mms)
        for thread_id in threads:
            #to make the thread wait for the other thread does not complete
            thread_id.join()
            #appending the return value to the list
            result.append(queue.get())
        #checking the return value is SUCCESS
        if (result[0] or result[1]) == Global.SUCCESS:
            return Global.SUCCESS, "SUCCESSFULL"
        else:
            return Global.FAILURE, "Error"

#---------------------------------------------------------------------------------------------

    def _ftpdownload(self, queue):
        """
        Execute the web browsing
        """
        #creating the lock
        lock = threading.Lock()
        lock.acquire()
        try:
            self._logger.info("inside _ftpdownload function")
            #Thread no
            self._logger.info(current_thread())
            #checking the pdp status
            pdp_context_status = self._networking_api._get_pdp_context_status()
            if pdp_context_status in ("0", "2"):
                self._networking_api.activate_pdp_context()
            time.sleep(self._wait_btwn_cmd)
            if self._direction == "DL":
                self._logger.info("FTP transfer " + str(self._direction) +
                                  " for " + str(self._dlfilename) + "...")
                # Uecmd to do ftp and storing the result
                result = self._networking_api.\
                    ftp_xfer(self._uecmd_types.XFER_DIRECTIONS.DL,  # pylint: disable=E1101
                             self._server_ip_address,
                             self._username,
                             self._password,
                             self._dlfilename,
                             self._xfer_timeout,
                             self._device.multimedia_path)
            else:
                self._error.Code = Global.FAILURE
                self._error.Msg = "%s is not a known xfer direction" % self._direction
                self._logger.info(self._error.Msg)
                queue.put(self._error.Code)
        except Exception as inst:
            self._error.Code = Global.FAILURE
            queue.put(self._error.Code)
            self._logger.info(inst)
            raise AcsConfigException(AcsConfigException.OPERATION_FAILED,
                                     "Exception : %s" % inst)
        finally:
            #lock is released
            lock.release()
            self.awake = True
        #giving the return value into queue
        queue.put(Global.SUCCESS)
#---------------------------------------------------------------------------------------------

    def _sendmms(self, queue):

        lock = threading.Lock()
        lock.acquire()
        try:
            time_to_receive_mms = None
            time_to_send_mms = None
            time_waited = 0

            # Max number of iteration done while waiting for the screen to turn off.
            # Used to prevent endless loops.
            max_time_waited = 200

            # Clear all SMS and MMS.
            self._mms_api.delete_all_messages()

            # Wait for the screen to turn off.
            while self._phonesystem_api.get_screen_status() \
                and time_waited < max_time_waited:
                time.sleep(5)
                time_waited += 5
            self._logger.info("Waited %s seconds for the screen to turn off." %
                              time_waited)
            # Checks if the screen turned off before a fixed timeout.
            if time_waited >= max_time_waited:
                raise DeviceException(
                    DeviceException.TIMEOUT_REACHED,
                    "The screen did not turned off in %s." % max_time_waited)

            # Wake up the phone screen.
            time.sleep(self._wait_btwn_cmd)
            self._logger.info("Turning the screen on.")
            self._phonesystem_api.set_phone_lock("off")
            self._phonesystem_api.wake_screen()
            self._phonesystem_api.set_phone_lock(0)

            # register on intent to receive incoming mms
            self._mms_api2.register_for_mms_reception()

            # Build the MMS.
            time.sleep(self._wait_btwn_cmd)
            self._mms_api.send_mms(self._mms_type, self._destination_number,
                                   self._mms_subject, self._message,
                                   self._attachment_file, self._repeat_count)

            time.sleep(self._wait_btwn_cmd)

            # Waiting for the MMS to be send.
            sent_time = self._mms_api.check_mms_sent(self._destination_number,
                                                     self._send_mms_timeout)

            # Waiting on incoming message.
            reception_date = self._mms_api2.wait_for_incoming_mms(
                self._received_mms_timeout, self._destination_number)

            # Logging the time taken to receive the MMS.
            time_to_receive_mms = float(reception_date) - float(sent_time)

            self._logger.info("The MMS has been received in %s seconds." %
                              time_to_receive_mms)

            # Compare the sent and received MMS.
            self._mms_api.request_remote_send_received_mms_compare(
                self._mms_type)
        except Exception as inst:
            self._error.Code = Global.FAILURE
            queue.put(self._error.Code)
            self._logger.info(inst)
            raise AcsConfigException(AcsConfigException.OPERATION_FAILED,
                                     "Exception : %s" % inst)
        finally:
            #lock is released
            lock.release()
            print("the awake for ftp")
            print(self.awake)

        queue.put(Global.SUCCESS)
#--------------------------------------------------------------------------------------------------

    def _setDefaultSim(self):

        self._device.run_cmd("adb shell input keyevent 82",
                             self._test_timeout,
                             force_execution=True)
        time.sleep(8)
        #To pop up the dialog box for selecting the sim
        statusintent = self._voicecall_api.get_sim_select(dialog=3, sim=0)
        self._logger.info(statusintent)
        #To check dailog is reached or not
        if statusintent == {}:
            err_msg = " The option dialog is not reached"
            raise DeviceException(DeviceException.OPERATION_SET_ERROR, err_msg)
            return Global.FAILURE, err_msg
        #Waiting for the dailog box
        if self.d(resourceId='android:id/title_template').wait.exists(
                timeout=5000):
            #clicking the default sim
            self.d(resourceId='android:id/button1').click()
            self._logger.info("Default sim is selected")
            return Global.SUCCESS, "Default sim is selected"
        else:
            err_msg = "Dialog is not opening"
            raise DeviceException(DeviceException.OPERATION_SET_ERROR, err_msg)
            return Global.FAILURE, err_msg

#-------------------------------------------------------------------------------------------------

    def _setDefaultSecondSim(self):

        self._device.run_cmd("adb shell input keyevent 82",
                             self._test_timeout,
                             force_execution=True)
        time.sleep(8)
        #To pop up the dialog box for selecting the sim
        statusintent = self._voicecall_api.get_sim_select(dialog=3, sim=1)
        self._logger.info(statusintent)
        #To check dailog is reached or not
        if statusintent == {}:
            err_msg = " The option dialog is not reached"
            raise DeviceException(DeviceException.OPERATION_SET_ERROR, err_msg)
            return Global.FAILURE, err_msg
        #Waiting for the dailog box
        if self.d(resourceId='android:id/title_template').wait.exists(
                timeout=5000):
            #clicking the default sim
            self.d(resourceId='android:id/button1').click()
            self._logger.info("Default sim is selected")
            return Global.SUCCESS, "Default sim is selected"
        else:
            err_msg = "Dialog is not opening"
            raise DeviceException(DeviceException.OPERATION_SET_ERROR, err_msg)
            return Global.FAILURE, err_msg

#-------------------------------------------------------------------------------------------------

    def _delete_file_if_exists(self, file_path, fail_on_error=True):
        """
        Deletes the given file on DUT if it exists.

        :type file_path: str
        :param file_path: the absolute path of the file to delete.

        :type fail_on_error: bool
        :param fail_on_error: [optional] a boolean indicating whether
            we want to raise an exception on error or not.
            Defaults to C{True}.
        """
        # Force file path to a str value
        file_path = str(file_path)
        rm_cmd = "adb shell rm %s" % file_path
        # We go on only if the file exists on the DUT
        if not self._phone_system_api.check_file_exist_from_shell(file_path):
            self._logger.debug("No such file to delete.")
            return
        # We try to delete the file
        try:
            # Run the command to remove the file, we give it 10 seconds to run
            self._logger.debug("Deleting file %s." % file_path)
            (exit_status, _output) = internal_shell_exec(rm_cmd, 10)
        except (KeyboardInterrupt, SystemExit):
            raise
        # We want to trap any kind of error/exception so
        # we use an empty exception clause and disable the
        # corresponding Pylint warning.
        # pylint: disable=W0702
        except:
            exit_status = Global.FAILURE
            traceback.print_exc()

        # Check the status of the command execution
        if exit_status != Global.SUCCESS:
            # Build an error message
            error_message = "Command execution failed (command: '%s')." % rm_cmd
            # Handle the error case as expected
            if fail_on_error:
                # If we have to fail, raise an exception
                raise DeviceException(DeviceException.OPERATION_FAILED,
                                      error_message)
            else:
                # Otherwise simply log a warning
                self._logger.warning(error_message)

        # We double-check that the file has been deleted
        if self._phone_system_api.check_file_exist_from_shell(file_path):
            # Build an error message
            error_message = "File deletion failed (file: '%s')." % file_path
            # Handle the error case as expected
            if fail_on_error:
                # If we have to fail, raise an exception
                raise DeviceException(DeviceException.OPERATION_FAILED,
                                      error_message)
            else:
                # Otherwise simply log a warning
                self._logger.warning(error_message)
        else:
            self._logger.info("File %s deleted successfully." % file_path)

#--------------------------------------------------------------------------------

    def _kill_messaging_app(self):
        """
        Kills the MMS application if it was running and makes sure it has been
        killed successfully
        """
        # Get the pid of the MMS application
        pid = self._system_api.pid_of("com.android.mms")
        # Killing the MMS application, if running
        if pid != "":
            self._mms_api.kill_mms_app()
            # Checking if the MMS application as really been killed.
            new_pid = self._system_api.pid_of("com.android.mms")
            if new_pid == pid:
                raise DeviceException(
                    DeviceException.OPERATION_FAILED,
                    "The stock messaging application"
                    " should not be running.")
        else:
            self._logger.info("The MMS application was not running.")
class LabNfcDualPhoneBeamTransfert(LabNfcBase):

    # the name of ref phone is the name in BENCH_CONFIG file
    REF_PHONE = "PHONE2"

    def __init__(self, tc_name, global_config):
        LabNfcBase.__init__(self, tc_name, global_config)

        # second phone init
        self._phone_ref = DeviceManager().get_device(
            LabNfcDualPhoneBeamTransfert.REF_PHONE)
        self._phone_ref.connect_board()

        # Check if we have the ref phone available
        if self._phone_ref is not None:
            if not self._phone_ref.is_available():
                DeviceManager().boot_device(
                    LabNfcDualPhoneBeamTransfert.REF_PHONE)
            self._nfc_api_phone_ref = self._phone_ref.get_uecmd(
                "LocalConnectivity")

        # get PhoneSystem uecmd instance for the ref phone
        self._phonesystem_api_dut = self._device.get_uecmd("PhoneSystem")
        self._phonesystem_api_ref = self._phone_ref.get_uecmd("PhoneSystem")

        self._appmgmt_api = self._phone_ref.get_uecmd("AppMgmt")
        # get file uecmd instance
        self._file_api_dut = self._device.get_uecmd("File")
        self._file_api_ref = self._phone_ref.get_uecmd("File")

        # Get NFC Tags application package name
        self._tag_app = str(self._dut_config.get("TagsAppPackageName"))
        # Get Browsers application package name (need to disable in order to be able to read URI tags)
        self._browser_app = str(self._dut_config.get("BrowserAppPackageName"))
        self._chrome_app = str(self._dut_config.get("ChromeAppPackageName"))

        # force phone 2 state unlock and display on
        # for the DUT this is made in LiveNfcBase class
        self._phonesystem_api_ref.display_on()
        self._phonesystem_api_ref.set_phone_lock(0)
        self._nfc_api_phone_ref.force_nfc_state(1)

        # BE careful here we have to be sure that the file is here (setup embbeded)
        self.__file_to_share = str(
            self._tc_parameters.get_param_value("FILE_TO_SHARE"))

        self.__beam_duration = int(
            self._tc_parameters.get_param_value("BEAM_DURATION"))
        self.__direction = str(
            self._tc_parameters.get_param_value("DIRECTION")).upper()

        self._nfc_robot_param = global_config.benchConfig.get_parameters(
            "NFC_ROBOT1")
        self._beam_path = self._tc_parameters.get_param_value("BEAM_PATH")

        # get ref phone position
        self.__ref_phone_position = self._tc_parameters.get_param_value(
            "REF_PHONE_POSITION")

        self._tag_up = self._nfc_robot_param.get_param_value(
            self.__ref_phone_position + "Up")
        self._tag_down = self._nfc_robot_param.get_param_value(
            self.__ref_phone_position + "Down")
        self._tag_X = self._nfc_robot_param.get_param_value(
            self.__ref_phone_position + "X")
        # get the antenna position
        antenna_position = self._device.get_config("NfcAntennaPosition")
        self._tag_Y = str(
            int(
                self._nfc_robot_param.get_param_value(
                    self.__ref_phone_position + "Y")) +
            int(antenna_position.split(",")[1]))

    # ----------------------------------------------------------------------------------------------

    def set_up(self):

        LabNfcBase.set_up(self)
        # dont need to check if BEAM activated because of the parameters
        # self._Device is DUT
        # self._phone_ref is the reference phone
        # disable "Tags" and browsers built-in apps

        # In DUT
        self._appmgmt_api.app_enable_disable(self._tag_app, False)
        self._appmgmt_api.app_enable_disable(self._browser_app, False)
        self._appmgmt_api.app_enable_disable(self._chrome_app, False)
        # in phone ref
        self._appmgmt_api.app_enable_disable(self._tag_app, False)
        self._appmgmt_api.app_enable_disable(self._browser_app, False)
        self._appmgmt_api.app_enable_disable(self._chrome_app, False)
        self.__size_of_file = 0
        # file have to be in both device, and get its size
        file_exist, result = self._file_api_dut.exist(
            posixpath.join(self._device.multimedia_path, self.__file_to_share))
        if file_exist:
            size = self._file_api_dut.size(
                posixpath.join(self._device.multimedia_path,
                               self.__file_to_share))
            self.__size_of_file = size
        else:
            msg = "File to transfert missing on DUT "
            raise AcsConfigException(AcsConfigException.FILE_NOT_FOUND, msg)
        size = 0
        file_exist, result = self._file_api_ref.exist(
            posixpath.join(self._device.multimedia_path, self.__file_to_share))
        if file_exist:
            size = self._file_api_ref.size(
                posixpath.join(self._device.multimedia_path,
                               self.__file_to_share))
            if size != self.__size_of_file:
                msg = "File to share are different size on DUT and reference phone"
                raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                         msg)
        else:
            msg = "File to transfert missing on reference phone "
            raise AcsConfigException(AcsConfigException.FILE_NOT_FOUND, msg)

        return Global.SUCCESS, "No errors"

    # ----------------------------------------------------------------------------------------------

    def run_test(self):

        msg = "No errors"

        # move robot to start position
        self._robot_positioning(self._tag_X, self._tag_Y, self._tag_up, 'null')

        # do the DUT to ref phone transfert
        if "SEND" or "FULL" in self.__direction:
            # starting beam sequence with DUT
            self.__beam_sequence(self._device)
            if not self.__is_transfert_ok(self._file_api_ref):
                msg = "Error : send BEAM failed on %s sequence" % self.__direction
        # clear beamed files
        self.__clear_beam_sequence()
        time.sleep(5)
        # do the ref phone to DUT transfert
        if "RECEIVE" or "FULL" in self.__direction:
            # starting beam sequence with phone ref
            self.__beam_sequence(self._phone_ref)
            if not self.__is_transfert_ok(self._file_api_dut):
                msg += "Error : receive BEAM failed on %s sequence" % self.__direction
        # clear beamed files
        self.__clear_beam_sequence()

        if msg != "No errors":
            raise DeviceException(DeviceException.OPERATION_FAILED, msg)

        return Global.SUCCESS, msg

    # ----------------------------------------------------------------------------------------------

    def tear_down(self):
        # move robot to start position
        self._robot_positioning(self._tag_X, self._tag_Y, self._tag_up, 'null')
        LabNfcBase.tear_down(self)

        return Global.SUCCESS, "No errors"

    # ----------------------------------------------------------------------------------------------

    def __is_transfert_ok(self, device_system_api):
        file_exist, result = device_system_api.exist(
            posixpath.join(self._beam_path, self.__file_to_share))
        if file_exist:
            size = device_system_api.size(
                posixpath.join(self._beam_path, self.__file_to_share))
            if size == self.__size_of_file:
                return True
            else:
                return False

    # ----------------------------------------------------------------------------------------------

    def __clear_beam_sequence(self):
        # clear beamed files on both devices
        self._file_api_dut.delete(
            posixpath.join(self._beam_path, self.__file_to_share))
        self._file_api_ref.delete(
            posixpath.join(self._beam_path, self.__file_to_share))
        return True

    # ----------------------------------------------------------------------------------------------

    def __open_image(self, device, file_to_open):
        cmd = "adb shell am start -d file:%s -t image/* -a android.intent.action.VIEW -n com.google.android.gallery3d/com.android.gallery3d.app.GalleryActivity" % str(
            file_to_open)
        device.run_cmd(cmd, 10)
        return True

    # ----------------------------------------------------------------------------------------------

    def __close_image(self, device):
        # close image
        cmd = "adb shell pm clear com.google.android.gallery3d"
        device.run_cmd(cmd, 10)
        time.sleep(1)
        return True

    # ----------------------------------------------------------------------------------------------

    def __beam_sequence(self, beamer):
        # first open photo on the beamer
        # DEBUG try to use an uecmd instead like start_display_image
        self._logger.info("Start to BEAM")
        self.__open_image(
            beamer, posixpath.join(beamer.multimedia_path,
                                   self.__file_to_share))
        # move nfc bot
        self._robot_positioning('null', 'null', self._tag_down, 'null')
        # wait a while
        time.sleep(2)

        if beamer.get_config("device_name") == "PHONE1":
            res = self._phonesystem_api_dut.get_screen_resolution().split("x")
            mres = "%dx%d" % (int(res[0]) / 2, int(res[1]) / 2)
            self._nfc_api.nfc_touch_to_beam(mres, 1)
        else:
            res = self._phonesystem_api_ref.get_screen_resolution().split("x")
            mres = "%dx%d" % (int(res[0]) / 2, int(res[1]) / 2)
            self._nfc_api_phone_ref.nfc_touch_to_beam(mres, 1)
        time.sleep(2)
        self._robot_positioning('null', 'null', self._tag_up, 'null')
        time.sleep(self.__beam_duration)
        # close gallery application
        self.__close_image(beamer)
示例#17
0
class LiveDualPhoneVcRingToneVibra(UseCaseBase):
    """
    Live Voice Call Ring Tone Vibra.
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call init of use case base
        UseCaseBase.__init__(self, tc_name, global_config)

        # Get Test Cases Parameters
        self.__minimum_variation = float(
            self._tc_parameters.get_param_value("MINIMUM_VARIATION"))

        # Read callSetupTimeout from Phone_Catalog.xml
        self.__call_setup_time = int(self._dut_config.get("callSetupTimeout"))

        # Get UECmdLayer
        self.__voice_call_api = self._device.get_uecmd("VoiceCall")
        self.__networking_api = self._device.get_uecmd("Networking")
        self.__sensor_api = self._device.get_uecmd("Sensor")
        self.__system_api = self._device.get_uecmd("System")

        # Load instance of the PHONE2
        self.__phone2 = DeviceManager().get_device("PHONE2")

        if self.__phone2 is not None:
            self.__voice_call_api2 = self.__phone2.get_uecmd("VoiceCall")
            self.__networking_api2 = self.__phone2.get_uecmd("Networking")

        else:
            self.__voice_call_api2 = None
            self.__networking_api2 = None

        # Get phone1 number
        self.__phone_number = str(self._device.get_phone_number())

        # Instantiate the instances for phone caller, receiver and releaser
        self.__caller_phone = self.__voice_call_api2
        self.__receiver_phone = self.__voice_call_api
        self.__releaser_phone = self.__voice_call_api2

        self.__check_accelerometer_time = 5
        self.__wait_btw_accelerometer_check = 0.5

#------------------------------------------------------------------------------

    def set_up(self):
        """
        Initialize the test
        """
        # Call set_up of use case base
        UseCaseBase.set_up(self)

        if not self.__minimum_variation or self.__minimum_variation <= 0.5:
            self.__minimum_variation = 0.5

        # Check if we have the second phone available
        if self.__phone2 is None:
            # We are using this multi UC with only one phone
            error_msg = "This use case requires two phones to be executed !"
            self._logger.error(error_msg)
            raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG,
                                     error_msg)

        # Boot the other phone (the DUT is already booted)
        if not self.__phone2.is_available():
            DeviceManager().boot_device("PHONE2")

        # Disable flight mode
        self.__networking_api.set_flight_mode("off")
        self.__networking_api2.set_flight_mode("off")

        # Phone1: set Ringtone volume to 0%, will be in vibration mode
        self.__system_api.adjust_specified_stream_volume('Ringtone', 0)

        return Global.SUCCESS, "No errors"

#------------------------------------------------------------------------------

    def run_test(self):
        """
        Execute the test
        """
        verdict = Global.SUCCESS
        msg = "No errors"

        # Call init of use case base
        UseCaseBase.run_test(self)

        # Release any previous call (Robustness)
        time.sleep(self._wait_btwn_cmd)
        self.__voice_call_api.release()
        self.__voice_call_api2.release()

        # PHONE1: Check accelerometer return before the call
        output, x, y, z = self.__sensor_api.check_sensor_info(
            "accelerometer", "data", "reserve")
        time.sleep(self._wait_btwn_cmd)
        initial_accelerometer_value = abs(x) + abs(y) + abs(z)

        # ESTABLISH THE CALL
        # Phone2 : Dial
        time.sleep(self._wait_btwn_cmd)
        self.__caller_phone.dial(self.__phone_number, False)

        # Phone1 : Wait for state incoming before callSetupTimeout seconds
        self.__receiver_phone.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.INCOMING,
            self.__call_setup_time)

        # PHONE1: Check accelerometer return during the call
        accelerometer_value_while_voice_call = 0
        for iteration in range(self.__check_accelerometer_time):
            output, x, y, z = self.__sensor_api.check_sensor_info(
                "accelerometer", "data", "reserve")
            # Store the highest accelerometer value
            if accelerometer_value_while_voice_call < abs(x) + abs(y) + abs(z):
                accelerometer_value_while_voice_call = abs(x) + abs(y) + abs(z)
            time.sleep(self.__wait_btw_accelerometer_check)

        if accelerometer_value_while_voice_call < initial_accelerometer_value + self.__minimum_variation:
            verdict = Global.FAILURE
            msg = "Accelerometer value during voice call: %s, is not as expected, should be >= %s " \
                % (str(accelerometer_value_while_voice_call), \
                   str(initial_accelerometer_value + self.__minimum_variation))

        # RELEASE THE CALL
        # Phone2 : Release the call
        time.sleep(self._wait_btwn_cmd)
        self.__releaser_phone.release()

        # Phone1 & 2 : Check call is idle
        self.__voice_call_api.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.NOCALL, self.__call_setup_time)
        self.__voice_call_api2.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.NOCALL, self.__call_setup_time)

        return verdict, msg

    def tear_down(self):
        """
        tear down
        """
        UseCaseBase.tear_down(self)

        # Phone1: set Ringtone volume to 50%
        self.__system_api.adjust_specified_stream_volume('Ringtone', 50)

        return self._error.Code, "No errors"
示例#18
0
class LabWifiDirectBase(UseCaseBase):
    """
    Lab Wifi Direct class.
    """

    DEFAULT_REGULATORY_DOMAIN = "US"

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        UseCaseBase.__init__(self, tc_name, global_config)

        self._device1_name = self._tc_parameters.get_param_value(
            "DEVICE1_NAME", "")
        self._device2_name = self._tc_parameters.get_param_value(
            "DEVICE2_NAME", "")

        # Get P2p interface name
        self._device1_p2pinterface = str(self._dut_config.get("p2pInterface"))

        self._device1_supplicant = None
        self._device1_client = None
        self._device1_mac = None
        self._device2_supplicant = None
        self._device2_client = None
        self._device2_mac = None
        self._phone2 = None
        self._networking2_api = None

        self._device2_p2pinterface = None
        if self._device2_name.startswith("PHONE"):
            self.dut_config2 = DeviceManager().get_device_config("PHONE2")
            self._device2_p2pinterface = str(
                self.dut_config2.get("p2pInterface"))

            # Get Device 2 Instance
            self._phone2 = DeviceManager().get_device(self._device2_name)
            self._networking2_api = self._phone2.get_uecmd("Networking")

        self._networking_api = self._device.get_uecmd("Networking")

        self._dut1_wlan_iface = str(self._dut_config.get("wlanInterface"))
        self._dut2_wlan_iface = str(self.dut_config2.get("wlanInterface"))

    def set_up(self):
        """
        Initialize the test
        """
        UseCaseBase.set_up(self)

        self.__check_tc_parameters()

        if self._phone2 is not None and not self._phone2.is_available():
            DeviceManager().boot_device(self._device2_name)

        # set wifi On on the DUT to allow regulatory domain to change
        self._networking_api.set_wifi_power("on")
        if self._networking2_api is not None:
            self._networking2_api.set_wifi_power("on")

        # set the regulatory domain
        self._networking_api.set_regulatorydomain(
            LabWifiDirectBase.DEFAULT_REGULATORY_DOMAIN, self._dut1_wlan_iface)
        if self._networking2_api is not None:
            self._networking2_api.set_regulatorydomain(
                LabWifiDirectBase.DEFAULT_REGULATORY_DOMAIN,
                self._dut2_wlan_iface)

        # set wifi Off on the DUT
        self._networking_api.set_wifi_power("off")
        if self._networking2_api is not None:
            self._networking2_api.set_wifi_power("off")

        return Global.SUCCESS, "No error"

#------------------------------------------------------------------------------

    def _get_supplicant_instance(self, device_name):
        """
        Get the p2p supplicant instance for the device

        :rtype: UECmd Object or Equipement Object
        :return: The p2p supplicant instance for the device
        """
        device_instance = self.__get_device_instance(device_name)

        if device_name.startswith("PHONE"):
            return device_instance.get_uecmd("P2PSupplicantCLI")

        if device_name.startswith("COMPUTER"):
            return device_instance.get_p2p("P2pSupplicant")

        msg = "device not found " + device_name
        self._logger.error(msg)
        raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg)

    def _get_client_instance(self, device_name):
        """
        return the p2p client instance for the device
        """
        device_instance = self.__get_device_instance(device_name)

        if device_name.startswith("PHONE"):
            return device_instance.get_uecmd("P2PClientCLI")

        if device_name.startswith("COMPUTER"):
            return device_instance.get_p2p("P2pClient")

        msg = "device not found " + device_name
        self._logger.error(msg)
        raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg)

    def __get_device_instance(self, device_name):
        """
        retrieve the device instance
        """
        if device_name.startswith("COMPUTER"):
            return self._em

        if device_name == "PHONE1":
            return self._device

        if device_name.startswith("PHONE"):
            if not self._phone2.is_available():
                DeviceManager().boot_device(device_name)

            return self._phone2

        msg = "device not found " + device_name
        self._logger.error(msg)
        raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg)

    def __check_tc_parameters(self):
        """
        Checks all TC parameters
        """
        if not self._device1_name:
            msg = "undefined device name 1."
            self._logger.error(msg)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg)

        if not self._device2_name:
            msg = "undefined device name 2."
            self._logger.error(msg)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg)