예제 #1
0
    def __init__(self, tc_name, global_config):
        """
        Initializes this instance.
        """

        # Call UseCase base __init__ method
        UseCaseBase.__init__(self, tc_name, global_config)

        # Retrieve testcase parameters
        self.__launch_mode = self._tc_parameters.get_param_value("LAUNCH_MODE")
        self.__command = self._tc_parameters.get_param_value("COMMAND")
        self.__expected_result = \
            self._tc_parameters.get_param_value("EXPECTED_RESULT")
        self.__command_timeout = \
            self._tc_parameters.get_param_value("COMMAND_TIMEOUT")

        # initialize at proxy connection parameters
        self.__serial_handler = SerialHandler()

        # Instantiate the modem UE commands
        self.__modem_flashing_api = self._device.get_uecmd("ModemFlashing")

        # Check input parameter LAUNCH_MODE
        possible_launch_mode = {"NORMAL": ModemFlashing.AT_PROXY_NORMAL_MODE,
                                "TUNNELING": ModemFlashing.AT_PROXY_TUNNELING_MODE}
        if self.__launch_mode in possible_launch_mode.keys():
            self.__launch_mode = possible_launch_mode[self.__launch_mode]
        else:
            self.__launch_mode = None

        # Check input parameter COMMAND_TIMEOUT
        if is_number(self.__command_timeout) is True:
            self.__command_timeout = int(self.__command_timeout)
        else:
            self.__command_timeout = None
예제 #2
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        LabGsmSmsCsBase.__init__(self, tc_name, global_config)
        # Set an artificial phone number
        self._destination_number = "123456789"
        # Read the test case params from test case xml
        # Get the max sms we can stored in sim card
        self._sms_amount_to_send = \
            int(self._tc_parameters.get_param_value("SMS_AMOUNT_TO_SEND"))
        # Retrieve testcase parameters for AT proxy usage
        self._launch_mode = 2
        self._command = "AT+CPMS?"
        self._index = 0
        self._expected_result = ""
        self._command_timeout = 20

        # Instantiate the PhoneSystem UE Command category
        self._phone_system = self._device.get_uecmd("PhoneSystem")

        # Instantiate the modem UE commands
        self._modem_flashing_api = self._device.get_uecmd("ModemFlashing")

        # Get Serial Handler instance
        self._serial_handler = SerialHandler()

        # Read SMS_TRANSFER_TIMEOUT from xml UseCase parameter file
        self._sms_transfer_timeout = \
            int(self._tc_parameters.get_param_value("SMS_TRANSFER_TIMEOUT"))
예제 #3
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        # Call Wcdma voice call  base Init function
        LabWcdmaVcBase.__init__(self, tc_name, global_config)

        self._phone_number = \
            str(self._tc_parameters.get_param_value("PHONE_NUMBER"))
        if self._phone_number.upper() == "[PHONE_NUMBER]":
            self._phone_number = str(self._device.get_phone_number())

        # Read IS_EMERGENCY_NUMBER from test case xml file
        self._is_emergency_number_param = \
            str(self._tc_parameters.get_param_value("IS_EMERGENCY_NUMBER"))

        # Retrieve testcase parameters for AT proxy usage
        self._launch_mode = self._tc_parameters.get_param_value("LAUNCH_MODE")
        self._command = self._tc_parameters.get_param_value("COMMAND")
        self._index = self._tc_parameters.get_param_value("INDEX")
        self._expected_result = \
            self._tc_parameters.get_param_value("EXPECTED_RESULT")
        self._command_timeout = \
            self._tc_parameters.get_param_value("COMMAND_TIMEOUT")
        self._command_timeout = int(self._command_timeout)

        # Instantiate the PhoneSystem UE Command category
        self._phone_system = self._device.get_uecmd("PhoneSystem")

        # Instantiate the modem UE commands
        self._modem_flashing_api = self._device.get_uecmd("ModemFlashing")

        # Get Serial Handler instance
        self._serial_handler = SerialHandler()

        # Initialize a boolean attribute corresponding to the
        # previously read parameter
        self._is_emergency_number = False

        # The attribute that will store the initial list
        # of emergency numbers.
        self._initial_emergency_numbers = None

        # Win COM port to be used
        self.at_proxy_com_port = None

        # Store the AT proxy connection availability
        self.modem_available = False

        # Store the verdict for AT@NVM interrogation
        self._at_inter_nvm_em_verdict = None

        # Store the response for AT@NVM interrogation
        self._at_inter_nvm_em = None

        # Store the verdict for setting EM in NVM via AT@NVM
        # it will be used in tear down to know if the initial values
        # should be restored or not in NVM:cust.emergency
        self._at_set_nvm_em = None

        # AT command that will be used for initial NVM:cust.emergency
        # values at the tear down.
        self.command_to_rest_em_in_nvm = None

        # AT command that will be used for setting new EM in  NVM:cust.emergency
        self.command_to_add_em_in_nvm = None

        # Store the initial list of RIL emergency number from UECmdTypes
        self._initial_ue_command_em_number = UECmdTypes.EMERGENCY_NUMBERS_LIST

        #Set up the parameters for the AT@NVM:cust.emergency
        # AT@NVM:cust.emergency[<index>]={<P1>,<P2>,<P3>,<P4>,<P5>,<P6>,<P7>,<P8>}

        # < index>, <index1>, <index2> - index of Emergency number to be stored
        self.index = self._index

        # <P1>,<P2>,<P3> BCD encoded ECC in decimal values
        # Make sure the provided Phone Number parameter is not present
        # in the list of emergency numbers
        self.em_no_length = len(self._phone_number)
        if self.em_no_length != 6:
            # Otherwise create an error message
            message = "Provided parameter PHONE_NUMBER [%s] should be 6 digits" % (
                self._phone_number)
            # Raise an exception
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        # <P1> (in BCD representation)
        self.p1_bcd = int_to_bcd(self._phone_number[0:2])

        # <P2> (in BCD representation)
        self.p2_bcd = int_to_bcd(self._phone_number[2:4])

        # <P2> (in BCD representation)
        self.p3_bcd = int_to_bcd(self._phone_number[4:6])

        #<P4> denotes whether ECC is valid when sim present or not
        # 0 - ECC is not valid when SIM present
        # 1 - ECC is valid when SIM is present
        self.p4 = 1

        #<P5> denotes ECC Category
        self.p5 = 1

        #<P6>, <P7>
        # MCC 2 bytes same as 3GPP PLMN format
        self.p6 = self._mcc
        self.p7 = self._mnc

        #<P8> reserved . give 0xff
        self.p8 = "255"
        self.command_to_add_em_in_nvm = "%s[%s]={%s, %s, %s, %s, %s, %s, %s, %s}" % (
            str(self._command), str(self._index), str(self.p1_bcd),
            str(self.p2_bcd), str(self.p3_bcd), str(self.p4), str(
                self.p5), str(self.p6), str(self.p7), str(self.p8))
