コード例 #1
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
コード例 #2
0
    def tear_down(self):
        """
        End and dispose the test
        """
        # check the power supply health
        if self.__check_and_clean_ps_error(self.get_eq_emulated_battery(),
                                           True):
            self.get_eq_emulated_battery().configure_basic_parameters()

        # Set Battery temperature using BatteryTemperature parameter
        self._io_card.set_battery_temperature(25)

        # call tear down of the common base
        UcBatteryModule.tear_down(self)

        if self._device.get_boot_mode() != "MOS":
            # connect USB host pc
            self._logger.info(self.__LOG_TAG +
                              "Connect usb host and wait for board state")
            self._io_card.usb_host_pc_connector(True)
            # wait some second to check if there is a usb connection
            timeout = 40
            start_time = time.time()
            while (time.time() - start_time) < timeout:
                if self._device.get_boot_mode() == "MOS":
                    # wait some sec to settle down
                    time.sleep(self._uc_base.usb_sleep)
                    # connect board
                    self._device.connect_board()
                    break

        if self._device.get_boot_mode() == "MOS":
            self._device.connect_board()
            # Call Control battery capacity to avoid OCV effect
            # self.control_battery_capacity(20, 1000)
        else:
            # Configure power supply parameters
            self._configure_power_supply(self.ps_properties)
            self._io_card.usb_connector(False)
            # disconnect the battery
            self.__battery_connector(False)
            time.sleep(3)
            # connect the battery
            self.__battery_connector(True)
            time.sleep(10)
            self.__boot_board()

        self._logger.info(self.__LOG_TAG + " Cleaning created files on DUT...")
        # clean daemon files
        if self._uc_base.is_board_and_acs_ok():
            self._uc_base.phonesystem_api.clean_daemon_files()
            # get application logs
            self._uc_base.get_application_logs()
        return Global.SUCCESS, "No errors"
コード例 #3
0
class LabEmBattCheckChargingStatusWithLoad(EmUsecaseBase):
    """
    Lab Energy Management class.
    """
    DEDICATED_BENCH = "BATTERY_BENCH"

    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

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

    def set_up(self):

        EmUsecaseBase.set_up(self)

        # get the tested capacity
        batt_info = self.update_battery_info()

        # initial state is dut charge at max_range
        if self.em_core_module.is_batt_capacity_below_target(
                batt_info, self.__tested_capacity):
            self._logger.info("Device capacity is %s : going to %s" %
                              (self.batt_capacity, self.__tested_capacity))
            self.em_core_module.monitor_charging(self.__tested_capacity,
                                                 self.__time_to_charge,
                                                 self.__report_file_handler)
        else:
            self._logger.info("Device capacity is %s : going to %s" %
                              (self.batt_capacity, self.__tested_capacity))
            self.em_core_module.monitor_discharging(
                self.__tested_capacity,
                self.__time_to_discharge,
                self.__report_file_handler,
                load_module=self.__load_module)

        return Global.SUCCESS, "No errors"

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

    def run_test_body(self):

        EmUsecaseBase.run_test_body(self)

        status_list = []

        # clean autolog
        self.em_api.clean_autolog()

        # choose to log msic register in autolog
        self.em_api.add_fct_to_auto_logger(self.em_api.AUTOLOG_UEVENT,
                                           "sequenced")

        # set time to log
        self.em_api.set_autolog_duration(self.__time_to_log)

        # start the autologger we put a first delay to have time to unplugged usb_HOST
        self.em_api.start_auto_logger(self.__autolog_delay, 1, "sequenced")

        # start the load
        self.__load_module.start_load()

        # disconnect board
        self._device.disconnect_board()
        self._io_card.remove_cable("ALL")

        # plug charger
        self._io_card.simulate_insertion(self.__charger)

        # wait a while
        time.sleep(self.__time_to_log + self.__autolog_delay)

        # connect usb_HOST
        self._io_card.usb_host_pc_connector(True)

        # connect board
        self._device.connect_board()
        time.sleep(self.usb_sleep)

        # stop auto logger
        self.em_api.stop_auto_logger()

        # get the results
        msic_list = self.em_api.get_autolog_msic_registers()

        # check if tested status is seen
        for measure_index in range(len(msic_list)):
            status_list.append(
                msic_list[measure_index][1]['BATTERY']['STATUS'][0].upper())

        # fill autolog result in file
        self.em_core_module.fill_autolog_result(msic_list, [],
                                                self.__report_file_handler,
                                                "Results of autologger")

        # raise an error if status is not seen
        if self.__status not in status_list:
            msg = "Status %s not seen on plug" % self.__status
            raise DeviceException(DeviceException.OPERATION_FAILED, msg)

        return Global.SUCCESS, "No errors"

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

    def tear_down(self):

        EmUsecaseBase.tear_down(self)
        # stop load
        self.em_core_module.clean_up()
        self.__load_module.stop_load()

        return Global.SUCCESS, "No errors"
