Exemplo n.º 1
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()

        # Read the battery capacity expected for the init of the test
        self.__high_load_timeout = self._tc_parameters.get_param_value("HIGH_LOAD_DISCHARGE_TIME", default_cast_type=int)
        self.__light_load_timeout = self._tc_parameters.get_param_value("LIGHT_LOAD_DISCHARGE_TIME", default_cast_type=int)
        self.__light_load = self._tc_parameters.get_param_value("LIGHT_LOAD", "")
        self.__high_load = self._tc_parameters.get_param_value("HIGH_LOAD")
        self.__load_module = LoadModule()
        self.__load_module.add_load(self.__light_load)
        self.__load_module.add_load(self.__high_load)
        #-----------------------------------------------------------------------

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_BATT_CRIT_THRESHOLD_ADAPTED", self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())

        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets)
        # Initialize EM  xml object
        # measurement file
        meas_file_name = os.path.join(self._saving_directory, "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
    def __init__(self, tc_name, global_config):

        EmUsecaseBase.__init__(self, tc_name, global_config)

        # get parameters
        self.__charger_to_use = self._tc_parameters.get_param_value("CHARGER")
        self.__load = self._tc_parameters.get_param_value("LOAD")
        self.__time_to_charge_full = self._tc_parameters.get_param_value(
            "TIME_TO_FULL", default_cast_type=int)
        self.__exit_maint_threshold = self._tc_parameters.get_param_value(
            "EXIT_MAINTENANCE_CHARGING_THRESHOLD", default_cast_type=float)
        self.__time_to_stabilize_board = self._tc_parameters.get_param_value(
            "TIME_TO_STABILIZE_BOARD", default_cast_type=int)
        self.__test_type = str(
            self._tc_parameters.get_param_value("TEST_TYPE")).upper()
        self.__test_timeout = self._tc_parameters.get_param_value(
            "TEST_TIMEOUT", default_cast_type=int)

        # create a report file to save all charge/discharge value for debug
        self.__report_file_handler = XMLMeasurementFile(
            os.path.join(self._saving_directory, "em_meas_report.xml"))

        # instance of load module
        self.__load_module = LoadModule()
        self.__load_module.add_load(self.__load)

        # constant
        self.__full_status = "FULL"
        self.__charging_status = "CHARGING"
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)

        # init fuel gauging parameters
        self.em_core_module.init_fg_param()

        setup_load = self._tc_parameters.get_param_value("SETUP_TECHNO", "")
        self.__cooldown = self._tc_parameters.get_param_value("SETUP_TIME_COOLDOWN_BOARD", 120, default_cast_type=int)
        self.__start_temp = self._tc_parameters.get_param_value("SETUP_START_TEMPERATURE", 30, default_cast_type=int)
        self.__temp_target = self._tc_parameters.get_param_value("TARGET_MAX_TEMPERATURE", default_cast_type=int)

        self.__benchmark_module = BenchmarkModule()
        self.__load_module = LoadModule()
        self.__load_module.add_load(setup_load)

        # measurement file
        meas_file_name = os.path.join(self._saving_directory, "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

        meas_file_name = os.path.join(self._saving_directory, "temperature_report.xml")
        self.__temp_meas_tab = XMLMeasurementFile(meas_file_name)

        meas_file_name = os.path.join(self._saving_directory, "benchmark_score_report.xml")
        self.__benchamrk_tab = XMLMeasurementFile(meas_file_name)

        self.__temp_camera = self._em.get_thermal_camera("THERMAL_CAMERA")
        self.__pic_folder = self._saving_directory
        self.__ref_temp = None
        self.__host_test_start_time = None
        self.__bk_delay = 30
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()

        setup_load = self._tc_parameters.get_param_value("SETUP_TECHNO", "")
        self.__record_duration = self._tc_parameters.get_param_value("VIDEO_RECORD_DURATION", 120, default_cast_type=int)
        self.__cooldown = self._tc_parameters.get_param_value("SETUP_TIME_COOLDOWN_BOARD", 120, default_cast_type=int)
        self.__start_temp = self._tc_parameters.get_param_value("SETUP_START_TEMPERATURE", 30, default_cast_type=int)
        self.__host_media = self._tc_parameters.get_param_value("MEDIA_TO_RECORD", "", default_cast_type=str)
        self.__host_monitor = self._tc_parameters.get_param_value("MONITOR_ON_WHICH_MEDIA_IS_PLAY", -1, default_cast_type=int)
        self.__temp_target = self._tc_parameters.get_param_value("TARGET_MAX_TEMPERATURE", default_cast_type=int)

        # load targets in order to measure iteration
        self.__video_capture_mod = VideoCaptureModule()
        self.__load_module = LoadModule()
        self.__load_module.add_load(setup_load)
        self.__video_record_api = self._device.get_uecmd("VideoRecorder", True)
        self.__media_player = None
        if self.__host_media != "":
            self.__media_player = MediaPlayer()
        # measurement file
        meas_file_name = os.path.join(self._saving_directory, "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

        meas_file_name = os.path.join(self._saving_directory, "temperature_report.xml")
        self.__temp_meas_tab = XMLMeasurementFile(meas_file_name)
        self.__temp_camera = self._em.get_thermal_camera("THERMAL_CAMERA")
        self.__pic_folder = self._saving_directory
        self.__ref_temp = None
Exemplo n.º 5
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)

        # Read parameters from tc
        self.__vbatt_lo = self._tc_parameters.get_param_value("VBATT_LOW", default_cast_type=float)
        self.__vbatt_hi = self._tc_parameters.get_param_value("VBATT_HIGH" , default_cast_type=float)
        self.__charger_to_plug = self._tc_parameters.get_param_value("CHARGE_TYPE_DURING_TEST")
        self.__max_time_high = self._tc_parameters.get_param_value("MAX_TIME_TO_SEE_CHANGE_FOR_VBATT_HIGH", default_cast_type=int)
        self.__max_time_low = self._tc_parameters.get_param_value("MAX_TIME_TO_SEE_CHANGE_FOR_VBATT_LOW", default_cast_type=int)
        self.__set_board_in_idle = self._tc_parameters.get_param_value("IDLE_STATE", default_cast_type=str_to_bool)
        self.__idle_time = self._tc_parameters.get_param_value("TIME_TO_WAIT_AFTER_IDLE_STATE", default_value=0, default_cast_type=int)

        # load targets in order to compute verdict
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_BATT_OVER_VOLTAGE", self._tc_parameters.get_params_as_dict(), self._device.get_phone_model())
        self._em_meas_verdict.load_target(self._em_targets, self.tcd_to_test)

        # Set initial value for setting Power Supply VBATT:
        # - VoltageLevel
        self.em_core_module.eqp_init_state["BATT"]["VoltageLevel"] = self.__vbatt_lo
        # measurement file
        meas_file_name = os.path.join(self._saving_directory, "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call LAB_EM_BASE Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()
        # misc parameter
        self.__battery_critical_threshold = self._tc_parameters.get_param_value(
            "BATTERY_CRITICAL_THRESHOLD", default_cast_type=int)
        load_to_apply_in_setup = self._tc_parameters.get_param_value(
            "LOAD_DURING_DISCHARGE", "")
        # call parameter
        self.__call_timeout = self._tc_parameters.get_param_value(
            "CALL_HOLD_TIME", default_cast_type=int)
        self.__hands_free_activation = self._tc_parameters.get_param_value(
            "HANDS_FREE_ACTIVATION", default_cast_type="str_to_bool")
        self.__fake_emergency_phone_number = self._tc_parameters.get_param_value(
            "PHONE_NUMBER", "012345")
        call_type = self._tc_parameters.get_param_value("CALL_TYPE")

        # Summarize the parameters
        self._logger.info("[TESTCASE]\tBattery Critical Threshold: %s%%" %
                          self.__battery_critical_threshold)
        self._logger.info("[TESTCASE]\tEmergency Phone Number : %s" %
                          self.__fake_emergency_phone_number)
        self._logger.info(
            "[TESTCASE]\tthe holding time of the call when battery reach critical level: %ss"
            % self.__call_timeout)
        self._logger.info("[TESTCASE]\tType of the call : %s" % call_type)
        self._logger.info("[TESTCASE]\tActivation of Hands Free : %s" %
                          self.__hands_free_activation)

        # Initial Emergency Number
        if call_type == "3G":
            # Initialization of module 3g
            self.__telmodule = TelephonyModule3g()
        elif call_type == "2G":
            # Initialization of module 3g
            self.__telmodule = TelephonyModule2g()
        else:
            txt = "Type of the call is not correct => Quit the test"
            self._logger.error(txt)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, txt)

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

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

        # init load module used to discharge board
        self.__load_module = LoadModule()
        self.__load_module.add_load(load_to_apply_in_setup)
        self.__initial_emergency_numbers = None
        self.__original_airplane_state = None
Exemplo n.º 7
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()

        self.__zone_to_inspect = str(
            self._tc_parameters.get_param_value("THERMAL_ZONE_TO_MONITOR",
                                                "ANY")).upper().strip()
        self.__record_duration = self._tc_parameters.get_param_value(
            "VIDEO_RECORD_DURATION", 120, default_cast_type=int)
        self.__host_media = self._tc_parameters.get_param_value(
            "MEDIA_TO_RECORD", "", default_cast_type=str)
        self.__host_monitor = self._tc_parameters.get_param_value(
            "MONITOR_ON_WHICH_MEDIA_IS_PLAY", -1, default_cast_type=int)

        setup_load = self._tc_parameters.get_param_value("SETUP_TECHNO", "")
        self.__start_temp = self._tc_parameters.get_param_value(
            "SETUP_START_TEMPERATURE", 30, default_cast_type=int)
        self.__cooldown = self._tc_parameters.get_param_value(
            "SETUP_TIME_COOLDOWN_BOARD", 120, default_cast_type=int)
        use_camera_to_cooldown = self._tc_parameters.get_param_value(
            "SETUP_COOLDOWN_WITH_CAMERA", False, default_cast_type=str_to_bool)
        self.__temp_camera = None
        if use_camera_to_cooldown:
            self.__temp_camera = self._em.get_thermal_camera("THERMAL_CAMERA")

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_COOLING_ACTION_VIDEO_CAPTURE",
            self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())
        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets,
                                          consider_all_target=True)
        self.__video_capture_mod = VideoCaptureModule()
        self.__parser_api = self._device.get_uecmd("Aplog", True)
        self.__load_module = LoadModule()
        self.__load_module.add_load(setup_load)
        self.__video_record_api = self._device.get_uecmd("VideoRecorder", True)
        self.__media_player = None
        if self.__host_media != "":
            self.__media_player = MediaPlayer()
        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
        self.__ref_temp = None
        self.__pic_folder = self._saving_directory
        meas_file_name = os.path.join(self._saving_directory,
                                      "temperature_report.xml")
        self.__temp_meas_tab = XMLMeasurementFile(meas_file_name)
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

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

        # init fuel gauging parameters
        self.em_core_module.init_fg_param()

        # High load
        load = self._tc_parameters.get_param_value("LOAD")
        self.__charger_type = self._tc_parameters.get_param_value("CHARGER_TYPE")
        self.__timeout_dut_adjust_charging_param = self._tc_parameters.get_param_value("TIME_TO_LET_DUT_ADJUST_CHARGING_PARAM", default_cast_type=int)
        self.__timeout_dut_adapt_temp = self._tc_parameters.get_param_value("TIME_TO_LET_DUT_ADAPT_TO_TEST_TEMP", 3600, default_cast_type=int)

        # Read TEMPERATURE from test case xml file
        self.tc_module = None
        self.__max_temperature = self._tc_parameters.get_param_value("MAX_TEMPERATURE")
        self.__min_temperature = self._tc_parameters.get_param_value("MIN_TEMPERATURE")
        if "ROOM" not in [self.__min_temperature, self.__max_temperature]:
            # get temperature chamber equipment if not room temperature
            self.__max_temperature = int(self.__max_temperature)
            self.__min_temperature = int(self.__min_temperature)
            self.tc_module = ThermalChamberModule(self._ambient_temperature)
            # inform module that this is not a default thermal test
            self.tc_module.set_test_type("SPECIFIC")
            self.__temperature = int((self.__min_temperature + self.__max_temperature) / 2)
        else:
            self.__temperature = "ROOM"

        # Summarize the parameters
        self._logger.info("Type of the charger: %s" % self.__charger_type)
        self._logger.info("Test MAX temperature: %s" % self.__max_temperature)
        self._logger.info("Test MIN temperature: %s" % self.__min_temperature)
        self._logger.info("Load to use during test: %s" % load)
        self._logger.info("Time to see change on DUT behavior at tested temperature: %s" % self.__timeout_dut_adjust_charging_param)

        # Load Module Initialization
        self.__load_module = LoadModule()
        self.__load_module.add_load(load)

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_ADJUST_CHARGING_PARAM_WITH_MAINT", self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())
        # get target and initialize measurement
        self._em_meas_verdict.load_target(self._em_targets, self.tcd_to_test)

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
        self.__charger_is_data_cable = None
Exemplo n.º 9
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)

        # init fuel gauging parameters
        self.em_core_module.init_fg_param()
        self.__zone_to_inspect = str(
            self._tc_parameters.get_param_value("THERMAL_ZONE_TO_MONITOR",
                                                "ANY")).upper().strip()

        setup_load = self._tc_parameters.get_param_value("SETUP_TECHNO", "")
        self.__cooldown = self._tc_parameters.get_param_value(
            "SETUP_TIME_COOLDOWN_BOARD", 1800, default_cast_type=int)
        self.__start_temp = self._tc_parameters.get_param_value(
            "SETUP_START_TEMPERATURE", 30, default_cast_type=int)
        use_camera_to_cooldown = self._tc_parameters.get_param_value(
            "SETUP_COOLDOWN_WITH_CAMERA", False, default_cast_type=str_to_bool)
        self.__temp_camera = None
        if use_camera_to_cooldown:
            self.__temp_camera = self._em.get_thermal_camera("THERMAL_CAMERA")

        self.__benchmark_module = BenchmarkModule()
        self.__load_module = LoadModule()
        self.__load_module.add_load(setup_load)

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

        meas_file_name = os.path.join(self._saving_directory,
                                      "temperature_report.xml")
        self.__temp_meas_tab = XMLMeasurementFile(meas_file_name)

        meas_file_name = os.path.join(self._saving_directory,
                                      "benchmark_score_report.xml")
        self.__benchamrk_tab = XMLMeasurementFile(meas_file_name)

        self.__ref_temp = None
        self.__pic_folder = self._saving_directory
        self.__host_test_start_time = None
        self.__bk_delay = 30
        self.__parser_api = self._device.get_uecmd("Aplog", True)
        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_COOLING_ACTION_BENCHMARK",
            self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())
        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets,
                                          consider_all_target=True)
Exemplo n.º 10
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

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

        # Read parameters from TC parameters
        self.__boot_mode = \
            self._tc_parameters.get_param_value("BOOT_MODE", "MOS")
        self.__video_path = \
            self._tc_parameters.get_param_value("VIDEO_PATH", "")
        self.__timer_expiration_value = \
            int(self._tc_parameters.get_param_value("TIMER_EXPIRATION_VALUE", "28800"))
        self.__check_time_value = \
            int(self._tc_parameters.get_param_value("CHECK_VALUE_TIME", "600"))
        self.__cos_capacity_start = \
            int(self._tc_parameters.get_param_value("COS_CAPACITY_START", "10"))

        self._logger.info("Type of OS : %s" % self.__boot_mode)
        self._logger.info("Path of the video : %s" % self.__video_path)
        self._logger.info("Value of timer expiration : %d" % self.__timer_expiration_value)
        self._logger.info("Value of check time : %d" % self.__check_time_value)

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_BATT_CHARGER_TIMER_EXPIRATION", self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())

        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets)

        # Update the target xml file
        update_conf(self._em_targets["VALUE_CHARGE_TIMER"],
                    "lo_lim", self.__timer_expiration_value - 600, "=")
        update_conf(self._em_targets["VALUE_CHARGE_TIMER"],
                    "hi_lim", self.__timer_expiration_value + 600, "=")

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
        # enable Global Measurement file
        name = os.path.join(self._campaign_folder,
                            self._em_cst.GLOBAL_MEAS_FILE)
        self.__em_meas_tab.enable_global_meas(name, self._name)

        self._system_api = self._device.get_uecmd("System")
        self._video_api = self._device.get_uecmd("Video")
        self._multimedia_path = self._device.multimedia_path
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

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

        # init fuel gauging parameters
        self.em_core_module.init_fg_param()
        # Type of the charger
        self.__charger_type = self._tc_parameters.get_param_value(
            "CHARGER_TYPE")
        self.__load = self._tc_parameters.get_param_value(
            "LOAD_TO_HELP_DISCHARGE_IN_SETUP")
        # charge to Full Timeout
        self.__charge_full_timeout = self._tc_parameters.get_param_value(
            "CHARGE_TO_FULL_DURATION", default_cast_type=int)
        # capacity that match with first full
        self.__first_full_capacity = self._tc_parameters.get_param_value(
            "CAPACITY_AT_WHICH_FULL_FIRST_APPEAR", 100, default_cast_type=int)
        self.__what_to_check = str(
            self._tc_parameters.get_param_value("WHAT_TO_CHECK")).upper()

        # Summarize the parameters
        self._logger.info("Charger type to plug during FULL charging: %s" %
                          self.__charger_type)
        self._logger.info("Capacity at which FULL shall first appear: %d" %
                          self.__first_full_capacity)
        self._logger.info("Test expected start capacity : %s" %
                          self.em_core_module.batt_start_capacity)

        # Load Module Initialization
        self.__load_module = LoadModule()
        self.__load_module.add_load(self.__load)

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_BATT_FULL_IDENTIFICATION",
            self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())

        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets,
                                          consider_all_target=True)

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
Exemplo n.º 12
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call the LAB_EM_USE_CASE init method
        EmUsecaseBase.__init__(self, tc_name, global_config)

        # Read mandatory charger info
        tmp_charger_minfo = self._tc_parameters.get_param_value("SYSFS_MANDATORY_INFO")
        tmp_charger_minfo = filter(None, tmp_charger_minfo.split(';'))
        tmp_charger_minfo = map(str.strip, tmp_charger_minfo)
        self.__sysfs_mandatory_charger_info = []

        self.__charger_type = self._tc_parameters.get_param_value("CHARGER_TYPE")
        self.__action_to_perform = self._tc_parameters.get_param_value("ACTION")
        self.__delay = self._tc_parameters.get_param_value("DELAY_BEFORE_CHECKING_INFO", 0, default_cast_type=int)

        if self.__action_to_perform == "BOOT_BOARD":
            for ele in tmp_charger_minfo:
                self.__sysfs_mandatory_charger_info.append(ele + self.__VARIATION_TAG)
        else:
            self.__sysfs_mandatory_charger_info = tmp_charger_minfo

        # get target and initialize measurement
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_EXPORT_INFO_ABOUT_CHARGER", self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())
        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets, self.__sysfs_mandatory_charger_info)
        # measurement file
        meas_file_name = os.path.join(self._saving_directory, "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
    def __init__(self, tc_name, global_config):

        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()
        # get the tc parameters
        self.__tested_capacity = self._tc_parameters.get_param_value(
            "TESTED_CAPACITY", default_cast_type=int)
        self.__charger = self._tc_parameters.get_param_value("CHARGER")
        self.__load = self._tc_parameters.get_param_value("LOAD")
        self.__jump_allowed = self._tc_parameters.get_param_value(
            "JUMP_ALLOWED", default_cast_type=float)
        self.__time_to_log = self._tc_parameters.get_param_value(
            "PLUG_DURATION", default_cast_type=int)

        # vars
        self.__time_to_charge = 60
        self.__time_to_discharge = 60
        self.__reports_file_name = os.path.join(self._saving_directory,
                                                "EM_meas_report.xml")
        # create a report file
        self.__em_meas_tab = XMLMeasurementFile(self.__reports_file_name)

        # Activate Loadmodule instance
        self.__load_module = LoadModule()
        self.__load_module.add_load(self.__load)
Exemplo n.º 14
0
    def __init__(self, tc_name, global_config):

        EmUsecaseBase.__init__(self, tc_name, global_config)

        # get base module
        self.em_core_module = UcBatteryModule(self)

        # get the tc parameters
        self.__tested_capacity = self._tc_parameters.get_param_value(
            "TESTED_CAPACITY", default_cast_type=int)
        self.__charger = self._tc_parameters.get_param_value("CHARGER")
        self.__status = self._tc_parameters.get_param_value("STATUS").upper()
        self.__load = self._tc_parameters.get_param_value("LOAD")

        # vars
        self.__time_to_charge = 60
        self.__time_to_discharge = 60
        self.__reports_file_name = os.path.join(self._saving_directory,
                                                "EM_meas_report.xml")
        self.__time_to_log = 60
        # create a report file
        self.__report_file_handler = XMLMeasurementFile(
            self.__reports_file_name)

        # Activate Loadmodule instance
        self.__load_module = LoadModule()
        self.__load_module.add_load(self.__load)

        # delay to launch autologger
        self.__autolog_delay = 20
Exemplo n.º 15
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

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

        # init fuel gauging parameters
        self.em_core_module.init_fg_param()
        self.__raw_behavior = str(
            self._tc_parameters.get_param_value("CYCLE_BEHAVIOR")).upper()
        load = self._tc_parameters.get_param_value("LOAD")
        self.__charger_type = self._tc_parameters.get_param_value(
            "CHARGER_TYPE")

        # Load Module Initialization
        self.__load_module = LoadModule()
        self.__load_module.add_load(load)

        # Initialize EM  xml object
        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
        # track the case where DUT is lost to gather em info later
        self.__fail_to_get_em_info = False
Exemplo n.º 16
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # Read BATT_MIN_CAPACITY from test case xml file
        self.em_core_module.init_fg_param()
        #-----------------------------------------------------------------------
        # Read Band from test case xml file (str)
        self.__cell_band = str(self._tc_parameters.get_param_value("CELL_BAND"))
        # Read CELL_SERVICE from test case xml file
        self.__cell_service = str(self._tc_parameters.get_param_value("CELL_SERVICE"))
        # Read TCH_ARFCN from test case xml file
        self.__tch_arfcn = int(self._tc_parameters.get_param_value("TCH_ARFCN"))
        # Read UPLINK_CHANNEL from test case xml file
        self.__uplink_channel = int(self._tc_parameters.get_param_value("UPLINK_CHANNEL"))
        # Read CELL_POWER from test case xml file
        self.__cell_power = int(self._tc_parameters.get_param_value("CELL_POWER"))
        # Read CALL_ORIGIN from test case xml file
        self.__call_origin = str(self._tc_parameters.get_param_value("CALL_ORIGIN")).upper()
        # Read DATA_CALL_MODE from test case xml file
        self.__data_call_mode = str(self._tc_parameters.get_param_value("DATA_CALL_MODE"))
        # Read registrationTimeout from Phone_Catalog.xml
        self._registration_timeout = \
            int(self._dut_config.get("registrationTimeout"))

        # Create cellular network simulator and retrieve 2G APIs
        self.__ns = self._em.get_cellular_network_simulator("NETWORK_SIMULATOR1")
        self.__ns_2g = self.__ns.get_cell_2g()
        self.__data_2g = self.__ns_2g.get_data()
        #-----------------------------------------------------------------------

        # Initialize EM  xml object
        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
        # enable Global Measurement file
        name = os.path.join(self._campaign_folder,
                            self._em_cst.GLOBAL_MEAS_FILE)
        self.__em_meas_tab.enable_global_meas(name, self._name)
        # enable OCV computing
        # get OCV target file
        target = self.em_core_module.ocv_target_file.parse_em_ocv_targets(
            self._device.get_phone_model(), self._tct)
        self.__ocv_tool = OcvComputingTool(target)
    def __init__(self, tc_name, global_config):

        EmUsecaseBase.__init__(self, tc_name, global_config)

        # get the tc parameters
        self.__min_range = self._tc_parameters.get_param_value(
            "MIN_RANGE", default_cast_type=int)
        self.__max_range = self._tc_parameters.get_param_value(
            "MAX_RANGE", default_cast_type=int)
        self.__charging_timeout = self._tc_parameters.get_param_value(
            "CHARGING_TIMEOUT", default_cast_type=int)
        self.__discharging_timeout = self._tc_parameters.get_param_value(
            "DISCHARGING_TIMEOUT", default_cast_type=int)
        self.__polling_delay = self._tc_parameters.get_param_value(
            "DATA_POLLING_DELAY", default_cast_type=int)
        self.__load = self._tc_parameters.get_param_value("LOAD")
        self.__target = str(
            self._tc_parameters.get_param_value("TARGET")).lower()
        self.__crit_batt_voltage = self._tc_parameters.get_param_value(
            "CRIT_VBATT_VOLTAGE", default_cast_type=float)
        self.__full_voltage_th = self._tc_parameters.get_param_value(
            "FULL_VOLTAGE_THRESHOLD", default_cast_type=float)
        self.__full_volt_offset = self._tc_parameters.get_param_value(
            "FULL_VOLTAGE_OFFSET", default_cast_type=float)
        self._critt_batt_offset = self._tc_parameters.get_param_value(
            "CRIT_VBATT_OFFSET", default_cast_type=float)

        # vars
        self.__time_to_charge = 500
        self.__time_to_discharge = 500
        self.__reports_file_name = os.path.join(self._saving_directory,
                                                "EM_meas_report.xml")
        # create a report file
        self.__report_file_handler = XMLMeasurementFile(
            self.__reports_file_name)

        # Activate Loadmodule instance
        self.__load_module = LoadModule()
        self.__load_module.add_load(self.__load)
Exemplo n.º 18
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call LAB_EM_BASE Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)

        # Read parameters from TC parameters
        self.__sensor = self._tc_parameters.get_param_value("SENSOR_TO_TEST").upper()

        self.__temperature_change_timeout = self._tc_parameters.get_param_value("TEMPERATURE_CHANGE_TIMEOUT",
                                                                                default_cast_type=int)
        # TODO: add charge type choice to allow shutdown without cable

        # Read TEMPERATURE from test case xml file
        self.tc_module = None
        # set a temperature or use SMART to use data from thermal conf file
        self.__temperature = self._tc_parameters.get_param_value("TEMPERATURE")
        # we can authorize to increase at most 10 more degree on the test temp
        # if board temperature does not move
        self.__max_temp_rising = self._tc_parameters.get_param_value("TEMP_MAX_INCREASE_MARGIN", 10,
                                                                     default_cast_type=int)
        if self.__temperature != "ROOM":
            # get temperature chamber equipment if not room temperature
            if self.__temperature != "SMART":
                self.__temperature = int(self.__temperature)
            self.tc_module = ThermalChamberModule(self._ambient_temperature)
            # inform module that this is not a default thermal test
            self.tc_module.set_test_type("SPECIFIC")

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_THERMAL_CRITICAL_STATE", self._tc_parameters.get_params_as_dict(), self._device.get_phone_model())
        self._em_meas_verdict.load_target(self._em_targets, self.tcd_to_test)
        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