예제 #4
0
class LabWcdmaFlightmodeEmVc(LabWcdmaVcBase):
    """
    Lab Wcdma Emergency Voice Call MO/MR with Flight Mode on.
    """

    EMERGENCY_NUMBER_PROPERTY_NAME = "ril.ecclist"
    """
    The name of the property corresponding to the
    list of emergency numbers.
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        # Call Wcdma voice call  base Init function
        LabWcdmaVcBase.__init__(self, tc_name, global_config)

        self._phone_number = \
            str(self._tc_parameters.get_param_value("PHONE_NUMBER"))
        if self._phone_number.upper() == "[PHONE_NUMBER]":
            self._phone_number = str(self._device.get_phone_number())

        # Read IS_EMERGENCY_NUMBER from test case xml file
        self._is_emergency_number_param = \
            str(self._tc_parameters.get_param_value("IS_EMERGENCY_NUMBER"))

        # Retrieve testcase parameters for AT proxy usage
        self._launch_mode = self._tc_parameters.get_param_value("LAUNCH_MODE")
        self._command = self._tc_parameters.get_param_value("COMMAND")
        self._index = self._tc_parameters.get_param_value("INDEX")
        self._expected_result = \
            self._tc_parameters.get_param_value("EXPECTED_RESULT")
        self._command_timeout = \
            self._tc_parameters.get_param_value("COMMAND_TIMEOUT")
        self._command_timeout = int(self._command_timeout)

        # Instantiate the PhoneSystem UE Command category
        self._phone_system = self._device.get_uecmd("PhoneSystem")

        # Instantiate the modem UE commands
        self._modem_flashing_api = self._device.get_uecmd("ModemFlashing")

        # Get Serial Handler instance
        self._serial_handler = SerialHandler()

        # Initialize a boolean attribute corresponding to the
        # previously read parameter
        self._is_emergency_number = False

        # The attribute that will store the initial list
        # of emergency numbers.
        self._initial_emergency_numbers = None

        # Win COM port to be used
        self.at_proxy_com_port = None

        # Store the AT proxy connection availability
        self.modem_available = False

        # Store the verdict for AT@NVM interrogation
        self._at_inter_nvm_em_verdict = None

        # Store the response for AT@NVM interrogation
        self._at_inter_nvm_em = None

        # Store the verdict for setting EM in NVM via AT@NVM
        # it will be used in tear down to know if the initial values
        # should be restored or not in NVM:cust.emergency
        self._at_set_nvm_em = None

        # AT command that will be used for initial NVM:cust.emergency
        # values at the tear down.
        self.command_to_rest_em_in_nvm = None

        # AT command that will be used for setting new EM in  NVM:cust.emergency
        self.command_to_add_em_in_nvm = None

        # Store the initial list of RIL emergency number from UECmdTypes
        self._initial_ue_command_em_number = UECmdTypes.EMERGENCY_NUMBERS_LIST

        #Set up the parameters for the AT@NVM:cust.emergency
        # AT@NVM:cust.emergency[<index>]={<P1>,<P2>,<P3>,<P4>,<P5>,<P6>,<P7>,<P8>}

        # < index>, <index1>, <index2> - index of Emergency number to be stored
        self.index = self._index

        # <P1>,<P2>,<P3> BCD encoded ECC in decimal values
        # Make sure the provided Phone Number parameter is not present
        # in the list of emergency numbers
        self.em_no_length = len(self._phone_number)
        if self.em_no_length != 6:
            # Otherwise create an error message
            message = "Provided parameter PHONE_NUMBER [%s] should be 6 digits" % (
                self._phone_number)
            # Raise an exception
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        # <P1> (in BCD representation)
        self.p1_bcd = int_to_bcd(self._phone_number[0:2])

        # <P2> (in BCD representation)
        self.p2_bcd = int_to_bcd(self._phone_number[2:4])

        # <P2> (in BCD representation)
        self.p3_bcd = int_to_bcd(self._phone_number[4:6])

        #<P4> denotes whether ECC is valid when sim present or not
        # 0 - ECC is not valid when SIM present
        # 1 - ECC is valid when SIM is present
        self.p4 = 1

        #<P5> denotes ECC Category
        self.p5 = 1

        #<P6>, <P7>
        # MCC 2 bytes same as 3GPP PLMN format
        self.p6 = self._mcc
        self.p7 = self._mnc

        #<P8> reserved . give 0xff
        self.p8 = "255"
        self.command_to_add_em_in_nvm = "%s[%s]={%s, %s, %s, %s, %s, %s, %s, %s}" % (
            str(self._command), str(self._index), str(self.p1_bcd),
            str(self.p2_bcd), str(self.p3_bcd), str(self.p4), str(
                self.p5), str(self.p6), str(self.p7), str(self.p8))

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

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

        # Call use case base Setup function
        LabWcdmaVcBase.set_up(self)

        # Update the attribute indicated whether phone number
        # is an emergency number in ril.ecclist
        self._is_emergency_number = \
            str_to_bool(self._is_emergency_number_param)

        # Check the phone number, ensuring that it is not
        # a number corresponding to a "real" emergency number
        # on the LIVE network

        # Retrieve the list of emergency numbers from the DUT as str
        emergency_numbers_string = self._device.get_property_value(
            LabWcdmaFlightmodeEmVc.EMERGENCY_NUMBER_PROPERTY_NAME)

        # Split the str to a list
        emergency_numbers = emergency_numbers_string.split(",")

        # Make sure the provided Phone Number parameter is not present
        # in the list of emergency numbers
        if self._phone_number in emergency_numbers:
            # Otherwise create an error message
            message = "Provided parameter PHONE_NUMBER [%s] as a value  \
                    that corresponds to a real emergency number on the LIVE  \
                    network [list: (%s)]. The test will not be executed." % (
                self._phone_number, emergency_numbers_string)
            # Raise an exception
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        # Store the list of emergency numbers from RIL so that we can
        # restore it later
        self._initial_emergency_numbers = emergency_numbers_string

        # Update the list of RIL Emergency Numbers in UE Command categories
        # Make the 'addition' of 2 tuples by using a single-element tuples
        # using the (<element>,) notation.
        # This needs only to be done if the provided phone number shall
        # be considered to be an Emergency number.
        if self._is_emergency_number:
            UECmdTypes.EMERGENCY_NUMBERS_LIST = \
                self._initial_ue_command_em_number + (self._phone_number,)

        return Global.SUCCESS, "No errors"

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

    def run_test(self):
        """
        Execute the test
        """
        # pylint: disable=E1101
        # Disable this pylint error due to Enum class VOICE_CALL_STATE

        # Call Wcdma VoiceCall base run_test function
        LabWcdmaVcBase.run_test(self)

        # Update the list of RIL Emergency Numbers on the DUT
        # This imperatively has to be done after settting the Flight Mode
        self._logger.info("Add Emergency Number in ril.ecclist list")
        if self._is_emergency_number:
            # Update the property holding the Emergency Numbers list.
            self._device.set_property_value(
                LabWcdmaFlightmodeEmVc.EMERGENCY_NUMBER_PROPERTY_NAME,
                self._phone_number)

        self._logger.info("Add Emergency Number in NVM:cust.emergency list "
                          "at index %s" % self._index)
        #Start up the proxy for sending AT commands
        self.at_proxy_com_port = self._modem_flashing_api.start_at_proxy_from_mos(
            int(self._launch_mode))
        #check serial connection
        self._serial_handler.set_data_analyser(
            ATCommandAnalyser(self._expected_result))
        self._serial_handler.set_default_timeout(self._command_timeout)
        self._logger.info("Connecting to the port " +
                          str(self.at_proxy_com_port))

        # Connect to the at proxy
        self._serial_handler.connect(self.at_proxy_com_port)

        # Check that the modem is available
        modem_status = self._modem_flashing_api.ping_modem_from_serial(
            self._serial_handler.get_serial())

        if modem_status:
            self._logger.info("AT Proxy correctly respond to ping command")
            self.modem_available = True
        else:
            raise TestEquipmentException(
                TestEquipmentException.CONNECTION_ERROR,
                "Connection to AT proxy failed")
        #Send AT@NVM to get initial parameters stored at index "self.index" for restore at
        #finalize
        self._logger.info("Read NVM:cust.emergency list at index %s" %
                          self._index)
        inerrogate_at_nvm_command = self._command + "[" + \
                                    str(self.index) + "]" + "?"
        self._logger.info("Send AT command: %s" % inerrogate_at_nvm_command)
        self._at_inter_nvm_em_verdict, at_nvm_params_to_be_rest_raw =\
                self._serial_handler.send_at_command_and_get_result(inerrogate_at_nvm_command, self._command_timeout)
        at_nvm_params_to_be_rest = re.match("{*.*}",
                                            at_nvm_params_to_be_rest_raw)
        at_nvm_params_to_be_rest = at_nvm_params_to_be_rest.group(0)
        self._logger.info(
            "Data read from NVM:cust.emergency list at index %s are: %s" %
            (self._index, at_nvm_params_to_be_rest))
        self.command_to_rest_em_in_nvm = "%s[%s]=%s" % (str(
            self._command), str(self._index), str(at_nvm_params_to_be_rest))
        #Send AT@NVM to add an emergency number to NNV emergency number list
        self._logger.info("Add NVM:cust.emergency number \"%s\" "
                          "at index %s" % (self._phone_number, self._index))
        self._at_set_nvm_em, msg = self._serial_handler.send_at_command_and_get_result(
            self.command_to_add_em_in_nvm, self._command_timeout)
        if msg == "OK":
            self._logger.info("Response to AT command %s "
                              "is: %s" % (self.command_to_add_em_in_nvm, msg))
        else:
            raise DeviceException(
                DeviceException.OPERATION_SET_ERROR,
                "Response to AT command %s is: %s" %
                (self.command_to_add_em_in_nvm, msg))

        self._logger.info(
            "Start the Emergency Call when DUT is in Flight Mode")
        # Release any previous call (Robustness)
        self._voice_call_api.release()

        # Enable flight mode
        self._networking_api.set_flight_mode("on")

        # Wait 30 seconds to be sure that modem is down before dialing
        time.sleep(30)

        # Wake the screen otherwise the Voice Call will not be established
        self._phone_system.wake_screen()
        self._phone_system.set_phone_lock(0)

        # Dial using PHONE_NUMBER parameter
        self._voice_call_api.dial(self._phone_number)

        # Check call state "CONNECTED" before callSetupTimeout seconds
        self._ns_voice_call_3g.check_call_connected(self._call_setup_time,
                                                    blocking=False)

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

        # Check call is connected for CALL_DURATION seconds
        self._ns_voice_call_3g.is_voice_call_connected(self._call_duration)

        # Mobile Release call
        self._voice_call_api.release()

        # Check voice call state is "IDLE" (8960)
        self._ns_voice_call_3g.check_call_state("IDLE",
                                                self._call_setup_time,
                                                blocking=False)

        # pylint: disable=E1101
        # Disable this pylint error due to Enum class VOICE_CALL_STATE
        # Check voice call state is "no_call" (CDK)
        time.sleep(self._wait_btwn_cmd)
        self._voice_call_api.wait_for_state(
            self._uecmd_types.VOICE_CALL_STATE.NOCALL, self._call_setup_time)
        # pylint: enable=E1101

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

        return Global.SUCCESS, "No errors"

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

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

        # Disable flight mode in the first place in any case
        self._networking_api.set_flight_mode("off")

        self._logger.info(
            "Restore initial emergency numbers in ril.ecclist list")
        # Restore the list of emergency number in UE Command categories
        # if we changed it in the beginning of the Use Case
        if self._is_emergency_number:
            UECmdTypes.EMERGENCY_NUMBERS_LIST = self._initial_ue_command_em_number

            # Restore the list of emergency numbers
            self._device.set_property_value(
                LabWcdmaFlightmodeEmVc.EMERGENCY_NUMBER_PROPERTY_NAME,
                self._initial_emergency_numbers)

        # Call power measurement base tear_down function
        LabWcdmaVcBase.tear_down(self)
        if self.modem_available and (self._at_set_nvm_em is not None):
            self._logger.info("Restore initial emergency numbers in "
                              "NVM:cust.emergency list at index %s" %
                              self._index)
            response, msg = self._serial_handler.send_at_command_and_get_result(
                self.command_to_rest_em_in_nvm, self._command_timeout)
            if msg == "OK":
                self._logger.info("Response to AT command %s is: %s" %
                                  (self.command_to_rest_em_in_nvm, msg))
            else:
                raise DeviceException(
                    DeviceException.OPERATION_SET_ERROR,
                    "Response to AT command %s is: %s" %
                    (self.command_to_rest_em_in_nvm, msg))
        #Stop AT Proxy
        self._logger.info("Stop AT Proxy")
        self._modem_flashing_api.stop_at_proxy_from_mos()

        #Close the serial connection
        self._logger.info("Close the serial connection")
        self._logger.info("Disconnecting from the port " +
                          str(self._serial_handler.get_port()))
        self._serial_handler.disconnect()

        return Global.SUCCESS, "No errors"
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call LabMobilityLte3gsmBase Init function
        LabMobilityLte3gsmBase.__init__(self, tc_name, global_config)

        # Get FTP server parameters
        self._server = \
            global_config.benchConfig.get_parameters("LAB_LTE_SERVER")
        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 = ""

        # Define PING parameters
        self._packet_size = 32
        self._nb_pings = 10

        # Read the the direction file name from UseCase xml Parameter
        self._direction = self._tc_parameters.get_param_value("DIRECTION")

        # Checking if the entered direction is correct.
        if self._direction not in ("UL", "DL", "BOTH"):
            self._error.Msg = "%s is not a known xfer direction" % \
                self._direction
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     self._error.Msg)

        # Read the ftp file name from UseCase xml Parameter
        if self._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('\\', '/')
        elif self._direction == "UL":
            # Read the UL_FILE value from UseCase xml Parameter//
            self._ftp_filename = os.path.join(
                self._ftp_path,
                self._tc_parameters.get_param_value("UL_FILENAME"))
            self._ftp_filename = self._ftp_filename.replace('\\', '/')
        elif self._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 UseCase xml Parameter
            self._ul_ftp_filename = os.path.join(
                self._ftp_path,
                self._tc_parameters.get_param_value("UL_FILENAME"))
            self._ul_ftp_filename = self._ul_ftp_filename.replace('\\', '/')

        # Read CH_BANDWIDTH from test case xml file
        self._bandwidth = \
            self._tc_parameters.get_param_value("CELL_CHANNEL_BANDWIDTH", "20")

        # Read ANTENNAS NUMBER from test case xml file
        self._antennas_number = \
            self._tc_parameters.get_param_value("ANTENNAS_NUMBER", '1')

        # Read TRANSMISSION_MODE from test case xml file
        self._transmission_mode = \
            self._tc_parameters.get_param_value("TRANSMISSION_MODE","TM1")
        # Read BANDWIDTH from test case xml file
        self._type0_bitmap = \
            str(self._tc_parameters.get_param_value("TYPE0_BITMAP","63"))
        # Read DL_RB_SIZE from test case xml file
        self._dl_nb_rb = \
            self._tc_parameters.get_param_value("DL_RB_SIZE","50")
        # Read UL_RB_SIZE from test case xml file
        self._ul_nb_rb = \
            self._tc_parameters.get_param_value("UL_RB_SIZE","10")
        # Read I_MCS from test case xml file
        self._dl_i_mcs = \
            self._tc_parameters.get_param_value("DL_I_MCS","23")
        # Read I_MCS from test case xml file
        self._ul_i_mcs = \
            self._tc_parameters.get_param_value("UL_I_MCS","3")
        # Read UL Grant Mode from test case xml file
        self._ul_grant_mode = \
            self._tc_parameters.get_param_value("UL_GRANT_MODE", "FIXEDMAC")

        # Read the the ip _version file name from UseCase xml Parameter
        self._ip_version = self._tc_parameters.get_param_value(
            "IP_VERSION", "IPV4")

        # Get the server ipv6 address from the BenchConfig, if the key
        # is present in the file.
        if self._server.has_parameter("IPV6"):
            self._server_ip_v6_address = self._server.get_param_value("IPV6")

        # 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

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

        self._two_eps_bearers = self._tc_parameters.get_param_value(
            "TWO_EPS_BEARER")
        self._two_eps_bearers = \
            str_to_bool(self._two_eps_bearers)

        # In case of 2 PDPs, define the APN and IP address for the 2nd one
        if self._two_eps_bearers is True:
            self._second_apn = "agilent2"
            self._second_dut_ip_version = "IPV4"
            self._second_dut_ip_address = "10.102.243.25"

        # Read Inter-Rat redirection type
        self._irat_type = self._tc_parameters.get_param_value("I-RAT_TYPE")
        if self._irat_type is None:
            self._irat_type = "NORMAL"
        elif self._irat_type not in ("NORMAL", "BLIND"):
            raise AcsConfigException(
                AcsConfigException.INVALID_PARAMETER,
                "I-RAT_TYP should be 'NORMAL' or 'BLIND'")

        # Default timeout for DUT camping
        self._camp_timeout = 180

        # Define timeout for AT command
        self._command_timeout = 10

        # Define AT PROXY launch mode
        self._launch_mode = 2

        # Initializing the variable which will contain the IP address to use.
        self._ip_address = None

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

        # if 2 EPS bearers were requested
        if self._two_eps_bearers == True:
            # Instantiate the modem UE commands
            self._modem_flashing_api = self._device.get_uecmd("ModemFlashing")

            # Get Serial Handler instance
            self._serial_handler = SerialHandler()

            # Win COM port to be used
            self.at_proxy_com_port = None

            # Store the AT proxy connection availability
            self.modem_available = False
class LabMobilityLte3gsmRedirFtp(LabMobilityLte3gsmBase):
    """
    Lab I-RAT LTE - 3G/2G FTP
    """
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call LabMobilityLte3gsmBase Init function
        LabMobilityLte3gsmBase.__init__(self, tc_name, global_config)

        # Get FTP server parameters
        self._server = \
            global_config.benchConfig.get_parameters("LAB_LTE_SERVER")
        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 = ""

        # Define PING parameters
        self._packet_size = 32
        self._nb_pings = 10

        # Read the the direction file name from UseCase xml Parameter
        self._direction = self._tc_parameters.get_param_value("DIRECTION")

        # Checking if the entered direction is correct.
        if self._direction not in ("UL", "DL", "BOTH"):
            self._error.Msg = "%s is not a known xfer direction" % \
                self._direction
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     self._error.Msg)

        # Read the ftp file name from UseCase xml Parameter
        if self._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('\\', '/')
        elif self._direction == "UL":
            # Read the UL_FILE value from UseCase xml Parameter//
            self._ftp_filename = os.path.join(
                self._ftp_path,
                self._tc_parameters.get_param_value("UL_FILENAME"))
            self._ftp_filename = self._ftp_filename.replace('\\', '/')
        elif self._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 UseCase xml Parameter
            self._ul_ftp_filename = os.path.join(
                self._ftp_path,
                self._tc_parameters.get_param_value("UL_FILENAME"))
            self._ul_ftp_filename = self._ul_ftp_filename.replace('\\', '/')

        # Read CH_BANDWIDTH from test case xml file
        self._bandwidth = \
            self._tc_parameters.get_param_value("CELL_CHANNEL_BANDWIDTH", "20")

        # Read ANTENNAS NUMBER from test case xml file
        self._antennas_number = \
            self._tc_parameters.get_param_value("ANTENNAS_NUMBER", '1')

        # Read TRANSMISSION_MODE from test case xml file
        self._transmission_mode = \
            self._tc_parameters.get_param_value("TRANSMISSION_MODE","TM1")
        # Read BANDWIDTH from test case xml file
        self._type0_bitmap = \
            str(self._tc_parameters.get_param_value("TYPE0_BITMAP","63"))
        # Read DL_RB_SIZE from test case xml file
        self._dl_nb_rb = \
            self._tc_parameters.get_param_value("DL_RB_SIZE","50")
        # Read UL_RB_SIZE from test case xml file
        self._ul_nb_rb = \
            self._tc_parameters.get_param_value("UL_RB_SIZE","10")
        # Read I_MCS from test case xml file
        self._dl_i_mcs = \
            self._tc_parameters.get_param_value("DL_I_MCS","23")
        # Read I_MCS from test case xml file
        self._ul_i_mcs = \
            self._tc_parameters.get_param_value("UL_I_MCS","3")
        # Read UL Grant Mode from test case xml file
        self._ul_grant_mode = \
            self._tc_parameters.get_param_value("UL_GRANT_MODE", "FIXEDMAC")

        # Read the the ip _version file name from UseCase xml Parameter
        self._ip_version = self._tc_parameters.get_param_value(
            "IP_VERSION", "IPV4")

        # Get the server ipv6 address from the BenchConfig, if the key
        # is present in the file.
        if self._server.has_parameter("IPV6"):
            self._server_ip_v6_address = self._server.get_param_value("IPV6")

        # 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

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

        self._two_eps_bearers = self._tc_parameters.get_param_value(
            "TWO_EPS_BEARER")
        self._two_eps_bearers = \
            str_to_bool(self._two_eps_bearers)

        # In case of 2 PDPs, define the APN and IP address for the 2nd one
        if self._two_eps_bearers is True:
            self._second_apn = "agilent2"
            self._second_dut_ip_version = "IPV4"
            self._second_dut_ip_address = "10.102.243.25"

        # Read Inter-Rat redirection type
        self._irat_type = self._tc_parameters.get_param_value("I-RAT_TYPE")
        if self._irat_type is None:
            self._irat_type = "NORMAL"
        elif self._irat_type not in ("NORMAL", "BLIND"):
            raise AcsConfigException(
                AcsConfigException.INVALID_PARAMETER,
                "I-RAT_TYP should be 'NORMAL' or 'BLIND'")

        # Default timeout for DUT camping
        self._camp_timeout = 180

        # Define timeout for AT command
        self._command_timeout = 10

        # Define AT PROXY launch mode
        self._launch_mode = 2

        # Initializing the variable which will contain the IP address to use.
        self._ip_address = None

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

        # if 2 EPS bearers were requested
        if self._two_eps_bearers == True:
            # Instantiate the modem UE commands
            self._modem_flashing_api = self._device.get_uecmd("ModemFlashing")

            # Get Serial Handler instance
            self._serial_handler = SerialHandler()

            # Win COM port to be used
            self.at_proxy_com_port = None

            # Store the AT proxy connection availability
            self.modem_available = False

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

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

        # Stay on if plugged
        self._phone_system.set_stay_on_while_plugged_in(3)

        # Remove screen off timeout
        self._phone_system.set_screen_timeout(3600)

        # Call LabMobilityLte3gsmBase set_up function
        LabMobilityLte3gsmBase.set_up(self)

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

        # Set Network Simulator 3GSM cell on
        self._ns_3gsm_cell.set_cell_on()

        # Set the same DUT IP address also for Agilent
        self._ns_3gsm_data.set_dut_ip_address(1, self._ns1_ip_dut)

        if self._two_eps_bearers is True:
            # Configure secondary PDP/EPS bearer on the NW simulators
            self._ns_lte.stop_scenario()
            self._configure_for_second_pdp()
            self._ns_lte.start_scenario()

        time.sleep(self._wait_btwn_cmd)

        if self._ns_3gsm_cell_tech == "3G":
            # Sets RAU FOP on 3G cell to manual:
            # FOProceed:CONTrol:AUTO 0
            # FOProceed:MANual 1
            self._ns_3gsm_cell.set_rau_fop_control(0, 1)
            time.sleep(self._wait_btwn_cmd)

        #  Set External EPC connection
        self._ns_3gsm_cell.set_external_epc_connection(self._ns_lte_ip_lan1,
                                                       self._ns_lte_dl_earfcn)

        # Set LTE Cell on
        self._ns_lte_cell.set_cell_on(self._ns_lte_mimo)

        # Set cell power to -115 dBm
        self._ns_3gsm_cell.set_cell_power(-115)

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

        # Check registration state is connected using
        # registrationTimeout from Device_Catalog.xml (Non blocking
        # for this test if function isn't implemented on CDK)
        self._modem_api.check_cdk_registration_bfor_timeout(
            self._registration_timeout)

        # Activate PDP context
        time.sleep(self._wait_btwn_cmd)
        self._logger.info("Active PDP Context...")
        self._networking_api.activate_pdp_context(self._ssid, False)

        # Check data connection state is "CON"
        self._ns_lte_data.check_data_connection_state(
            "CON",
            self._camp_timeout,
            blocking=False,
            cell_id=self._ns_lte_cell_id)

        # Get RAT from Equipment
        network_type = self._ns_lte_data.get_network_type()
        # Check that DUT is registered on the good RAT
        self._modem_api.check_network_type_before_timeout(
            network_type, self._registration_timeout)

        # Wait 10 seconds
        time.sleep(10)

        if self._irat_type == "NORMAL":
            # Set cell power to -70 dBm
            self._ns_3gsm_cell.set_cell_power(-70)

        # Start FTP service on equipment side
        self._ns_lte_data.start_ftp_service()

        # Selecting the  IPV6 address of the FTP server, according to
        # the TC parameter value.
        if self._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_address

        return Global.SUCCESS, "No errors"

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

    def run_test(self):
        """
        Execute the test
        Test steps:
            Launch FTP.
            'Normal' or 'blind' Inter-RAT redirection from LTE to UTRAN/GSM
            Wait for the transfer to finish.
            Measure FTP duration
            Get transferred file size on phone
            Compute throughput
            We are using here ftpput and ftpget methods
        """

        # -------------------- 2 EPS bearers procedure -----------------------

        # If 2 EPS bearer are requested to be activated
        if self._two_eps_bearers == True:
            #Start up the proxy for sending AT commands
            self.at_proxy_com_port = self._modem_flashing_api.start_at_proxy_from_mos(
                int(self._launch_mode))
            #check serial connection
            self._expected_result = "OK"
            self._serial_handler.set_data_analyser(
                ATCommandAnalyser(self._expected_result))

            self._serial_handler.set_default_timeout(self._command_timeout)
            self._logger.info("Connecting to the port " +
                              str(self.at_proxy_com_port))

            # Connect to the at proxy
            self._serial_handler.connect(self.at_proxy_com_port)

            # Check that the modem is available
            modem_status = self._modem_flashing_api.ping_modem_from_serial(
                self._serial_handler.get_serial())

            if modem_status:
                self._logger.info("AT Proxy correctly respond to ping command")
                self.modem_available = True
            else:
                raise TestEquipmentException(
                    TestEquipmentException.CONNECTION_ERROR,
                    "Connection to AT proxy failed")

            # Activate the 2nd EPS bearer
            self._activate_2nd_eps_bearer()

            # Query for the number of active PDPs
            number_active_pdp = self._get_number_active_pdp()
            if number_active_pdp != 2:
                self._error.Code = Global.FAILURE
                self._error.Msg = "The number of the active EPS bearers is not the expected one (2). Currently active: %d" \
                                    % number_active_pdp
                return self._error.Code, self._error.Msg

        # Ping the FTp server first
        packet_loss = self._networking_api.\
            ping(self._server_ip_address,
                 self._packet_size,
                 self._nb_pings)

        # Check packet loss
        if packet_loss.value > 80:
            self._error.Code = Global.FAILURE
            self._error.Msg = "Pinging the FTP server has failed"
            return self._error.Code, self._error.Msg

        # -------------------- FTP procedure -----------------------

        if self._direction == "UL":
            ftp_file_path = os.path.join(
                self._device.multimedia_path,
                self._tc_parameters.get_param_value("UL_FILENAME"))
            d1 = datetime.datetime.now()
            (process, _q) = self._networking_api.ftpput(
                self._ip_address, self._username, self._password,
                self._ftp_filename, ftp_file_path)
        elif self._direction == "DL":
            # the FTP download file will write to /data/ to get max throughput
            # because of emmc sequential write limitation
            ftp_file_path = os.path.join(
                self._device.binaries_path,
                self._tc_parameters.get_param_value("DL_FILENAME"))
            d1 = datetime.datetime.now()

            (process, _q) = self._networking_api.ftpget(
                self._ip_address, self._username, self._password,
                ftp_file_path, self._ftp_filename)

        elif self._direction == "BOTH":
            # Launch FTP download
            # the FTP download file will write to /data/ to get max throughput
            # because of emmc sequential write limitation
            dl_ftp_file_path = os.path.join(
                self._device.binaries_path,
                self._tc_parameters.get_param_value("DL_FILENAME"))
            d1_dl = datetime.datetime.now()
            (process_dl, _q_dl) = self._networking_api.ftpget(
                self._ip_address, self._username, self._password,
                dl_ftp_file_path, self._dl_ftp_filename)
            # Launch FTP upload
            ul_ftp_file_path = os.path.join(
                self._device.multimedia_path,
                self._tc_parameters.get_param_value("UL_FILENAME"))
            d1_ul = datetime.datetime.now()
            (process_ul, _q_ul) = self._networking_api.ftpput(
                self._ip_address, self._username, self._password,
                self._ul_ftp_filename, ul_ftp_file_path)

            while process_ul.poll() is None and process_dl.poll() is None:
                pass
            if process_dl.poll() is not None:
                # Compute end of transfer time
                d2_dl = datetime.datetime.now()
                while process_ul.poll() is None:
                    pass
                d2_ul = datetime.datetime.now()
            elif process_ul.poll() is not None:
                # Compute end of transfer time
                d2_ul = datetime.datetime.now()
                while process_dl.poll() is None:
                    pass
                d2_dl = datetime.datetime.now()

        # Wait 30 seconds during FTP data transfer and then redirect to UTRAN/GSM cell
        while process.poll() is None:
            d2 = datetime.datetime.now()
            d3 = d2 - d1
            # Wait 30 seconds and send DUT release
            if d3.seconds > 30:
                # Check if the file exists
                if (self._direction == "DL"):
                    self._phone_system.check_file_exist(ftp_file_path)

                if self._irat_type == "BLIND":
                    # Set cell power to -70 dBm
                    self._ns_3gsm_cell.set_cell_power(-70)
                    #time.sleep(self._wait_btwn_cmd)

                # Initiate a LTE RRC Connection Release
                self._logger.info("Send LTE Detach")
                self._ns_lte_data.ue_detach()
                # Exit the loop
                break
            # Sleep 1 second
            time.sleep(1)

        # Compute end of transfer time
        #d2 = datetime.datetime.now()
        timeout = 30
        if self._ns_3gsm_cell_tech == "3G":
            # Check Data Connection State on 3GSM cell => ATTACHED before timeout
            result = self._ns_3gsm_data.check_data_connection_state(
                "ATTACHED", timeout, blocking=True)
        if process.poll() is not None:
            self._logger.info("Transfer ended after DUT is attached on 3G cell - %s"\
                              %(str(process.poll())))

        # Wait 20 seconds
        self._logger.info("Wait 20 seconds")
        time.sleep(20)

        # Gets the connection status
        connection_status = self._ns_3gsm_data.get_data_connection_status()
        t1 = datetime.datetime.now()

        # Wait 60 seconds during FTP data transfer
        self._logger.info(
            "Check if FTP data transfer remains active for at least 60 seconds after IRAT redirection"
        )
        while process.poll() is None:

            t2 = datetime.datetime.now()
            t3 = t2 - t1
            # Gets the connection status
            connection_status = self._ns_3gsm_data.get_data_connection_status()

            # Exit the loop if PDP has been released
            if (self._ns_3gsm_cell_tech == "3G") and \
                (connection_status not in ("PDP_ACTIVATING","PDP_ACTIVE")):
                break

            # Exit the loop if PDP has been released
            if (self._ns_3gsm_cell_tech == "2G") and \
                (connection_status not in ("TRANSFERRING","PDP_ACTIVE")):
                break

            # Wait 60 seconds and exit the loop
            if t3.seconds > 60:
                break
            # Sleep 1 second
            time.sleep(1)

        # Compute end of transfer time
        d2 = datetime.datetime.now()
        tput = self._compute_ftp_tput(d1, d2, ftp_file_path)

        try:
            if (tput == -1.0) or \
                ((t3 is not None) and (t3.seconds < 60)):
                self._error.Msg = "FTP data transfer has been interrupted"
                return Global.FAILURE, self._error.Msg

        except UnboundLocalError:
            self._error.Msg = "FTP data transfer has been interrupted"
            return Global.FAILURE, self._error.Msg

        # If 2 EPS bearer were requested to be activated
        if self._two_eps_bearers == True:
            # Query for the number of active PDPs
            number_active_pdp = self._get_number_active_pdp()

        self._error.Msg = "Throughput is %.2f kbits/s" % (tput)
        if tput > 0:
            self._error.Code = Global.SUCCESS
        else:
            self._error.Code = Global.FAILURE

        # If 2 EPS bearer were requested to be activated check how many are active after IRAT redirection
        if self._two_eps_bearers == True:
            # Query for the number of active PDPs
            number_active_pdp = self._get_number_active_pdp()

            if number_active_pdp != 1:
                self._error.Code = Global.FAILURE
                self._error.Msg = "The number of the active PDPs is not the expected one (1). Currently active: %d" \
                                    % number_active_pdp
                return self._error.Code, self._error.Msg

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

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

    def tear_down(self):
        """
        Finishing the test.
        Stopping the FTP service and releasing the equipment.
        """
        # Stopping the FTP service before releasing the equipment.
        self._ns_lte_data.stop_ftp_service()

        # Disconnect from external EPC
        self._ns_3gsm.disconnect_from_external_epc()

        if self._ns_3gsm_cell_tech == "3G":
            # Sets RAU FOP on 3G cell to auto:
            # FOProceed:CONTrol:AUTO 1
            # FOProceed:MANual 0
            self._ns_3gsm_cell.set_rau_fop_control(1, 0)

        # Reset the stay on setting if plugged
        self._phone_system.set_stay_on_while_plugged_in(0)

        # Set the initial screen off timeout
        self._phone_system.set_screen_timeout(60)

        # If 2 EPS bearers were requested
        if self._two_eps_bearers == True:
            #Stop AT Proxy
            self._logger.info("Stop AT Proxy")
            self._modem_flashing_api.stop_at_proxy_from_mos()

            #Close the serial connection
            self._logger.info("Close the serial connection")
            self._logger.info("Disconnecting from the port " +
                              str(self._serial_handler.get_port()))
            self._serial_handler.disconnect()

        LabMobilityLte3gsmBase.tear_down(self)

        return Global.SUCCESS, "No errors"

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

    def _compute_ftp_tput(self, d1, d2, ftp_file_path):
        """
        compute FTP data throughput
        :type d1: datetime
        :param d1: FTP start time
        :type d2: datetime
        :param d2: FTP end time
        :type ftp_file_path: string
        :param ftp_file_path: path to ftp transferred file on phone

        :rtype: float
        :return: throughput in kbps or -1 if an error occured
        """

        d3 = d2 - d1
        # Remove 1 second to total duration for FTP connection establishment time
        d = (d3.seconds - 1) * 1000000 + d3.microseconds
        self._logger.info(
            "FTP finished or interrupted on purpose in %d seconds " %
            (d3.seconds))

        # If transfer time is too short it means that FTP connection
        # was lost (ftpput and get do not return error)
        if d3.seconds < 3:
            self._error.Msg = "The FTP transfer is too short (less than 3 seconds), FTP connection is lost"
            return -1.0

        # Check if the file exists
        if (self._direction == "DL"):
            self._phone_system.check_file_exist(ftp_file_path)

        size = self._phone_system.get_file_size(ftp_file_path)
        self._logger.info("file size %d" % size)
        # compute throughput = file_size in kbits/duration in s
        #                    = (size * 8/1000) / (d/1000000)
        #                    = (size * 8 * 1000) / d
        tput = float((size * 1000 * 8) / d)
        self._logger.info("Measured Throughput  %.2f kbits/s" % tput)

        return tput

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

    def _get_lte_max_tput_params(self):
        """
        Compute and return lte parameters to reach the phone maximum throughput.
        Read max lteCategory supported from DeviceCatalog.xml
        get antennas number and bandwidth for maximum throughput available for this category

        :rtype: str
        :return: lte_category, the maximum lte category supported by the phone
        :rtype: str
        :return: mimo, mimo support by phone
        :rtype: str
        :return: bw, the maximum bandwidth supported by phone
        :rtype: str
        :return: antennas_number, the maximum number of antenna supported by phone
        """

        mimo = "False"
        antennas_number = "1"
        bw = "10"
        lte_category = str(self._dut_config.get("maxSupportedLteCategory",
                                                "3"))
        if int(lte_category) > 1:
            mimo = "True"
            antennas_number = "2"
        if int(lte_category) > 2:
            bw = "20"

        return mimo, lte_category, bw, antennas_number

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

    def _activate_2nd_eps_bearer(self):
        """
        Activate the 2nd EPS bearer on LTE cell
        Raise errors if some AT commands dones't return the expected message for a succesfull activation

        """

        self._logger.info(
            "Start the procedure for activating the 2nd EPS bearer")

        # Define the 2nd EPS bearer APN on CID 2
        at_command_config_2nd_eps = "at+cgdcont=2,\"IP\",\"%s\"" % (
            self._second_apn)
        expected_at_command_response = "OK"

        # Execute AT command
        at_command_verdict, at_command_response_raw =\
                self._serial_handler.send_at_command_and_get_result(at_command_config_2nd_eps,
                                                                    self._command_timeout)

        if at_command_response_raw != expected_at_command_response:
            self._logger.debug("at_command_response_raw = " +
                               at_command_response_raw)
            self._error.Msg = "Failed to configure the 2nd EPS bearer"
            raise AcsConfigException(AcsConfigException.OPERATION_FAILED,
                                     self._error.Msg)

        # Wait 5 seconds
        time.sleep(5)

        # Activate 2nd EPS bearer
        at_command_activate_2nd_eps_bearer = "at+cgact=1,2"
        expected_at_command_response = "OK"
        at_command_verdict, at_command_response_raw =\
                self._serial_handler.send_at_command_and_get_result(at_command_activate_2nd_eps_bearer,
                                                                    self._command_timeout)

        if at_command_response_raw != expected_at_command_response:
            self._logger.debug("at_command_response_raw = " +
                               at_command_response_raw)
            self._error.Msg = "Failed to configure the 2nd EPS bearer"
            raise AcsConfigException(AcsConfigException.OPERATION_FAILED,
                                     self._error.Msg)

        # Wait 10 seconds
        time.sleep(10)

        at_comand_interogate_status_eps_bearers = "at+cgact?"
        expected_at_command_response = "+CGACT: 1,1+CGACT: 2,1OK"
        at_command_verdict, at_command_response_raw =\
                self._serial_handler.send_at_command_and_get_result(at_comand_interogate_status_eps_bearers,
                                                                    self._command_timeout)

        if at_command_response_raw != expected_at_command_response:
            self._logger.debug("at_command_response_raw = " +
                               at_command_response_raw)
            self._error.Msg = "Failed to configure the 2nd EPS bearer"
            raise AcsConfigException(AcsConfigException.OPERATION_FAILED,
                                     self._error.Msg)

        # Wait 5 seconds
        time.sleep(5)

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

    def _get_number_active_pdp(self):
        """
        Return the number of the activated PDPs

        :rtype: int
        :return: number_pdp_active, the number of active PDPs
        """

        # Initialize the number of active PDPs
        number_pdp_active = 0

        # Execute "AT+CGACT?" AT command to see the status of active PDPs
        at_comand_interogate_status_eps_bearers = "at+cgact?"
        at_command_verdict, at_command_response =\
                self._serial_handler.send_at_command_and_get_result(at_comand_interogate_status_eps_bearers,
                                                                    self._command_timeout)
        self._logger.debug("at_command_response = " + at_command_response)

        # Check how many PDPs/EPS bearers are active
        i = 1
        for i in xrange(1, 8):
            pdp_active_check_seq = "+CGACT: %d,1" % (i)
            if pdp_active_check_seq in at_command_response:
                number_pdp_active = number_pdp_active + 1

        # Return the number of active PDPs/EPS bearers
        return number_pdp_active

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

    def _configure_for_second_pdp(self):
        """
        Sets the IP which will be configured for the 2nd EPS bearer (on PXT)
        and 2nd PDP context (on Agilent8960)
        """

        # Set the 2nd IP address on Agilent8960
        self._ns_3gsm_data.set_dut_ip_address(2, self._second_dut_ip_address)

        time.sleep(self._wait_btwn_cmd)

        # Configure the EPS bearer config 2 on PXT
        self._ns_lte_data.configure_eps_bearer_config_2(
            self._second_apn, self._second_dut_ip_version,
            self._second_dut_ip_address)
예제 #7
0
    def __init__(self, tc_name, global_config):
        # Call LabMobilityLteCsfb init method
        LabMobilityLteCsfb.__init__(self, tc_name, global_config)

        self.__rejection_cause = self._tc_parameters.get_param_value(
            "REJECTION_CAUSE", "not defined", str)

        self._flight_mode = self._tc_parameters.get_param_value(
            "FLIGHT_MODE", "not defined", str)
        self._flight_mode = str_to_bool(self._flight_mode)

        # Instantiate the PhoneSystem UE Command category
        self._phone_system = self._device.get_uecmd("PhoneSystem")

        # Instantiate the modem UE commands
        self._modem_flashing_api = self._device.get_uecmd("ModemFlashing")

        # Get Serial Handler instance
        self._serial_handler = SerialHandler()

        # Initialize launch mode for AT proxy
        self._launch_mode = 2

        # Initialize the AT command timeout
        self._command_timeout = 10

        # The attribute that will store the initial list
        # of emergency numbers.
        self._initial_emergency_numbers = None

        # Win COM port to be used
        self.at_proxy_com_port = None

        # Store the AT proxy connection availability
        self.modem_available = False

        # Store the verdict for AT@NVM interrogation
        self._at_inter_nvm_em_verdict = None

        # Store the response for AT@NVM interrogation
        self._at_inter_nvm_em = None

        # Store the verdict for setting EM in NVM via AT@NVM
        # it will be used in tear down to know if the initial values
        # should be restored or not in NVM:cust.emergency
        self._at_set_nvm_em = None

        # AT command that will be used for initial NVM:cust.emergency
        # values at the tear down.
        self.command_to_rest_em_in_nvm = None

        # AT command that will be used for setting new EM in  NVM:cust.emergency
        self.command_to_add_em_in_nvm = None

        # Store the initial list of RIL emergency number from UECmdTypes
        self._initial_ue_command_em_number = UECmdTypes.EMERGENCY_NUMBERS_LIST

        #Set up the parameters for the AT@NVM:cust.emergency
        # AT@NVM:cust.emergency[<index>]={<P1>,<P2>,<P3>,<P4>,<P5>,<P6>,<P7>,<P8>}

        # < index>, <index1>, <index2> - index of Emergency number to be stored
        self._index = 0
        self.index = self._index

        # Make sure the provided Phone Number parameter is not present
        # in the list of emergency numbers
        self.em_no_length = len(self._phone_number)
        if self.em_no_length != 6:
            # Otherwise create an error message
            message = "Provided parameter PHONE_NUMBER [%s] should be 6 digits" % (
                self._phone_number)
            # Raise an exception
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        # <P1> (in BCD representation)
        self.p1_bcd = int_to_bcd(self._phone_number[0:2])

        # <P2> (in BCD representation)
        self.p2_bcd = int_to_bcd(self._phone_number[2:4])

        # <P2> (in BCD representation)
        self.p3_bcd = int_to_bcd(self._phone_number[4:6])

        #<P4> denotes whether ECC is valid when sim present or not
        # 0 - ECC is not valid when SIM present
        # 1 - ECC is valid when SIM is present
        self.p4 = 1

        #<P5> denotes ECC Category
        self.p5 = 1

        #<P6>, <P7>
        # MCC 2 bytes same as 3GPP PLMN format
        self.p6 = self._ns_lte_mcc
        self.p7 = self._ns_lte_mnc

        #<P8> reserved . give 0xff

        #this AT command writes Emergency Number to NVM AT@NVM
        self._command = "AT@NVM:cust.emergency"
        self.p8 = "255"
        self.command_to_add_em_in_nvm = "%s[%s]={%s, %s, %s, %s, %s, %s, %s, %s}" % (
            str(self._command), str(self._index), str(self.p1_bcd),
            str(self.p2_bcd), str(self.p3_bcd), str(self.p4), str(
                self.p5), str(self.p6), str(self.p7), str(self.p8))
예제 #8
0
class LabMobilityLteEmergencyCallCsfb(LabMobilityLteCsfb):
    """
    Test specific cases of calls during a circuit switched fallback from LTE
    to UTRAN:
    - Network rejecting the call
    - Cancel voice call before establishment
    """

    EMERGENCY_NUMBER_PROPERTY_NAME = "ril.ecclist"

    def __init__(self, tc_name, global_config):
        # Call LabMobilityLteCsfb init method
        LabMobilityLteCsfb.__init__(self, tc_name, global_config)

        self.__rejection_cause = self._tc_parameters.get_param_value(
            "REJECTION_CAUSE", "not defined", str)

        self._flight_mode = self._tc_parameters.get_param_value(
            "FLIGHT_MODE", "not defined", str)
        self._flight_mode = str_to_bool(self._flight_mode)

        # Instantiate the PhoneSystem UE Command category
        self._phone_system = self._device.get_uecmd("PhoneSystem")

        # Instantiate the modem UE commands
        self._modem_flashing_api = self._device.get_uecmd("ModemFlashing")

        # Get Serial Handler instance
        self._serial_handler = SerialHandler()

        # Initialize launch mode for AT proxy
        self._launch_mode = 2

        # Initialize the AT command timeout
        self._command_timeout = 10

        # The attribute that will store the initial list
        # of emergency numbers.
        self._initial_emergency_numbers = None

        # Win COM port to be used
        self.at_proxy_com_port = None

        # Store the AT proxy connection availability
        self.modem_available = False

        # Store the verdict for AT@NVM interrogation
        self._at_inter_nvm_em_verdict = None

        # Store the response for AT@NVM interrogation
        self._at_inter_nvm_em = None

        # Store the verdict for setting EM in NVM via AT@NVM
        # it will be used in tear down to know if the initial values
        # should be restored or not in NVM:cust.emergency
        self._at_set_nvm_em = None

        # AT command that will be used for initial NVM:cust.emergency
        # values at the tear down.
        self.command_to_rest_em_in_nvm = None

        # AT command that will be used for setting new EM in  NVM:cust.emergency
        self.command_to_add_em_in_nvm = None

        # Store the initial list of RIL emergency number from UECmdTypes
        self._initial_ue_command_em_number = UECmdTypes.EMERGENCY_NUMBERS_LIST

        #Set up the parameters for the AT@NVM:cust.emergency
        # AT@NVM:cust.emergency[<index>]={<P1>,<P2>,<P3>,<P4>,<P5>,<P6>,<P7>,<P8>}

        # < index>, <index1>, <index2> - index of Emergency number to be stored
        self._index = 0
        self.index = self._index

        # Make sure the provided Phone Number parameter is not present
        # in the list of emergency numbers
        self.em_no_length = len(self._phone_number)
        if self.em_no_length != 6:
            # Otherwise create an error message
            message = "Provided parameter PHONE_NUMBER [%s] should be 6 digits" % (
                self._phone_number)
            # Raise an exception
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        # <P1> (in BCD representation)
        self.p1_bcd = int_to_bcd(self._phone_number[0:2])

        # <P2> (in BCD representation)
        self.p2_bcd = int_to_bcd(self._phone_number[2:4])

        # <P2> (in BCD representation)
        self.p3_bcd = int_to_bcd(self._phone_number[4:6])

        #<P4> denotes whether ECC is valid when sim present or not
        # 0 - ECC is not valid when SIM present
        # 1 - ECC is valid when SIM is present
        self.p4 = 1

        #<P5> denotes ECC Category
        self.p5 = 1

        #<P6>, <P7>
        # MCC 2 bytes same as 3GPP PLMN format
        self.p6 = self._ns_lte_mcc
        self.p7 = self._ns_lte_mnc

        #<P8> reserved . give 0xff

        #this AT command writes Emergency Number to NVM AT@NVM
        self._command = "AT@NVM:cust.emergency"
        self.p8 = "255"
        self.command_to_add_em_in_nvm = "%s[%s]={%s, %s, %s, %s, %s, %s, %s, %s}" % (
            str(self._command), str(self._index), str(self.p1_bcd),
            str(self.p2_bcd), str(self.p3_bcd), str(self.p4), str(
                self.p5), str(self.p6), str(self.p7), str(self.p8))

    def set_up(self):
        """
        Set up the test configuration
        """
        status, msg = LabMobilityLteCsfb.set_up(self)

        # Check REJECTION_CAUSE parameter
        if self._loss_coverage_type == "REJECTION":
            if self.__rejection_cause in ("not defined", "", None):
                return Global.FAILURE, "Rejection cause parameter is not correct (%s). Please update your test-case"\
                       % self.__rejection_cause

        # Cancel call specific setup
        if self._loss_coverage_type == "CANCELLATION":
            if self._ns_3gsm_cell_tech == "2G":
                # Set call setup timeout to 100 seconds
                self._ns_3gsm_vc.set_mt_originate_call_timeout(100)

        # Check the phone number, ensuring that it is not
        # a number corresponding to a "real" emergency number
        # on the LIVE network

        # Retrieve the list of emergency numbers from the DUT as str
        emergency_numbers_string = self._device.get_property_value(
            self.EMERGENCY_NUMBER_PROPERTY_NAME)

        # Split the str to a list
        emergency_numbers = emergency_numbers_string.split(",")

        # Log the initial EM Number List
        self._logger.info("The initial emergency number list is: (%s)" %
                          (emergency_numbers_string))

        # Make sure the provided Phone Number parameter is not present
        # in the list of emergency numbers
        if self._phone_number in emergency_numbers and self._phone_number != "123456":
            # Otherwise create an error message
            message = "Provided parameter PHONE_NUMBER [%s] as a value  \
                    that corresponds to a real emergency number on the LIVE  \
                    network [list: (%s)]. The test will not be executed." % (
                self._phone_number, emergency_numbers_string)
            # No need to raise an exception
            self._logger.info(message)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     message)

        # Store the list of emergency numbers from RIL so that we can
        # restore it later
        self._initial_emergency_numbers = emergency_numbers_string

        # Update the list of RIL Emergency Numbers in UE Command categories
        # Make the 'addition' of 2 tuples by using a single-element tuples
        # using the (<element>,) notation.
        # This needs only to be done if the provided phone number shall
        # be considered to be an Emergency number.
        UECmdTypes.EMERGENCY_NUMBERS_LIST = \
            self._initial_ue_command_em_number + (self._phone_number,)

        return status, msg

    def run_test(self):
        """
        Execute the test
        """
        time_to_wait_before_3g_idle = 10
        status = Global.SUCCESS
        status_msg = "No error occurred"

        try:
            # Configure the EM numbers
            self.__configure_cust_em_number()

            self._logger.info(
                "Start the Emergency Call when DUT is in Flight Mode")

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

            if self._flight_mode == True:
                # Enable flight mode
                self._networking_api.set_flight_mode("on")
                # Wait 5 seconds
                time.sleep(5)

            if self._loss_coverage_type != "REJECTION":
                # Initiate a LTE RRC Connection Release when performing MO Call to go back to IDLE
                self._ns_lte_data.ue_detach()
            else:
                self._logger.info(
                    "The EM call will be rejected with cause '%s' by LTE NW thanks to loaded scenario, but it will be accepted on UTRAN/2G NW "
                    % (self.__rejection_cause))

            # Dial using the phone number given in parameters
            self._logger.info("Calling %s ..." % self._phone_number)

            # Wake the screen otherwise the Voice Call will not be established
            self._phone_system.wake_screen()
            self._phone_system.set_phone_lock(0)

            #Dial
            self._voicecall_api.dial(self._phone_number)

            # Check voice call is incoming on reselected network side
            self._ns_3gsm_vc.check_call_state("CONN",
                                              3 * self._call_setup_time,
                                              blocking=True)

            # Check call is connected for CALL_DURATION seconds
            self._ns_3gsm_vc.is_voice_call_connected(self._call_duration)

            # If flight mode on
            if self._flight_mode == True:
                self._logger.info(
                    "Voice call will be release and set the flight mode OFF")
                # Mobile Release call
                self._voicecall_api.release()
                # DISABLE flight mode
                self._networking_api.set_flight_mode("off")

                # Wait 5 seconds
                time.sleep(5)

                # Check Data Connection State => CON before timeout
                self._ns_lte_data.check_data_connection_state(
                    "CON",
                    self._registration_timeout,
                    blocking=True,
                    cell_id=self._ns_lte_cell_id)

            # Specific cases for call cancellation
            # (rejection is done automatically)
            if self._loss_coverage_type == "CANCELLATION" or self._loss_coverage_type == "REJECTION":
                #Release normally the call from the DUT
                self.release_csfb_vc(time_to_wait_before_3g_idle)

            # Check current RAT, the MS shall be camped on LTE cell
            if self._modem_api.get_current_rat() != "LTE":
                # Check also the status on 4G cell
                current_state = self._ns_lte_data.get_data_connection_status(
                    cell_id=self._ns_lte_cell_id)
                # If the NW response is not CONNECTED, raise an error
                if current_state != "CON":
                    status_msg = "MS is camped in the WRONG RAT - NOT on LTE !"
                    status = Global.FAILURE
                    self._logger.error(status_msg)
                    return (status, status_msg)
                else:
                    self._logger.info(
                        "The MS is camped on LTE - normal behavior!")

            # Wait 10 seconds
            self._logger.info("Wait 10 seconds")
            time.sleep(10)

            # make a ping
            ping(self._networking_api,
                 self._server_ip_address,
                 self._packet_size,
                 self._nb_pings,
                 self._target_ping_packet_loss_rate,
                 self._logger,
                 blocking=True)

        except TestEquipmentException:
            raise TestEquipmentException(
                TestEquipmentException.CONNECTION_ERROR,
                "Connection to AT proxy failed")

        except DeviceException:
            raise DeviceException(DeviceException.CONNECTION_LOST,
                                  "Connection to DUT Lost")

        except:
            # In case of any exception, return FAILED status
            e = sys.exc_info()[0]
            self._logger.error("Error: %s" % e)
            status = Global.FAILURE
            status_msg = "Error: %s" % e

        finally:
            # Reset 3G cell
            self._ns_3gsm_cell.set_cell_power(self._ns_3gsm_cell_power)

            #in case of any error
            if self._flight_mode == True:
                # disable flight mode
                self._networking_api.set_flight_mode("off")

            return status, status_msg

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

        # Disable flight mode in the first place in any case
        self._networking_api.set_flight_mode("off")

        # Restore the initial Emergency Numbers
        self.__restore_initial_em_numbers()
        # Call tear down
        LabMobilityLteCsfb.tear_down(self)
        # Wait 10 seconds
        time.sleep(10)
        # return result
        return Global.SUCCESS, "No errors"

    def __restore_initial_em_numbers(self):
        """
        Restores the initial emergency number in ril list

        Raise an exception in case of error during AT commands execution
        """

        self._logger.info(
            "Restore initial emergency numbers in ril.ecclist list")
        # Restore the list of emergency number in UE Command categories
        # if we changed it in the beginning of the Use Case
        UECmdTypes.EMERGENCY_NUMBERS_LIST = self._initial_ue_command_em_number

        # Restore the list of emergency numbers
        self._device.set_property_value(self.EMERGENCY_NUMBER_PROPERTY_NAME,
                                        self._initial_emergency_numbers)

        if self.modem_available and (self._at_set_nvm_em is not None):
            self._logger.info("Restore initial emergency numbers in "
                              "NVM:cust.emergency list at index %s" %
                              self._index)
            response, msg_serial = self._serial_handler.send_at_command_and_get_result(
                self.command_to_rest_em_in_nvm, self._command_timeout)
            if msg_serial == "OK":
                self._logger.info("Response to AT command %s is: %s" %
                                  (self.command_to_rest_em_in_nvm, msg_serial))
            else:
                raise DeviceException(
                    DeviceException.OPERATION_SET_ERROR,
                    "Response to AT command %s is: %s" %
                    (self.command_to_rest_em_in_nvm, msg_serial))
        #Stop AT Proxy
        self._logger.info("Stop AT Proxy")
        self._modem_flashing_api.stop_at_proxy_from_mos()

        #Close the serial connection
        self._logger.info("Close the serial connection")
        self._logger.info("Disconnecting from the port " +
                          str(self._serial_handler.get_port()))
        self._serial_handler.disconnect()

    def __configure_cust_em_number(self):
        """
        Configure the emergency number in ril list

        Raise an exception in case of error during AT commands execution
        """
        # Update the list of RIL Emergency Numbers on the DUT
        # This imperatively has to be done after setting the Flight Mode
        self._logger.info("Add Emergency Number in ril.ecclist list")
        # Update the property holding the Emergency Numbers list.
        self._device.set_property_value(self.EMERGENCY_NUMBER_PROPERTY_NAME,
                                        self._phone_number)

        self._logger.info("Add Emergency Number in NVM:cust.emergency list "
                          "at index %s" % self._index)
        # Start up the proxy for sending AT commands
        self.at_proxy_com_port = self._modem_flashing_api.start_at_proxy_from_mos(
            int(self._launch_mode))
        # Check serial connection
        self._expected_result = "OK"
        self._serial_handler.set_data_analyser(
            ATCommandAnalyser(self._expected_result))

        self._serial_handler.set_default_timeout(self._command_timeout)
        self._logger.info("Connecting to the port " +
                          str(self.at_proxy_com_port))

        # Connect to the at proxy
        self._serial_handler.connect(self.at_proxy_com_port)

        # Check that the modem is available
        modem_status = self._modem_flashing_api.ping_modem_from_serial(
            self._serial_handler.get_serial())

        if modem_status:
            self._logger.info("AT Proxy correctly respond to ping command")
            self.modem_available = True
        else:
            raise TestEquipmentException(
                TestEquipmentException.CONNECTION_ERROR,
                "Connection to AT proxy failed")
        #Send AT@NVM to get initial parameters stored at index "self.index" for restore at
        #finalize
        self._logger.info("Read NVM:cust.emergency list at index %s" %
                          self._index)
        interrogate_at_nvm_command = self._command + "[" + \
                                    str(self.index) + "]" + "?"
        self._logger.info("Send AT command: %s" % interrogate_at_nvm_command)

        self._at_inter_nvm_em_verdict, at_nvm_params_to_be_rest_raw =\
                self._serial_handler.send_at_command_and_get_result(interrogate_at_nvm_command, self._command_timeout)
        at_nvm_params_to_be_rest = re.match("{*.*}",
                                            at_nvm_params_to_be_rest_raw)
        at_nvm_params_to_be_rest = at_nvm_params_to_be_rest.group(0)
        self._logger.info(
            "Data read from NVM:cust.emergency list at index %s are: %s" %
            (self._index, at_nvm_params_to_be_rest))
        self.command_to_rest_em_in_nvm = "%s[%s]=%s" % (str(
            self._command), str(self._index), str(at_nvm_params_to_be_rest))
        #Send AT@NVM to add an emergency number to NNV emergency number list
        self._logger.info("Add NVM:cust.emergency number \"%s\" "
                          "at index %s" % (self._phone_number, self._index))
        self._at_set_nvm_em, msg = self._serial_handler.send_at_command_and_get_result(
            self.command_to_add_em_in_nvm, self._command_timeout)
        if msg == "OK":
            self._logger.info("Response to AT command %s "
                              "is: %s" % (self.command_to_add_em_in_nvm, msg))
        else:
            raise DeviceException(
                DeviceException.OPERATION_SET_ERROR,
                "Response to AT command %s is: %s" %
                (self.command_to_add_em_in_nvm, msg))
예제 #9
0
class LiveAtProxy(UseCaseBase):

    """
    Live AT proxy class, used for checking that AT proxy is functional.
    """

    def __init__(self, tc_name, global_config):
        """
        Initializes this instance.
        """

        # Call UseCase base __init__ method
        UseCaseBase.__init__(self, tc_name, global_config)

        # Retrieve testcase parameters
        self.__launch_mode = self._tc_parameters.get_param_value("LAUNCH_MODE")
        self.__command = self._tc_parameters.get_param_value("COMMAND")
        self.__expected_result = \
            self._tc_parameters.get_param_value("EXPECTED_RESULT")
        self.__command_timeout = \
            self._tc_parameters.get_param_value("COMMAND_TIMEOUT")

        # initialize at proxy connection parameters
        self.__serial_handler = SerialHandler()

        # Instantiate the modem UE commands
        self.__modem_flashing_api = self._device.get_uecmd("ModemFlashing")

        # Check input parameter LAUNCH_MODE
        possible_launch_mode = {"NORMAL": ModemFlashing.AT_PROXY_NORMAL_MODE,
                                "TUNNELING": ModemFlashing.AT_PROXY_TUNNELING_MODE}
        if self.__launch_mode in possible_launch_mode.keys():
            self.__launch_mode = possible_launch_mode[self.__launch_mode]
        else:
            self.__launch_mode = None

        # Check input parameter COMMAND_TIMEOUT
        if is_number(self.__command_timeout) is True:
            self.__command_timeout = int(self.__command_timeout)
        else:
            self.__command_timeout = None

    def set_up(self):
        """
        Initializes this test.
        """
        # Run the inherited 'set_up' method
        UseCaseBase.set_up(self)

        # Raise an exception if at least one of checked parameters is None
        # (meaning unknown)
        if self.__launch_mode is None:
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                   "Unknown LAUNCH_MODE value")
        if self.__command_timeout is None:
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                   "COMMAND_TIMEOUT value must be a number")

        # Check that the phone is in Main OS
        boot_mode = self._device.get_boot_mode()
        if boot_mode != "MOS":
            raise DeviceException(DeviceException.INVALID_DEVICE_STATE,
                                   "Usecase is only available with a board booted in Main OS")

        # Start AT proxy, according to LAUNCH_MODE
        self._logger.info("Starting AT proxy")
        at_proxy_tty = \
            self.__modem_flashing_api.start_at_proxy_from_mos(self.__launch_mode)

        # Setup AT proxy serial connection
        self.__serial_handler.set_data_analyser(
            ATCommandAnalyser(self.__expected_result))
        self.__serial_handler.set_default_timeout(self.__command_timeout)
        self._logger.info("Connecting to the port " + str(at_proxy_tty))

        # Connect to the at proxy
        self.__serial_handler.connect(at_proxy_tty)

        # Check that the modem is available
        modem_available = self.__modem_flashing_api.ping_modem_from_serial(
            self.__serial_handler.get_serial())

        if not modem_available:
            return Global.FAILURE, "AT proxy hasn't been correctly launched"

        # Return SUCCESS status
        return Global.SUCCESS, "No error"

    def run_test(self):
        """
        Executes the test
        """
        # Call the usecase base run_test method
        UseCaseBase.run_test(self)

        # Execute the AT command 'COMMAND' through the serial connection
        # Wait a maximum of COMMAND_TIMEOUT seconds for result
        # Compare command result with EXPECTED_RESULT
        # Return verdict
        self._logger.info("Executing AT command: " + str(self.__command) +
                          " and checking result until " + str(self.__command_timeout) +
                          " seconds")
        verdict, msg = self.__serial_handler.write_and_analyse(self.__command)
        self._logger.info("AT command result: " + str(msg))

        # Return verdict
        return verdict, msg

    def tear_down(self):
        """
        Disposes this test.
        """
        # call the usecase base tear_down method
        UseCaseBase.tear_down(self)

        # Stop AT proxy
        self.__modem_flashing_api.stop_at_proxy_from_mos()

        # Close the serial connection
        self._logger.info("Disconnecting from the port " +
                          str(self.__serial_handler.get_port()))
        self.__serial_handler.disconnect()

        # Return SUCCESS status
        return Global.SUCCESS, "No error"
예제 #10
0
class LabGsmSmsMtOnSim(LabGsmSmsCsBase):

    """
    GSM Mobile Terminated SMS over CS on network simulator class.
    """

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        LabGsmSmsCsBase.__init__(self, tc_name, global_config)
        # Set an artificial phone number
        self._destination_number = "123456789"
        # Read the test case params from test case xml
        # Get the max sms we can stored in sim card
        self._sms_amount_to_send = \
            int(self._tc_parameters.get_param_value("SMS_AMOUNT_TO_SEND"))
        # Retrieve testcase parameters for AT proxy usage
        self._launch_mode = 2
        self._command = "AT+CPMS?"
        self._index = 0
        self._expected_result = ""
        self._command_timeout = 20

        # Instantiate the PhoneSystem UE Command category
        self._phone_system = self._device.get_uecmd("PhoneSystem")

        # Instantiate the modem UE commands
        self._modem_flashing_api = self._device.get_uecmd("ModemFlashing")

        # Get Serial Handler instance
        self._serial_handler = SerialHandler()

        # Read SMS_TRANSFER_TIMEOUT from xml UseCase parameter file
        self._sms_transfer_timeout = \
            int(self._tc_parameters.get_param_value("SMS_TRANSFER_TIMEOUT"))

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

        #Start up the proxy for sending AT commands
        self.at_proxy_com_port = self._modem_flashing_api.start_at_proxy_from_mos(
                                                                        int(self._launch_mode))
        #check serial connection
        self._serial_handler.set_data_analyser(
            ATCommandAnalyser(self._expected_result))
        self._serial_handler.set_default_timeout(self._command_timeout)
        self._logger.info("Connecting to the port " + str(self.at_proxy_com_port))

        # Connect to the at proxy
        self._serial_handler.connect(self.at_proxy_com_port)

        # Check that the modem is available
        modem_status = self._modem_flashing_api.ping_modem_from_serial(
            self._serial_handler.get_serial())

        if modem_status:
            self._logger.info("AT Proxy correctly respond to ping command")
            self.modem_available = True
        else:
            raise DeviceException(DeviceException.CONNECTION_LOST,
                                         "Connection to AT proxy failed")

        #Send AT+CPMS to get storage SIM information
        interrogate_at_command = "AT+CPMS?"
        self._logger.info("Send AT command: %s" % interrogate_at_command)
        self._at_inter_nvm_em_verdict, response =\
                self._serial_handler.send_at_command_and_get_result(interrogate_at_command, self._command_timeout)

        try:
            sm_index = response.split(",").index('"SM"')
        except ValueError:
            self._error.Msg = "Storage SIM information error"
            raise DeviceException(DeviceException.PHONE_OUTPUT_ERROR, self._error.Msg)

        self.max_storage = response.split(",")[sm_index + 2]

        # Clear NS and Phone side sms
        self._ns_messaging_2g.clear_message_data()

        self._messaging_api.delete_all_sms()

        self._nb_segments = \
                compute_sms_segments(self._sms_text,
                                 self._nb_bits_per_char)

        self.sms_sent = SmsMessage(self._sms_text,
                                    self._destination_number,
                                    "GSM",
                                    self._ns_messaging_2g,
                                    self._messaging_api,
                                    self._data_coding_sheme,
                                    self._nb_bits_per_char,
                                    self._sms_transfer_timeout,
                                    self._content_type,
                                    "MT")

        return Global.SUCCESS, "No errors"

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

        # Call the LAB_GSM_SMS_CS_BASE run_test function
        LabGsmSmsCsBase.run_test(self)

        # Send sms_amount_to_send SMS to sim card.
        for i in xrange(1, self._sms_amount_to_send):

            if(self._nb_segments > 1):
                # [SEND MO SMS PROCESS]
                # Activate loopback on equipment
                self._ns_messaging_2g.set_sms_mo_loopback_state("ON")

                # Enable message queuing
                self._ns_messaging_2g.set_sms_message_queuing_state("ON")

                # Send SMS to equipment using SMS parameters :
                # - SMS_TEXT
                # - DESTINATION_NUMBER
                # Also ask the UE Command to use synchronization
                self._messaging_api.send_sms(
                    self._destination_number,
                    self._sms_text,
                    True)

                # Wait all incoming sms from DUT to Network Simulator
                self._ns_messaging_2g.\
                check_sms_delivery_state(self.sms_sent,
                                         self._nb_segments,
                                         self._sms_transfer_timeout)

                # Read all messages in the queue
                self._ns_messaging_2g.read_all_received_sms()

            else:

                # retrieve instance in order to get sent messages
                self._ns_messaging_2g.\
                        select_sms_content(self._content_type)

                if(self._content_type == "CTEX"):
                    self._ns_messaging_2g.\
                        set_custom_sms_text(self._sms_text)
                elif (self._content_type == "CDAT"):
                    self._ns_messaging_2g.\
                        set_custom_sms_data(self._sms_text)

                # Send SMS to CDK using SMS parameters :
                # - SMS_TEXT
                self.sms_sent.send_sms()

                # Check sms acknowledged by network simulator
                self._ns_messaging_2g.check_sms_state(
                    'ACK', self._sms_transfer_timeout)

            # get sms received
            sms_received = self._messaging_api.wait_for_incoming_sms(self._sms_transfer_timeout)

            # Compare sent and received SMS (Text,
            # Destination number)
            (result_verdict, result_message) = \
                compute_sms_equals(self.sms_sent, sms_received)

            if result_verdict == Global.FAILURE:
                self._logger.error(result_message)
                # Exit loop
                break

        return result_verdict, result_message

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

        #Stop AT Proxy
        self._logger.info("Stop AT Proxy")
        self._modem_flashing_api.stop_at_proxy_from_mos()

        #Close the serial connection
        self._logger.info("Close the serial connection")
        self._logger.info("Disconnecting from the port " +
                            str(self._serial_handler.get_port()))
        self._serial_handler.disconnect()

        return Global.SUCCESS, "No errors"