コード例 #4
0
    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        UseCaseBase.__init__(self, tc_name, global_config)
        self._overmind = None
        # init em stamp
        self.em_stamp = self._name
        self._uc_id_logged = False
        # override IO CARD with a not None type but not implemented type
        if self._io_card is None:
            self._io_card = IIOCard()

        # get em parameter from device catalog here
        self.phone_info = self._device.get_em_parameters()
        # feed the overmind
        self._overmind = OverMind()
        self._overmind.init(device=self._device,
                            tc_parameters=self._tc_parameters,
                            equipment_manager=self._em,
                            bench_config=global_config.benchConfig,
                            dut_config=self._dut_config)

        # Get uecmd api
        self.em_api = self._device.get_uecmd("EnergyManagement")
        self.phonesystem_api = self._device.get_uecmd("PhoneSystem")
        self.modem_api = self._device.get_uecmd("Modem")
        self.voicecall_api = self._device.get_uecmd("VoiceCall")
        self.networking_api = self._device.get_uecmd("Networking")
        self.bt_api = self._device.get_uecmd("LocalConnectivity")

        # init temperature chamber
        self._tct = self._tc_parameters.get_param_value("TCT",
                                                        default_cast_type=int)
        if self._tct is not None:
            self.tc_module = ThermalChamberModule(self._tct)
        else:
            self.tc_module = None

        # Each raw measurement data & xml files are
        # stored in a folder bearing the name
        # of the TC + a time stamp
        directory_name = self._name + "_" + time.strftime("%Y-%m-%d_%Hh%M.%S")
        report_tree = global_config.campaignConfig.get("campaignReportTree")
        self._saving_directory = report_tree.create_subfolder(directory_name)
        campaign_pass_rate = float(
            global_config.campaignConfig.get("targetB2bPassRate"))
        # resume file
        self._campaign_folder = report_tree.get_report_path()
        # verdict file
        self._em_meas_verdict = EMUtil.EMMeasurement(self._saving_directory,
                                                     campaign_pass_rate)

        # Call ConfigsParser to parse Energy_Management
        external_target_path = self._device.get_config("EMExternalTarget")
        if external_target_path is not None and os.path.exists(
                external_target_path):
            # Call ConfigsParser to parse Energy_Management
            self._logger.info("[EM BASE] External EM target file found : %s" %
                              external_target_path)
            self._target_file = ConfigsParser(external_target_path,
                                              config_folder="")
        else:
            # If no external target file , parse default one
            self._logger.info(
                "[EM BASE] No external target file found, use default EM target file"
            )
            self._target_file = ConfigsParser("Energy_Management")

        # Enable ACS secondary reports
        self._secondary_report = SecondaryTestReport(
            self._device.get_report_tree().get_report_path())

        # init variables
        # var for robustness
        self.start_time = time.time()
        self.__phone_date = ""
        self._ambient_temperature = 25
        self.phone_as_reboot = False
        self._consecutive_meas_error = 5
        # pylint: disable=W0212
        # Ignore used of protected member, will be change if a getter is created later
        self.pwr_btn_boot = self._device._prss_pwr_btn_time_switch_on
        self.pwr_btn_off = self._device._prss_pw_btn_time_switch_off

        # INIT PARAMETERS HERE
        # param related to usecase
        self._em_cst = EMUtil.EMConstant
        self._em_targets = None
        # add usb sleep for avoiding to lost connection during usb recognition
        self.usb_sleep = self._device._usb_sleep_duration  # pylint: disable=w0212

        # param related to device
        self.vbatt_mos_shutdown = self.phone_info["BATTERY"][
            "VBATT_MOS_SHUTDOWN"] + 0.1
        self.vbatt_mos_boot = self.phone_info["BATTERY"]["VBATT_MOS_BOOT"] + 0.1

        # param that are designed to be updated
        self.batt_capacity = -1
        self.batt_voltage = -1
        # measurement list where we store measurement inside
        self._meas_list = EMUtil.MeasurementList()

        # init core module at the end
        self.em_core_module = None
        bench_type = self._tc_parameters.get_param_value(
            "BENCH_TYPE", self.DEDICATED_BENCH).upper()
        if bench_type == "POWER_SUPPLY_BENCH":
            self.em_core_module = UcPowerSupplyModule(self)
        elif bench_type == "BATTERY_BENCH":
            self.em_core_module = UcBatteryModule(self)
        self._logger.info("Loaded EM TEST_SCRIPT configuration for %s" %
                          self.DEDICATED_BENCH)
        # get the list of TCD to test, it can have several entries
        # if the parameter is missing or empty ( meaning None) the old verdict system will be used.
        self.tcd_to_test = self._tc_parameters.get_param_value(
            EMConstant.TC_PARAMETER_TO_CHECK, "")
        if type(self.tcd_to_test) is str:
            self.tcd_to_test = filter(None, self.tcd_to_test.split(";"))
            self.tcd_to_test = map(str.strip, self.tcd_to_test)