Exemplo n.º 19
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()
        # Read the battery capacity expected for the init of the test
        self.__discharge_timeout = self._tc_parameters.get_param_value(
            "DISCHARGE_TIMEOUT", default_cast_type=int)
        self.__cable_type = self._tc_parameters.get_param_value(
            "CABLE_TYPE_DURING_DISCHARGE")
        load_to_apply_in_setup = self._tc_parameters.get_param_value(
            "LOAD_TO_HELP_DISCHARGE")

        #-----------------------------------------------------------------------
        # Get load Parameters
        self.__load_module = LoadModule()
        self.__load_module.add_load(load_to_apply_in_setup)

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

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_BATT_LOW_CAP_SHUTDOWN",
            self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())

        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets, self.tcd_to_test)
        # Initialize EM measurement file xml object
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
        self.__charger_is_data_cable = None
        self.__parser_api = self._device.get_uecmd("Aplog", True)
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """

        # Call LAB_EM_BASE Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()
        # Read parameters from TC parameters
        self.__test_process = \
            self._tc_parameters.get_param_value("TEST_PROCESS")
        self.__test_length = \
            int(self._tc_parameters.get_param_value("TEST_LENGTH"))
        self.__shutdown_time = \
            int(self._tc_parameters.get_param_value("SHUTDOWN_TIME"))

        self._logger.info("Process of the test : %s" % self.__test_process)
        self._logger.info("Length of the test : %d" % self.__test_length)
        self._logger.info("Max Capacity of the Battery : %s" %
                          self.em_core_module.batt_max_capacity)
        self._logger.info("Time of Charge : %d" %
                          self.em_core_module.charge_time)

        # toggle param depending of what was put in LOAD var
        if "VIDEO" in self.__test_process:
            self.__multimedia_file = \
                self._tc_parameters.get_param_value("VIDEO_PATH", "")
            self.__volume = \
                int(self._tc_parameters.get_param_value("VOLUME", "100"))
            self._logger.info("Multimedia File : %s" % self.__multimedia_file)
            self._logger.info("Volume of the Video: %d" % self.__volume)

            self._system_api = self._device.get_uecmd("System")
            self._video_api = self._device.get_uecmd("Video")
            self._multimedia_path = self._device.multimedia_path

        if "CALL3G" in self.__test_process:
            self.__telmodule = TelephonyModule3g()

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

        self.__batt_temp = None
class LabEmAdjustParamWithMaint(EmUsecaseBase):

    """
    Lab Energy Management class.
    """
    DEDICATED_BENCH = "BATTERY_BENCH"

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

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

        # init fuel gauging parameters
        self.em_core_module.init_fg_param()

        # High load
        load = self._tc_parameters.get_param_value("LOAD")
        self.__charger_type = self._tc_parameters.get_param_value("CHARGER_TYPE")
        self.__timeout_dut_adjust_charging_param = self._tc_parameters.get_param_value("TIME_TO_LET_DUT_ADJUST_CHARGING_PARAM", default_cast_type=int)
        self.__timeout_dut_adapt_temp = self._tc_parameters.get_param_value("TIME_TO_LET_DUT_ADAPT_TO_TEST_TEMP", 3600, default_cast_type=int)

        # Read TEMPERATURE from test case xml file
        self.tc_module = None
        self.__max_temperature = self._tc_parameters.get_param_value("MAX_TEMPERATURE")
        self.__min_temperature = self._tc_parameters.get_param_value("MIN_TEMPERATURE")
        if "ROOM" not in [self.__min_temperature, self.__max_temperature]:
            # get temperature chamber equipment if not room temperature
            self.__max_temperature = int(self.__max_temperature)
            self.__min_temperature = int(self.__min_temperature)
            self.tc_module = ThermalChamberModule(self._ambient_temperature)
            # inform module that this is not a default thermal test
            self.tc_module.set_test_type("SPECIFIC")
            self.__temperature = int((self.__min_temperature + self.__max_temperature) / 2)
        else:
            self.__temperature = "ROOM"

        # Summarize the parameters
        self._logger.info("Type of the charger: %s" % self.__charger_type)
        self._logger.info("Test MAX temperature: %s" % self.__max_temperature)
        self._logger.info("Test MIN temperature: %s" % self.__min_temperature)
        self._logger.info("Load to use during test: %s" % load)
        self._logger.info("Time to see change on DUT behavior at tested temperature: %s" % self.__timeout_dut_adjust_charging_param)

        # Load Module Initialization
        self.__load_module = LoadModule()
        self.__load_module.add_load(load)

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_ADJUST_CHARGING_PARAM_WITH_MAINT", self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())
        # get target and initialize measurement
        self._em_meas_verdict.load_target(self._em_targets, self.tcd_to_test)

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
        self.__charger_is_data_cable = None

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

    def set_up(self):
        """
        Initialize the test
        """
        # Call the UseCaseBase Setup function
        EmUsecaseBase.set_up(self)

        # Check specific option if they are chosen
        if self.__charger_type not in self._io_card.SUPPORTED_DEVICE_TYPE:
            txt = "io card does not support charger type %s " % self.__charger_type
            self._logger.error(txt)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, txt)

        if self.tc_module is not None:
            self.tc_module.set_up_eq()
            self.tc_module.get_eq().set_regulation(True)
            start_temp = self.__temperature
            low_temp = self.phone_info["BATTERY"]["THERMAL_CHARGING_LOW_LIMIT"]
            high_temp = self.phone_info["BATTERY"]["THERMAL_CHARGING_HIGH_LIMIT"]
            # avoid setting temperature at not charging temp but near it
            if start_temp <= low_temp:
                self._logger.info("test temperature at %s is <= the min temperature for charging:%s, adjusting it" % (self.__temperature, low_temp))
                start_temp = low_temp + 10
            elif start_temp >= high_temp :
                self._logger.info("test temperature at %s is >= the max temperature for charging:%s, adjusting it" % (self.__temperature, high_temp))
                start_temp = high_temp - 10

            self.tc_module.get_eq().set_temperature(start_temp)
        # set the temperature
        self.em_api.set_thermal_management(False)
        # a reboot is required to apply this change
        self._device.reboot()

        # do this job one time in case of B2B
        if self.__charger_is_data_cable is None:
            self.__charger_is_data_cable = self.em_core_module.is_host_connection_available_when_charger_plug(self.__charger_type)
            self._logger.info("test sequences will adjust to this")

        # Update Battery Information
        em_info = self.update_battery_info()

        # we want to start at given capacity
        if self.em_core_module.is_batt_capacity_above_target(em_info, self.em_core_module.batt_start_capacity):

            # Discharge part
            self.em_core_module.monitor_discharging(self.em_core_module.batt_start_capacity,
                                     self.em_core_module.discharge_time,
                                     self.__em_meas_tab, self.__load_module)
        elif self.em_core_module.is_batt_capacity_below_target(em_info, self.em_core_module.batt_start_capacity):
            # charge part
            self.em_core_module.monitor_charging(self.em_core_module.batt_start_capacity,
                                         self.em_core_module.charge_time,
                                         self.__em_meas_tab)

        # wait that the board see the test temperature
        self.__wait_for_temp(self.__temperature)

        return Global.SUCCESS, "No errors"

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

    def run_test_body(self):
        """
        Execute the test
        """
        # Call LAB_EM_BASE Run function
        EmUsecaseBase.run_test_body(self)

        if self.__charger_is_data_cable:
            self.__test_with_data(self.__temperature)
        else:
            self.__test_without_data(self.__temperature)

        # value comparing are done in private function
        self._em_meas_verdict.judge()

        return self._em_meas_verdict.get_current_result_v2()

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

    def tear_down(self):
        """
        End and dispose the test
        """
        # call tear down after some operations
        EmUsecaseBase.tear_down(self)
        if self.tc_module is not None:
            # Go to the ambient temperature
            self.tc_module.release_eq()

        # clean the board state and retrieve logs
        self.em_core_module.clean_up()

        # restore thermal management setting
        self.em_api.set_thermal_management(True)
        # a reboot is required to apply this change
        self._device.reboot()
        return Global.SUCCESS, "No errors"

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

    def __wait_for_temp(self, temperature):
        """
        wait that the DUT see the test temperature
        """
        # heat the DUT
        self._logger.info("check that DUT is between [%s;%s] degree celsius" % (self.__min_temperature, self.__max_temperature))
        last_batt_temp = self.update_battery_info()["BATTERY"]["TEMP"][0]
        if self.tc_module is not None and not (self.__min_temperature <= last_batt_temp <= self.__max_temperature):
            self.phonesystem_api.sleep_screen()
            exceed_timeout = True
            self.tc_module.get_eq().set_temperature(temperature)
            self.tc_module.get_eq().wait_for_temperature(temperature)
            timeout_to_see_temp_change = 300
            start_time_to_see_temp_change = time.time()
            timeout = time.time() + self.__timeout_dut_adapt_temp
            while time.time() < timeout:
                self._logger.info("wait 60s")
                time.sleep(60)
                try:
                    # try to read measurement
                    msic_reg = self.update_battery_info()
                    thermal_conf = self.em_api.get_thermal_sensor_info()
                    # store result on xml
                    self.__em_meas_tab.add_dict_measurement(msic_reg)
                    self.__em_meas_tab.add_dict_measurement(thermal_conf)
                    local_temp = msic_reg["BATTERY"]["TEMP"][0]

                    if last_batt_temp != local_temp:
                        start_time_to_see_temp_change = time.time()
                    last_batt_temp = local_temp

                    # stop usecase if board take too long to reach battery capacity
                    if (time.time() - start_time_to_see_temp_change) > timeout_to_see_temp_change:
                        self._logger.info("DUT temperature did not change in %ss, adjusting chamber temperature" % timeout_to_see_temp_change)
                        if local_temp < self.__min_temperature:
                            temperature += 1

                        elif  local_temp > self.__max_temperature:
                            temperature -= 1
                        self.tc_module.get_eq().set_temperature(temperature)
                        start_time_to_see_temp_change = time.time()

                except AcsBaseException as e:
                    # try to catch why uecmd may fail
                    if not self.is_board_and_acs_ok():
                        txt = "connection with DUT lost during temperature change to be between [%s;%s] degree celsius" % (self.__min_temperature, self.__max_temperature)
                    else:
                        txt = "error happened during temperature change to let it see [%s;%s] degree celsius : %s" % (self.__min_temperature, self.__max_temperature, str(e))
                    self._logger.error(txt)
                    raise DeviceException(DeviceException.OPERATION_FAILED, txt)
                finally:
                    # Store various information
                    self.__em_meas_tab.add_measurement([self.get_time_tuple(),
                                            (self._em_cst.COMMENTS, "SETUP:Waiting for the DUT to reach [%s;%s] degree celsius" % (self.__min_temperature, self.__max_temperature))])
                    # switch meas to next meas
                    self.__em_meas_tab.switch_to_next_meas()
                # exit if the battery temp match with test temp
                if self.__min_temperature <= last_batt_temp <= self.__max_temperature:
                    self._logger.info("The DUT has reached %s degree celsius which is between expected target [%s;%s] !" % (last_batt_temp, self.__min_temperature, self.__max_temperature))
                    exceed_timeout = False
                    break

            if exceed_timeout:
                txt = "timeout exceeded (%ss) to heat up the DUT to %s degree celsius" % (str(self.__timeout_dut_adapt_temp), temperature)
                self._logger.error(txt)
                raise DeviceException(DeviceException.OPERATION_FAILED, txt)

    def __test_with_data(self, temperature):
        """
        test that we can see the CC & CV expected for this temperature
        with a data cable plug
        """
        self._logger.info("testing charger and battery behavior at [%s;%s] degree celsius while data is active" % (self.__min_temperature, self.__max_temperature))
        # init var
        full_constently_seen = False
        maintenance_constently_seen = False
        full_seen_one_time = False
        maintenance_seen_one_time = False
        maitenance_started = False
        msic_reg = self.update_battery_info()

        # timeout to see CC and CV updated
        timeout = time.time() + self.__timeout_dut_adjust_charging_param
        while time.time() < timeout and not maitenance_started:
            self._logger.info("wait 60s")
            time.sleep(60)
            try:
                # try to read measurement
                msic_reg = self.update_battery_info()
                thermal_conf = self.em_api.get_thermal_sensor_info()
                # store result on xml
                self.__em_meas_tab.add_dict_measurement(msic_reg)
                self.__em_meas_tab.add_dict_measurement(thermal_conf)
                # compare values with targets
                if msic_reg["BATTERY"]["STATUS"] == "FULL":
                    full_constently_seen = True
                    full_seen_one_time = True
                else:
                    full_constently_seen = False

                # check that we reach maintenance charging
                if msic_reg["CHARGER"]["ENABLE_CHARGING"] == 0 and full_constently_seen:
                    maintenance_constently_seen = True
                    maintenance_seen_one_time = True
                else:
                    maintenance_constently_seen = False

                if maintenance_constently_seen and full_constently_seen:
                    # compute verdict by taking the last batt info seen
                    self._meas_list.add_dict("EM_INFO", msic_reg)
                    self._em_meas_verdict.compare_list(self._meas_list, self._em_targets, clean_meas_list=True)
                    maitenance_started = True

            except AcsBaseException as e:
                # try to catch why uecmd may fail
                if not self.is_board_and_acs_ok():
                    txt = "connection with DUT lost during change waiting on DUT behavior"
                else:
                    txt = "error happened during change waiting on DUT behavior: " + str(e)
                self._logger.error(txt)
                raise DeviceException(DeviceException.OPERATION_FAILED, txt)
            finally:
                # Store various information
                self.__em_meas_tab.add_measurement([self.get_time_tuple(),
                                        (self._em_cst.COMMENTS, "RUNTEST:Waiting for the DUT behavior to change at [%s;%s] degree" % (self.__min_temperature, self.__max_temperature))])
                # switch meas to next meas
                self.__em_meas_tab.switch_to_next_meas()
            if maintenance_constently_seen and full_constently_seen:
                break

        txt = ""
        # check that board reach full
        if not full_constently_seen:
            if not full_seen_one_time:
                txt = "battery FULL state was never reached at a temperature between [%s;%s] degree celsius " % (self.__min_temperature, self.__max_temperature)
            else:
                txt = "battery FULL state was seen but lost at a temperature between [%s;%s] degree celsius" % (self.__min_temperature, self.__max_temperature)
        # check that maintenance have started if we reach full
        elif not maintenance_constently_seen:
            if not maintenance_seen_one_time:
                txt = "MAINTENANCE charging state was never reached at a temperature between [%s;%s] degree celsius" % (self.__min_temperature, self.__max_temperature)

            else:
                txt = "MAINTENANCE charging was seen but lost at a temperature between [%s;%s] degree celsius" % (self.__min_temperature, self.__max_temperature)

        if txt != "":
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)

    def __test_without_data(self, temperature):
        """
        test that we can see the CC & CV expected for this temperature
        without a data cable plug
        """
        self._logger.info("testing charger and battery behavior at  [%s;%s] degree celsius while data is not active" % (self.__min_temperature, self.__max_temperature))
        self.em_api.clean_autolog()
        # choose function to put in logger
        self.em_api.add_fct_to_auto_logger(self.em_api.AUTOLOG_UEVENT, "sequenced")
        self.em_api.add_fct_to_auto_logger(self.em_api.AUTOLOG_THERMAL, "sequenced")
        self.em_api.set_autolog_duration(self.__timeout_dut_adjust_charging_param)
        # start  non persistent autolog with a short period of data polling
        self.em_api.start_auto_logger(30, 10, "sequenced")

        # switch charger
        self._device.disconnect_board()
        # connect WALL Charger
        self._io_card.simulate_insertion(self.__charger_type)
        # wait x min
        self._logger.info("wait %ss to see any change on DUT behavior" % str(self.__timeout_dut_adjust_charging_param + 60))
        time.sleep(self.__timeout_dut_adjust_charging_param + 60)
        self._io_card.usb_host_pc_connector(True)
        # wait x seconds
        time.sleep(self.usb_sleep)
        # connect board
        self._device.connect_board()
        self.em_api.stop_auto_logger()
        # parse autolog response and reset them
        msic_list = self.em_api.get_autolog_msic_registers()
        thermal_list = self.em_api.get_autolog_thermal_sensor_info()
        self.em_api.clean_autolog()

        # init var
        full_constently_seen = False
        maintenance_constently_seen = False
        full_seen_one_time = False
        maintenance_seen_one_time = False

        # get the highest logs length
        log_length = max(len(thermal_list), len(msic_list))
        for i in range(log_length):

            try:
                # get battery/charger info
                if len(msic_list) > i:
                    msic_dict = msic_list[i]
                    if len(msic_dict) > 1:
                        msic_dict = msic_dict[1]
                        # store result on xml
                        self.__em_meas_tab.add_dict_measurement(msic_dict)
                        # check that we reach full and stay in this state
                        if msic_dict["BATTERY"]["STATUS"][0] == "FULL":
                            full_constently_seen = True
                            full_seen_one_time = True
                        else:
                            full_constently_seen = False

                        # check that we reach maintenance charging
                        if msic_dict["CHARGER"]["ENABLE_CHARGING"][0] == 0 and full_constently_seen:
                            maintenance_constently_seen = True
                            maintenance_seen_one_time = True
                        else:
                            maintenance_constently_seen = False

                    # get thermal info
                    if len(thermal_list) > i:
                        thermal_dict = thermal_list[i]
                        if len(thermal_dict) > 1:
                            # store result on xml
                            self.__em_meas_tab.add_dict_measurement(thermal_dict[1])

            finally:
                self.__em_meas_tab.add_measurement(
                    [self.get_time_tuple(), (self._em_cst.COMMENTS,
                        "RUNTEST:Waiting for the DUT behavior to change when it is between [%s;%s] degree and not data cable plug" % (self.__min_temperature, self.__max_temperature))])
                # switch meas to next meas
                self.__em_meas_tab.switch_to_next_meas()

        txt = ""
        # check that board reach full
        if not full_constently_seen:
            if not full_seen_one_time:
                txt = "battery FULL state was never reached at a temperature between [%s;%s] degree celsius " % (self.__min_temperature, self.__max_temperature)
            else:
                txt = "battery FULL state was seen but lost at a temperature between [%s;%s] degree celsius" % (self.__min_temperature, self.__max_temperature)
        # check that maintenance have started if we reach full
        elif not maintenance_constently_seen:
            if not maintenance_seen_one_time:
                txt = "MAINTENANCE charging state was never reached at a temperature between [%s;%s] degree celsius" % (self.__min_temperature, self.__max_temperature)

            else:
                txt = "MAINTENANCE charging was seen but lost at a temperature between [%s;%s] degree celsius" % (self.__min_temperature, self.__max_temperature)

        if txt != "":
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)

        # compute verdict by taking the last batt info seen
        self._meas_list.add_dict("EM_INFO", msic_list[-1][1])
        self._em_meas_verdict.compare_list(self._meas_list, self._em_targets, clean_meas_list=True)
Exemplo n.º 22
0
class LabEmBattCritThresholdAdapted(EmUsecaseBase):

    """
    Lab Energy Management base class.
    """
    DEDICATED_BENCH = "BATTERY_BENCH"

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()

        # Read the battery capacity expected for the init of the test
        self.__high_load_timeout = self._tc_parameters.get_param_value("HIGH_LOAD_DISCHARGE_TIME", default_cast_type=int)
        self.__light_load_timeout = self._tc_parameters.get_param_value("LIGHT_LOAD_DISCHARGE_TIME", default_cast_type=int)
        self.__light_load = self._tc_parameters.get_param_value("LIGHT_LOAD", "")
        self.__high_load = self._tc_parameters.get_param_value("HIGH_LOAD")
        self.__load_module = LoadModule()
        self.__load_module.add_load(self.__light_load)
        self.__load_module.add_load(self.__high_load)
        #-----------------------------------------------------------------------

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_BATT_CRIT_THRESHOLD_ADAPTED", self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())

        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets)
        # Initialize EM  xml object
        # measurement file
        meas_file_name = os.path.join(self._saving_directory, "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

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

    def set_up(self):
        """
        Initialize the test
        """
        # Call the UseCaseBase Setup function
        EmUsecaseBase.set_up(self)
        # init capacity
        self.update_battery_info()

        # discharge battery
        if str(self.em_core_module.batt_start_capacity).isdigit() and \
            (self.batt_capacity > self.em_core_module.batt_start_capacity):
            # add video to the setup discharge load

            self.em_core_module.monitor_discharging(self.em_core_module.batt_start_capacity,
                                     self.em_core_module.discharge_time,
                                     self.__em_meas_tab, self.__load_module)

        # help board to discharge faster

        return Global.SUCCESS, "No errors"

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

    def run_test_body(self):
        """
        here we discharge twice to compare the voltage at shutdown level.
        Shutdown level is at 0% of capacity on android system.
        it may change on other
        """
        EmUsecaseBase.run_test_body(self)
        msic = self.update_battery_info()
        # get voltage unit
        unit = msic["BATTERY"]["VOLTAGE"][1]

        def __discharge_part(load, load_timeout, text):
            self.__load_module.stop_load()
            self.__load_module.start_load(load)
            self.__discharge_to_off_without_data(load_timeout)
            error_text = ""

            # plug a data cable to see if the board boot in COS or MOS
            self.__retrieve_the_board_to_mos()

            if self.is_board_and_acs_ok():
                voltage = self.__retrieve_autolog_result(text)
                # exit here if we fail to get the voltage at 0%
                if voltage is None:
                    error_text = "load %s never reach 0%% of capacity" % str(load)

            if error_text != "":
                # leave here as test is KO if 0% not seen
                self._meas_list.add("DELTA_BETWEEN_HIGH_AND_LIGHT_LOAD", "CAPACITY_AT_ZERO_NEVER_REACHED", "")
                self._logger.error(error_text)
                raise DeviceException(DeviceException.OPERATION_FAILED, error_text)

            return voltage

        # First discharge with the load that take more time to discharge
        light_voltage = __discharge_part(self.__light_load, self.__light_load_timeout, "light_load")
        if self.is_board_and_acs_ok() and light_voltage is not None:
            # if board capacity is too low then charge a little bit
            if self.batt_capacity + 1 < int(self.em_core_module.batt_start_capacity):
                self.em_core_module.monitor_charging(self.em_core_module.batt_start_capacity, 120, self.__em_meas_tab)

            # Discharge with high load
            high_voltage = __discharge_part(self.__high_load, self.__high_load_timeout, "high_load")

            if high_voltage is not None:
                # generate em verdict
                self._meas_list.add("DELTA_BETWEEN_HIGH_AND_LIGHT_LOAD", high_voltage - light_voltage, unit)

        self._em_meas_verdict.compare_list(self._meas_list, self._em_targets, True)
        self._em_meas_verdict.judge(ignore_blocked_tc=True)
        # Save data report in xml file
        return(self._em_meas_verdict.get_current_result(),
               self._em_meas_verdict.save_data_report_file())

    def tear_down(self):
        """
        End and dispose the test
        """
        # call tear down after some operations
        EmUsecaseBase.tear_down(self)
        # check the board health, get the aplog, and charge again if necessary
        load_stopped = False
        if self.is_board_and_acs_ok():
            # restore setting that does not persist on reboot
            self.__load_module.stop_load(raise_error=False)
            load_stopped = True

        # clean the board state and retrieve logs
        self.em_core_module.clean_up()
        if not load_stopped:
            self.__load_module.stop_load(raise_error=False)

        return Global.SUCCESS, "No errors"

    def __discharge_to_off_without_data(self, timeout):
        """
        discharge board until shutdown
        designed for a short discharge period(like discharging from 20% to 0).
        If discharge fail to reach shutdown , it will discharge for the all of the shutdown
        timeout set
        """
        # start  non persistent autolog with a short period of data polling
        # choose function to put in logger
        self.em_api.clean_autolog()
        self.em_api.add_fct_to_auto_logger(self.em_api.AUTOLOG_THERMAL, "sequenced")
        self.em_api.add_fct_to_auto_logger(self.em_api.AUTOLOG_UEVENT, "sequenced")
        self.em_api.start_auto_logger(60, 1, "sequenced")
        # disconnect board and plug the wanted cable
        self._device.disconnect_board()
        self._io_card.ac_charger_connector(False)
        self._io_card.usb_connector(False)

        # wait for 0% of battery capacity or connection lost
        self._logger.info("Waiting %ss to let the board discharge from %s%% to off" % (timeout, self.batt_capacity))
        time.sleep(timeout)
        self._io_card.usb_host_pc_connector(True)
        time.sleep(self.usb_sleep)
        mode = self._device.get_boot_mode()
        if mode == "MOS":
            self._device.connect_board()
            self.update_battery_info()
            self.__load_module.restart_load(consider_only_checkable_load=True)
            self._logger.info("board not yet turn off, Waiting %ss to let the board discharge from %s%% to off" % (
            timeout / 2, self.batt_capacity))
            self._device.disconnect_board()
            self._io_card.usb_host_pc_connector(False)

    def __retrieve_the_board_to_mos(self):
        """
        retrieve the board.
        """
        # plug a data cable to see if the board boot in COS or MOS
        self._io_card.usb_host_pc_connector(True)
        time.sleep(self.usb_sleep)
        mode = self._device.get_boot_mode()
        if mode != "MOS":
            # wait for a while to let the board boot
            if self.phone_info.get("DATA_WHILE_CHARGING") is True:
                self._logger.info("Waiting 5 minutes for the board to boot")
                time.sleep(300)
                self._logger.info("Waiting at most 15 minutes to see the boot mode")
                end_time = time.time() + 900
                while time.time() < end_time:
                    mode = self._device.get_boot_mode()
                    if mode in ["COS", "MOS"]:
                        self._logger.info("Board seen booted in %s after %ss" % (mode, abs((time.time() - end_time) + 900)))
                        break

            if mode != "MOS":
                # plug a charge and charge it for a while
                self._io_card.wall_charger_connector(True)
                self._logger.info("Waiting 20 minutes to charge the board with a wall charger")
                time.sleep(1200)
                # plug a data cable to see if the board boot is still in COS
                self._io_card.wall_charger_connector(False)
                self._io_card.usb_host_pc_connector(True)
                mode = self._device.get_boot_mode()
                self._logger.info("Waiting at most 10 minutes to detect the boot mode")
                end_time = time.time() + 600
                while time.time() < end_time:
                    mode = self._device.get_boot_mode()
                    if mode != "UNKNOWN":
                        self._logger.info("Board seen booted in %s after %ss" % (mode, abs((time.time() - end_time) + 600)))
                        break

                # if the boot mode is not unknown , try to reboot the board
                if mode == "UNKNOWN":
                    self.em_core_module.reboot_board("HARD")
                # if in MOS connect board
                elif mode != "MOS":
                    self._device.reboot(skip_failure=True)

                # after all of this , try to connect ACS
                mode = self._device.get_boot_mode()

        if mode == "MOS":
            # else we are in MOS thus connecting ACS
            self._device.connect_board()

        # finally do action here only if board is well booted
        if not self.is_board_and_acs_ok():
            tmp_txt = "failed to retrieve the board in MAIN OS and connect ACS after shutdown link to load testing"
            self._logger.error(tmp_txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt)

    def __retrieve_autolog_result(self, text):
        """
        retrieve data from autolog.
        return voltage when capacity reach the first 0%.
        """
        # get info from autologger
        result = None
        self.update_battery_info()
        self.em_api.stop_auto_logger()
        msic_list = self.em_api.get_autolog_msic_registers()
        thermal_list = self.em_api.get_autolog_thermal_sensor_info()
        self.em_api.clean_autolog()

        # get the highest logs length
        log_length = max(len(thermal_list), len(msic_list))
        for i in range(log_length):
            try:
                # get battery/charger info
                if len(msic_list) > i:
                    msic_dict = msic_list[i][1]
                    if len(msic_dict) > 1:
                        # get the voltage for the first 0% reported
                        # FIXME: maybe check the 0 from aplog to catch  exactly what board see
                        if result is None and msic_dict["BATTERY"]["CAPACITY"][0] == 0:
                            result = msic_dict["BATTERY"]["VOLTAGE"][0]
                        self.__em_meas_tab.add_dict_measurement(msic_dict)

                    # get thermal info
                if len(thermal_list) > i:
                    thermal_dict = thermal_list[i][1]
                    if len(thermal_dict) > 1:
                        # store result on xml
                        self.__em_meas_tab.add_dict_measurement(thermal_dict)

                # reset error
                measurement_fail = 0
            except AcsBaseException as e:
                # try to reconnect to the board if uecmd failed
                self._logger.error("fail to get measurement: " + str(e))
                measurement_fail += 1

                # stop the usecase if measurement fail several times.
                if measurement_fail >= self._consecutive_meas_error:
                    tmp_txt = "Measurement failed after %s times, abort usecase" % \
                        self._consecutive_meas_error
                    self._logger.error(tmp_txt)
                    # leave here ,this is not used to generate this test verdict
                    # so not error raised
                    return
            finally:
                # Store various information
                self.__em_meas_tab.add_measurement([self.get_time_tuple(),
                                                  (self._em_cst.COMMENTS,
                                                   "RUNTEST : Discharge without data cable with load : %s" % text)])
                # switch meas to next meas
                self.__em_meas_tab.switch_to_next_meas()
        return result
Exemplo n.º 23
0
class LabEmBattBenchCycle2g(EmUsecaseBase):

    """
    Lab Energy Management base class.
    """
    DEDICATED_BENCH = "BATTERY_BENCH"

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # Read BATT_MIN_CAPACITY from test case xml file
        self.em_core_module.init_fg_param()
        #-----------------------------------------------------------------------
        # Read Band from test case xml file (str)
        self.__cell_band = str(self._tc_parameters.get_param_value("CELL_BAND"))
        # Read CELL_SERVICE from test case xml file
        self.__cell_service = str(self._tc_parameters.get_param_value("CELL_SERVICE"))
        # Read TCH_ARFCN from test case xml file
        self.__tch_arfcn = int(self._tc_parameters.get_param_value("TCH_ARFCN"))
        # Read UPLINK_CHANNEL from test case xml file
        self.__uplink_channel = int(self._tc_parameters.get_param_value("UPLINK_CHANNEL"))
        # Read CELL_POWER from test case xml file
        self.__cell_power = int(self._tc_parameters.get_param_value("CELL_POWER"))
        # Read CALL_ORIGIN from test case xml file
        self.__call_origin = str(self._tc_parameters.get_param_value("CALL_ORIGIN")).upper()
        # Read DATA_CALL_MODE from test case xml file
        self.__data_call_mode = str(self._tc_parameters.get_param_value("DATA_CALL_MODE"))
        # Read registrationTimeout from Phone_Catalog.xml
        self._registration_timeout = \
            int(self._dut_config.get("registrationTimeout"))

        # Create cellular network simulator and retrieve 2G APIs
        self.__ns = self._em.get_cellular_network_simulator("NETWORK_SIMULATOR1")
        self.__ns_2g = self.__ns.get_cell_2g()
        self.__data_2g = self.__ns_2g.get_data()
        #-----------------------------------------------------------------------

        # Initialize EM  xml object
        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
        # enable Global Measurement file
        name = os.path.join(self._campaign_folder,
                            self._em_cst.GLOBAL_MEAS_FILE)
        self.__em_meas_tab.enable_global_meas(name, self._name)
        # enable OCV computing
        # get OCV target file
        target = self.em_core_module.ocv_target_file.parse_em_ocv_targets(
            self._device.get_phone_model(), self._tct)
        self.__ocv_tool = OcvComputingTool(target)

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

    def set_up(self):
        """
        Initialize the test
        """
        # Call the UseCaseBase Setup function
        EmUsecaseBase.set_up(self)

        if self.__call_origin not in ["SIMULATOR", "PHONE"]:
            tmp_txt = "invalid CALL_ORIGIN parameter value : %s " % \
                      self.__call_origin
            self._logger.error(tmp_txt)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, tmp_txt)

        # set usb charging on
        self.em_api.set_usb_charging("on")

        # Configure CMU
        # Connect to cellular network simulator
        self.__ns.init()
        # Perform Full Preset
        self.__ns.perform_full_preset()
        # Set cell band using CELL_BAND parameter
        self.__ns_2g.set_band(self.__cell_band)
        # Set cell off
        self.__ns_2g.set_cell_off()
        # Set cell service using CELL_SERVICE parameter
        self.__ns_2g.set_cell_service(self.__cell_service)
        # Set Traffic Channel Arfcn using TCH_ARFCN parameter
        self.__ns_2g.set_tch_arfcn(self.__tch_arfcn)
        # Set cell power using CELL_POWER parameter
        self.__ns_2g.set_cell_power(self.__cell_power)
        # set data uplink channel
        self.__data_2g.set_data_channel(self.__uplink_channel)
        # configure cellular network burst slots
        slots_conf = self.em_core_module.configure_slot()

        # Set main timeslot to 3 and set slot configs
        self.__data_2g.set_custom_multislot_config(
            3, slots_conf["DL_STATE"],
            slots_conf["DL_VALUE"],
            slots_conf["UL_STATE"],
            slots_conf["UL_VALUE"])

        # get capability targets
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_BATT_BENCH_CYCLE_2G", self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())

        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets)

        # init verdict value
        msic = self.update_battery_info()

        if self._em_targets["MSIC_REGISTER_CHARGE.BATTERY.CHARGE_NOW"] is not None:
            update_conf(self._em_targets["MSIC_REGISTER_CHARGE.BATTERY.CHARGE_NOW"],
                        "hi_lim", msic["BATTERY"]["CHARGE_FULL"][0], "=")
        # setting to be dne only if chamber is here and used
        if self.tc_module is not None:
            if self._em_targets["THERMAL_MSIC_REGISTER_CHARGE.BATTERY.TEMP"] is not None:
                update_conf(self._em_targets["THERMAL_MSIC_REGISTER_CHARGE.BATTERY.TEMP"],
                            ["lo_lim", "hi_lim"], self._tct, "*")
            if self._em_targets["THERMAL_MSIC_REGISTER_DISCHARGE.BATTERY.TEMP"] is not None:
                update_conf(self._em_targets["THERMAL_MSIC_REGISTER_DISCHARGE.BATTERY.TEMP"],
                            ["lo_lim", "hi_lim"], self._tct, "*")

        # Charge battery
        if (self.em_core_module.batt_start_capacity != "FULL" and str(self.em_core_module.batt_start_capacity).isdigit() and
           self.batt_capacity > int(self.em_core_module.batt_start_capacity)):
            self.em_core_module.monitor_discharging(self.em_core_module.batt_start_capacity, self.em_core_module.discharge_time,
                                     self.__em_meas_tab)
        else:
            self.em_core_module.monitor_charging(self.em_core_module.batt_start_capacity,
                                  self.em_core_module.charge_time,
                                  self.__em_meas_tab)

        return Global.SUCCESS, "No errors"

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

    def run_test_body(self):
        EmUsecaseBase.run_test_body(self)

        # charge board
        self.__charge_phase_mos()

        # setting for discharge loop
        # set CMU cell phone ON
        self.__data_2g.set_data_cell_on()
        # register phone
        self.__data_2g.data_register_dut(None,
                                         self._registration_timeout)
        # Check registration status on DUT
        self.modem_api.check_cdk_registration_bfor_timeout(
            self._registration_timeout)
        # establish call
        if self.__call_origin == "SIMULATOR":
            self.__data_2g.data_call(self.__data_call_mode)
            self.__data_2g.check_data_call_connected(60)
        elif self.__call_origin == "PHONE":
            self.voicecall_api.dial("OOOO12121121")

        # discharge the board
        self.__discharge_phase()

        return(self._em_meas_verdict.get_global_result(),
               self._em_meas_verdict.generate_msg_verdict())

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

    def tear_down(self):
        """
        End and dispose the test
        """
        # call tear down after some operations
        EmUsecaseBase.tear_down(self)

        # clean the measurement file from last ocv computing
        self.__em_meas_tab.remove_meas(
            self.__ocv_tool.get_constant_list())
        # compute ocv and store it in measurement file
        result = self.__ocv_tool.compute_as_meas()
        map(self.__em_meas_tab.add_computed_meas, result)  # pylint: disable=W0141
        # retrieve measurement from test
        self.__em_meas_tab.generate_global_file()
        # as measurement is kept over B2B iteration,
        # just reset global file to its init state
        self.__em_meas_tab.reset_global_file()

        # set CMU cell phone OFF
        if self.__data_2g is not None:
            self.__data_2g.set_data_cell_off()
            # Disconnect from the equipment (Network simulator)
            self.__ns.release()

        if self.is_board_and_acs_ok():
            self.em_api.set_usb_charging("on")

        # clean the board state and retrieve logs
        self.em_core_module.clean_up()

        if self.is_board_and_acs_ok():
            self.phonesystem_api.set_screen_timeout(30)
            self.phonesystem_api.clean_daemon_files()

        return Global.SUCCESS, "No errors"

# private-----------------------------------------------------------------------------

    def __charge_phase_mos(self):
        """
        Charge the board with a dcp, screen off
        """
        # start charging through usb
        self.em_api.set_usb_charging("on")
        # init capacity
        msic = self.update_battery_info()
        battery_status = msic["BATTERY"]["STATUS"][0].upper()

        # set a fake value to capacity if status full is wanted
        max_capacity = 10000
        good_text = "FULL"
        if self.em_core_module.batt_max_capacity.isdigit():
            max_capacity = int(self.em_core_module.batt_max_capacity)
            good_text = str(max_capacity) + "%"

        measurement_fail = 0
        # Charge battery, if board is already full then leave
        if (self.em_core_module.batt_max_capacity == "FULL" and battery_status != self.em_core_module.batt_max_capacity) or\
                (self.em_core_module.batt_max_capacity != "FULL" and self.batt_capacity < max_capacity) or battery_status != "FULL":
            self._logger.info("Start to charge battery until %s before %s seconds" %
                              (good_text,
                               self.em_core_module.charging_time_limit))

            keep_looping = True
            msic_charge_time = abs(self.em_core_module.charge_time - 10)
            local_start_time = time.time()
            while keep_looping:
                # charge board
                try:
                    # start scheduled operation and get result
                    # first num is the time to wait before reaching dcp plug state
                    task_id = self.em_api.poll_multi_msic_registers(30, msic_charge_time, 10)
                    self.em_core_module.charge_battery(self.em_core_module.charge_time)
                    msic_list = self.em_api.get_multi_msic_registers(task_id)

                    # get the highest logs length
                    for msic_dict in msic_list:
                        try:
                            # get battery/charger info
                            if len(msic_dict) > 1:
                                msic_batt = msic_dict["BATTERY"]
                                self.batt_capacity = msic_batt["CAPACITY"][0]
                                self.batt_voltage = msic_batt["VOLTAGE"][0]
                                battery_status = msic_batt["STATUS"][0].upper()
                                # store result on xml
                                self.__em_meas_tab.add_dict_measurement(msic_dict)
                                # get ocv limit
                                ocv_lo_lim, ocv_hi_lim = self.__ocv_tool.get_ocv_limit(self.batt_capacity)
                                self.__em_meas_tab.add_measurement(
                                    [(self._em_cst.OCV_NOW_LOW_LIM, ocv_lo_lim, self.__ocv_tool.UNIT),
                                     (self._em_cst.OCV_NOW_HIGH_LIM, ocv_hi_lim, self.__ocv_tool.UNIT)])
                                # compute battery capacity error
                                battery_capacity_err = (float(msic_batt["CHARGE_NOW"][0]) /
                                                        float(msic_batt["CHARGE_FULL"][0])) * 100 - self.batt_capacity
                                # store verdict
                                self._meas_list.add("BATTERY_CAPACITY_CHARGE_ERR",
                                                    (battery_capacity_err, "none"))
                                self._meas_list.add_dict("MSIC_REGISTER_CHARGE", msic_dict)
                                if self.tc_module is not None:
                                    self._meas_list.add_dict("THERMAL_MSIC_REGISTER_CHARGE", msic_dict)

                        finally:
                            # Store various information
                            self.__em_meas_tab.add_measurement(
                                [self.get_time_tuple(),
                                 (self._em_cst.COMMENTS, "RUNTEST: Charging phase"),
                                 (self._em_cst.REBOOT, self.phone_as_reboot)])

                            if self.tc_module is not None:
                                self.__em_meas_tab.add_measurement(
                                    [self.tc_module.feed_meas_report()])

                            # reinitialize reboot variable
                            self.phone_as_reboot = False

                            # switch meas to next meas
                            self.__em_meas_tab.switch_to_next_meas()
                            # exit if condition are respected else apply verdict
                            if (self.em_core_module.batt_max_capacity == "FULL" and battery_status == self.em_core_module.batt_max_capacity) or\
                                    (self.em_core_module.batt_max_capacity != "FULL" and self.batt_capacity >= max_capacity) or battery_status == "FULL":
                                keep_looping = False
                            else:
                                # apply verdict
                                self._em_meas_verdict.compare_list(self._meas_list, self._em_targets, True)
                                self._em_meas_verdict.judge(ignore_blocked_tc=True)

                    # reset error
                    measurement_fail = 0
                except AcsBaseException as e:
                    # try to reconnect to the board if uecmd failed
                    self._logger.error("fail to get measurement: " + str(e))
                    measurement_fail += 1
                    # stop the usecase if measurement fail several times.
                    if measurement_fail >= self._consecutive_meas_error:
                        tmp_txt = "Measurement failed after %s times, abort usecase" % \
                            self._consecutive_meas_error
                        self._logger.error(tmp_txt)
                        raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt)

                    # check the board connection
                    self.em_core_module.check_board_connection(tries=1, use_exception=False)

                # stop usecase if board take too long to reach battery max capacity
                if (time.time() - local_start_time) > self.em_core_module.charging_time_limit:
                    tmp_txt = "Phone failed to reach %s before %s seconds" % \
                        (good_text, self.em_core_module.charging_time_limit)
                    self._logger.error(tmp_txt)
                    raise DeviceException(DeviceException.TIMEOUT_REACHED, tmp_txt)

            # stop all daemonized ACS process & clean measurement done
            self._meas_list.clean()
            self.phonesystem_api.clean_daemon_files()

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

    def __discharge_phase(self):
        """
        discharge the board with a 2G call
        """
        measurement_fail = 0
        # re update target with last charge full value
        msic = self.em_api.get_msic_registers()
        if self._em_targets["MSIC_REGISTER_DISCHARGE.BATTERY.CHARGE_NOW"] is not None:
            update_conf(self._em_targets["MSIC_REGISTER_DISCHARGE.BATTERY.CHARGE_NOW"],
                        "hi_lim", msic["BATTERY"]["CHARGE_FULL"][0], "=")

        # discharge loop -----------------------------------------------------------------------------------
        msic_reg = self.update_battery_info()

        if self.batt_capacity > self.em_core_module.batt_min_capacity:
            # stop charging through usb
            self.em_api.set_usb_charging("off")
            # launch uecmd to help the discharge
            self.phonesystem_api.set_screen_timeout(3600)
            # deactivate set auto brightness
            self.phonesystem_api.set_brightness_mode("manual")
            # set display brightness to max value
            self.phonesystem_api.set_display_brightness(100)
            self.phonesystem_api.set_phone_lock(0)
            # reinitialize consecutive error
            self.phone_as_reboot = False

            good_text = "DEAD"
            if self.em_core_module.batt_min_capacity > -1:
                good_text = str(self.em_core_module.batt_min_capacity) + "%"

            # reset consecutive error
            measurement_fail = 0
            self.phone_as_reboot = False
            self._logger.info("Start to discharge battery until %s" % good_text)
            local_start_time = time.time()
            while self.batt_capacity > self.em_core_module.batt_min_capacity:
                try:
                    # try to read measurement
                    # get msic registers value after booting
                    msic_reg = self.update_battery_info()
                    self._meas_list.add_dict("MSIC_REGISTER_DISCHARGE", msic_reg)
                    msic_batt = msic_reg["BATTERY"]
                    self.__em_meas_tab.add_dict_measurement(msic_reg)
                    # get ocv and soc information
                    ocv_pass = self.__ocv_tool.add(self.batt_capacity,
                                                   self.batt_voltage)
                    # get ocv limit
                    ocv_lo_lim, ocv_hi_lim = self.__ocv_tool.get_ocv_limit(self.batt_capacity)
                    self.__em_meas_tab.add_measurement(
                        [(self._em_cst.OCV_NOW_LOW_LIM, ocv_lo_lim, self.__ocv_tool.UNIT),
                         (self._em_cst.OCV_NOW_HIGH_LIM, ocv_hi_lim, self.__ocv_tool.UNIT),
                         (self._em_cst.OCV_NOW_LIM_VERDICT, ocv_pass)])

                    # compute battery capacity error
                    battery_capacity_err = (float(msic_batt["CHARGE_NOW"][0]) /
                                            float(msic_batt["CHARGE_FULL"][0])) * 100 - self.batt_capacity
                    self._meas_list.add("BATTERY_CAPACITY_DISCHARGE_ERR",
                                        (battery_capacity_err, "none"))

                    # check thermal capabilities only if thermal chamber is used
                    if self.tc_module is not None:
                        # Store various information
                        self._meas_list.add_dict("THERMAL_MSIC_REGISTER_DISCHARGE", msic_reg)

                    # get the call state------------------------------------------------------------------------
                    call_state = self.__cell_service
                    if self.__call_origin == "SIMULATOR":
                        # Check data call state
                        try:
                            self.__data_2g.check_data_call_connected(10)
                            call_state += "_DATA_CALL_CONNECTED"
                        except TestEquipmentException as error:
                            self._logger.error(error)
                            call_state += "_DATA_CALL_DISCONNECTED"
                            self.__data_2g.data_call(self.__data_call_mode)
                    elif self.__call_origin == "PHONE":
                        # Check cs call state
                        call_state_tmp = self.voicecall_api.get_state()
                        call_state += "_CALL_" + str(call_state_tmp)
                        # pylint: disable=E1101
                        if call_state_tmp == VOICE_CALL_STATE.NOCALL:
                            self.voicecall_api.dial("OOOO12121121")

                    # Store various information
                    self.__em_meas_tab.add_measurement(
                        [("REGISTRATION", self.modem_api.get_network_registration_status()),
                         ("VOICE_CALL_" + self.__call_origin, call_state)])
                    #------------------------------------------------------------------------
                    # stop charging through usb
                    self.em_api.set_usb_charging("off")
                    # reset consecutive fail
                    measurement_fail = 0

                except AcsBaseException as e:
                    # try to reconnect to the board if uecmd failed
                    self._logger.error("fail to get measurement: %s" % str(e))
                    measurement_fail += 1

                    # stop the usecase if measurement fail several times.
                    if measurement_fail >= self._consecutive_meas_error:
                        if self.batt_voltage > self.vbatt_mos_shutdown or \
                                self.batt_voltage == -1:
                            tmp_txt = "Measurement failed after %s times, stop usecase" % \
                                self._consecutive_meas_error
                            self._logger.error(tmp_txt)
                            raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt)
                        else:
                            self._logger.info("battery must be empty, stop discharging")
                            break
                    elif self._device.get_boot_mode() == "COS" and self.em_core_module.batt_min_capacity < 0:
                        self._logger.info("board booted in COS, stop discharging")
                        break
                    # check the board connection
                    self.em_core_module.check_board_connection(1, use_exception=False)
                finally:
                    # Store various information
                    if self.tc_module is not None:
                        self.__em_meas_tab.add_measurement(
                            [self.tc_module.feed_meas_report()])

                    self.__em_meas_tab.add_measurement(
                        [self.get_time_tuple(),
                         (self._em_cst.COMMENTS, "RUNTEST:discharge phase test with 2G call "),
                         (self._em_cst.REBOOT, self.phone_as_reboot)])

                    # generate em verdict
                    self._em_meas_verdict.compare_list(self._meas_list, self._em_targets, True)
                    self._em_meas_verdict.judge(ignore_blocked_tc=True)

                    # switch to next meas
                    self.__em_meas_tab.switch_to_next_meas()

                # stop usecase if board take too long to reach battery min capacity
                if (time.time() - local_start_time) > self.em_core_module.charging_time_limit:
                    tmp_txt = "Phone failed to discharge to %s before %s seconds" % \
                        (good_text, self.em_core_module.charging_time_limit)
                    self._logger.error(tmp_txt)
                    raise DeviceException(DeviceException.TIMEOUT_REACHED, tmp_txt)

                # restart uecmd if board have shutdown
                if self.has_board_reboot():
                    # stop charging through usb
                    self.em_api.set_usb_charging("off")
                    # establish a call
                    if self.__call_origin == "SIMULATOR":
                        try:
                            self.__data_2g.data_call(self.__data_call_mode)
                            self.__data_2g.check_data_call_connected(10)
                        except TestEquipmentException as error:
                            self._logger.error(error)
                    elif self.__call_origin == "PHONE":
                        self.voicecall_api.dial("OOOO12121121")

                    self.phone_as_reboot = False

            # when leaving this function stop multimedia and restart charging
            if self.is_board_and_acs_ok():
                self.em_api.set_usb_charging("on")
class LabEmBattFullIdentification(EmUsecaseBase):
    """
    Lab Energy Management class.
    """
    DEDICATED_BENCH = "BATTERY_BENCH"
    __ACTION = [
        "CAPACITY_JUMP_NEAR_FULL", "CAPACITY_AT_WHICH_FIRST_FULL_APPEAR",
        "TIME_TO_CHARGE_TO_FULL_FROM_START_CAPACITY",
        "TIME_TO_SEE_FULL_AT_MAX_CAPACITY", "CHARGE_STOP_ONCE_FULL"
    ]

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

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

        # init fuel gauging parameters
        self.em_core_module.init_fg_param()
        # Type of the charger
        self.__charger_type = self._tc_parameters.get_param_value(
            "CHARGER_TYPE")
        self.__load = self._tc_parameters.get_param_value(
            "LOAD_TO_HELP_DISCHARGE_IN_SETUP")
        # charge to Full Timeout
        self.__charge_full_timeout = self._tc_parameters.get_param_value(
            "CHARGE_TO_FULL_DURATION", default_cast_type=int)
        # capacity that match with first full
        self.__first_full_capacity = self._tc_parameters.get_param_value(
            "CAPACITY_AT_WHICH_FULL_FIRST_APPEAR", 100, default_cast_type=int)
        self.__what_to_check = str(
            self._tc_parameters.get_param_value("WHAT_TO_CHECK")).upper()

        # Summarize the parameters
        self._logger.info("Charger type to plug during FULL charging: %s" %
                          self.__charger_type)
        self._logger.info("Capacity at which FULL shall first appear: %d" %
                          self.__first_full_capacity)
        self._logger.info("Test expected start capacity : %s" %
                          self.em_core_module.batt_start_capacity)

        # Load Module Initialization
        self.__load_module = LoadModule()
        self.__load_module.add_load(self.__load)

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_BATT_FULL_IDENTIFICATION",
            self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())

        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets,
                                          consider_all_target=True)

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

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

    def set_up(self):
        """
        Initialize the test
        """
        # Call the UseCaseBase Setup function
        EmUsecaseBase.set_up(self)

        # Check expected result first
        if self.__what_to_check not in self.__ACTION:
            txt = "wrong value for TC parameter WHAT_TO_CHECK %s, can only be %s" % (
                self.__what_to_check, str(self.__ACTION))
            self._logger.error(txt)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, txt)

        # Update Battery Information
        em_info = self.update_battery_info()

        if self.em_core_module.is_batt_capacity_above_target(
                em_info, self.em_core_module.batt_start_capacity):
            # Discharge part
            self.em_core_module.monitor_discharging(
                self.em_core_module.batt_start_capacity,
                self.em_core_module.discharge_time, self.__em_meas_tab,
                self.__load_module)
        elif self.em_core_module.is_batt_capacity_below_target(
                em_info, self.em_core_module.batt_start_capacity):
            # Charge part
            self.em_core_module.monitor_charging(
                self.em_core_module.batt_start_capacity,
                self.em_core_module.charge_time, self.__em_meas_tab)

        return Global.SUCCESS, "No errors"

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

    def run_test_body(self):
        """
        Execute the test
        Check the end of the main battery charge
        """
        # Call LAB_EM_BASE Run function
        EmUsecaseBase.run_test_body(self)

        # first of all charge to full
        em_info_list = self.__charge_without_data()
        start_index = None
        full_seen = False
        index = 0
        # search for the first iteration of the capacity at which full appear
        for em_dico in em_info_list:
            if em_dico["BATTERY"]["CAPACITY"][
                    0] == self.__first_full_capacity and start_index is None:
                start_index = index
            if em_dico["BATTERY"]["STATUS"][0] == "FULL":
                full_seen = True
                break
            index += 1

        # all the test above consider that the FULL status has already been seen
        # else an error is raised here
        if not full_seen:
            txt = "Battery FULL status was not reached after waiting %ss with %s plugged" % (
                self.__charge_full_timeout, self.__charger_type)
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)

        if self.__what_to_check == "CAPACITY_AT_WHICH_FIRST_FULL_APPEAR":
            self.__check_first_full_capacity(em_info_list)
        elif self.__what_to_check == "TIME_TO_SEE_FULL_AT_MAX_CAPACITY":
            self.__check_first_full_timeout(em_info_list, start_index)
        elif self.__what_to_check == "TIME_TO_CHARGE_TO_FULL_FROM_START_CAPACITY":
            self.__check_charge_to_full_timeout(em_info_list)
        elif self.__what_to_check == "CAPACITY_JUMP_NEAR_FULL":
            self.__check_capacity_jump(em_info_list, start_index)
        elif self.__what_to_check == "CHARGE_STOP_ONCE_FULL":
            self.__check_charge_stop(em_info_list)

        # compare values with targets
        self._em_meas_verdict.compare_list(self._meas_list,
                                           self._em_targets,
                                           clean_meas_list=True)
        self._em_meas_verdict.judge()

        return self._em_meas_verdict.get_current_result_v2()

    def tear_down(self):
        """
        End and dispose the test
        """
        # call tear down after some operations
        EmUsecaseBase.tear_down(self)
        # clean the board state and retrieve logs
        self.em_core_module.clean_up()
        self.__load_module.clean()

        return Global.SUCCESS, "No errors"

    def __charge_without_data(self):
        """
        charge without a data cable plug

        :rtype: list
        :return: list of em dictionary
        """
        adjusted_time = 90
        self._logger.info(
            "Trying to charge board from %s%% to FULL during %ss" %
            (self.batt_capacity, self.__charge_full_timeout))
        self.em_api.clean_autolog()
        # choose function to put in logger
        self.em_api.add_fct_to_auto_logger(self.em_api.AUTOLOG_UEVENT,
                                           "sequenced")
        self.em_api.add_fct_to_auto_logger(self.em_api.AUTOLOG_THERMAL,
                                           "sequenced")
        self.em_api.set_autolog_duration(self.__charge_full_timeout)
        # start non persistent autolog with a short period of data polling
        self.em_api.start_auto_logger(30, 10, "sequenced")

        # switch charger
        self._device.disconnect_board()
        # connect WALL Charger
        self._io_card.simulate_insertion(self.__charger_type)
        # wait x min
        self._logger.info("waiting %ss (+ %ss adjusted) to reach FULL status" %
                          (self.__charge_full_timeout, adjusted_time))
        time.sleep(self.__charge_full_timeout + adjusted_time)

        self._io_card.usb_host_pc_connector(True)
        # wait x seconds
        time.sleep(self.usb_sleep)
        # connect board
        self._device.connect_board()
        self.em_api.stop_auto_logger()
        # parse autolog response and reset them
        msic_list = self.em_api.get_autolog_msic_registers()
        thermal_list = self.em_api.get_autolog_thermal_sensor_info()
        self.em_api.clean_autolog()

        # get the highest logs length
        log_length = max(len(thermal_list), len(msic_list))
        em_info_list = []
        for i in range(log_length):

            try:
                # get battery/charger info
                if len(msic_list) > i:
                    msic_dict = msic_list[i]
                    if len(msic_dict) > 1:
                        msic_dict = msic_dict[1]
                        # store result on xml
                        em_info_list.append(msic_dict)
                        self.__em_meas_tab.add_dict_measurement(msic_dict)
                    # get thermal info
                    if len(thermal_list) > i:
                        thermal_dict = thermal_list[i]
                        if len(thermal_dict) > 1:
                            # store result on xml
                            self.__em_meas_tab.add_dict_measurement(
                                thermal_dict[1])

            finally:
                self.__em_meas_tab.add_measurement([
                    self.get_time_tuple(),
                    (self._em_cst.COMMENTS, "RUNTEST:charging board to FULL")
                ])
                # switch meas to next meas
                self.__em_meas_tab.switch_to_next_meas()

        return em_info_list

    def __check_capacity_jump(self, em_info_list, start_index):
        """
        check if there is capacity jump when charging to full
        """
        self._logger.info(
            "Check if capacity jump happen when we are near to FULL ...")
        # Check if start index is superior than 0 , else we can't evaluate the jump state
        if start_index in [0, None]:
            txt = "Can't compute capacity jump as the first measurement was already at %s%% which is the capacity where battery FULL should firstly appear" % self.__first_full_capacity
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)

        end_capacity = em_info_list[start_index]["BATTERY"]["CAPACITY"][0]
        start_capacity = em_info_list[start_index -
                                      1]["BATTERY"]["CAPACITY"][0]
        measured_jump = end_capacity - start_capacity

        self._meas_list.add("CAPACITY_JUMP_AT_MAX_CAPACITY", measured_jump,
                            "none")

    def __check_charge_to_full_timeout(self, em_info_list):
        """
        Check the time it takes to see status FULL from start capacity
        """
        self._logger.info(
            "Check the time it takes to see status FULL from the start capacity at %s%%"
            % self.em_core_module.batt_start_capacity)
        stop_time = None
        start_time = em_info_list[0]["TIME_STAMP"][0]
        start_time = time.mktime(time.strptime(start_time,
                                               "%Y-%m-%d_%Hh%M.%S"))

        # search for the FULL
        for em_dico in em_info_list:
            if em_dico["BATTERY"]["STATUS"][0] == "FULL":
                stop_time = em_dico["TIME_STAMP"][0]
                stop_time = time.mktime(
                    time.strptime(stop_time, "%Y-%m-%d_%Hh%M.%S"))
                break

        # raise error if full is not seen
        if stop_time is None:
            txt = "Battery FULL status was never seen"
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)

        self._meas_list.add("TIME_TO_CHARGE_TO_FULL", stop_time - start_time,
                            "second")

    def __check_first_full_capacity(self, em_info_list):
        """
        check that the first full seen appear at the right capacity
        """
        self._logger.info(
            "check that the first FULL seen appear at the right capacity")
        full_capacity = None
        for em_dico in em_info_list:
            if em_dico["BATTERY"]["STATUS"][0] == "FULL":
                full_capacity = em_dico["BATTERY"]["CAPACITY"][0]
                break

        if full_capacity != self.__first_full_capacity:
            txt = "Battery FULL status was seen at %s%% of capacity instead of expecting %s%%" % (
                full_capacity, self.__first_full_capacity)
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)

        self._meas_list.add("CAPACITY_AT_WHICH_FIRST_FULL_APPEAR",
                            full_capacity, "none")

    def __check_first_full_timeout(self, em_info_list, start_index):
        """
        Check the time it takes to see status FULL once max capacity is seen
        """
        self._logger.info(
            "Check the time it takes to see status FULL from the first %s%% of capacity seen ..."
            % self.__first_full_capacity)

        if start_index is None:
            txt = "Can't compute the time it takes to see FULL status once %s%% capacity is reached: this capacity was never reached" % self.__first_full_capacity
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)

        stop_time = None
        stop_capacity = None
        start_time = em_info_list[start_index]["TIME_STAMP"][0]
        start_time = time.mktime(time.strptime(start_time,
                                               "%Y-%m-%d_%Hh%M.%S"))

        # search for the FULL
        for em_dico in em_info_list:
            if em_dico["BATTERY"]["STATUS"][0] == "FULL":
                stop_time = em_dico["TIME_STAMP"][0]
                stop_time = time.mktime(
                    time.strptime(stop_time, "%Y-%m-%d_%Hh%M.%S"))
                stop_capacity = em_dico["BATTERY"]["CAPACITY"][0]
                break

        # raise error if full is not seen
        if stop_capacity is not None and stop_capacity != self.__first_full_capacity:
            txt = "Battery FULL status was seen at %s%% of capacity instead of expecting %s%%" % (
                stop_capacity, self.__first_full_capacity)
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)

        self._meas_list.add("TIME_TO_SEE_FULL_AT_MAX_CAPACITY",
                            stop_time - start_time, "second")

    def __check_charge_stop(self, em_info_list):
        """
        Check that the charge stop once FULL is reached
        """
        self._logger.info("Check that the charge stop once FULL is reached")
        result = False
        # search for the FULL
        for em_dico in em_info_list:
            if em_dico["BATTERY"]["STATUS"][0] == "FULL" and em_dico[
                    "CHARGER"]["ENABLE_CHARGING"][0] == 0:
                self._meas_list.add_dict("EM_INFO", em_dico)
                result = True
                break

        if not result:
            txt = "The charge did not stop after battery FULL reached"
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)
class LabEmTestChargingBattTemp(EmUsecaseBase):
    """
    Lab Energy Management class.
    """
    DEDICATED_BENCH = "BATTERY_BENCH"
    __ACTION = {
        "CHARGE_RESUME": {
            "START": "OVERHEAT",
            "STOP": "GOOD"
        },
        "CHARGE_STOP": {
            "START": "GOOD",
            "STOP": "OVERHEAT"
        }
    }

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

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

        # init fuel gauging parameters
        self.em_core_module.init_fg_param()

        # High load
        load = self._tc_parameters.get_param_value("SETUP_LOAD")
        self.__charger_type = self._tc_parameters.get_param_value(
            "CHARGER_TYPE")
        self.__timeout_dut_adjust_stop_temp = self._tc_parameters.get_param_value(
            "TIME_TO_ADJUST_TO_STOP_TEMPERATURE", default_cast_type=int)
        self.__timeout_dut_adapt_start_temp = self._tc_parameters.get_param_value(
            "TIME_TO_ADJUST_TO_START_TEMPERATURE", 3600, default_cast_type=int)

        # Read TEMPERATURE from test case xml file
        self.tc_module = None
        self.__start_max_temperature = self._tc_parameters.get_param_value(
            "START_MAX_TEMPERATURE")
        self.__start_min_temperature = self._tc_parameters.get_param_value(
            "START_MIN_TEMPERATURE")
        self.__stop_temp = self._tc_parameters.get_param_value(
            "STOP_TEMPERATURE")
        self.__action_to_peform = str(
            self._tc_parameters.get_param_value("WHAT_TO_CHECK")).upper()
        # ROOM is only for debug purpose
        if "ROOM" not in [
                self.__stop_temp, self.__start_max_temperature,
                self.__start_min_temperature
        ]:
            self.__start_max_temperature = int(self.__start_max_temperature)
            self.__start_min_temperature = int(self.__start_min_temperature)
            # get temperature chamber equipment if not room temperature
            self.__stop_temp = int(self.__stop_temp)
            self.tc_module = ThermalChamberModule(self._ambient_temperature)
            # inform module that this is not a default thermal test
            self.__start_temperature = int(
                (self.__start_min_temperature + self.__start_max_temperature) /
                2)
            self.tc_module.set_test_type("SPECIFIC")
        else:
            self.__start_temperature = "ROOM"

        # Summarize the parameters
        self._logger.info("Type of the charger: %s" % self.__charger_type)
        self._logger.info("Test start MAX temperature: %s" %
                          self.__start_max_temperature)
        self._logger.info("Test start MIN temperature: %s" %
                          self.__start_min_temperature)
        self._logger.info("Test stop temperature: %s" % self.__stop_temp)
        self._logger.info("What we want to check: %s" %
                          self.__action_to_peform)
        self._logger.info(
            "Time to see change on DUT behavior at tested temperature: %s" %
            self.__timeout_dut_adjust_stop_temp)

        # Load Module Initialization
        self.__load_module = LoadModule()
        self.__load_module.add_load(load)

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_TEST_CHARGING_BATT_TEMP",
            self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())
        # get target and initialize measurement
        self._em_meas_verdict.load_target(self._em_targets, self.tcd_to_test)

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
        self.__charger_is_data_cable = None

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

    def set_up(self):
        """
        Initialize the test
        """
        # Call the UseCaseBase Setup function
        EmUsecaseBase.set_up(self)
        # Check specific option if they are chosen
        if self.__charger_type not in self._io_card.SUPPORTED_DEVICE_TYPE:
            txt = "io card does not support charger type %s " % self.__charger_type
            self._logger.error(txt)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, txt)

        # Update Battery Information
        em_info = self.update_battery_info()
        if self.em_core_module.is_batt_capacity_above_target(
                em_info, self.em_core_module.batt_max_capacity):

            # Discharge if we are too high
            self.em_core_module.monitor_discharging(
                self.em_core_module.batt_max_capacity,
                self.em_core_module.discharge_time, self.__em_meas_tab,
                self.__load_module)

        if self.tc_module is not None:
            self.tc_module.set_up_eq()
            self.tc_module.get_eq().set_regulation(True)
            self.tc_module.get_eq().set_temperature(self.__start_temperature)

        # set the temperature
        self.em_api.set_thermal_management(False)
        # a reboot is required to apply this change
        self._device.reboot()
        self.phonesystem_api.set_screen_timeout(3600)

        # do this job one time in case of B2B
        if self.__charger_is_data_cable is None:
            self.__charger_is_data_cable = self.em_core_module.is_host_connection_available_when_charger_plug(
                self.__charger_type, True)
            self._logger.info("test sequences will adjust to this")

        # wait that the board see the test temperature
        remaining_time = time.time()
        self.em_core_module.adjust_batt_temp(
            self.__start_min_temperature, self.__start_max_temperature,
            self.__timeout_dut_adapt_start_temp, self.tc_module,
            self.__em_meas_tab)

        remaining_time = max(
            self.__timeout_dut_adapt_start_temp -
            (time.time() - remaining_time), 120)
        self.__track_battery_health_change(remaining_time)

        return Global.SUCCESS, "No errors"

    def __track_battery_health_change(self, test_timeout):
        """
        track a battery health change
        """
        exceed_timeout = True
        timeout = time.time() + test_timeout
        crash__alowed = 3
        while time.time() < timeout:
            try:
                # try to read measurement
                msic_reg = self.update_battery_info()
                thermal_conf = self.em_api.get_thermal_sensor_info()
                # store result on xml
                self.__em_meas_tab.add_dict_measurement(msic_reg)
                self.__em_meas_tab.add_dict_measurement(thermal_conf)
                # temporary workaround to detect the end condition
                batt_health = str(msic_reg["BATTERY"]["HEALTH"][0]).upper()
                if self.__ACTION[
                        self.__action_to_peform]["START"] == batt_health:
                    exceed_timeout = False
                    break

            except AcsBaseException as e:
                crash__alowed -= 1
                # try to catch why uecmd may fail
                if not self.is_board_and_acs_ok():
                    txt = "connection with DUT lost during change waiting on DUT battery health"
                else:
                    txt = "error happened during change waiting on DUT on DUT battery health: " + str(
                        e)
                self._logger.error(txt)
                if crash__alowed <= 0:
                    raise DeviceException(DeviceException.OPERATION_FAILED,
                                          txt)
            finally:
                # Store various information
                self.__em_meas_tab.add_measurement([
                    self.get_time_tuple(),
                    (self._em_cst.COMMENTS,
                     "SETUP:Waiting for the DUT to modify its battery health inside [%s;%s] degree celsius"
                     % (self.__start_min_temperature,
                        self.__start_max_temperature))
                ])
                # switch meas to next meas
                self.__em_meas_tab.switch_to_next_meas()
                # exist if we see the expected battery health

        if exceed_timeout:
            txt = "timeout exceeded (%ss) to see a change on battery health inside [%s,%s] degree celsius" % (
                str(test_timeout), self.__start_min_temperature,
                self.__start_max_temperature)

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

    def run_test_body(self):
        """
        Execute the test
        """
        # Call LAB_EM_BASE Run function
        EmUsecaseBase.run_test_body(self)

        if self.__charger_is_data_cable:
            self.__test_with_data(self.__stop_temp)
        else:
            self.__test_without_data(self.__stop_temp)

        # value comparing are done in private function
        self._em_meas_verdict.judge()

        return self._em_meas_verdict.get_current_result_v2()

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

    def tear_down(self):
        """
        End and dispose the test
        """
        # call tear down after some operations
        EmUsecaseBase.tear_down(self)
        if self.tc_module is not None:
            # Go to the ambient temperature
            self.tc_module.release_eq()

        # clean the board state and retrieve logs
        self.em_core_module.clean_up()

        # restore thermal management setting
        self.em_api.set_thermal_management(True)
        # a reboot is required to apply this change
        self._device.reboot()
        return Global.SUCCESS, "No errors"

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

    def __test_with_data(self, temperature):
        """
        test charging resume or stop while a data cable is plugged
        """
        self._logger.info(
            "test if %s when we move from [%s;%s] degree celsius to %s degree celsius with an active data connection"
            % (self.__action_to_peform, self.__start_min_temperature,
               self.__start_max_temperature, self.__stop_temp))
        # when we are here, it means that we are already at START charging temperature condition
        msic_reg = self.update_battery_info()
        self._meas_list.add_dict("EM_INFO_START_TEMP", msic_reg)
        self._em_meas_verdict.compare_list(self._meas_list,
                                           self._em_targets,
                                           clean_meas_list=True)

        # change the test temperature
        if self.tc_module is not None:
            self.tc_module.get_eq().set_temperature(temperature)

        # monitor temp until we are outside the start temp
        test_timeout = self.__timeout_dut_adjust_stop_temp
        last_batt_temp = self.update_battery_info()["BATTERY"]["TEMP"][0]
        if self.__start_min_temperature <= last_batt_temp <= self.__start_max_temperature:
            consumed_time = time.time()
            self._logger.info(
                "check that DUT is moving outside START temperature [%s;%s] degree celsius"
                % (self.__start_min_temperature, self.__start_max_temperature))
            exceed_timeout = True
            timeout = time.time() + test_timeout

            while time.time() < timeout:
                try:
                    # try to read measurement
                    msic_reg = self.update_battery_info()
                    thermal_conf = self.em_api.get_thermal_sensor_info()
                    # store result on xml
                    self.__em_meas_tab.add_dict_measurement(msic_reg)
                    self.__em_meas_tab.add_dict_measurement(thermal_conf)
                    last_batt_temp = msic_reg["BATTERY"]["TEMP"][0]

                except AcsBaseException as e:
                    # try to catch why uecmd may fail
                    if not self.is_board_and_acs_ok():
                        txt = "connection with DUT lost during temperature change to exit range [%s;%s] degree celsius" % (
                            self.__start_min_temperature,
                            self.__start_max_temperature)
                    else:
                        txt = "error happened during temperature change to  exit range [%s;%s] degree celsius : %s" % (
                            self.__start_min_temperature,
                            self.__start_max_temperature, str(e))
                    self._logger.error(txt)
                    raise DeviceException(DeviceException.OPERATION_FAILED,
                                          txt)
                finally:
                    # Store various information
                    self.__em_meas_tab.add_measurement([
                        self.get_time_tuple(),
                        (self._em_cst.COMMENTS,
                         "RUNTEST:Waiting for the DUT to move outside [%s;%s] degree celsius"
                         % (self.__start_min_temperature,
                            self.__start_max_temperature))
                    ])
                    # switch meas to next meas
                    self.__em_meas_tab.switch_to_next_meas()
                # exit if the battery temp match with test temp
                if not (self.__start_min_temperature <= last_batt_temp <=
                        self.__start_max_temperature):
                    self._logger.info(
                        "The DUT has reached %s degree celsius which is outside [%s;%s] !"
                        % (last_batt_temp, self.__start_min_temperature,
                           self.__start_max_temperature))
                    exceed_timeout = False
                    break
            # remove the time spent to track for the change from allowed test duration
            consumed_time = time.time() - consumed_time
            test_timeout = test_timeout - consumed_time
            if exceed_timeout:
                txt = "timeout exceeded (%ss) to move the DUT temperature outside [%s,%s] degree celsius" % (
                    str(self.__timeout_dut_adjust_stop_temp),
                    self.__start_min_temperature, self.__start_max_temperature)
                self._logger.error(txt)
                raise DeviceException(DeviceException.OPERATION_FAILED, txt)

        # once here we wait until a change is seen
        result = False
        exceed_timeout = True
        msic_reg = None
        time_take_to_see_a_change = time.time()
        timeout = time.time() + test_timeout
        while time.time() < timeout and not result:
            try:
                # try to read measurement
                msic_reg = self.update_battery_info()
                thermal_conf = self.em_api.get_thermal_sensor_info()
                # store result on xml
                self.__em_meas_tab.add_dict_measurement(msic_reg)
                self.__em_meas_tab.add_dict_measurement(thermal_conf)
                # temporary workaround to detect the end condition
                batt_health = str(msic_reg["BATTERY"]["HEALTH"][0]).upper()
                if batt_health != self.__ACTION[
                        self.__action_to_peform]["START"]:
                    self._meas_list.add_dict("EM_INFO_STOP_TEMP", msic_reg)
                    if self._em_meas_verdict.test_list(self._meas_list,
                                                       self._em_targets):
                        self._meas_list.add(
                            "TIME_TO_SEE_A_CHANGE",
                            time.time() - time_take_to_see_a_change, "second")
                        self._em_meas_verdict.compare_list(
                            self._meas_list,
                            self._em_targets,
                            clean_meas_list=True)
                        result = True

            except AcsBaseException as e:
                # try to catch why uecmd may fail
                if not self.is_board_and_acs_ok():
                    txt = "connection with DUT lost during change waiting on DUT behavior"
                else:
                    txt = "error happened during change waiting on DUT behavior: " + str(
                        e)
                self._logger.error(txt)
                raise DeviceException(DeviceException.OPERATION_FAILED, txt)
            finally:
                # Store various information
                self.__em_meas_tab.add_measurement([
                    self.get_time_tuple(),
                    (self._em_cst.COMMENTS,
                     "RUNTEST:Waiting for the DUT to modify its behavior outside [%s;%s] degree celsius"
                     % (self.__start_min_temperature,
                        self.__start_max_temperature))
                ])
                # switch meas to next meas
                self.__em_meas_tab.switch_to_next_meas()
                # exist if we see the expected battery health
                if result:
                    exceed_timeout = False
                    break

        if exceed_timeout:
            txt = "timeout exceeded (%ss) to see a change on battery/charger behavior outside [%s,%s] degree celsius" % (
                str(self.__timeout_dut_adjust_stop_temp),
                self.__start_min_temperature, self.__start_max_temperature)
            # take the last em info read
            if msic_reg is not None:
                self._meas_list.add_dict("EM_INFO_STOP_TEMP", msic_reg)
                self._em_meas_verdict.compare_list(self._meas_list,
                                                   self._em_targets,
                                                   clean_meas_list=True)
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)

    def __test_without_data(self, temperature):
        """
        test charging resume or stop while a data cable is not plugged
        """
        self._logger.info(
            "test if %s when we move from [%s;%s] degree celsius to %s degree celsius without an active data connection"
            % (self.__action_to_peform, self.__start_min_temperature,
               self.__start_max_temperature, self.__stop_temp))
        self.em_api.clean_autolog()
        # choose function to put in logger
        self.em_api.add_fct_to_auto_logger(self.em_api.AUTOLOG_UEVENT,
                                           "sequenced")
        self.em_api.add_fct_to_auto_logger(self.em_api.AUTOLOG_THERMAL,
                                           "sequenced")
        self.em_api.set_autolog_duration(self.__timeout_dut_adjust_stop_temp)
        # start  non persistent autolog with a short period of data polling
        self.em_api.start_auto_logger(30, 10, "sequenced")

        # switch charger
        self._device.disconnect_board()
        self._io_card.simulate_insertion(self.__charger_type)
        self._logger.info(
            "wait 60s to capture the first em info at START temperature")
        time.sleep(60)
        # remove the time spent in adjusting the temperature chamber and wait what it left
        remaning_time = time.time()
        self.tc_module.get_eq().set_temperature(temperature)
        self.tc_module.get_eq().wait_for_temperature(temperature)
        remaning_time = time.time() - remaning_time
        remaning_time = self.__timeout_dut_adjust_stop_temp + 60 - remaning_time

        if remaning_time > 0:
            self._logger.info("wait %ss to see any change on DUT behavior" %
                              str(remaning_time))
            time.sleep(self.__timeout_dut_adjust_stop_temp + 60)

        self._io_card.usb_host_pc_connector(True)
        # wait x seconds
        time.sleep(self.usb_sleep)
        # connect board
        self._device.connect_board()
        self.em_api.stop_auto_logger()
        # parse autolog response and reset them
        msic_list = self.em_api.get_autolog_msic_registers()
        thermal_list = self.em_api.get_autolog_thermal_sensor_info()
        self.em_api.clean_autolog()

        log_length = len(msic_list)
        start_time = None
        stop_time = None
        battery_health_change = False
        for i in range(log_length):

            try:
                # get battery/charger info
                if len(msic_list) > i:
                    msic_dict = msic_list[i]
                    if len(msic_dict) > 1:
                        msic_dict = msic_dict[1]
                        # first track when we are outside the range
                        if start_time is None:
                            batt_temp = msic_dict["BATTERY"]["TEMP"][0]
                            if not (self.__start_min_temperature <= batt_temp
                                    <= self.__start_max_temperature):
                                start_time = msic_dict["TIME_STAMP"][0]
                                start_time = time.mktime(
                                    time.strptime(start_time,
                                                  "%Y-%m-%d_%Hh%M.%S"))

                        # else track when we notice a change on battery health
                        elif stop_time is None:
                            if msic_dict["BATTERY"]["HEALTH"][0].upper(
                            ) != self.__ACTION[
                                    self.__action_to_peform]["START"]:
                                battery_health_change = True
                                self._meas_list.add_dict(
                                    "EM_INFO_STOP_TEMP", msic_dict)
                                # test if the verdict comparison is true
                                if self._em_meas_verdict.test_list(
                                        self._meas_list, self._em_targets):
                                    self._em_meas_verdict.compare_list(
                                        self._meas_list,
                                        self._em_targets,
                                        clean_meas_list=True)
                                    stop_time = msic_dict["TIME_STAMP"][0]
                                    stop_time = time.mktime(
                                        time.strptime(stop_time,
                                                      "%Y-%m-%d_%Hh%M.%S"))
                                    stop_time -= start_time

                        # store result on xml
                        self.__em_meas_tab.add_dict_measurement(msic_dict)
                    # get thermal info
                    if len(thermal_list) > i:
                        thermal_dict = thermal_list[i]
                        if len(thermal_dict) > 1:
                            # store result on xml
                            self.__em_meas_tab.add_dict_measurement(
                                thermal_dict[1])

            finally:
                self.__em_meas_tab.add_measurement([
                    self.get_time_tuple(),
                    (self._em_cst.COMMENTS,
                     "RUNTEST:Waiting temperature change without data cable plug"
                     )
                ])
                # switch meas to next meas
                self.__em_meas_tab.switch_to_next_meas()

        # compute verdict by taking the last batt info seen
        if log_length > 0:
            self._meas_list.add_dict("EM_INFO_START_TEMP", msic_list[1][1])
        # get the duration it takes to see the right info
        if stop_time is not None:
            self._meas_list.add("TIME_TO_SEE_A_CHANGE", stop_time, "second")

        if not battery_health_change:
            self._meas_list.add_dict("EM_INFO_STOP_TEMP", msic_list[-1][1])

        self._em_meas_verdict.compare_list(self._meas_list,
                                           self._em_targets,
                                           clean_meas_list=True)
Exemplo n.º 26
0
class LabEmCoolingActionVideoCapture(EmUsecaseBase):
    """
    Class Lab cooling action during Video Capture
    """

    DEDICATED_BENCH = "BATTERY_BENCH"

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()

        self.__zone_to_inspect = str(
            self._tc_parameters.get_param_value("THERMAL_ZONE_TO_MONITOR",
                                                "ANY")).upper().strip()
        self.__record_duration = self._tc_parameters.get_param_value(
            "VIDEO_RECORD_DURATION", 120, default_cast_type=int)
        self.__host_media = self._tc_parameters.get_param_value(
            "MEDIA_TO_RECORD", "", default_cast_type=str)
        self.__host_monitor = self._tc_parameters.get_param_value(
            "MONITOR_ON_WHICH_MEDIA_IS_PLAY", -1, default_cast_type=int)

        setup_load = self._tc_parameters.get_param_value("SETUP_TECHNO", "")
        self.__start_temp = self._tc_parameters.get_param_value(
            "SETUP_START_TEMPERATURE", 30, default_cast_type=int)
        self.__cooldown = self._tc_parameters.get_param_value(
            "SETUP_TIME_COOLDOWN_BOARD", 120, default_cast_type=int)
        use_camera_to_cooldown = self._tc_parameters.get_param_value(
            "SETUP_COOLDOWN_WITH_CAMERA", False, default_cast_type=str_to_bool)
        self.__temp_camera = None
        if use_camera_to_cooldown:
            self.__temp_camera = self._em.get_thermal_camera("THERMAL_CAMERA")

        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_COOLING_ACTION_VIDEO_CAPTURE",
            self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())
        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets,
                                          consider_all_target=True)
        self.__video_capture_mod = VideoCaptureModule()
        self.__parser_api = self._device.get_uecmd("Aplog", True)
        self.__load_module = LoadModule()
        self.__load_module.add_load(setup_load)
        self.__video_record_api = self._device.get_uecmd("VideoRecorder", True)
        self.__media_player = None
        if self.__host_media != "":
            self.__media_player = MediaPlayer()
        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)
        self.__ref_temp = None
        self.__pic_folder = self._saving_directory
        meas_file_name = os.path.join(self._saving_directory,
                                      "temperature_report.xml")
        self.__temp_meas_tab = XMLMeasurementFile(meas_file_name)

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

    def set_up(self):
        """
        Initialize the test
        """
        # Call LabPwrMeasBase base Setup function
        EmUsecaseBase.set_up(self)
        # first turn off board for a while to allow it to cool down
        if self.__media_player is None:
            self._logger.warning(
                "no media was set to be launched on the HOST side, no media will be play during video capture"
            )
        else:
            if not os.path.exists(self.__host_media):
                error_msg = "The video %s you want to play on the host side does not exist" % self.__host_media
                self._logger.error(error_msg)
                raise AcsConfigException(AcsConfigException.FILE_NOT_FOUND,
                                         error_msg)

        # check that logs you want to parse exist:
        stop_tag = "TEST_IF_COOLING_INTENT_EXIST-" + time.strftime(
            "-%Y-%m-%d_%Hh%M.%S")
        self.__parser_api.inject_tag(stop_tag)
        cooling_intents = self.__parser_api.find_txt_between_tag(
            self.__parser_api.PUPDR_MISC_TAG.get("MAIN_BOOT"),
            stop_tag,
            self.__parser_api.THERMAL_TAG.get("COOLING_INTENT"),
            raise_error=False)
        if len(cooling_intents) <= 0:
            # it means that cooling intent does not exist,  we cant do the test
            error_msg = "No thermal throttling/de-throttling message has been seen since last boot, check if thermal service is working on your DUT or an update of the thermal parser may be necessary"
            self._logger.error(error_msg)
            raise DeviceException(DeviceException.OPERATION_FAILED, error_msg)

        ####################################### SETUP CAMERAS ###########################################
        if self.__temp_camera is not None:
            # init camera connection
            self.__temp_camera.init()
            self.__temp_camera.delete_all_pictures()
        # clean video storage
        self.__video_record_api.clean_video_storage()
        # Update Battery Information
        ####################################### CHARGE BOARD ###########################################
        em_info = self.update_battery_info()
        if self.em_core_module.is_batt_capacity_below_target(
                em_info, self.em_core_module.batt_min_capacity):
            # charge part
            self.em_core_module.monitor_charging(
                self.em_core_module.batt_min_capacity,
                self.em_core_module.charge_time, self.__em_meas_tab)

        ####################################### COOLDOWN BOARD ###########################################
        self.phonesystem_api.set_screen_timeout(3600)
        self.__video_capture_mod.setup()

        self._device.switch_off()
        # remove any cable after this
        self._io_card.remove_cable("ALL")

        if self.__temp_camera is not None:
            # do the thermal camera setting during the off phase to let the board cool down
            self._setup_camera()
            # wait a given time to let the board cool down
            self._monitor_board_temp(self.__cooldown, self.__start_temp)
        else:
            # wait a given time to let the board cool down
            wait_time = self.__cooldown + 15
            self._logger.info(
                "waiting %ss+15s to let the board cool down while it should be OFF"
                % str(self.__cooldown))
            time.sleep(wait_time)

        # turn on board and launch every load
        self._device.switch_on()
        # this measurement is done only for debugging purpose
        self.em_api.get_thermal_sensor_info()
        # start all environment load
        self.__load_module.start_load()

        if self.__temp_camera is not None:
            # collect a ref temperature before starting the test once board is on
            cam_meas = self.__temp_camera.get_measurement_from_box()
            self.__temp_meas_tab.add_dict_measurement(cam_meas)
            self.__temp_meas_tab.add_measurement([
                self.get_time_tuple(),
                (self._em_cst.COMMENTS,
                 "Setup: Temperature just before starting the test")
            ])
            self.__temp_meas_tab.switch_to_next_meas()

        return Global.SUCCESS, "No errors"

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

    def run_test_body(self):
        """
        run test
        """
        EmUsecaseBase.run_test_body(self)
        # inject a start tag with the host date as unique id
        start_tag = "START_WAITING_FOR_INTENT-" + time.strftime(
            "-%Y-%m-%d_%Hh%M.%S")
        if not self.__parser_api.inject_tag(start_tag):
            error_msg = "The tag [%s] failed to be injected on logs" % (
                start_tag)
            self._logger.error(error_msg)
            raise DeviceException(DeviceException.OPERATION_FAILED, error_msg)

        # start HOST Video
        if not self.__media_player is None:
            self.__media_player.play(self.__host_media, self.__host_monitor)
            # media may take time to start
            start_time = time.time()
            while time.time() - start_time < 10:
                time.sleep(1)
                if self.__media_player.is_playing():
                    break

            if not self.__media_player.is_playing():
                error_msg = "Fail to start the video playback on the HOST side"
                self._logger.error(error_msg)
                raise DeviceException(DeviceException.OPERATION_FAILED,
                                      error_msg)

        # start video recording
        self.phonesystem_api.wake_screen()
        self.phonesystem_api.set_phone_lock(False)
        raw_video_filename, _ = self.__video_capture_mod.start_recording()
        # Check if the video file exist
        if not self.__video_record_api.check_video_exist(raw_video_filename):
            self._logger.error("Recording fail to start, retry again")
            raw_video_filename, _ = self.__video_capture_mod.start_recording()
            # Check if the video file exist
            if not self.__video_record_api.check_video_exist(
                    raw_video_filename):
                screen_path = self._device.screenshot(filename=os.path.join(
                    self.__pic_folder, "camera_record_start_fail.png"))
                error_msg = "Fail to see the raw video file generated during the record, it seems that the video record may has not started."
                if screen_path is not None:
                    error_msg += "\nPlease check the screenshot at %s." % screen_path
                self._logger.error(error_msg)
                raise DeviceException(DeviceException.OPERATION_FAILED,
                                      error_msg)

        # remove any cable
        self._device.disconnect_board()
        self._io_card.remove_cable("ALL")

        self._logger.info("waiting %ss to let the video recording be done" %
                          str(self.__record_duration))
        time.sleep(self.__record_duration)

        # reconnect usb cable
        self._io_card.usb_host_pc_connector(True)
        time.sleep(self.usb_sleep)
        self._device.connect_board()
        # check if board did not went off during the test
        boot_mode = self._device.get_boot_mode()
        if boot_mode != "MOS":
            error_msg = "The board is seen not booted in MOS but in %s at the end of the test , cant compute result" % (
                boot_mode)
            self._logger.error(error_msg)
            raise DeviceException(DeviceException.OPERATION_FAILED, error_msg)

        # get a screenshot to check if camera is still recording
        self._device.screenshot(filename=os.path.join(
            self.__pic_folder, "test_end_board_screen.png"))
        self.__video_capture_mod.stop_recording()
        # inject a stop tag with the host date as unique id
        stop_tag = "STOP_WAITING_FOR_INTENT-" + time.strftime(
            "-%Y-%m-%d_%Hh%M.%S")
        if not self.__parser_api.inject_tag(stop_tag):
            error_msg = "The tag [%s] failed to be injected on logs " % (
                stop_tag)
            self._logger.error(error_msg)
            raise DeviceException(DeviceException.OPERATION_FAILED, error_msg)

        # stop HOST Video
        if not self.__media_player is None:
            self.__media_player.stop()

        # get start intent to extract the time
        start_intent = self.__parser_api.find_txt_between_tag(
            start_tag,
            stop_tag,
            self.__video_record_api.CAMERA_TAG.get("RECORD_START"),
            raise_error=True)[0]
        # "ACS_TAG_INJECTOR: START_WAITING_FOR_INTENT--2014-12-22_11h40.22"
        cooling_intents = self.__parser_api.find_txt_between_tag(
            start_tag,
            stop_tag,
            self.__parser_api.THERMAL_TAG.get("COOLING_INTENT"),
            raise_error=False)

        action_seen = False
        local_msg = ""
        action_before_video = False
        # parse every zone to analyze only the wanted one
        for cooling_intent in cooling_intents:
            result = self.__parser_api.parse_thermal_cooling_event(
                cooling_intent)
            if result is not None:
                zone, level, temperature = result
                zone = zone.upper()

                # this way allow to compare simple str to several monitored zone
                # if we are in ANY case, compute the first seen and leave the test here
                if self.__zone_to_inspect in ["ANY", zone]:
                    # get the time structure for the cooling intent
                    thermal_time_structure, thermal_millisec = self.__parser_api.get_log_date(
                        cooling_intent)
                    time_cooling_happen = float(
                        calendar.timegm(thermal_time_structure)) + (
                            float(thermal_millisec) * 0.001)

                    # get the time structure for start intent
                    start_time_structure, start_millisec = self.__parser_api.get_log_date(
                        start_intent)
                    time_intent_sent = float(
                        calendar.timegm(start_time_structure)) + (
                            float(start_millisec) * 0.001)

                    # if the time between cooling action and the video camera start is < 0 then it is a pass but with a warning
                    spend_time = time_cooling_happen - time_intent_sent

                    if spend_time < 0:
                        self._meas_list.add(
                            "TIME_TAKEN_TO_SEE_FIRST_COOLING_ACTION",
                            spend_time, "SECOND")
                        local_msg += "A cooling action has been seen %ss before video recording start: zone=%s level=%s temperature=%s.\n" % (
                            abs(spend_time), zone, level, temperature)
                        action_before_video = True
                    else:
                        self._meas_list.add(
                            "TIME_TAKEN_TO_SEE_FIRST_COOLING_ACTION",
                            spend_time, "SECOND")
                        local_msg += "First cooling action seen %ss after video recording start: zone=%s level=%s temperature=%s.\n" % (
                            spend_time, zone, level, temperature)
                        action_seen = True
                        break

        msg = "no cooling action seen."
        if local_msg != "":
            msg = local_msg
        if action_before_video == True:
            msg += "A manual check on cooling actions before video start is required to see if it is a real FAIL or PASS.."

        # generate em verdict
        if not action_seen:
            self._meas_list.add("TIME_TAKEN_TO_SEE_FIRST_COOLING_ACTION",
                                self.__record_duration, "SECOND")
        self._em_meas_verdict.compare_list(self._meas_list, self._em_targets,
                                           True)
        self._em_meas_verdict.judge()
        verdict, verdict_msg = self._em_meas_verdict.get_current_result_v2()
        msg = msg + "\n" + verdict_msg
        return verdict, msg

    def tear_down(self):
        """
        End and dispose the test
        """
        EmUsecaseBase.tear_down(self)
        if self.__temp_camera is not None:
            try:
                self.__temp_camera.delete_all_pictures()
                self.__temp_camera.set_linear_temperature_mode(False)
            except Exception as e:
                self._logger.error(
                    "error happen when releasing thermal camera %s" % str(e))
            finally:
                self.__temp_camera.release()
        if not self.__media_player is None:
            self.__media_player.stop()

        # stop all load
        self.em_core_module.clean_up()
        self.__load_module.stop_load()
        # stop any remaining video capture
        self.__video_record_api.force_stop()
        self.__video_record_api.restore_camera_setup()
        self.__video_record_api.clean_video_storage()

        return Global.SUCCESS, "No errors"

    def _setup_camera(self):
        """
        setup the camera
        """
        self.__temp_camera.auto_setup()
        x, y, h, w = self.__temp_camera.get_image_geometry()
        self.__temp_camera.set_linear_temperature_mode(True)
        self.__temp_camera.configure_measurement_box(True, x, y, h, w)

    def _monitor_board_temp(self, monitor_timeout, target_temp):
        """
        monitor board temperature until it reach given value or a value below it.
        :todo: this function only monitor for cooling condition,
                it may be change to offer the possibility to monitor for heating one
        """
        start_temp_seen = False
        wait_time = monitor_timeout + 15
        self._logger.info(
            "waiting at most %ss+15s to let the board cool down below %s degree"
            % (str(monitor_timeout), str(target_temp)))
        start_time = time.time()
        while time.time() - start_time < wait_time:
            cam_meas = self.__temp_camera.get_measurement_from_box()

            try:
                self.__temp_meas_tab.add_dict_measurement(cam_meas)
                self.__temp_meas_tab.add_measurement([
                    self.get_time_tuple(),
                    (self._em_cst.COMMENTS, "Setup: cooling down the board")
                ])
                self.__temp_meas_tab.switch_to_next_meas()
            except Exception as e:
                msg = "error happen when filling temperature value in file: %s" % str(
                    e)
                self._logger.error(msg)

            if cam_meas["MAXT"][0] <= target_temp:
                self._logger.info(
                    "the MAX temperature seen is %s, test can continue " %
                    str(cam_meas["MAXT"]))
                # take a ref picture
                pic_path = self.__temp_camera.take_picture("ref_phone_off")
                self.__temp_camera.pull_picture(pic_path, self.__pic_folder)
                start_temp_seen = True
                self.__ref_temp = cam_meas["MAXT"][0]
                break

        if not start_temp_seen:
            cam_meas = self.__temp_camera.get_measurement_from_box()
            pic_path = self.__temp_camera.take_picture(
                "pic_temp_after_cooldown_fail")
            self.__temp_camera.pull_picture(pic_path, self.__pic_folder)
            error_msg = "The board fail to cool down below %s degree after spending %ss in OFF state, the last temperature seen was %s degree" % (
                target_temp, monitor_timeout, str(cam_meas["MAXT"]))
            self._logger.error(error_msg)
            self._device.switch_on()
            raise DeviceException(DeviceException.INVALID_DEVICE_STATE,
                                  error_msg)
class LabEmTempMonitorVideoCapture(EmUsecaseBase):

    """
    Class Lab temperature during Video Capture
    """

    DEDICATED_BENCH = "BATTERY_BENCH"

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()

        setup_load = self._tc_parameters.get_param_value("SETUP_TECHNO", "")
        self.__record_duration = self._tc_parameters.get_param_value("VIDEO_RECORD_DURATION", 120, default_cast_type=int)
        self.__cooldown = self._tc_parameters.get_param_value("SETUP_TIME_COOLDOWN_BOARD", 120, default_cast_type=int)
        self.__start_temp = self._tc_parameters.get_param_value("SETUP_START_TEMPERATURE", 30, default_cast_type=int)
        self.__host_media = self._tc_parameters.get_param_value("MEDIA_TO_RECORD", "", default_cast_type=str)
        self.__host_monitor = self._tc_parameters.get_param_value("MONITOR_ON_WHICH_MEDIA_IS_PLAY", -1, default_cast_type=int)
        self.__temp_target = self._tc_parameters.get_param_value("TARGET_MAX_TEMPERATURE", default_cast_type=int)

        # load targets in order to measure iteration
        self.__video_capture_mod = VideoCaptureModule()
        self.__load_module = LoadModule()
        self.__load_module.add_load(setup_load)
        self.__video_record_api = self._device.get_uecmd("VideoRecorder", True)
        self.__media_player = None
        if self.__host_media != "":
            self.__media_player = MediaPlayer()
        # measurement file
        meas_file_name = os.path.join(self._saving_directory, "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

        meas_file_name = os.path.join(self._saving_directory, "temperature_report.xml")
        self.__temp_meas_tab = XMLMeasurementFile(meas_file_name)
        self.__temp_camera = self._em.get_thermal_camera("THERMAL_CAMERA")
        self.__pic_folder = self._saving_directory
        self.__ref_temp = None

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

    def set_up(self):
        """
        Initialize the test
        """
        # Call LabPwrMeasBase base Setup function
        EmUsecaseBase.set_up(self)
        # reset the ref value
        self.__ref_temp = None
        # check that media exist
        if self.__media_player is None:
            self._logger.warning("no media was set to be launched on the HOST side, no media will be play during video capture")
        else:
            if not os.path.exists(self.__host_media):
                error_msg = "The video %s you want to play on the host side does not exist" % self.__host_media
                self._logger.error(error_msg)
                raise AcsConfigException(AcsConfigException.FILE_NOT_FOUND, error_msg)

        # clean video storage
        self.__video_record_api.clean_video_storage()
        # init camera connection
        self.__temp_camera.init()
        self.__temp_camera.delete_all_pictures()
        # Update Battery Information
        em_info = self.update_battery_info()
        if self.em_core_module.is_batt_capacity_below_target(em_info, self.em_core_module.batt_min_capacity):
            # charge part
            self.em_core_module.monitor_charging(self.em_core_module.batt_min_capacity,
                                         self.em_core_module.charge_time,
                                         self.__em_meas_tab)

        self.__video_capture_mod.setup()
        self.phonesystem_api.set_screen_timeout(3600)
        self._device.switch_off()
        # remove any cable after this
        self._io_card.remove_cable("ALL")
        # do the thermal camera setting during the off phase to let the board cooldown
        self._setup_camera()
        # wait a given time to let the board cool down
        start_temp_seen = False
        wait_time = self.__cooldown + 15
        self._logger.info("waiting at most %ss+15s to let the board cool down below %s degree" % (str(self.__cooldown), str(self.__start_temp)))
        start_time = time.time()
        while time.time() - start_time < wait_time:
            cam_meas = self.__temp_camera.get_measurement_from_box()

            try:
                self.__temp_meas_tab.add_dict_measurement(cam_meas)
                self.__temp_meas_tab.add_measurement([self.get_time_tuple(),
                                    (self._em_cst.COMMENTS, "Setup: cooling down the board")])
                self.__temp_meas_tab.switch_to_next_meas()
            except Exception as e:
                msg = "error happen when filling temperature value in file: %s" % str(e)
                self._logger.error(msg)

            if cam_meas["MAXT"][0] <= self.__start_temp:
                self._logger.info("the MAX temperature seen is %s, test can continue " % str(cam_meas["MAXT"]))
                # take a ref picture
                pic_path = self.__temp_camera.take_picture("ref_phone_off")
                self.__temp_camera.pull_picture(pic_path, self.__pic_folder)
                start_temp_seen = True
                self.__ref_temp = cam_meas["MAXT"][0]
                break

        if not start_temp_seen:
            cam_meas = self.__temp_camera.get_measurement_from_box()
            pic_path = self.__temp_camera.take_picture("pic_temp_after_cooldown_fail")
            self.__temp_camera.pull_picture(pic_path, self.__pic_folder)
            error_msg = "The board fail to cool down below %s degree after spending %ss in OFF state, the last temperature seen was %s degree" % (self.__start_temp,
                                                                                                                                                  self.__cooldown,
                                                                                                                                                  str(cam_meas["MAXT"]))
            self._logger.error(error_msg)
            self._device.switch_on()
            raise DeviceException(DeviceException.INVALID_DEVICE_STATE, error_msg)

        # turn on board and launch every load
        self._device.switch_on()
        self.em_api.get_thermal_sensor_info()
        # start all environment load
        self.__load_module.start_load()

        # start HOST Video
        if not self.__media_player is None:
            self.__media_player.play(self.__host_media, self.__host_monitor)
            # media may take time to start
            start_time = time.time()
            while time.time() - start_time < 10:
                time.sleep(1)
                if self.__media_player.is_playing():
                    break

            if not self.__media_player.is_playing():
                error_msg = "Fail to start the video playback on the HOST side"
                self._logger.error(error_msg)
                raise AcsBaseException(AcsBaseException.OPERATION_FAILED, error_msg)

        # collect a ref temperature before starting the test once board is on
        cam_meas = self.__temp_camera.get_measurement_from_box()
        self.__temp_meas_tab.add_dict_measurement(cam_meas)
        self.__temp_meas_tab.add_measurement([self.get_time_tuple(),
                        (self._em_cst.COMMENTS, "Setup: Temperature just before starting the test")])
        self.__temp_meas_tab.switch_to_next_meas()
        # start video recording
        self.phonesystem_api.wake_screen()
        self.phonesystem_api.set_phone_lock(False)
        raw_video_filename, _ = self.__video_capture_mod.start_recording()
        # Check if the video file exist
        if not self.__video_record_api.check_video_exist(raw_video_filename):
            self._logger.error("Recording fail to start, retry again")
            raw_video_filename, _ = self.__video_capture_mod.start_recording()
            # Check if the video file exist
            if not self.__video_record_api.check_video_exist(raw_video_filename):
                screen_path = self._device.screenshot(filename=os.path.join(self.__pic_folder, "camera_record_fail.png"))
                error_msg = "Fail to see the raw video file generated during the record, it seems that the video record may has not started."
                if screen_path is not None:
                    error_msg += "\nPlease check the screenshot at %s." % screen_path
                self._logger.error(error_msg)
                raise DeviceException(DeviceException.FILE_SYSTEM_ERROR, error_msg)

        return Global.SUCCESS, "No errors"

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

    def run_test_body(self):
        """
        run test
        """
        EmUsecaseBase.run_test_body(self)

        # remove any cable
        self._device.disconnect_board()
        self._io_card.remove_cable("ALL")

        self._logger.info("Monitoring temperature during %ss " % str(self.__record_duration))
        # do the monitoring job
        maxt = self.__temp_camera.get_measurement_from_box()["MAXT"]
        last_max_temp_seen = maxt[0]
        unit = maxt[1]
        pic_path = None
        start_time = time.time()
        while time.time() - start_time < self.__record_duration:
        # we want to monitor and see the highest temperature seen by the board
            cam_meas = self.__temp_camera.get_measurement_from_box()
            max_temp = cam_meas["MAXT"][0]
            if max_temp > last_max_temp_seen:
                # save a picture of each highest temperature seen
                pic_path = self.__temp_camera.take_picture("max_during_record")
                last_max_temp_seen = max_temp
            try:
                self.__temp_meas_tab.add_dict_measurement(cam_meas)
                self.__temp_meas_tab.add_measurement([self.get_time_tuple(),
                                                    (self._em_cst.COMMENTS, "Runtest: video record ongoing")])
                self.__temp_meas_tab.switch_to_next_meas()
            except Exception as e:
                msg = "error happen when filling temperature value in file: %s" % str(e)
                self._logger.error(msg)

        # reconnect usb cable
        self._io_card.usb_host_pc_connector(True)
        if pic_path is not None:
            self.__temp_camera.pull_picture(pic_path, self.__pic_folder)

        time.sleep(self.usb_sleep)
        self._device.connect_board()
        # check if board did not went off during the test
        boot_mode = self._device.get_boot_mode()
        if boot_mode != "MOS":
            error_msg = "The board is seen not booted in MOS but in %s at the end of the test , cant compute result" % (boot_mode)
            self._logger.error(error_msg)
            raise DeviceException(DeviceException.OPERATION_FAILED, error_msg)

        # get a proof that video was still running
        self._device.screenshot(filename=os.path.join(self.__pic_folder, "test_end_board_screen.png"))
        self.__video_capture_mod.stop_recording()
        # stop HOST Video
        if not self.__media_player is None:
            self.__media_player.stop()

        verdict = Global.FAILURE
        msg = "The ref temperature when board is OFF was at %s %s.\n" % (self.__ref_temp, unit)
        msg += "The max temperature seen on the DUT during %ss of video recording is %s %s" % (self.__record_duration,
                                                                                           last_max_temp_seen, unit)
        if last_max_temp_seen > self.__temp_target :
            msg += " which is above"
        else:
            msg += " which is below or equal to"
            verdict = Global.SUCCESS
        msg += " the target not to exceed : %s degree" % (self.__temp_target)
        self._logger.info(msg)
        return verdict, msg

    def tear_down(self):
        """
        End and dispose the test
        """
        EmUsecaseBase.tear_down(self)
        try:
            self.__temp_camera.set_linear_temperature_mode(False)
            self.__temp_camera.delete_all_pictures()
        except Exception as e:
            self._logger.error("error happen when releasing thermal camera %s" % str(e))
        finally:
            self.__temp_camera.release()

        if not self.__media_player is None:
            self.__media_player.stop()

        # stop all load
        self.em_core_module.clean_up()
        self.__load_module.stop_load()
        # stop any remaining video capture
        self.__video_record_api.force_stop()
        self.__video_record_api.restore_camera_setup()
        self.__video_record_api.clean_video_storage()

        return Global.SUCCESS, "No errors"

    def _setup_camera(self):
        """
        setup the camera
        """
        self.__temp_camera.auto_setup()
        x, y, h, w = self.__temp_camera.get_image_geometry()
        self.__temp_camera.set_linear_temperature_mode(True)
        self.__temp_camera.configure_measurement_box(True, x, y, h, w)
Exemplo n.º 28
0
class LabEmCoolingActionBenchmark(EmUsecaseBase):
    """
    Montinor cooling action during benchmark
    """

    DEDICATED_BENCH = "BATTERY_BENCH"

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)

        # init fuel gauging parameters
        self.em_core_module.init_fg_param()
        self.__zone_to_inspect = str(
            self._tc_parameters.get_param_value("THERMAL_ZONE_TO_MONITOR",
                                                "ANY")).upper().strip()

        setup_load = self._tc_parameters.get_param_value("SETUP_TECHNO", "")
        self.__cooldown = self._tc_parameters.get_param_value(
            "SETUP_TIME_COOLDOWN_BOARD", 1800, default_cast_type=int)
        self.__start_temp = self._tc_parameters.get_param_value(
            "SETUP_START_TEMPERATURE", 30, default_cast_type=int)
        use_camera_to_cooldown = self._tc_parameters.get_param_value(
            "SETUP_COOLDOWN_WITH_CAMERA", False, default_cast_type=str_to_bool)
        self.__temp_camera = None
        if use_camera_to_cooldown:
            self.__temp_camera = self._em.get_thermal_camera("THERMAL_CAMERA")

        self.__benchmark_module = BenchmarkModule()
        self.__load_module = LoadModule()
        self.__load_module.add_load(setup_load)

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

        meas_file_name = os.path.join(self._saving_directory,
                                      "temperature_report.xml")
        self.__temp_meas_tab = XMLMeasurementFile(meas_file_name)

        meas_file_name = os.path.join(self._saving_directory,
                                      "benchmark_score_report.xml")
        self.__benchamrk_tab = XMLMeasurementFile(meas_file_name)

        self.__ref_temp = None
        self.__pic_folder = self._saving_directory
        self.__host_test_start_time = None
        self.__bk_delay = 30
        self.__parser_api = self._device.get_uecmd("Aplog", True)
        # Call ConfigsParser to parse Energy_Management
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_COOLING_ACTION_BENCHMARK",
            self._tc_parameters.get_params_as_dict(),
            self._device.get_phone_model())
        # load targets in order to measure iteration
        self._em_meas_verdict.load_target(self._em_targets,
                                          consider_all_target=True)

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

    def __push_score(self, score_list):
        """
        take in entry the result for get_score() and format the benchmark score
        for TCR upload in order to upload all the score together

        :type score_list: list
        :param score_list: a list of dictionary containing score from benchmarks

        :rtype: dict of dict
        :return:  return a dict of dictionary
        """
        result = {}
        i = 0
        # get the highest number of digit in score list, for example 2 for 10
        max_iter_count = len(str(len(score_list)))
        max_logged_iteration = 1

        # search for the highest logged iteration
        for dico in score_list:
            digit_length = len(str(dico.get(BenchmarkModule.DITER, 1)))
            # we consider that the value is always a digit when it is returned
            if digit_length > max_logged_iteration:
                max_logged_iteration = digit_length

        for dico in score_list:
            i += 1
            # push dico on sysfs
            self.__benchamrk_tab.add_dict_measurement(dico)
            self.__benchamrk_tab.add_measurement([
                self.get_time_tuple(),
                (self._em_cst.COMMENTS, "Getting benchmark scores")
            ])
            self.__benchamrk_tab.switch_to_next_meas()

            # push dico on TCR
            if len(dico) > 1:
                score_dico = {}
                score_iter = dico.get(BenchmarkModule.DITER)
                if score_iter is None:
                    i_str = str(i).zfill(max_iter_count)
                    iter_tag = "BENCHMARK_MANUAL_COUNT_ITERATION_%s" % i_str
                else:
                    score_iter = str(score_iter).zfill(max_logged_iteration)
                    iter_tag = "BENCHMARK_ITERATION_%s" % score_iter
                for key, value in dico.iteritems():
                    # store everything under iteration tag except iteration
                    if key != BenchmarkModule.DITER:
                        score_dico[key] = value
                result[iter_tag] = score_dico

        if len(result) > 0:
            LiveReporting.instance().update_running_tc_info(test_info=result)
        return result

    def set_up(self):
        """
        Initialize the test
        """
        EmUsecaseBase.set_up(self)
        self.__benchmark_module.setup()
        if self.__temp_camera is not None:
            # init camera connection
            self.__temp_camera.init()
            self.__temp_camera.delete_all_pictures()

        # check that logs you want to parse exist:
        stop_tag = "TEST_IF_COOLING_INTENT_EXIST-" + time.strftime(
            "-%Y-%m-%d_%Hh%M.%S")
        self.__parser_api.inject_tag(stop_tag)
        cooling_intents = self.__parser_api.find_txt_between_tag(
            self.__parser_api.PUPDR_MISC_TAG.get("MAIN_BOOT"),
            stop_tag,
            self.__parser_api.THERMAL_TAG.get("COOLING_INTENT"),
            raise_error=False)
        if len(cooling_intents) <= 0:
            # it means that cooling intent does not exist,  we cant do the test
            error_msg = "No thermal throttling/de-throttling message has been seen since last boot, check if thermal service is working on your DUT or an update of the thermal parser may be necessary"
            self._logger.error(error_msg)
            raise DeviceException(DeviceException.OPERATION_FAILED, error_msg)

        ####################################### CHARGE BOARD ###########################################
        # Update Battery Information
        em_info = self.update_battery_info()
        if self.em_core_module.is_batt_capacity_below_target(
                em_info, self.em_core_module.batt_min_capacity):
            # charge part
            self.em_core_module.monitor_charging(
                self.em_core_module.batt_min_capacity,
                self.em_core_module.charge_time, self.__em_meas_tab)

        ####################################### COOL DOWN BOARD ###########################################
        self.phonesystem_api.set_screen_timeout(3600)
        self._device.switch_off()
        # remove any cable after this
        self._io_card.remove_cable("ALL")

        if self.__temp_camera is not None:
            # do the thermal camera setting during the off phase to let the board cool down
            self._setup_camera()
            # wait a given time to let the board cool down
            self._monitor_board_temp(self.__cooldown, self.__start_temp)
        else:
            # wait a given time to let the board cool down
            wait_time = self.__cooldown + 15
            self._logger.info(
                "waiting %ss+15s to let the board cool down while it should be OFF"
                % str(self.__cooldown))
            time.sleep(wait_time)

        # turn on board and launch every load
        self._device.switch_on()
        # this measurement is done only for debugging purpose
        self.em_api.get_thermal_sensor_info()
        # start all environment load
        self.__load_module.start_load()

        if self.__temp_camera is not None:
            # collect a ref temperature before starting the test once board is on
            cam_meas = self.__temp_camera.get_measurement_from_box()
            self.__temp_meas_tab.add_dict_measurement(cam_meas)
            self.__temp_meas_tab.add_measurement([
                self.get_time_tuple(),
                (self._em_cst.COMMENTS,
                 "Setup: Temperature just before starting the test")
            ])
            self.__temp_meas_tab.switch_to_next_meas()

        ####################################### START BENCHMARK ###########################################
        self.phonesystem_api.wake_screen()
        self.phonesystem_api.set_phone_lock(False)
        self.__benchmark_module.execute_test(background=True,
                                             delay=self.__bk_delay)
        self.__host_test_start_time = time.time()

        start_timeout = 60
        running = False
        start_time = time.time()
        self._logger.info(
            "wait at most %ss to see that benchmark has been launched" %
            str(start_timeout))
        while time.time() - start_time < start_timeout:
            running = self.__benchmark_module.is_running()
            if running:
                break

        if not running:
            txt = "benchmark fail to start after waiting %ss" % str(
                start_timeout)
            self._logger.error(txt)
            self._logger.error("benchmark execution logs for debugging : %s " %
                               self.__benchmark_module.get_output_log())
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)
        self.__benchmark_module.check_crash()
        return Global.SUCCESS, "No errors"

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

    def run_test_body(self):
        """
        run test
        """
        EmUsecaseBase.run_test_body(self)
        ####################################### TAG TEST START, WAIT FOR TEST, THEN TAG TEST END ###########################################
        # inject a start tag with the host date as unique id
        start_tag = "START_WAITING_FOR_INTENT-" + time.strftime(
            "-%Y-%m-%d_%Hh%M.%S")
        if not self.__parser_api.inject_tag(start_tag):
            error_msg = "The tag [%s] failed to be injected on logs" % (
                start_tag)
            self._logger.error(error_msg)
            raise DeviceException(DeviceException.OPERATION_FAILED, error_msg)

        # remove any cable
        self._device.disconnect_board()
        self._io_card.remove_cable("ALL")
        bk_duration = self.__benchmark_module.get_exec_whole_duration()
        delay_left = self.__bk_delay - (time.time() -
                                        self.__host_test_start_time)
        if delay_left > 1:
            self._logger.info(
                "Waiting %ss to align benckmark launching time with beginning of waiting duration"
                % str(delay_left))
            time.sleep(delay_left)

        start_time = time.time()
        self._logger.info("waiting %ss of benchmark execution" %
                          str(bk_duration))
        time.sleep(bk_duration)
        stop_time = time.time()
        # reconnect usb cable
        warning_crash = False
        self._io_card.usb_host_pc_connector(True)
        time.sleep(self.usb_sleep)
        self._device.connect_board()

        # check if board did not went off during the test
        boot_mode = self._device.get_boot_mode()
        if boot_mode != "MOS":
            error_msg = "The board is seen not booted in MOS but in %s at the end of the test , cant compute result" % (
                boot_mode)
            self._logger.error(error_msg)
            raise DeviceException(DeviceException.OPERATION_FAILED, error_msg)
        self._device.screenshot(filename=os.path.join(
            self.__pic_folder, "test_end_board_screen.png"))

        # inject a stop tag with the host date as unique id
        stop_tag = "STOP_WAITING_FOR_INTENT-" + time.strftime(
            "-%Y-%m-%d_%Hh%M.%S")
        if not self.__parser_api.inject_tag(stop_tag):
            error_msg = "The tag [%s] failed to be injected on logs " % (
                stop_tag)
            self._logger.error(error_msg)
            raise DeviceException(DeviceException.OPERATION_FAILED, error_msg)

        ####################################### CHECK BENCHMARK CRASH ###########################################
        # first check that there were no crashes
        start_date = self.__benchmark_module.get_start_date()
        crash_date, _ = self.__benchmark_module.get_crash()

        # if a crash happen but after that the test end , then the test may be passed with a warning
        if start_date is not None:
            if crash_date is not None:
                bk_exact_duration = crash_date - start_date
                host_exact_duration = stop_time - start_time
                if bk_exact_duration <= host_exact_duration:
                    self.__benchmark_module.check_crash()
                else:
                    warning_crash = True
        else:
            error_msg = "Cant retrieve benchmark start date, it seems that the benchmark may have not been started"
            self._logger.error(error_msg)
            raise DeviceException(DeviceException.OPERATION_FAILED, error_msg)

        # try to stop the benchmark, if it fail, continue the measurement
        try:
            self.__benchmark_module.stop_execution()
        except Exception as e:
            self._logger.error("error happen when stopping benchmark %s" %
                               str(e))

        # upload benchmark result
        try:
            score_list = self.__benchmark_module.get_score()
            self.__push_score(score_list)
        except Exception as e:
            self._logger.error(
                "Error happen when trying to upload benchmark: %s" % str(e))

        ####################################### SEARCH FOR COOLING ACTION ###########################################
        # get start intent to extract the time
        start_intent = self.__parser_api.find_txt_between_tag(
            start_tag,
            stop_tag,
            self.__benchmark_module.BENCHMARK_START_TAG,
            raise_error=True)[0]
        # "ACS_TAG_INJECTOR: START_WAITING_FOR_INTENT--2014-12-22_11h40.22"
        cooling_intents = self.__parser_api.find_txt_between_tag(
            start_tag,
            stop_tag,
            self.__parser_api.THERMAL_TAG.get("COOLING_INTENT"),
            raise_error=False)
        action_seen = False
        local_msg = ""
        action_before_benchmark = False
        # parse every zone to analyze only the wanted one
        for cooling_intent in cooling_intents:
            result = self.__parser_api.parse_thermal_cooling_event(
                cooling_intent)
            if result is not None:
                zone, level, temperature = result
                zone = zone.upper()

                # this way allow to compare simple str to several monitored zone
                # if we are in ANY case, compute the first seen and leave the test here
                if self.__zone_to_inspect in ["ANY", zone]:
                    # get the time structure for the cooling intent
                    thermal_time_structure, thermal_millisec = self.__parser_api.get_log_date(
                        cooling_intent)
                    time_cooling_happen = float(
                        calendar.timegm(thermal_time_structure)) + (
                            float(thermal_millisec) * 0.001)

                    # get the time structure for start intent
                    start_time_structure, start_millisec = self.__parser_api.get_log_date(
                        start_intent)
                    time_intent_sent = float(
                        calendar.timegm(start_time_structure)) + (
                            float(start_millisec) * 0.001)

                    spend_time = time_cooling_happen - time_intent_sent
                    if spend_time < 0:
                        self._meas_list.add(
                            "TIME_TAKEN_TO_SEE_FIRST_COOLING_ACTION",
                            spend_time, "SECOND")
                        local_msg += "A cooling action has been seen %ss before benchmark start and after board was cool down : zone=%s level=%s temperature=%s.\n" % (
                            abs(spend_time), zone, level, temperature)
                        action_before_benchmark = True
                    else:
                        self._meas_list.add(
                            "TIME_TAKEN_TO_SEE_FIRST_COOLING_ACTION",
                            spend_time, "SECOND")
                        local_msg += "First cooling action seen %ss after benchmark start: zone=%s level=%s temperature=%s.\n" % (
                            spend_time, zone, level, temperature)
                        action_seen = True
                        break

        msg = "no cooling action seen."
        if local_msg != "":
            msg = local_msg
        if action_before_benchmark == True:
            msg += "A manual check on cooling actions before benchmark is required to see if it is a real FAIL or PASS.."
        # generate em verdict
        if not action_seen:
            self._meas_list.add("TIME_TAKEN_TO_SEE_FIRST_COOLING_ACTION",
                                bk_duration, "SECOND")
        self._em_meas_verdict.compare_list(self._meas_list, self._em_targets,
                                           True)
        self._em_meas_verdict.judge()
        verdict, verdict_msg = self._em_meas_verdict.get_current_result_v2()
        msg = msg + "\n" + verdict_msg
        if warning_crash:
            msg = "A crash happened but it was after the test end, result can be computed.\n" + msg
        msg += "\nBenchmark scores may be seen in file %s" % self.__benchamrk_tab.get_report_path(
        )
        return verdict, msg

    def tear_down(self):
        """
        End and dispose the test
        """
        EmUsecaseBase.tear_down(self)
        benchmark_stopped = False
        # stop benchmark here to prevent it from running in loop while charging below
        if self.is_board_and_acs_ok():
            try:
                self.__benchmark_module.clean()
                benchmark_stopped = True
            except Exception as e:
                self._logger.error("error happen when stopping benchmark %s" %
                                   str(e))

        #  stop camera anyway
        if self.__temp_camera is not None:
            try:
                self.__temp_camera.delete_all_pictures()
                self.__temp_camera.set_linear_temperature_mode(False)
            except Exception as e:
                self._logger.error(
                    "error happen when releasing thermal camera %s" % str(e))
            finally:
                self.__temp_camera.release()

        # stop all load
        self.em_core_module.clean_up()
        self.__load_module.stop_load()
        if not benchmark_stopped:
            self.__benchmark_module.clean()
        # stop benchmark
        return Global.SUCCESS, "No errors"

    def _setup_camera(self):
        """
        setup the camera
        """
        self.__temp_camera.auto_setup()
        x, y, h, w = self.__temp_camera.get_image_geometry()
        self.__temp_camera.set_linear_temperature_mode(True)
        self.__temp_camera.configure_measurement_box(True, x, y, h, w)

    def _monitor_board_temp(self, monitor_timeout, target_temp):
        """
        monitor board temperature until it reach given value or a value below it.
        :todo: this function only monitor for cooling condition,
                it may be change to offer the possibility to monitor for heating one
        """
        start_temp_seen = False
        wait_time = monitor_timeout + 15
        self._logger.info(
            "waiting at most %ss+15s to let the board cool down below %s degree"
            % (str(monitor_timeout), str(target_temp)))
        start_time = time.time()
        while time.time() - start_time < wait_time:
            cam_meas = self.__temp_camera.get_measurement_from_box()

            try:
                self.__temp_meas_tab.add_dict_measurement(cam_meas)
                self.__temp_meas_tab.add_measurement([
                    self.get_time_tuple(),
                    (self._em_cst.COMMENTS, "Setup: cooling down the board")
                ])
                self.__temp_meas_tab.switch_to_next_meas()
            except Exception as e:
                msg = "error happen when filling temperature value in file: %s" % str(
                    e)
                self._logger.error(msg)

            if cam_meas["MAXT"][0] <= target_temp:
                self._logger.info(
                    "the MAX temperature seen is %s, test can continue " %
                    str(cam_meas["MAXT"]))
                # take a ref picture
                pic_path = self.__temp_camera.take_picture("ref_phone_off")
                self.__temp_camera.pull_picture(pic_path, self.__pic_folder)
                start_temp_seen = True
                self.__ref_temp = cam_meas["MAXT"][0]
                break

        if not start_temp_seen:
            cam_meas = self.__temp_camera.get_measurement_from_box()
            pic_path = self.__temp_camera.take_picture(
                "pic_temp_after_cooldown_fail")
            self.__temp_camera.pull_picture(pic_path, self.__pic_folder)
            error_msg = "The board fail to cool down below %s degree after spending %ss in OFF state, the last temperature seen was %s degree" % (
                target_temp, monitor_timeout, str(cam_meas["MAXT"]))
            self._logger.error(error_msg)
            self._device.switch_on()
            raise DeviceException(DeviceException.INVALID_DEVICE_STATE,
                                  error_msg)
class LabEmBattEmergencyCallCriticalThreshold(EmUsecaseBase):
    """
    Lab Energy Management class.
    """
    DEDICATED_BENCH = "BATTERY_BENCH"

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call LAB_EM_BASE Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)
        # init fuel gauging parameters
        self.em_core_module.init_fg_param()
        # misc parameter
        self.__battery_critical_threshold = self._tc_parameters.get_param_value(
            "BATTERY_CRITICAL_THRESHOLD", default_cast_type=int)
        load_to_apply_in_setup = self._tc_parameters.get_param_value(
            "LOAD_DURING_DISCHARGE", "")
        # call parameter
        self.__call_timeout = self._tc_parameters.get_param_value(
            "CALL_HOLD_TIME", default_cast_type=int)
        self.__hands_free_activation = self._tc_parameters.get_param_value(
            "HANDS_FREE_ACTIVATION", default_cast_type="str_to_bool")
        self.__fake_emergency_phone_number = self._tc_parameters.get_param_value(
            "PHONE_NUMBER", "012345")
        call_type = self._tc_parameters.get_param_value("CALL_TYPE")

        # Summarize the parameters
        self._logger.info("[TESTCASE]\tBattery Critical Threshold: %s%%" %
                          self.__battery_critical_threshold)
        self._logger.info("[TESTCASE]\tEmergency Phone Number : %s" %
                          self.__fake_emergency_phone_number)
        self._logger.info(
            "[TESTCASE]\tthe holding time of the call when battery reach critical level: %ss"
            % self.__call_timeout)
        self._logger.info("[TESTCASE]\tType of the call : %s" % call_type)
        self._logger.info("[TESTCASE]\tActivation of Hands Free : %s" %
                          self.__hands_free_activation)

        # Initial Emergency Number
        if call_type == "3G":
            # Initialization of module 3g
            self.__telmodule = TelephonyModule3g()
        elif call_type == "2G":
            # Initialization of module 3g
            self.__telmodule = TelephonyModule2g()
        else:
            txt = "Type of the call is not correct => Quit the test"
            self._logger.error(txt)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, txt)

        # measurement file
        meas_file_name = os.path.join(self._saving_directory,
                                      "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

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

        # init load module used to discharge board
        self.__load_module = LoadModule()
        self.__load_module.add_load(load_to_apply_in_setup)
        self.__initial_emergency_numbers = None
        self.__original_airplane_state = None

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

    def set_up(self):
        """
        Initialize the test
        """
        # Call the UseCaseBase Setup function
        EmUsecaseBase.set_up(self)
        # deactivate flight mode for this test
        self.__original_airplane_state = self.networking_api.get_flight_mode()
        if self.__original_airplane_state:
            self.networking_api.set_flight_mode(False)

        # setup network simulator
        self.__telmodule.set_up_eq()
        # Brightness Configuration
        self.phonesystem_api.set_phone_lock(0)
        # set the screen on and brightness to 100%
        self.phonesystem_api.set_screen_timeout(3600)
        # deactivate set auto brightness
        self.phonesystem_api.set_brightness_mode("manual")
        # set display brightness to max value
        self.phonesystem_api.set_display_brightness(100)
        # Wake up the screen
        self.phonesystem_api.wake_screen()
        # wait for registration
        self.__telmodule.register_to_network()

        # Check if the fake number is a real emergency number
        if self.__fake_emergency_phone_number in UECmdTypes.EMERGENCY_NUMBERS_LIST:
            txt = "Fake phone number is a real emergency phone number => Quit the test, know emergency number are %s" % str(
                UECmdTypes.EMERGENCY_NUMBERS_LIST)
            self._logger.error(txt)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, txt)

        if self.__initial_emergency_numbers is None:
            initial_emergency_numbers = self.modem_api.get_emergency_numbers()
            if self.__fake_emergency_phone_number not in initial_emergency_numbers:
                self.__initial_emergency_numbers = initial_emergency_numbers
            else:
                self.__initial_emergency_numbers = initial_emergency_numbers.remove(
                    self.__fake_emergency_phone_number)

        # Add the fake emergency phone number
        self.modem_api.set_emergency_numbers(
            [self.__fake_emergency_phone_number], False)
        # Update Battery Information
        self.update_battery_info()
        # Discharge the battery if we are above critical threshold
        if self.batt_capacity > self.__battery_critical_threshold:
            self.em_core_module.monitor_discharging(
                self.__battery_critical_threshold,
                self.em_core_module.discharge_time, self.__em_meas_tab,
                self.__load_module)

            # Check the board is still alive
            self._logger.info(
                "Check if we haven't lost the board connection after discharging"
            )
            if not self.is_board_and_acs_ok():
                cause_txt = "At the beginning of the test, the board status is not in MOS, abort testcase !"
                self._logger.info(cause_txt)
                raise DeviceException(DeviceException.DUT_BOOT_ERROR,
                                      cause_txt)

        # try to reboot in MOS if we discharge too much
        if self._device.get_boot_mode() == "COS":
            self._device.reboot()

        return Global.SUCCESS, "No errors"

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

    def run_test_body(self):
        """
        Execute the test
        Check the end of the main battery charge
        """
        # Call LAB_EM_BASE Run function
        EmUsecaseBase.run_test_body(self)

        # Check the battery capacity to 0%
        self._logger.info(
            "BEGIN OF THE TEST : Battery capacity is equal to %d%%" %
            self.batt_capacity)

        # if registration has been lost, register again
        if self.modem_api.get_network_registration_status() not in [
                "registered", "roaming"
        ]:
            self.__telmodule.register_to_network()
        # if fake number has been lost restore it here
        if self.__fake_emergency_phone_number not in self.modem_api.get_emergency_numbers(
        ):
            self.modem_api.set_emergency_numbers(
                [self.__fake_emergency_phone_number], False)
        # First Part, Check emergency call alone
        # establish voice call
        self._logger.info("Board is in MOS, Initiate the call !")
        self.voicecall_api.emergency_dial(self.__fake_emergency_phone_number)

        # Add the hands free
        if self.__hands_free_activation:
            self._logger.info("Activate the Speaker !")
            self.phonesystem_api.switch_audio_output("speaker")

        # Discharge the board
        return self.__discharge_when_data(0)

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

    def tear_down(self):
        """
        End and dispose the test
        """
        # call tear down after some operations
        EmUsecaseBase.tear_down(self)

        # release equipment
        self.__telmodule.release_eq()

        # clean the board state and retrieve logs
        self.em_core_module.clean_up()

        if self.is_board_and_acs_ok():
            # restore flight mode if it was turn off and previous test
            if self.__original_airplane_state:
                self.networking_api.set_flight_mode(True)

            if self.__initial_emergency_numbers is not None:
                # Restore the list of emergency number
                self.modem_api.set_emergency_numbers(
                    self.__initial_emergency_numbers, True)
                # Check the effect of the command
                if self.modem_api.get_emergency_numbers(
                ) != self.__initial_emergency_numbers:
                    txt = "Could not restore the list of emergency number"
                    self._logger.error(txt)
                    raise DeviceException(DeviceException.OPERATION_FAILED,
                                          txt)

        # restore the hands free
        if self.__hands_free_activation:
            self._logger.info("restore speaker")
            self.phonesystem_api.switch_audio_output("headset")

        return Global.SUCCESS, "No errors"

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

    def __discharge_when_data(self, min_capacity):
        """
        monitor the discharging by applying loads.
        can discharge until shutdown.

        :type min_capacity: int
        :param min_capacity: min battery capacity

        :rtype: int
        :return: battery capacity reached
        """
        self.update_battery_info()
        # find away to compute this
        timeout = 3600
        end_time = time.time() + timeout
        # discharge until 0% is reached
        last_capacity = self.batt_capacity
        capacity_increase_timeout = 900
        capa_inc_detect_once = False
        start_time_capacity_increase = time.time()

        while self.batt_capacity > min_capacity:

            try:
                # try to read measurement
                msic_reg = self.update_battery_info()
                thermal_conf = self.em_api.get_thermal_sensor_info()
                # store result on xml
                self.__em_meas_tab.add_dict_measurement(msic_reg)
                self.__em_meas_tab.add_dict_measurement(thermal_conf)
                # check call state
                call_state = self.voicecall_api.get_state()
                # pylint: disable=E1101
                if call_state == VOICE_CALL_STATE.NOCALL:
                    self._logger.warning(
                        "Call is OFF => Re-Activate the call !")
                    self.voicecall_api.emergency_dial(
                        self.__fake_emergency_phone_number)

                # Store various information
                self.__em_meas_tab.add_measurement([
                    ("REGISTRATION",
                     self.modem_api.get_network_registration_status()),
                    ("VOICE_CALL", str(call_state))
                ])

                # Detect if battery is charging, if it is the case stop usecase later
                if not capa_inc_detect_once:
                    if self.batt_capacity <= last_capacity:
                        start_time_capacity_increase = time.time()
                        capa_inc_detect_once = False
                    else:
                        capa_inc_detect_once = True

                else:
                    if self.batt_capacity < last_capacity:
                        start_time_capacity_increase = time.time()
                        capa_inc_detect_once = False

                last_capacity = self.batt_capacity

                # stop usecase if board take too long to reach battery capacity
                if time.time(
                ) - start_time_capacity_increase > capacity_increase_timeout:
                    tmp_txt = "board capacity keep increasing or not change during %ss instead of decreasing; abort usecase" % capacity_increase_timeout
                    self._logger.error(tmp_txt)
                    raise DeviceException(DeviceException.TIMEOUT_REACHED,
                                          tmp_txt)

            except AcsBaseException as e:
                # try to catch why uecmd may fail
                if not self.is_board_and_acs_ok():
                    txt = "connection with board lost during discharge to reach 0% of capacity"
                else:
                    txt = "error happened during discharge to reach 0% : " + str(
                        e)
                self._logger.error(txt)
                raise DeviceException(DeviceException.OPERATION_FAILED, txt)
            finally:
                # Store various information
                self.__em_meas_tab.add_measurement([
                    self.get_time_tuple(),
                    (self._em_cst.COMMENTS,
                     "RUNTEST:Discharging while emergency call is normally active"
                     )
                ])
                # switch meas to next meas
                self.__em_meas_tab.switch_to_next_meas()

            # stop usecase if board take too long to reach battery capacity
            if time.time() > end_time:
                tmp_txt = "Phone failed to reach 0%% of capacity before %ss" % (
                    timeout)
                self._logger.error(tmp_txt)
                raise DeviceException(DeviceException.TIMEOUT_REACHED, tmp_txt)

        # if we are here it means that capacity is at 0%, now checking if the call is still active
        call_state = self.voicecall_api.get_state()
        # pylint: disable=E1101
        if call_state != VOICE_CALL_STATE.ACTIVE:
            txt = "The call is not ACTIVE after reaching %s%% => Objective of UC is not reached => FAIL" % self.batt_capacity
            self._logger.error(txt)
            raise DeviceException(DeviceException.OPERATION_FAILED, txt)

        # now is call last when we are at critical level
        self._logger.info("Battery capacity is equal to %s%%" %
                          self.batt_capacity)
        # remove all potential cable that may supply the board
        self._device.disconnect_board()
        # disconnect usb
        self._io_card.usb_connector(False)
        self._logger.info(
            "test if the emergency call can hold %ss at battery critical level"
            % self.__call_timeout)
        time.sleep(self.__call_timeout)
        # connect to board
        self._io_card.usb_host_pc_connector(True)
        # connect board
        self._device.connect_board()
        # Check the board status

        if not self.is_board_and_acs_ok():
            text_cause = "The board status is not more seen at the end of the call lasting test"
            self._logger.error(text_cause)
            raise DeviceException(DeviceException.OPERATION_FAILED, text_cause)
        else:
            # get the call state------------------------------------------------------------------------
            self._logger.info("Check the call state !")
            call_state = self.voicecall_api.get_state()
            # pylint: disable=E1101
            if call_state != VOICE_CALL_STATE.ACTIVE:
                txt = "the call is not in ACTIVE state but in %s state after spending %ss at critical battery level " % (
                    str(call_state), self.__call_timeout)
                self._logger.error(txt)
                raise DeviceException(DeviceException.OPERATION_FAILED, txt)
            self.update_battery_info()

        # if we reach here it means that the test passed
        return Global.SUCCESS, "The call has been held in state %s during %ss" % (
            str(call_state), self.__call_timeout)
Exemplo n.º 30
0
class LabEmBattOverVoltage(EmUsecaseBase):

    """
    Lab Energy Management class.
    :TODO: change this usecase to be a voltage change UC, meaning that it can test voltage drop too.
    """
    DEDICATED_BENCH = "POWER_SUPPLY_BENCH"

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call Init function
        EmUsecaseBase.__init__(self, tc_name, global_config)

        # Read parameters from tc
        self.__vbatt_lo = self._tc_parameters.get_param_value("VBATT_LOW", default_cast_type=float)
        self.__vbatt_hi = self._tc_parameters.get_param_value("VBATT_HIGH" , default_cast_type=float)
        self.__charger_to_plug = self._tc_parameters.get_param_value("CHARGE_TYPE_DURING_TEST")
        self.__max_time_high = self._tc_parameters.get_param_value("MAX_TIME_TO_SEE_CHANGE_FOR_VBATT_HIGH", default_cast_type=int)
        self.__max_time_low = self._tc_parameters.get_param_value("MAX_TIME_TO_SEE_CHANGE_FOR_VBATT_LOW", default_cast_type=int)
        self.__set_board_in_idle = self._tc_parameters.get_param_value("IDLE_STATE", default_cast_type=str_to_bool)
        self.__idle_time = self._tc_parameters.get_param_value("TIME_TO_WAIT_AFTER_IDLE_STATE", default_value=0, default_cast_type=int)

        # load targets in order to compute verdict
        self._em_targets = self._target_file.parse_energy_management_targets(
            "LAB_EM_BATT_OVER_VOLTAGE", self._tc_parameters.get_params_as_dict(), self._device.get_phone_model())
        self._em_meas_verdict.load_target(self._em_targets, self.tcd_to_test)

        # Set initial value for setting Power Supply VBATT:
        # - VoltageLevel
        self.em_core_module.eqp_init_state["BATT"]["VoltageLevel"] = self.__vbatt_lo
        # measurement file
        meas_file_name = os.path.join(self._saving_directory, "EM_meas_report.xml")
        self.__em_meas_tab = XMLMeasurementFile(meas_file_name)

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

    def set_up(self):
        """
        Initialize the test:
        """
        EmUsecaseBase.set_up(self)
        # Set screen timeout to 30 minutes
        self.phonesystem_api.set_screen_timeout(60 * 60)
        return Global.SUCCESS, "No errors"

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

    def run_test_body(self):
        """
        Execute the test
        """
        # Call LAB_EM_BASE Run function
        EmUsecaseBase.run_test_body(self)
        self.em_api.clean_autolog()
        log_delay = 30
        extra_time_due_to_idle = 0
        if self.__set_board_in_idle == True:
            extra_time_due_to_idle = 20

        # compute test duration by adding some extra time to let the board see charge insertion
        test_duration = self.__max_time_low + self.__max_time_high + self.__idle_time + extra_time_due_to_idle + 30
        # choose function to put in logger
        self.em_api.add_fct_to_auto_logger(self.em_api.AUTOLOG_UEVENT, "sequenced")
        self.em_api.set_autolog_duration(test_duration)
        # start  non persistent autolog with a short period of data polling
        self.em_api.start_auto_logger(log_delay, 5, "sequenced")

        #---    SWITCH CHARGER         ------#
        start_time = time.time()
        self._device.disconnect_board()
        self.em_core_module.plug_charger(self.__charger_to_plug, ext_ps=True)
        time.sleep(self.usb_sleep)
        remaning_time = log_delay - (time.time() - start_time)
        if remaning_time > 0 :
            self._logger.info("wait %ss to sync measurement with the test beginning" % remaning_time)
            time.sleep(remaning_time)

        #--- VOLTAGE CAPACITY JUMP CASE ------#
        self.__voltage_jump()

        # sync the end of the test to avoid having measurement when data cable is plug back
        remaning_time = test_duration + log_delay + 50 - (time.time() - start_time)
        if remaning_time > 0 :
            self._logger.info("wait %ss to sync measurement with the test end" % remaning_time)
            time.sleep(remaning_time)

        #--- CONNECT DATA AND COLLECT EM INFO --#
        self._io_card.usb_host_pc_connector(True)
        time.sleep(self.usb_sleep)
        self._device.connect_board()
        if self.is_board_and_acs_ok():
            self.em_api.stop_auto_logger()
            # parse autolog response and reset them
            msic_list = self.em_api.get_autolog_msic_registers()
            self.em_api.clean_autolog()

            meas_length = len(msic_list)
            test_step = 0
            test_dict = ["EM_INFO_REF", "EM_INFO_HIGH", "EM_INFO_LOW"]

            for i in range(meas_length):
                try:
                    # get battery/charger info
                    msic_tuple = msic_list[i]
                    if len(msic_tuple) > 1:
                        msic_dict = msic_tuple[1]
                        #--- search for a good battery health proof as reference state --#
                        if test_step < len(test_dict):

                            self._meas_list.add_dict(test_dict[test_step], msic_dict)
                            if self._em_meas_verdict.test_list(self._meas_list, self._em_targets):
                                self._em_meas_verdict.compare_list(self._meas_list, self._em_targets, clean_meas_list=True)
                                test_step += 1

                            # case we reach the end of the measurement, we commit the last test step
                            if (i + 1) == meas_length:
                                self._em_meas_verdict.compare_list(self._meas_list, self._em_targets, clean_meas_list=True)

                        # store result on xml
                        self.__em_meas_tab.add_dict_measurement(msic_dict)
                finally:
                    self.__em_meas_tab.add_measurement(
                        [self.get_time_tuple(), (self._em_cst.COMMENTS,
                            "RUNTEST:battery voltage change")])
                    # switch meas to next meas
                    self.__em_meas_tab.switch_to_next_meas()

        # generate em verdict
        self._em_meas_verdict.judge()
        self._meas_list.clean()
        return self._em_meas_verdict.get_current_result_v2()

    def __voltage_jump(self):
        """
        this is when the vbatt suddenly jump from one value to another
        """
        # turn board in idle and ensure that it was done
        if self.__set_board_in_idle:

            idle_try = 2
            while idle_try > 0:
                ibatt_before_idle = self.em_core_module.get_battery_current()
                self._io_card.press_power_button(0.3)
                time.sleep(5)
                ibatt_after_idle = self.em_core_module.get_battery_current()
                if ibatt_after_idle[0] < ibatt_before_idle[0]:
                    break
                else:
                    self._logger.warning("it seems that the board did not went in idle : IBATT before %s, IBATT after %s" % (ibatt_before_idle, ibatt_after_idle))
                    idle_try -= 1
                    if idle_try <= 0:
                        tmp_txt = "board failed to be seen in idle : IBATT before %s, IBATT after %s" % (ibatt_before_idle, ibatt_after_idle)
                        self._logger.error(self +tmp_txt)
                        raise DeviceException(DeviceException.INVALID_DEVICE_STATE, tmp_txt)

            self._logger.info("Waiting %ss to go in idle mode" % self.__idle_time)
            # wait that board go in idle
            time.sleep(self.__idle_time)

        #------ get some reference values ---#
        ibatt_ref = self.em_core_module.get_battery_current()
        icharger_ref = self.em_core_module.get_charger_current(self._io_card.WALL_CHARGER)
        # store value for comparison
        self._meas_list.add("IBATT_REF", ibatt_ref)
        self._meas_list.add("ICHARGER_REF", icharger_ref)

        start_time = time.time()
        #---- set the vbatt to HIGH value ----#
        ibatt_high, icharger_high = self.__change_voltage(self.__vbatt_hi, ibatt_ref, self.__max_time_high)
        # store value for comparison
        self._meas_list.add("IBATT_HIGH", ibatt_high)
        self._meas_list.add("ICHARGER_HIGH", icharger_high)
        remaning_time = self.__max_time_high - (time.time() - start_time)
        if remaning_time > 0 :
            self._logger.info("wait %ss to let the board see the first voltage change" % remaning_time)
            time.sleep(remaning_time)

        start_time = time.time()
        #---- set the vbatt back to LOW value ----#
        ibatt_low, icharger_low = self.__change_voltage(self.__vbatt_lo, ibatt_high, self.__max_time_low)
        # store value for comparison
        self._meas_list.add("IBATT_LOW", ibatt_low)
        self._meas_list.add("ICHARGER_LOW", icharger_low)
        remaning_time = self.__max_time_low - (time.time() - start_time)
        if remaning_time > 0 :
            self._logger.info("wait %ss to let the board see the first voltage change" % remaning_time)
            time.sleep(remaning_time)

        self._em_meas_verdict.compare_list(self._meas_list, self._em_targets, clean_meas_list=True)

    def __change_voltage(self, vbatt, ref_ibatt, time_to_wait):
        """
        factorized code
        """
        self.em_core_module.set_battery_voltage(vbatt)
        # monitor a change on ibatt
        end_time = time.time() + time_to_wait
        while time.time() < end_time:
            # Measure current from Vbatt
            ibatt = self.em_core_module.get_battery_current()
            # if the product of the ibatt is negative , it means a drastically change has been done
            # and thus we can stop the measurement here
            if ibatt[0] * ref_ibatt[0] < 0:
                break
            time.sleep(1)

        # Measure ICHARGER
        icharger = self.em_core_module.get_charger_current(self._io_card.WALL_CHARGER)
        self._logger.info("VBATT set to voltage %s : IBatt = %s , ICharger= %s " % (vbatt, ibatt, icharger))
        return ibatt, icharger