コード例 #5
0
class EmUsecaseBase(UseCaseBase):
    """
    Lab Energy Management base class.
    """
    # by default test are set to be run with only normal battery
    DEDICATED_BENCH = "BASIC_BENCH"

    def __init__(self, tc_name, global_config):
        """
        Constructor
        """
        # Call UseCase base Init function
        UseCaseBase.__init__(self, tc_name, global_config)
        self._overmind = None
        # init em stamp
        self.em_stamp = self._name
        self._uc_id_logged = False
        # override IO CARD with a not None type but not implemented type
        if self._io_card is None:
            self._io_card = IIOCard()

        # get em parameter from device catalog here
        self.phone_info = self._device.get_em_parameters()
        # feed the overmind
        self._overmind = OverMind()
        self._overmind.init(device=self._device,
                            tc_parameters=self._tc_parameters,
                            equipment_manager=self._em,
                            bench_config=global_config.benchConfig,
                            dut_config=self._dut_config)

        # Get uecmd api
        self.em_api = self._device.get_uecmd("EnergyManagement")
        self.phonesystem_api = self._device.get_uecmd("PhoneSystem")
        self.modem_api = self._device.get_uecmd("Modem")
        self.voicecall_api = self._device.get_uecmd("VoiceCall")
        self.networking_api = self._device.get_uecmd("Networking")
        self.bt_api = self._device.get_uecmd("LocalConnectivity")

        # init temperature chamber
        self._tct = self._tc_parameters.get_param_value("TCT",
                                                        default_cast_type=int)
        if self._tct is not None:
            self.tc_module = ThermalChamberModule(self._tct)
        else:
            self.tc_module = None

        # Each raw measurement data & xml files are
        # stored in a folder bearing the name
        # of the TC + a time stamp
        directory_name = self._name + "_" + time.strftime("%Y-%m-%d_%Hh%M.%S")
        report_tree = global_config.campaignConfig.get("campaignReportTree")
        self._saving_directory = report_tree.create_subfolder(directory_name)
        campaign_pass_rate = float(
            global_config.campaignConfig.get("targetB2bPassRate"))
        # resume file
        self._campaign_folder = report_tree.get_report_path()
        # verdict file
        self._em_meas_verdict = EMUtil.EMMeasurement(self._saving_directory,
                                                     campaign_pass_rate)

        # Call ConfigsParser to parse Energy_Management
        external_target_path = self._device.get_config("EMExternalTarget")
        if external_target_path is not None and os.path.exists(
                external_target_path):
            # Call ConfigsParser to parse Energy_Management
            self._logger.info("[EM BASE] External EM target file found : %s" %
                              external_target_path)
            self._target_file = ConfigsParser(external_target_path,
                                              config_folder="")
        else:
            # If no external target file , parse default one
            self._logger.info(
                "[EM BASE] No external target file found, use default EM target file"
            )
            self._target_file = ConfigsParser("Energy_Management")

        # Enable ACS secondary reports
        self._secondary_report = SecondaryTestReport(
            self._device.get_report_tree().get_report_path())

        # init variables
        # var for robustness
        self.start_time = time.time()
        self.__phone_date = ""
        self._ambient_temperature = 25
        self.phone_as_reboot = False
        self._consecutive_meas_error = 5
        # pylint: disable=W0212
        # Ignore used of protected member, will be change if a getter is created later
        self.pwr_btn_boot = self._device._prss_pwr_btn_time_switch_on
        self.pwr_btn_off = self._device._prss_pw_btn_time_switch_off

        # INIT PARAMETERS HERE
        # param related to usecase
        self._em_cst = EMUtil.EMConstant
        self._em_targets = None
        # add usb sleep for avoiding to lost connection during usb recognition
        self.usb_sleep = self._device._usb_sleep_duration  # pylint: disable=w0212

        # param related to device
        self.vbatt_mos_shutdown = self.phone_info["BATTERY"][
            "VBATT_MOS_SHUTDOWN"] + 0.1
        self.vbatt_mos_boot = self.phone_info["BATTERY"]["VBATT_MOS_BOOT"] + 0.1

        # param that are designed to be updated
        self.batt_capacity = -1
        self.batt_voltage = -1
        # measurement list where we store measurement inside
        self._meas_list = EMUtil.MeasurementList()

        # init core module at the end
        self.em_core_module = None
        bench_type = self._tc_parameters.get_param_value(
            "BENCH_TYPE", self.DEDICATED_BENCH).upper()
        if bench_type == "POWER_SUPPLY_BENCH":
            self.em_core_module = UcPowerSupplyModule(self)
        elif bench_type == "BATTERY_BENCH":
            self.em_core_module = UcBatteryModule(self)
        self._logger.info("Loaded EM TEST_SCRIPT configuration for %s" %
                          self.DEDICATED_BENCH)
        # get the list of TCD to test, it can have several entries
        # if the parameter is missing or empty ( meaning None) the old verdict system will be used.
        self.tcd_to_test = self._tc_parameters.get_param_value(
            EMConstant.TC_PARAMETER_TO_CHECK, "")
        if type(self.tcd_to_test) is str:
            self.tcd_to_test = filter(None, self.tcd_to_test.split(";"))
            self.tcd_to_test = map(str.strip, self.tcd_to_test)

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

    def get_application_logs(self):
        """
        get the log from the board, zip it and store it on usecase result.
        """
        pulled_files = []
        directory = os.path.join(
            self._saving_directory,
            "aplogs_" + time.strftime("%Y-%m-%d_%Hh%M.%S"))
        # create the destination directory
        if not os.path.exists(directory):
            os.mkdir(directory)

        # try to pull application log from tag
        if self._uc_id_logged:
            pulled_files = self._device.get_application_logs(
                directory, self.em_stamp)

        # if fail to pull file for any reason then pull all file
        if pulled_files is None or len(pulled_files) == 0:
            # if tag not found pull all logs
            pulled_files = self._device.get_application_logs(directory)

        # zip only if there is file to zip
        if pulled_files is not None and len(pulled_files) > 0:
            archive_util.make_archive(directory, "zip", root_dir=directory)
            time.sleep(1)
            shutil.rmtree(directory, ignore_errors=True)
            if os.path.isdir(directory):
                self._logger.warning("fail do delete tempdir %s" % directory)

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

    def get_time_tuple(self):
        """
        return a tuple for logging time in xml measurement.
        Time will be evaluate in hours.

        :rtype: tuple
        :return: (str name, float value, str unit)
        """
        result = (self._em_cst.TIME_TAG,
                  (time.time() - self.start_time) / 3600, self._em_cst.HR)
        return result

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

    def get_time_from_board(self):
        """
        get the time from the board itself.

        :rtype: int
        :return: time taken from the board in seconds
        """
        result = self.phonesystem_api.get_date()
        time_tuple = time.strptime(result, "%Y %m-%d %H:%M:%S")
        return int(time.mktime(time_tuple))

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

    def update_battery_info(self):
        """
        launch command to get battery info , return them as dict
        also update protected var that target voltage & capacity

        :rtype: dict
        :return: uevent charger & battery info
        """
        result = self.em_api.get_msic_registers()
        self.batt_capacity = result["BATTERY"]["CAPACITY"][0]
        self.batt_voltage = result["BATTERY"]["VOLTAGE"][0]
        return result

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

    def is_board_and_acs_ok(self):
        """
        check if board is alive and ACS connected

        :rtype: bool
        :return: True if all is ok to communicate with board, False otherwise
        """
        result = False
        if self._device.get_boot_mode() == "MOS" and self._device.is_available(
        ):
            result = True

        return result

    def has_board_reboot(self):
        """
        check if board is alive and has rebooted

        :rtype: bool
        :return: True if board rebooted, False otherwise
        """
        result = False
        if self.phone_as_reboot and self._device.get_state() == "alive":
            result = True

        return result
#------------------------------------------------------------------------------

    def _wait_smart_time(self, origin, time_used_for_schedule_cmd):
        """
        Function used to wait a judicious time and let the read of the msic register to be executed.
        """
        now = time.time()
        safety_timer = 8
        if now < (origin + time_used_for_schedule_cmd + safety_timer):

            time2wait = int((origin + time_used_for_schedule_cmd +
                             safety_timer) - now)

            if time2wait > time_used_for_schedule_cmd + safety_timer:
                # this should never occurs
                self._logger.warning("Timer computing error " +
                                     "(time used for schedule cmd: %d)" %
                                     time_used_for_schedule_cmd)
                time2wait = time_used_for_schedule_cmd + safety_timer

            self._logger.debug(
                "waiting %s second(s) remaining to elapse the %s s timer" %
                (time2wait, time_used_for_schedule_cmd))
            time.sleep(time2wait)

        else:
            self._logger.debug("waiting 0 second(s) to elapse the %s s timer" %
                               time_used_for_schedule_cmd)

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

    def set_up(self):
        """
        setup is designed to be done only once
        put here settings that persist all along a test like :
         - equipment connection and configuration.
         - turning on feature
        """
        # before all, update and inject EM stamp
        self.em_stamp = self._name + time.strftime("-%Y-%m-%d_%Hh%M.%S")
        self._uc_id_logged = self._device.inject_device_log(
            "i", self._em_cst.EM_INJECT_TAG, self.em_stamp)
        # Call the UseCaseBase Setup function
        UseCaseBase.set_up(self)
        self.em_core_module.set_up()

        # temperature settings
        if self.tc_module is not None and self.tc_module.is_default_test():
            self.tc_module.set_up_eq()
            self.tc_module.adjust_temp_according_to_test_value()
        # one shot measurement
        if self._device.get_state() == "alive":
            # reset reboot var
            self.phone_as_reboot = False
        return Global.SUCCESS, "No errors"

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

    def run_test(self):
        """
        the heart of your test.
        measurement should be done in this function.
        No test clean should be on it except if it is need by the test steps.
        """
        UseCaseBase.run_test(self)

        # temperature settings
        if self.tc_module is not None and self.tc_module.is_default_test():
            self.tc_module.adjust_temp_according_to_current_value()

        # implementation for B2B continuous
        # Do before_runtest without a try, if it can't be done then the DUT must be KO
        self.run_test_start()
        result = Global.FAILURE
        result_msg = ""
        import traceback
        try:
            result, result_msg = self.run_test_body()
        # the warning is known and left here to remember it
        except Exception as ee:
            _, exc_tb = sys.exc_info()[1:]
            self._logger.error("Error happen in RUN TEST BODY : %s" % str(ee))
            self._logger.error(str(traceback.format_tb(exc_tb)))
            self._logger.error(
                "Trying to execute RUN TEST STOP before finishing test")
            result_msg = str(ee)
        finally:
            # in any case do a cleaning
            try:
                self.run_test_stop()
                # the warning is known and left here to remember it
            except Exception as e:
                _, exc_tb = sys.exc_info()[1:]
                self._logger.error("Exception during RUN TEST BODY: %s" %
                                   str(e))
                self._logger.error(str(traceback.format_tb(exc_tb)))

        return result, result_msg

    def run_test_start(self):
        """
        put here non persistent settings like:
        - feature which need to be set again after a reboot
        - initialization of a boolean
        - establish a call
        """
        # Reset the global result
        self._logger.debug("\tRUN TEST BEGIN")
        self._em_meas_verdict.reset_current_verdict()

    def run_test_body(self):
        """
        the heart of your test.
        measurement should be done in this function.
        No test clean should be on it except if it is need by the test steps.
        """
        self._logger.debug("\tRUN TEST BODY")
        return Global.SUCCESS, "No actions"

    def run_test_stop(self):
        """
        put here temporary cleaning like :
        - emptying folder
        - reboot the board if KO
        - equipment settings necessary to re apply settings on before_runtest
        - verdict computing
        """
        self._logger.debug("\tRUN TEST END")

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

    def tear_down(self):
        """
        tear down is here to clean your test for next testcase
        put here final cleaning like:
        - equipment release
        - board charging

        """
        # Call the UseCaseBase tear down function
        UseCaseBase.tear_down(self)
        self.em_core_module.tear_down()

        # sink last measurement and reset meas_dict
        self._em_meas_verdict.compare_list(self._meas_list, self._em_targets,
                                           True)
        self._em_meas_verdict.judge()

        # feed awr secondary reports
        result = self._em_meas_verdict.get_local_result_v2()
        self._secondary_report.add_result_from_dict(result, self.get_name(),
                                                    self.tc_order)
        # feed TCR
        LiveReporting.instance().update_running_tc_info(test_info=result)

        if self.tc_module is not None and self.tc_module.is_default_test():
            self.tc_module.release_eq()

        return Global.SUCCESS, "No errors"

    def finalize(self):
        UseCaseBase.finalize(self)
        if self._overmind is not None:
            del self._overmind

        return Global.SUCCESS, "No errors"
コード例 #6
0
    def set_up(self):
        """
        Initialize the test
        """
        # Call the setup from inheritance
        UcBatteryModule.set_up(self)
        action_on_battery = False

        if self.ps_properties == {}:
            raise AcsConfigException(
                AcsConfigException.INVALID_BENCH_CONFIG,
                "Energy Management use cases are not functional without Power Supply !"
            )

        if self._patlib is not None:
            self._patlib.configure(self._pat_file)

        # check the power supply health
        self.__check_and_clean_ps_error(self.get_eq_emulated_battery(), False)

        # Configure power supply parameters
        # TODO: this redundant action should be done once
        self._configure_power_supply(self.eqp_init_state)

        # Set Battery temperature using BatteryTemperature parameter
        self._io_card.set_battery_temperature(
            self.io_card_init_state["BatteryTemperature"])

        # TODO: need to check if there is a delta between init value and current value

        # SET INITIAL STATE ON IO CARD
        # Insert/Remove battery using Battery parameter
        self._logger.info("set up: batt_state = %s ; batt_expected = %s" %
                          (str(self._io_card.get_battery_state()),
                           self.io_card_init_state["Battery"]))
        self._logger.info(
            "set up: current battery type = %s ; type_expected = %s" %
            (str(self._io_card.get_battery_type()),
             self.io_card_init_state["BatteryType"]))
        if (self._io_card.get_battery_state() != self.io_card_init_state["Battery"]) or \
                (self.io_card_init_state["BatteryType"] != self._io_card.get_battery_type()):

            self._logger.info(
                "set up: wanted battery type %s - wanted state %s" %
                (self.io_card_init_state["BatteryType"],
                 self.io_card_init_state["Battery"]))
            self.__switch_battery_type()
            if self.io_card_init_state["Battery"] == True:
                self.__stablized_inserted_batt()
            action_on_battery = True

        # Platform CANT be ON without a battery in most of case but some DUT can accept that.
        if self.io_card_init_state["Platform"] == "ON":
            # Initialize Variable

            # boot board
            self.__boot_board()

            # CHECK BATTERY IDENTIFICATION
            if self._uc_base.is_board_and_acs_ok():
                is_valid_batt = self.__check_battery_is_valid()
                if not is_valid_batt:
                    txt = "Battery is not recognized as expected %s by the DUT, cant do the test" % self.battery_type
                    self._logger.error(self.__LOG_TAG + txt)
                    raise AcsConfigException(
                        AcsConfigException.OPERATION_FAILED, txt)
                else:
                    self._logger.info("Expected battery type seen")
                    # Log test id to logcat to retrieve application log from here
                    if not self._uc_id_logged:
                        self._uc_id_logged = self._device.inject_device_log(
                            "i", self._em_cst.EM_INJECT_TAG,
                            self._uc_base.em_stamp)
                        self._device.inject_device_log("i", "ACS_TESTCASE",
                                                       "SETUP")

        # Else turn off board
        elif self.io_card_init_state["Platform"] == "OFF":
            boot_mode = self._device.get_boot_mode()
            if boot_mode != "UNKNOWN":
                if not self._uc_id_logged:
                    # log testcase tag
                    self._uc_id_logged = self._device.inject_device_log(
                        "i", self._em_cst.EM_INJECT_TAG,
                        self._uc_base.em_stamp)

                self.__shutdown()
            else:
                # TODO: we know that an action on battery mean to have perform a shutdown and remove the charger
                if not action_on_battery:
                    self.__shutdown()

        return Global.SUCCESS, "No errors"
コード例 #7
0
    def __init__(self, uc_base):
        """
        Constructor
        """
        UcBatteryModule.__init__(self, uc_base)
        # Var common to all usecase, these warning are known
        # and cant be remove without changing framework var
        global_config = self._uc_base._global_conf
        self._em = self._uc_base._em
        self._uc_id_logged = self._uc_base._uc_id_logged
        self._execution_config_path = self._uc_base._execution_config_path

        # Get the path of execution config folder
        self._patlib = None
        self.eqp_init_state = {}
        self.ps_properties = {}
        # Get pwr supply config file folder from BenchConfig.xml
        self.vbatt = None
        self.vusb = None
        self.vac = None
        self.resistance = None

        # Get pwr supply config file folder from BenchConfig.xml
        # Read POWER_SUPPLY attributes
        # (Vbatt, Vusb, Vacc...) from BenchConfig.xml:
        #     - Instance of the service
        #     - PortNumber
        #     - CurrentLevel
        #     - VoltageLevel
        #     - VoltageProtectLevel

        for equipment_name in global_config.benchConfig.get_parameters_name():
            if "POWER_SUPPLY" not in equipment_name:
                continue

            pwrs = global_config.benchConfig.get_parameters(equipment_name)
            ps_type = pwrs.get_param_value("Model")
            # Get power supply properties if its type is not NONE
            if ps_type in ["NONE", None]:  # no output to configure
                continue

            for attr_name in pwrs.get_parameters_name():
                if "OUTPUT" not in attr_name:
                    continue

                out_p = pwrs.get_parameters(attr_name)
                out_t = out_p.get_param_value("Type")

                if "ACCHG" in out_t:
                    continue

                if out_t == "BATT":
                    self.vbatt = float(str(out_p.get_param_value("Voltage")))
                    self.resistance = float(pwrs.get_param_value("Resistance"))
                if out_t == "USB":
                    self.vusb = float(str(out_p.get_param_value("Voltage")))
                if out_t == "AC":
                    self.vac = float(str(out_p.get_param_value("Voltage")))

                # Get output properties if its name is not NONE
                if out_t == "NONE":
                    continue

                # For each output create an entry of ps_properties dictionary
                self.ps_properties[out_t] = {
                    "PortNumber":
                    int(out_p.get_param_value("PortNumber")),
                    "CurrentLevel":
                    float(str(out_p.get_param_value("MaxCurrent"))),
                    "VoltageLevel":
                    float(str(out_p.get_param_value("Voltage"))),
                    "VoltageProtectLevel":
                    float(str(pwrs.get_param_value("VoltageProtectLevel")))
                }

                self.eqp_init_state[out_t] = {
                    "PortNumber":
                    int(out_p.get_param_value("PortNumber")),
                    "CurrentLevel":
                    float(str(out_p.get_param_value("MaxCurrent"))),
                    "VoltageLevel":
                    float(str(out_p.get_param_value("Voltage"))),
                    "VoltageProtectLevel":
                    float(str(pwrs.get_param_value("VoltageProtectLevel")))
                }
        # Set initial value for setting IO_CARD:
        self.io_card_init_state = {
            # the one from device model
            "BatteryType": self._uc_base.phone_info["BATTERY"]["BATTID_TYPE"],
            # battery plug platform ON
            "Battery": True,
            "Platform": "ON",
            "BatteryTemperature": 25
        }

        # GET THE EQUIPMENT DRIVER
        # use PAT if enable rather than power supply to measure
        if "POWER_ANALYZER_TOOL" in global_config.benchConfig.get_parameters_name(
        ):
            try:
                self._patlib = self._em.get_power_analyzer_tool(
                    "POWER_ANALYZER_TOOL")
                pat_node = global_config.benchConfig.get_parameters(
                    "POWER_ANALYZER_TOOL")
                self._pat_file = os.path.join(
                    self._execution_config_path,
                    pat_node.get_param_value("ConfFile"))

            except ImportError as error:
                self._logger.error(self.__LOG_TAG +
                                   " PAT is declared in your benchconfig but" +
                                   " can't be imported: %s" % str(error))

        # VBATT and VUSB VAC power supplies

        self.__pwrs_vusb = None
        self.__pwrs_vac = None
        self.__pwrs_vbatt = self._em.get_power_supply("BATT")
        if "USB" in self.eqp_init_state.keys():
            self.__pwrs_vusb = self._em.get_power_supply("USB")
        if "AC" in self.eqp_init_state.keys():
            self.__pwrs_vac = self._em.get_power_supply("AC")

        # # allow overriding of some parameters
        self.vbatt = self._tc_parameters.get_param_value(
            "VBATT", self.vbatt, default_cast_type=float)
        self.vusb = self._tc_parameters.get_param_value(
            "VUSB", self.vusb, default_cast_type=float)
        self.battery_type = self._tc_parameters.get_param_value(
            "BATTERY_TYPE", self._uc_base.phone_info["BATTERY"]["BATTID_TYPE"])
        self.battery_temperature = int(
            self._tc_parameters.get_param_value("BATTERY_TEMPERATURE", 25))

        # set a default value for platform state
        # below dictionary is used to set the start condition
        # if you want to override start condition , you need to edit this entry on your usecase
        # some of these condition can be override from test case params
        self.io_card_init_state["BatteryType"] = self.battery_type
        self.io_card_init_state[
            "BatteryTemperature"] = self.battery_temperature
        self.io_card_init_state["Battery"] = True
        # Platform ON mean board in MOS with data cable plugged
        # Platform OFF mean board OFF and no cable plugged
        self.io_card_init_state["Platform"] = "ON"

        # init common em parameters:
        self._boot_tries = 3
        self.wait_voltage_time = 120