def audio_streaming_monitor_function(self): # Listen for silence # Do it again start_time = time.time() # Subtract 30 seconds from runtime because we generally have to wait some time to ensure audio playback has started. runtime_seconds = (self._pars.duration * 60) - 30 loop_iteration = 0 test_passed = True # Start with True. Change to false on failure. while time.time() - start_time < runtime_seconds: loop_iteration += 1 self._logger.info(self._pars.id + ": Loop %d" % loop_iteration) self._logger.debug(self._pars.id + ": Listening for silence on the PC line in.") audio_output_file = os.path.join( self.report_path, "captured_audio_%d.mp3" % loop_iteration) self._logger.info(self._pars.id + ": Saving audio capture data to %s" % audio_output_file) # To keep from timing out in the app and to keep our wav files at a manageable size, limit listen_time to something less than 30 minutes. Especially in longer test runs. listen_time = runtime_seconds - (time.time() - start_time) if listen_time > self._pars.listen_length * 60: listen_time = self._pars.listen_length * 60 try: silence_offsets = audio_verification.verify_audio_input( output_file_path=audio_output_file, silence_threshold_seconds=self._pars. silence_threshold_length, silence_callback_func=self.debug_silence_in_new_thread, audio_resume_callback_func=None, listen_len_seconds=listen_time, silence_threshold=self._pars.silence_threshold_raw) except IOError as e: self._logger.debug( self._pars.id + ": I/o error({0}) from verify_audio_input: {1}".format( e.errno, e.strerror)) raise except: self._logger.debug( self._pars.id + ": Unexpected error occured from verify_audio_input\n" + traceback.format_exc()) raise if len(silence_offsets) > 0: silence_offset_str = "" for offset_pair in silence_offsets: silence_begin_minutes = int(offset_pair[0] / 60) silence_begin_seconds = int(offset_pair[0] - (silence_begin_minutes * 60)) silence_end_minutes = int(offset_pair[1] / 60) silence_end_seconds = int(offset_pair[1] - (silence_end_minutes * 60)) silence_offset_str += "%d:%02d-%d:%02d, " % ( silence_begin_minutes, silence_begin_seconds, silence_end_minutes, silence_end_seconds) # Remove the comma at the end silence_offset_str = silence_offset_str[:-2] self._logger.error(self._pars.id + ": Silence detected at offset " + silence_offset_str) self._logger.error( self._pars.id + ": Setting test result to FAIL due to silence detected.") test_passed = False self._logger.debug(self._pars.id + ": End of monitoring loop.") if test_passed: self._logger.info(self._pars.id + ": Monitoring loop passed!") else: self._logger.error(self._pars.id + ": Monitoring loop failed!!") self.ts_verdict_msg = self._pars.id + ": Monitoring loop failed!!" raise DeviceException( DeviceException.OPERATION_FAILED, self._pars.id + ": Test has failed while monitoring audio!")
def parse_msic_response_from_shell(self, output, log_output=True): """ Parses the response gotten from the get shell msic register in order to extract the following parameters: The function return at most 2 dictionaries (for battery and charger info) Each object in the returned dictionary is a dictionary build from the "tag=value" parsed line format :type output: str :param output: output result from msic registers embd uecmd :type log_output: boolean :param log_output: allow output logging , used to avoid spaming log on autolog :rtype: dict :return: a dictionary that contains the msic battery and charger info """ msic_register = {} battery = {} charger = {} try: document = etree.fromstring(output.strip()) except etree.Error as e: tmp_txt = "failed to parse msic uecmd response: " + str(e) self.logger.error(tmp_txt) self.logger.error("output file parsed :\n" + output.strip()) raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt) tmp_txt = "" # check potential error first if document is None: tmp_txt = "parsing uevent msic info contains no information" self.logger.error(tmp_txt) raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt) # check battery info battery_info = document.findtext("BATTERY") if battery_info is not None: battery_info = str(battery_info).strip().split("\n") else: tmp_txt += "parsing uevent battery info contains no information." # check charger info charger_info = document.findtext("CHARGER") if charger_info is not None: charger_info = str(charger_info).strip().split("\n") else: tmp_txt += "parsing uevent charger info contains no information." if tmp_txt != "": self.logger.error(tmp_txt) raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt) # get time stamp cosmetic_text = "" time_stamp = document.findtext("TIME_STAMP") if time_stamp is not None: time_stamp = str(time_stamp).replace("\n", "").strip() msic_register.update({"TIME_STAMP": (str(time_stamp), "none")}) if log_output: cosmetic_text = "[GENERAL info]:\n" cosmetic_text += " TIME_STAMP = " + str(time_stamp) + "\n" else: msic_register.update({"TIME_STAMP": ("Failed to get", "none")}) # get charger info for element in charger_info: # clean the element element = element.strip() element = element.split("=", 1) # if no '=' found skip this element if len(element) != 2: continue tag = element[0].strip().upper() value = element[1].strip() tag = sub('^POWER_SUPPLY_', '', tag) if tag == "CHARGE_VOLTAGE": charger["VOLTAGE"] = (float(value) / 1000, "V") elif tag in [ "MAX_CHARGING_CURRENT", "INPUT_CUR_LIMIT", "MAX_CHARGE_CURRENT" ]: temp_tag = tag if tag == "MAX_CHARGE_CURRENT": temp_tag = 'MAX_CHARGING_CURRENT' charger[temp_tag] = (float(value) / 1000, "A") elif tag == "CHARGE_CURRENT": charger["CURRENT"] = (float(value) / 1000, "A") elif tag in ["ENABLE_CHARGER", "ENABLE_CHARGING"]: charger[tag] = (int(value), "none") else: charger[tag] = (str(value), "none") msic_register.update({"CHARGER": charger}) if log_output: cosmetic_text += "[CHARGER info]:\n" for key in sorted(charger.keys()): value = charger[key] cosmetic_text += " " + key + " = " + str(value[0]) if value[1] != "none": cosmetic_text += " " + str(value[1]) cosmetic_text += "\n" # get battery info for element in battery_info: # clean the element element = element.strip() element = element.split("=", 1) # if no '=' found skip this element if len(element) != 2: continue tag = element[0].strip().upper() value = element[1].strip() tag = sub('^POWER_SUPPLY_', '', tag) if tag in ["CAPACITY"]: battery[tag] = (int(value), "none") # voltage tag elif tag in [ "VOLTAGE_AVG", "VOLTAGE_MIN_DESIGN", "VOLTAGE_NOW", "VOLTAGE_OCV" ]: battery[tag] = (float(value) / 1000000, "V") elif tag in ["CURRENT_AVG", "CURRENT_NOW"]: battery[tag] = (float(value) / 1000000, "A") elif tag in ["CHARGE_NOW", "CHARGE_FULL", "CHARGE_FULL_DESIGN"]: battery[tag] = (int(value), "C") elif tag == "TEMP": battery[tag] = (int(value) / 10, "DegreeCelsius") elif tag == "STATUS": battery[tag] = (str(value).upper(), "none") else: battery[tag] = (str(value), "none") # harmonized tag name into one tag, first look for OCV else look for NOW if "VOLTAGE_OCV" in battery: battery["VOLTAGE"] = battery["VOLTAGE_OCV"] elif "VOLTAGE_OCV" in battery: battery["VOLTAGE"] = battery["VOLTAGE_NOW"] msic_register.update({"BATTERY": battery}) if log_output: cosmetic_text += "[BATTERY info]:\n" for key in sorted(battery.keys()): value = battery[key] cosmetic_text += " " + key + " = " + str(value[0]) if value[1] != "none": cosmetic_text += " " + str(value[1]) cosmetic_text += "\n" if log_output: self.logger.debug(cosmetic_text) # check vital key on msic_register vital_key = ["CAPACITY", "CURRENT_NOW", "VOLTAGE", "STATUS"] if "BATTERY" not in msic_register or \ not set(vital_key).issubset(msic_register["BATTERY"].keys()): tmp_txt = "missing vital BATTERY keys on msic registers: %s" % vital_key self.logger.error(tmp_txt) raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt) return msic_register
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") bk_duration = self.__benchmark_module.get_exec_whole_duration() self._logger.info("Monitoring temperature during a total duration of %ss " % bk_duration) # do the monitoring job tmpd = tempfile.gettempdir() maxt = self.__temp_camera.get_measurement_from_box()["MAXT"] last_max_temp_seen = maxt[0] unit = maxt[1] pic_nb = 0 max_temp_list = [] 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 with temperature recording" % str(delay_left)) time.sleep(delay_left) start_time = time.time() while time.time() - start_time < bk_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_benchmark") pic_exte = os.path.splitext(pic_path)[1] final_file_name = "max_during_benchmark_" + str(pic_nb) if pic_exte != "": final_file_name += "." + pic_exte host_pic_path = self.__temp_camera.pull_picture(pic_path, tmpd, final_file_name) max_temp_list.append((max_temp, host_pic_path, time.time())) last_max_temp_seen = max_temp pic_nb += 1 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: benchmark execution")]) 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) time.sleep(1) stop_time = time.time() # reconnect usb cable verdict_msg = "" 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) # first that there were no crashes and that all iterations have been done 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)) bk_expected_iter = -1 if self.__benchmark_module.is_based_on_iteration(): bk_expected_iter = self.__benchmark_module.get_expected_iter() iteration, _ = self.__benchmark_module.get_last_complete_iter() if iteration < bk_expected_iter: error_msg = "benchmark iteration failed to iter the expected %s time, only %s iteration seen" % (bk_expected_iter, iteration) self._logger.error(error_msg) raise DeviceException(DeviceException.OPERATION_FAILED, error_msg) # 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)) # get execution info to see if all benchmark run has been done verdict = Global.FAILURE # search for the picture that match with the right data if len (max_temp_list) > 0: for temp, pic, pic_time in reversed(max_temp_list): # check that the measurement time was done at or before the benchmark test end # if based on a iteration number , we consider only picture taken during the benchmark run if (self.__benchmark_module.is_based_on_iteration() and pic_time > (start_time + bk_duration)): verdict_msg = "the picture date was done after the benchmark iteration end, cant compute result!" continue # otherwise we consider all picture move(pic, self.__pic_folder) verdict_msg = "The ref temperature when board is OFF was at %s %s.\n" % (self.__ref_temp, unit) if self.__benchmark_module.is_based_on_iteration(): verdict_msg += "The max temperature seen on the DUT during %s iteration of benchmark execution is %s %s" % (bk_expected_iter, temp, unit) else: verdict_msg += "The max temperature seen on the DUT during %ss of benchmark execution is %s %s" % (bk_duration, temp, unit) if temp > self.__temp_target : verdict_msg += " which is above" else: verdict_msg += " which is below or equal to" verdict = Global.SUCCESS verdict_msg += " the target not to exceed : %s degree" % (self.__temp_target) break else: verdict_msg = "the temperature before starting the test was at %s %s and was never exceed during the test, something may went wrong during your test" % (last_max_temp_seen, unit) if warning_crash : verdict_msg = "A crash happened but it was after the test end, result can be computed." + verdict_msg verdict_msg += "\nBenchmark scores may be seen in file %s" % self.__benchamrk_tab.get_report_path() self._logger.info(verdict_msg) return verdict, verdict_msg
""" Runs the test step @type context: TestStepContext @param context: test case context """ DeviceTestStepBase.run(self, context) date_format = "%Y-%m-%d" time_format = "%H:%M:%S" if self._pars.date_format not in ["", None]: date_format = self._pars.date_format if self._pars.time_format not in ["", None]: time_format = self._pars.time_format try: date = datetime.strptime(self._pars.date, date_format).date() except ValueError, e: raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, "Bad date format : {0}".format(e.message)) try: time = datetime.strptime(self._pars.time, time_format).time() except ValueError, e: raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, "Bad time format : {0}".format(e.message)) date_time = datetime.combine(date, time) return_code, return_msg = self._system_api.set_date_and_time(date_time) if return_code == Util.Global.FAILURE: raise DeviceException(DeviceException.OPERATION_FAILED, return_msg)
def reboot(self, mode="MOS", wait_for_transition=True, transition_timeout=None, skip_failure=False, wait_settledown_duration=False): """ Perform a software reboot on the board. By default will bring you to MOS and connect acs once MOS is seen. this reboot require that you are in a state where adb command can be run. :type mode: str or list :param mode: mode to reboot in, support MOS. .. warning:: it is not always possible to reboot in a mode from another mode :type wait_for_transition: boolean :param wait_for_transition: if set to true, it will wait until the wanted mode is reached :type transition_timeout: int :param transition_timeout: timeout for reaching the wanted mode by default will be equal to boot timeout set on device catalog :type skip_failure: boolean :param skip_failure: skip the failure, avoiding raising execption, using this option block the returned value when it is equal to False :type wait_settledown_duration: boolean :param wait_settledown_duration: if set to True, it will wait settleDownDuration seconds after reboot for Main OS only. :rtype: boolean :return: return True if reboot action succeed depending of the option used, False otherwise - if wait_for_transition not used, it will return True if the reboot action has been seen by the board - if wait_for_transition used , it will return True if the reboot action has been seen by the board and the wanted reboot mode reached. """ self.get_logger().info("Rebooting the board...") transition_timeout = self._init_boot_timeout(transition_timeout) rebooted = False # if device is already OFF do not do soft shutdown procedure if self.is_available(): # Disconnect logging threads before sending the reboot command # in case the reboot takes effect whereas logging is still active self.disconnect_board() time.sleep(2) # Reboot the board try: self.run_uecmd("Intel.Acs.TestFmk.DeviceSystem", "Intel.Acs.TestFmk.DeviceSystem.DeviceSystemActivity", "StartDutReboot", "", 0) # Wait for device is off if wait_for_transition: # Wait enough end of reboot self.get_logger().info("Wait Reboot duration (%d s)..." % transition_timeout) endtime = time.time() + transition_timeout while endtime > time.time(): if not self.is_booted(): self.get_logger().info("Device shutdown ...") rebooted = True break if not rebooted: msg = "Dut didn't shutdown in time..." self.get_logger().error(msg) raise DeviceException(DeviceException.PROHIBITIVE_BEHAVIOR, msg) else: rebooted = False while endtime > time.time(): if self.is_booted(): self.get_logger().info("DUT is rebooted...") rebooted = True break self.get_logger().info("Check if DUT is rebooted...") # Reconnect board if self.is_booted(): self.get_logger().info("DUT is rebooted...") self.connect_board() else: msg = "Mobile is in unknown state" self.get_logger().error(msg) raise DeviceException(DeviceException.PROHIBITIVE_BEHAVIOR, msg) except DeviceException as e: self.get_logger().error(" Reboot FAILED !! %s" % str(e)) if not skip_failure: raise else: rebooted = False else: msg = "Mobile is unavailable" if not skip_failure: raise DeviceException(DeviceException.PROHIBITIVE_BEHAVIOR, msg) rebooted = False return rebooted
def _fetch_result(self): if self._result is not None: self._results["score"].append(float(self._result)) else: raise DeviceException(DeviceException.OPERATION_FAILED, "Can't fetch result for Smartbench")
def run(self, context): """ Runs the test step @type context: TestStepContext @param context: test case context """ self._logger.info(self._pars.id + ": Run") if self._file_type == "MP3": option_file_type = "audio/mp3" elif self._file_type == "M4A": option_file_type = "audio/m4a" elif self._file_type == "WMA": option_file_type = "audio/wma" elif self._file_type == "FLAC": option_file_type = "audio/flac" elif self._file_type == "OGG": option_file_type = "audio/ogg" elif self._file_type == "M4P": option_file_type = "audio/m4p" elif self._file_type is None: err_msg = "No File type specified" raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, err_msg) else: err_msg = "File type unsupported" raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, err_msg) pref_setting_file = "/data/system/users/0/package-restrictions.xml" packages_restrictions = "package-restrictions" # Load package-restrictions file tmp_dir = tempfile.gettempdir() tmp_file = "%s_temp_file.xml" % packages_restrictions tmp_file = os.path.join(tmp_dir, tmp_file) cmd = 'adb pull %s %s' % (pref_setting_file, tmp_file) (status, output) = self._device.run_cmd(cmd, 50) if status != Global.SUCCESS: self._logger.error(output) raise DeviceException(DeviceException.OPERATION_FAILED, output) # Edit package-restrictions file xml_pref = etree.parse(tmp_file, parser=None) doc = xml_pref.getroot() # Find AudioPreview audio_preview = doc.findall( "./preferred-activities/item/[@name='com.google.android.music/.AudioPreview']" ) audio_preview_set_name1 = doc.findall( "./preferred-activities/item/set/[@name='com.google.android.music/.AudioPreview']" ) audio_preview_set_name2 = doc.findall( "./preferred-activities/item/set/[@name='com.android.music/.AudioPreview']" ) audio_preview_type = doc.findall( "./preferred-activities/item/filter/type[@name='audio/mp3']") len_audio_preview = len(audio_preview) len_audio_preview_set_name1 = len(audio_preview_set_name1) len_audio_preview_set_name2 = len(audio_preview_set_name2) len_audio_preview_type = len(audio_preview_type) # AudioPreview not found if len_audio_preview == 0: if len_audio_preview_set_name1 == 0: if len_audio_preview_set_name2 == 0: if len_audio_preview_type == 0: self._logger.debug( "AudioPreview not found in package-restrictions.xml" ) self._logger.debug( "Set Google Play Music default program to open %s", str(option_file_type)) # Add all elements needed node_preferred_activities = doc.find( "preferred-activities") elt_audio_preview = etree.Element( "item", name="com.google.android.music/.AudioPreview", match="600000", always="true", set="2") etree.SubElement( elt_audio_preview, 'set', name='com.google.android.music/.AudioPreview') etree.SubElement( elt_audio_preview, 'set', name='com.android.music/.AudioPreview') elt_filter = etree.SubElement(elt_audio_preview, 'filter') etree.SubElement(elt_filter, 'action', name='android.intent.action.VIEW') etree.SubElement( elt_filter, 'cat', name='android.intent.category.DEFAULT') etree.SubElement(elt_filter, 'type', name=str(option_file_type)) node_preferred_activities.append(elt_audio_preview) # Write package-restrictions temp file doc_info = xml_pref.docinfo with open(tmp_file, "w") as xml_file: xml_pref.write(xml_file, pretty_print=False, encoding=doc_info.encoding, standalone=doc_info.standalone, xml_declaration=True) # Push the file on the device cmd = 'adb push %s %s' % (tmp_file, pref_setting_file) (status, output) = self._device.run_cmd(cmd, 50) if status != Global.SUCCESS: self._logger.error(output) raise DeviceException( DeviceException.OPERATION_FAILED, output)
def run_test(self): """ Execute the test """ sysdbg_modules_config = self._tc_parameters.get_param_value( "SYSDEBUG_MODULES") self._sysdebug_apis.init(sysdbg_modules_config) sleep_parameter = self._tc_parameters.get_param_value("SLEEP_DURATION") if sleep_parameter is not None and sleep_parameter != "" and sleep_parameter.isdigit( ): self._sleep_duration = int(sleep_parameter) # Call live sleep use case base SystemSleepBase.run_test(self) self._tc_date = time.strftime("%Y-%m-%d %H:%M:%S") self.__results.update({"date": self._tc_date}) while not self._sysdebug_apis.synchronize(): time.sleep(10) adbConnectTimeout = self._device.get_config("adbConnectTimeout", 10, float) usbReplugRetries = self._device.get_config("usbReplugRetries", 1, int) if self._io_card is not None: self._device.disconnect_board() self._sysdebug_apis.reset() # will clear mid_pmu_states self._residency_api.clear( self._sleep_duration) # will also clear mid_pmu_states # but this is needed to do the fetch on this instance self._io_card.usb_host_pc_connector(False) # Unplug wall charger only if it is AC_CHGR if self._device.get_default_wall_charger( ) == self._io_card.AC_CHGR: self._io_card.wall_charger_connector(False) # Update device uptime updated, self._device_uptime_begin = self._device._update_device_up_state( 0) if not updated: self._device_uptime_begin = None if self._sleep_duration: self._logger.info( "Wait for %s s before measurement (sleep duration before %s)" % (str(self._sleep_duration), self._sleep_mode)) time.sleep(self._sleep_duration) self._sysdebug_apis.start() self._logger.info("Wait for %s s to enter in %s" % (str(self._duration), self._sleep_mode)) time.sleep(self._duration) self._sysdebug_apis.stop() residency_spent = 0 ret_code = None if self._io_card is not None: for cnt in range(0, usbReplugRetries + 1): self._logger.debug("Loop Iteration: %d" % cnt) # plug wall charger only if it is AC_CHGR if self._device.get_default_wall_charger( ) == self._io_card.AC_CHGR: self._io_card.wall_charger_connector(True) self._io_card.usb_host_pc_connector(True) self._logger.debug("Wait for device %s seconds" % self.__adbConnectionTimeout) ret_code = self._system_api.wait_for_device( self.__adbConnectionTimeout) self._logger.debug("Wait for device return code: %s" % ret_code) if not ret_code: if cnt < usbReplugRetries: self._logger.warning( "timeout on wait-for-device, trying to unplug/replug (try %s/%s)" % (str(cnt + 1), str(usbReplugRetries))) self._io_card.usb_host_pc_connector(False) # Unplug wall charger only if it is AC_CHGR if self._device.get_default_wall_charger( ) == self._io_card.AC_CHGR: self._io_card.wall_charger_connector(False) time.sleep(10) continue residency_spent = self._residency_api.get_value( "residency", self._sleep_mode_api.get_sleep_mode()) self._sysdebug_apis.fetch() self._device.connect_board() self._logger.debug("device retrieved after %s tries" % str(cnt + 1)) break if not ret_code: raise DeviceException( DeviceException.OPERATION_FAILED, "Could not retrieve the device after %s plug/unplug cycles" % str(usbReplugRetries)) if residency_spent is None: raise DeviceException( DeviceException.INVALID_PARAMETER, "There is no %s sleep mode for this device model" % self._sleep_mode_api.get_sleep_mode()) # Get device uptime and raise an exception if the device rebooted if self._device_uptime_begin: updated, uptime = self._device._update_device_up_state( self._device_uptime_begin) if updated and not self._device.is_up: self._logger.warning( "the device uptime was %s before the measurement, %s now !" % (str(self._device_uptime_begin), str(uptime))) raise DeviceException( DeviceException.OPERATION_FAILED, "Device rebooted during the measurement") sysreport = self._sysdebug_apis.report() self.__results.append(sysreport) self.__results.write() return self._residency_verdict(residency_spent)
def _toggle_wifi_disconnection_policy(self): """ Toogle wifi disconnection policy in order to avoid or enable wifi disconnection if the network is too far away (wifi power too low). """ KEYCODE_DPAD_UP = "19" KEYCODE_DPAD_DOWN = "20" KEYCODE_DPAD_CENTER = "23" KEYCODE_HOME = "3" KEYCODE_MENU = "82" # Unlock the phone self._phone_system.set_phone_lock(0) self._logger.info("Toggle Avoid poor connection") # Open Network Settings directly output = self._exec( "adb shell am start -n com.android.settings/.Settings") if output.find("Error:") != -1: error_msg = output[output.find("Error: ") + len("Error: "):] raise DeviceException(DeviceException.PHONE_OUTPUT_ERROR, error_msg) if output.find("Warning: ") != -1: warning_msg = output[output.find("Warning: ") + len("Warning: "):] self._logger.warning(warning_msg) # Ensure we are at the bottom of the current view count = 1 while count < 19: self._exec("adb shell input keyevent " + KEYCODE_DPAD_UP) count += 1 # Down to Wifi enabled options self._exec("adb shell input keyevent " + KEYCODE_DPAD_DOWN) # Go into wifi settings self._exec("adb shell input keyevent " + KEYCODE_DPAD_CENTER) # Go into wifi settings menu self._exec("adb shell input keyevent " + KEYCODE_MENU) # Choose and enter to the advanced menu self._exec("adb shell input keyevent " + KEYCODE_DPAD_UP) self._exec("adb shell input keyevent " + KEYCODE_DPAD_CENTER) # Ensure we are at the bottom of the current view count = 1 while count < 6: self._exec("adb shell input keyevent " + KEYCODE_DPAD_UP) count += 1 # Choose the wifi disconnection policy button self._exec("adb shell input keyevent " + KEYCODE_DPAD_DOWN) self._exec("adb shell input keyevent " + KEYCODE_DPAD_DOWN) self._exec("adb shell input keyevent " + KEYCODE_DPAD_DOWN) # Toogle the button self._exec("adb shell input keyevent " + KEYCODE_DPAD_CENTER) # Exit the com.android.settings/.SubSettings application self._exec("adb shell input keyevent " + KEYCODE_HOME) # Re-allow phone locking self._phone_system.set_phone_lock(1)
def _write_read_action(self, data, read_time_measurement=False): """ Perform a write action, and a read action on the TAG. :type data: String :param data: data to write. Can be "EMPTY" to erase the TAG. :type read_time_measurement: Boolean :param read_time_measurement: if true, the read time is added to the read time list in order to be able to compute the read time mean """ # Initialize the write and the read threads self._logger.info("Positioning robot before launching test") self._robot_positioning("null", "null", self._tag_up, "null") writing_thread = threading.Thread(target=self._robot_positioning, args=('null', 'null', self._tag_down, 'null')) reading_thread = threading.Thread(target=self._robot_positioning, args=('null', 'null', self._tag_down, 'null')) report_msg = "Write (%s) test." % data try: self._logger.info("Write \"" + data + "\" in NFC tag") writing_thread.start() self._nfc_api.write_nfc_tag(self._record_type_description, data) writing_thread.join() self._robot_positioning("null", "null", self._tag_up, "null") self._logger.info("Read data from NFC tag") reading_thread.start() self._logger.info("Start read time measurement") start_time = time.time() read_data_from_tag = self._nfc_api.read_nfc_tag() stop_time = time.time() self._logger.info("Stop read time measurement") # Store the time to read the TAG if read_time_measurement: read_time = stop_time - start_time self._read_time_list.append(read_time) report_msg += " Read TAG time: %.2f sec." % read_time if self.get_b2b_iteration() == self._current_iteration_num: # This is the last iteration of back to back test report_msg += self.__compute_final_report_msg() reading_thread.join() self._logger.info("Compare read and written values...") msg = 'Read value is "' + read_data_from_tag + '" when written one is "' + data + '"' if read_data_from_tag != data: msg = "Unexpected result! " + msg self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) self._logger.info(msg) self._secondary_report.add_result(report_msg, SecondaryTestReport.verdict.PASS, "Test pass", self.get_name(), self.tc_order) except: if read_time_measurement and self.get_b2b_iteration( ) == self._current_iteration_num: # This is the last iteration of back to back test report_msg += self.__compute_final_report_msg() self._secondary_report.add_result(report_msg, SecondaryTestReport.verdict.FAIL, "Test fail", self.get_name(), self.tc_order) raise finally: writing_thread.join() try: reading_thread.join() except: pass self._logger.info("Ensure robot is at TOP position for the end") self._robot_positioning("null", "null", self._tag_up, "null")
def run(self, context): """ Runs the test step :type context: TestStepContext :param context: test case context """ DeviceTestStepBase.run(self, context) self.__json = [] self.__mutex = Lock() # ------------------------- get params ---------------------------- droidbot_jar_path = context.get_info("JAR_FILE_PATH_DROIDBOT") pnptests_jar_path = context.get_info("JAR_FILE_PATH_PNP_TESTS") droidbot_extra_args = self._pars.extra_opts self._droidbot_test_name = self._pars.test_name self.__droidbot_timer = self._pars.timeout self._iteration_name = self._droidbot_test_name.split('.')[-1] # get test case name, based on its path testcase_name = self._testcase_name.replace("\\", "/").split("/")[-1] # add each iteration in external report self._logger.info("RunPnpPerf: Starting") cmd = "adb shell uiautomator runtest {0} {1} -s -c {2}".format( droidbot_jar_path, pnptests_jar_path, self._droidbot_test_name) if droidbot_extra_args: cmd += " " + str(droidbot_extra_args) # ------------------------- run droidbot ---------------------------- self._logger.info("Droidbot cmd: {}".format(cmd)) # Start watchdog for droidbot cancelable = Cancel() min_timeout = 60 logtag = "DROIDBOT_TIMER" self._device.get_device_logger().add_trigger_message(logtag) thread = Thread(target=self.droidbot_watchdog, args=(cancelable, min_timeout, logtag)) thread.start() # run droidbot command, using cancel object from watchdog regex_dict_result = "INSTRUMENTATION_STATUS: result=(?P<dict_result>{.*})" regex_dict_report = "INSTRUMENTATION_STATUS: report=(?P<dict_report>{.*})" _proc, q = run_local_command(cmd) output = "" self.__droidbot_timer *= 60 verdict = Global.FAILURE while self.__droidbot_timer > 0 and _proc is not None and _proc.poll( ) is None: # pylint: disable=C0103 # Agree to keep t0 & t1 variable names t0 = time.time() time.sleep(0.2) t1 = time.time() self.__mutex.acquire() self.__droidbot_timer -= (t1 - t0) self.__mutex.release() stdout_data_list = self._dequeue(q) for el in stdout_data_list: output += el + "\n" self._logger.debug("uiautomator_output : %s" % el) if "report" in el: matches_res = re.compile(regex_dict_report).search(el) if matches_res: content = matches_res.group('dict_report') #FIXME: Need to convert verdict into Global.Status verdict = Global.SUCCESS #if content["verdict"] == "PASS" else elif "result" in el: matches_res = re.compile(regex_dict_result).search(el) content = None if matches_res: content = matches_res.group('dict_result') self._send_iteration(content) # droidbot command is done : call cancel() to stop watchdog cancelable.cancel() if verdict != Global.SUCCESS: raise DeviceException(DeviceException.OPERATION_FAILED, "RunPnpPerf: run_cmd failed") # ------------------------- format output ---------------------------- # json dict is printed in logs with all test output data # example : OK (1 test) # this log will indicate that all tests have been successfully executed regex_result_ok = re.compile("OK \(\d+ test\)") results = [] success = False for line in output.split('\n'): # retrieve test output info matches_res = re.compile(regex_dict_result).search(line) if matches_res: content = matches_res.group('dict_result') try: # serialize string as dict json_test_result = json.loads(content) results.append(json_test_result) except ValueError as error: self._logger.warning( "error during loading {0} : {1}".format( content, error)) elif regex_result_ok.match(line): success = True # ------------------------- analyze output ---------------------------- if results: # get artifacts from device artifacts_dir = os.path.join( self._device.get_report_tree().get_report_path(), self._testcase_name, "{0}_artifacts".format(testcase_name)) if not os.path.exists(artifacts_dir): os.makedirs(artifacts_dir) for result in results: if 'artifacts' in result: for artifact in result['artifacts']: artifact_dir = os.path.join( artifacts_dir, os.path.join(*artifact.split('/')[-3:-1])) if not os.path.exists(artifact_dir): os.makedirs(artifact_dir) adb_command = "adb pull " + artifact + " " + os.path.join( artifact_dir, artifact.split('/')[-1]) self._device.run_cmd(adb_command, 30) # write results in json file # example : _Report/ReportCampaign/PHONE1/test_case_name/results.json test_data_dir = os.path.join( self._device.get_report_tree().get_report_path(), self._testcase_name, "{0}_result".format(testcase_name)) # create folder if it does not exist if not os.path.exists(test_data_dir): os.makedirs(test_data_dir) # dump json to string try: json_string = json.dumps(results) except Exception as e: msg = "Error while dumping json results to string ({0})".format( e) self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, "RunPnpPerf: {0}".format(msg)) # dump data in file score_file_path = os.path.join(test_data_dir, "results.json") with open(score_file_path, 'w') as outfile: outfile.write(json_string) # compute scores and add them to secondary report success = success and self.computeScores( context, self._device, testcase_name, json_string) else: raise DeviceException( DeviceException.OPERATION_FAILED, "RunPnpPerf: no results returned, test has failed!") if not success: raise DeviceException( DeviceException.OPERATION_FAILED, "RunPnpPerf: check logs, test has not been executed properly") self._logger.info("RunPnpPerf: Done")
def set_up(self): """ Initialize the test """ LabNfcBase.set_up(self) # air plane mode status if self.__flight_mode_status is not "APM_NONE": if self.__flight_mode_status == "APM_ONOFF_NFC_OFF": self._nfc_api.nfc_disable() self._logger.info("Turn flight mode ON") self._networking_api.set_flight_mode(1) if not self._networking_api.get_flight_mode(): msg = "Unable to activate flight mode" self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) if self.__flight_mode_status == "APM_NFC_ON": self._logger.info("Activate NFC after turning flight mode ON") self._nfc_api.nfc_enable() if self.__flight_mode_status == "APM_ONOFF_NFC_ON": #reactivate self._logger.info("Turn flight mode OFF") self._networking_api.set_flight_mode(0) if self._record_type_description not in ("RTD_TEXT", "RTD_SP", "RTD_URI"): msg = "Set wrong RTD type. Could only be RTD_TEXT, RTD_SP or RTD_URI. " msg += "Read Value: " + self._data_to_write self._logger.error(msg) raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg) # Get the time in seconds during which the Robot presents the NFC tag to the DUT self._read_max_duration = self._nfc_robot_param.get_param_value( "NfcReadTime", self._read_max_duration) self._write_max_duration = self._nfc_robot_param.get_param_value( "NfcWriteTime", self._write_max_duration) # Get the TAG coordinates if self._tag_type == "TOPAZ": tag_x = self._nfc_robot_param.get_param_value("TopazX") tag_y = self._nfc_robot_param.get_param_value("TopazY") self._tag_up = self._nfc_robot_param.get_param_value("TopazUp") self._tag_down = self._nfc_robot_param.get_param_value("TopazDown") elif self._tag_type == "MIFARE_ULTRALIGHT": tag_x = self._nfc_robot_param.get_param_value("MifareUltralightX") tag_y = self._nfc_robot_param.get_param_value("MifareUltralightY") self._tag_up = self._nfc_robot_param.get_param_value( "MifareUltralightUp") self._tag_down = self._nfc_robot_param.get_param_value( "MifareUltralightDown") elif self._tag_type == "MULC": tag_x = self._nfc_robot_param.get_param_value("MifareUltralightCX") tag_y = self._nfc_robot_param.get_param_value("MifareUltralightCY") self._tag_up = self._nfc_robot_param.get_param_value( "MifareUltralightCUp") self._tag_down = self._nfc_robot_param.get_param_value( "MifareUltralightCDown") elif self._tag_type == "FELICA": tag_x = self._nfc_robot_param.get_param_value("FelicaX") tag_y = self._nfc_robot_param.get_param_value("FelicaY") self._tag_up = self._nfc_robot_param.get_param_value("FelicaUp") self._tag_down = self._nfc_robot_param.get_param_value( "FelicaDown") elif self._tag_type == "DESFIRE_A": tag_x = self._nfc_robot_param.get_param_value("DesfireX") tag_y = self._nfc_robot_param.get_param_value("DesfireY") self._tag_up = self._nfc_robot_param.get_param_value("DesfireUp") self._tag_down = self._nfc_robot_param.get_param_value( "DesfireDown") elif self._tag_type == "TYPE4_B": tag_x = self._nfc_robot_param.get_param_value("Type4BX") tag_y = self._nfc_robot_param.get_param_value("Type4BY") self._tag_up = self._nfc_robot_param.get_param_value("Type4BUp") self._tag_down = self._nfc_robot_param.get_param_value( "Type4BDown") elif self._tag_type == "MIFARE_CLASSIC": tag_x = self._nfc_robot_param.get_param_value("MifareClassicX") tag_y = self._nfc_robot_param.get_param_value("MifareClassicY") self._tag_up = self._nfc_robot_param.get_param_value( "MifareClassicUp") self._tag_down = self._nfc_robot_param.get_param_value( "MifareClassicDown") elif self._tag_type == "MIFARE4K": tag_x = self._nfc_robot_param.get_param_value("MifareClassic4KX") tag_y = self._nfc_robot_param.get_param_value("MifareClassic4KY") self._tag_up = self._nfc_robot_param.get_param_value( "MifareClassic4KUp") self._tag_down = self._nfc_robot_param.get_param_value( "MifareClassic4KDown") elif self._tag_type == "LIBRARY_TAG": tag_x = self._nfc_robot_param.get_param_value("LibraryX") tag_y = self._nfc_robot_param.get_param_value("LibraryY") self._tag_up = self._nfc_robot_param.get_param_value("LibraryUp") self._tag_down = self._nfc_robot_param.get_param_value( "LibraryDown") elif self._tag_type == "CENTER": tag_x = self._nfc_robot_param.get_param_value("CenterX") tag_y = self._nfc_robot_param.get_param_value("CenterY") self._tag_up = self._nfc_robot_param.get_param_value("CenterUp") self._tag_down = self._nfc_robot_param.get_param_value( "CenterDown") else: msg = "Unknown tag type! Read value: " + self._tag_type self._logger.error(msg) raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg) # disable "Tags" and browsers built-in apps if self._tag_app in ["None", ""]: msg = "NFC not available on this device!" self._logger.error(msg) raise AcsConfigException(AcsConfigException.FEATURE_NOT_AVAILABLE, msg) self._appmgmt_api.app_enable_disable(self._tag_app, False) self._appmgmt_api.app_enable_disable(self._browser_app, False) self._appmgmt_api.app_enable_disable(self._chrome_app, False) self._robot_positioning(tag_x, tag_y, "null", "null") return Global.SUCCESS, "No errors"
def run_test(self): """ Execute the test """ UseCaseBase.run_test(self) # Setup embedded for all defined devices for device in DeviceManager().get_all_devices(): # get the signing keys from the device's BENCHCFG signing_key = device.get_config("appSigningKey", "") if not signing_key: error_msg = "appSigningKey parameter is not present in Device Catalog nor in Bench Config" raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, error_msg) system_api = device.get_uecmd("System") app_api = device.get_uecmd("AppMgmt") phone_system_api = device.get_uecmd("PhoneSystem") device_name = device.whoami().get("device", "") if not device_name: error_msg = "Device name cannot be found from device instance!" raise AcsConfigException( AcsConfigException.INSTANTIATION_ERROR, error_msg) # Boot the device if not booted and connect it if not device.is_available(): DeviceManager().boot_device(device_name) signing_key_name = None signing_key_folder = None # Get key to sign apps if necessary if not device.has_intel_os(): signing_key = None if signing_key: artifact_manager = self._em.get_artifact_manager( "ARTIFACT_MANAGER") artifact_manager.get_artifact(artifact_name=signing_key + ".pk8", transfer_timeout=10) local_artifact = artifact_manager.get_artifact( artifact_name=signing_key + ".x509.pem", transfer_timeout=10) signing_key_folder = os.path.dirname(local_artifact) signing_key_name = os.path.basename(signing_key) for agent_path in self._agent_paths: agent_path = agent_path.strip() if not agent_path: error_msg = "Split parameter error. An application path is empty. Did you forget a \";\" ?" raise AcsConfigException( AcsConfigException.INVALID_PARAMETER, error_msg) # check if path to ACS_AGENT exists if not os.path.exists(agent_path): error_msg = "Application not found {0} !".format( agent_path) raise AcsConfigException( AcsConfigException.INVALID_PARAMETER, error_msg) # if app signing is needed, do it now if signing_key_folder and signing_key_name: app_path = self.__sign_app(app_api, agent_path, signing_key_folder, signing_key_name) # actually install the app status, status_msg = app_api.install_device_app(app_path) if status != Global.SUCCESS: error_msg = "Unable to install application from {0} : {1}".format( app_path, status_msg) raise DeviceException(DeviceException.OPERATION_FAILED, error_msg) # disable app verification if device.is_rooted(): phone_system_api.set_verify_application(False) # Reboot device in order to "clean" the system after install device.reboot() # Initialize UI api self._ui_api.init() #disable SetupWizard verdict, msg = self._disable_wizard() if verdict != Global.SUCCESS: error_msg = "Unable to disable SetupWizard. Error Message: {0}".format( msg) raise DeviceException(DeviceException.OPERATION_FAILED, error_msg) return Global.SUCCESS, ""
def set_up(self): """ Set up the test configuration """ # Call UseCaseBase Setup function UseCaseBase.set_up(self) # Check if we have the second phone available if self._phone2 is not None: if not self._phone2.is_available(): self._phone2.switch_on(simple_switch_mode=True) self._system_api2 = self._phone2.get_uecmd("System") else: # We are using this multi UC with only one phone error_msg = \ "This test case requires two phones to be executed !" self._logger.error(error_msg) raise AcsConfigException(AcsConfigException.INVALID_BENCH_CONFIG, error_msg) # Swap 2G 3G or 4G. if self._call_type == "2G": self._networking_api.set_preferred_network_type( PreferredNetwork.GSM_ONLY) elif self._call_type == "3G": self._networking_api.set_preferred_network_type( PreferredNetwork.WCDMA_ONLY) elif self._call_type == "4G": self._networking_api.set_preferred_network_type( PreferredNetwork.LTE_ONLY) else: if self._call_type not in "VOIP": msg = "wrong value of parameter CALL TYPE" self._logger.error(msg) raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg) # Audio Analyzer Initialization if self._audio_analyzer.initialization(self._device.get_phone_model(), self._test_type) != 0: error_msg = \ "Audio Analyzer Initialization Failed !" self._logger.error(error_msg) raise TestEquipmentException( TestEquipmentException.OPERATION_FAILED, error_msg) if self._acc_list.count("BLUETOOTH") > 0: # Get dut bt address self._dut_bt_address = self._bt_api.get_bt_adapter_address() # Push the first Bluetooth accessories in first l_bluetooth_acc_position = 0 for i in self._acc_list_split: if i.find("BLUETOOTH") != -1: # Initialization of _acc_type with the bluetooth accessories self._acc_type = i self._acc_list_split.insert(len(self._acc_list_split), i) self._acc_active_list_split.insert( len(self._acc_active_list_split), self._acc_active_list_split[l_bluetooth_acc_position]) self._call_volume_ref_list_split.insert( len(self._call_volume_ref_list_split), self. _call_volume_ref_list_split[l_bluetooth_acc_position]) self._call_volume_dut_list_split.insert( len(self._call_volume_dut_list_split), self. _call_volume_dut_list_split[l_bluetooth_acc_position]) break l_bluetooth_acc_position += 1 # Connect Bluetooth device if self._audio_analyzer.connect_bt(self._acc_type, self._dut_bt_address) != 0: error_msg = \ "Connect Bluetooth failed !" self._logger.error(error_msg) raise DeviceException(DeviceException.OPERATION_FAILED, error_msg) return Global.SUCCESS, "No errors"
def release(self): """ Used to disconnect from a port, and/or all other action to do to release the Ui uecmd instance """ raise DeviceException(DeviceException.FEATURE_NOT_IMPLEMENTED)
def run_test(self): """ Execute the test """ # Call LabAudioQualityBase run_test function LabAudioQualityBase.run_test(self) # In case of back-to-back iterations, the DUT or reference phone might have been unplugged if self._use_io_card: if self._device.get_state() == "unknown": self._io_card.usb_connector(plug=True) self._system_api.wait_for_device(timeout=60) self._device.connect_board() if self._io_card_2: if self._phone2.get_state() == "unknown": self._io_card_2.usb_connector(plug=True) self._system_api2.wait_for_device(timeout=60) self._phone2.connect_board() if self._phone_calling: if self._phone_calling.get_sip_call_state() is not self._uecmd_types.SIP_CALL_STATE.READY_TO_CALL: self._logger.info("Read state of calling phone: %s" % self._phone_calling.get_sip_call_state()) self._phone_calling.release() self._phone_calling.wait_for_state( self._uecmd_types.SIP_CALL_STATE.READY_TO_CALL, self._call_setup_time) if self._phone_receiving: if self._phone_receiving.get_sip_call_state() is not self._uecmd_types.SIP_CALL_STATE.READY_TO_CALL: self._logger.info("Read state of receiving phone: %s" % self._phone_receiving.get_sip_call_state()) self._phone_receiving.release() self._phone_receiving.wait_for_state( self._uecmd_types.SIP_CALL_STATE.READY_TO_CALL, self._call_setup_time) # Dial using PHONE_NUMBER parameter if self._phone_calling: if self._phone2: self._phone_calling.dial(self._calling_phone_number) else: self._phone_calling.dial(self._calling_phone_number, check_state=False) else: self._voip_server.start_mt_call(self._dut_sip_address.split('@')[0], self._peer_sip_address.split('@')[0]) if self._phone_receiving: self._phone_receiving.wait_for_state( self._uecmd_types.SIP_CALL_STATE.INCOMING_CALL, self._call_setup_time) self._phone_receiving.answer() # Phone1 & 2 : Check voice call is active if self._phone_calling: self._phone_calling.wait_for_state( self._uecmd_types.SIP_CALL_STATE.IN_CALL, self._call_setup_time) if self._phone_receiving: self._phone_receiving.wait_for_state( self._uecmd_types.SIP_CALL_STATE.IN_CALL, self._call_setup_time) # Set Voice Call Volume self._system_api.adjust_specified_stream_volume("VoiceCall", self._call_stream_volume_dut) if self._phone_receiving and self._phone2: self._system_api2.adjust_specified_stream_volume("VoiceCall", self._call_stream_volume_ref) start_time = time.localtime() if self._elapsed_time > 0: self._elapsed_time = 0 polqa_result_dl = [] polqa_result_ul = [] # Start audio quality measurement while self._elapsed_time < self._call_duration: # Unplug IO card(s) if self._use_io_card: self._device.disconnect_board() self._io_card.usb_connector(plug=False) if self._io_card_2: self._phone2.disconnect_board() self._io_card_2.usb_connector(plug=False) # If only 1 phone is used, the acquisition of DL and UL audio stream are done using a SIP server if not self._phone2: # For DL, switch to a playback call profile self._voip_server.change_call_profile(self._dut_sip_address.split('@')[0], VoIPServerCallUtilities.sip_profiles["PLAYBACK"]) # Start POLQA measurement in DL [tmp_polqa_result_dl, meas_in_range_dl] = self.__start_audio_quality_mos("POLQA", "DL", self._audio_analyzer_meas_retry) # If the current measurement result is not in the expected MOS range, do not take it into account if meas_in_range_dl: polqa_result_dl.append(float(tmp_polqa_result_dl)) # If User does not want to keep recorded audio file, it will not be stored # only if test is PASS if self._keep_record is True or polqa_result_dl[-1] < float(self._polqa_target): self._host_deg_file_path += time.strftime('%Y%m%d_%H%M%S', time.localtime()) + "_DL" ".wav" self._audio_analyzer.copy_from_upv(self._aa_deg_file_path, self._host_deg_file_path) self._host_deg_file_path = self._host_deg_file_path.split(str(time.localtime().tm_year))[0] if not self._phone2: # For UL, switch to a record call profile self._voip_server.change_call_profile(self._dut_sip_address.split('@')[0], VoIPServerCallUtilities.sip_profiles["RECORD"]) self._audio_analyzer.start_single_measurement(wait_for_result=False) self._audio_analyzer.wait_for_meas_state("measurement_terminated") self._voip_server_computer.copy_file_in_local_path(self._voip_server_deg_file, self._local_deg_file) # Copy degraded audio file to UPV for offline POLQA measurement self._audio_analyzer.copy_to_upv(os.path.join(self._aa_conf_path, self._degraded_audio_file), self._aa_deg_file_path) # Start POLQA measurement in offline mode [tmp_polqa_result_ul, meas_in_range_ul] = self.__start_audio_quality_mos("POLQA", "DL", self._audio_analyzer_meas_retry, load_setup=False, offline=True) else: # Start POLQA measurement in UL [tmp_polqa_result_ul, meas_in_range_ul] = self.__start_audio_quality_mos("POLQA", "UL", self._audio_analyzer_meas_retry) # Plug IO card(s) if self._use_io_card: self._io_card.usb_connector(plug=True) self._system_api.wait_for_device(timeout=60) self._device.connect_board() if self._io_card_2: self._io_card_2.usb_connector(plug=True) self._system_api2.wait_for_device(timeout=60) self._phone2.connect_board() # If the current measurement result is not in the expected MOS range, do not take it into account if meas_in_range_ul: polqa_result_ul.append(float(tmp_polqa_result_ul)) # If User does not want to keep recorded audio file, it will not be stored # only if test is PASS if self._keep_record is True or polqa_result_ul[-1] < float(self._polqa_target): self._host_deg_file_path += time.strftime('%Y%m%d_%H%M%S', time.localtime()) + "_UL" + ".wav" self._audio_analyzer.copy_from_upv(self._aa_deg_file_path, self._host_deg_file_path) self._host_deg_file_path = self._host_deg_file_path.split(str(time.localtime().tm_year))[0] if meas_in_range_dl and meas_in_range_ul: self._error.Msg = "Current POLQA result (DL/UL) : %f / %f, POLQA target : %s" % (polqa_result_dl[-1], polqa_result_ul[-1], self._polqa_target) self._logger.info(self._error.Msg) else: self._error.Msg = "POLQA result is out of range after %d retry. No usable result for this iteration." \ % self._audio_analyzer_meas_retry self._logger.error(self._error.Msg) self._result_verdict = Global.BLOCKED # Maintain the VOIP call for wait_between_measure s before starting a new measurement self._logger.info( "Maintain the VOIP call for %d s before starting a new measurement" % self._wait_between_measure) time.sleep(self._wait_between_measure) # Get elapsed time since call establishment in s self._elapsed_time = self.__get_elapsed_time(start_time, time.localtime()) # Check if call is still connected if self._sip_call_api.get_sip_call_state() is not self._uecmd_types.SIP_CALL_STATE.IN_CALL: msg = "VOIP call interrupted after %d seconds, state is %s !" % (self._elapsed_time, self._sip_call_api.get_sip_call_state()) self.get_logger().error(msg) raise DeviceException(DeviceException.INVALID_DEVICE_STATE, msg) else: self.get_logger().info( "VOIP call still connected after %d seconds!", self._elapsed_time) # RELEASE THE CALL # Phone1 & 2 : Check call is still active if self._phone_calling: self._phone_calling.wait_for_state( self._uecmd_types.SIP_CALL_STATE.IN_CALL, self._call_setup_time) if self._phone_receiving: self._phone_receiving.wait_for_state( self._uecmd_types.SIP_CALL_STATE.IN_CALL, self._call_setup_time) if self._phone_releasing: self._phone_releasing.release() time.sleep(self._wait_btwn_cmd) self._phone_releasing.wait_for_state( self._uecmd_types.SIP_CALL_STATE.READY_TO_CALL, self._call_setup_time) else: self._voip_server.release_call(self._dut_sip_address.split('@')[0]) if self._phone_receiving: self._phone_receiving.wait_for_state( self._uecmd_types.SIP_CALL_STATE.READY_TO_CALL, self._call_setup_time) if self._result_verdict is not Global.BLOCKED: self._error.Msg = "Median POLQA result (DL/UL) : %f / %f, POLQA target : %s" % ( float(numpy.median(numpy.array(polqa_result_dl))), float(numpy.median(numpy.array(polqa_result_ul))), self._polqa_target) # Compare the result of POLQA process with POLQA targets # Compute test verdict (if POLQA result > POLQA target the test pass, # else the test fails) if float(numpy.median(numpy.array(polqa_result_dl))) > float(self._polqa_target) \ and float(numpy.median(numpy.array(polqa_result_ul))) > float(self._polqa_target): self._logger.info(self._error.Msg) self._result_verdict = Global.SUCCESS else: self._logger.error(self._error.Msg) self._result_verdict = Global.FAILURE self._error.Msg += "" return self._result_verdict, self._error.Msg
def run_test_body(self): """ Execute the test """ # Call LAB_EM_BASE Run function EmUsecaseBase.run_test_body(self) # schedule operations pid1 = self.em_api.get_msic_registers( "scheduled", self.__action_timeout + self.__uecmd_com_timing) time1 = time.time() + self.__action_timeout + self.__uecmd_com_timing pid2 = self.em_api.get_msic_registers( "scheduled", self.__action_timeout * 2 + self.__uecmd_com_timing) time2 = time.time() + self.__action_timeout * 2 + \ self.__uecmd_com_timing # disconnect the board during test self._device.disconnect_board() # check that timing control is enough good if time.time() > time1: raise DeviceException( DeviceException.TIMEOUT_REACHED, "the time of the embedded msic register measure was reached before" " the action was done. You need to increase the parameter TIMEOUT" ) # do the first action ( plug or unplug ) self.__charger_action(self.__action[0]) # wait some time before check measure self._logger.info("Wait %s s before the first measure" % str(time1 + 5 - time.time())) while time.time() < time1 + 5: time.sleep(1) # check that timing control is enough good if time.time() > time2: raise DeviceException( DeviceException.TIMEOUT_REACHED, "the time of the embedded msic register measure was reached before" " the action was done. You need to increase the parameter TIMEOUT" ) # do the second action ( plug or unplug ) self.__charger_action(self.__action[1]) # wait some time before check measure self._logger.info("Wait %s s before second measure" % str(time2 + 5 - time.time())) while time.time() < time2 + 5: time.sleep(1) # reconnect and get info self._io_card.usb_connector(False) self._io_card.usb_host_pc_connector(True) time.sleep(self.usb_sleep) self._device.connect_board() self.em_core_module.check_board_connection() # Read Platform OS and compare with expected values msic_registers = self.em_api.get_msic_registers("read", pid1) self._meas_list.add_dict("EMINFO_DURING_" + str(self.__action[0]), msic_registers, msic_registers["TIME_STAMP"][0]) # Read Platform OS and compare with expected values msic_registers = self.em_api.get_msic_registers("read", pid2) self._meas_list.add_dict("EMINFO_DURING_" + str(self.__action[1]), msic_registers, msic_registers["TIME_STAMP"][0]) self._em_meas_verdict.compare_list(self._meas_list, self._em_targets) self._em_meas_verdict.judge(ignore_blocked_tc=True) self._meas_list.clean() return self._em_meas_verdict.get_current_result_v2()
def stress_discharge(self, timeout): """ stress the board during discharge """ start_time = time.time() # turn on data cell if self._load in ["HEAVY", "MEDIUM"]: self._data_2g.set_data_cell_on() # launch uecmd only if board is available if self.is_board_and_acs_ok(): try: # give write access self._device.set_filesystem_rw() # stop charging through usb self.em_api.set_usb_charging("off") # stress cpu self.phonesystem_api.stress_cpu("on") # stress emmc self.phonesystem_api.stress_emmc("on") # wake phone self.phonesystem_api.wake_screen() if self._load in ["HEAVY"]: # connect wifi self.networking_api.\ wifi_connect(self._ssid) # start to download file through ftp self.networking_api.\ start_ftp_xfer(self._uecmd_types.XFER_DIRECTIONS.DL, # pylint: disable=E1101 self._ftp_ip_address, self._ftp_username, self._ftp_password, self._dlfilename, self._device.get_ftpdir_path(), True) # set flash self.phonesystem_api.set_torchlight("on") if self._load in ["HEAVY", "MEDIUM"]: # set vibration self.phonesystem_api.set_vibration("on") # set music volume self._system_api.adjust_specified_stream_volume( "Media", self._volume) # play music self._audio_api.play( self._multimedia_path + self._audio_file, True) # establish data call 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(str(error)) # init failed measurement counter self.phone_as_reboot = False self.measurement_fail = 0 except AcsBaseException as e: self._logger.error("fail to set hard stress setup : " + str(e)) # start to discharge self._logger.info("Stress discharge cycle during %s" % timeout) while (self.batt_capacity > self.em_core_module.batt_min_capacity and (time.time() - start_time) < timeout): try: # try to read measurement self.__total_test += 1 self._logger.info("TEST iteration_%s" % str(self.__total_test)) # get msic registers value after booting msic_reg = self.update_battery_info() self.__em_meas_tab.add_dict_measurement(msic_reg) # get thermal thermal_conf = self.em_api.get_thermal_sensor_info() self.__em_meas_tab.add_dict_measurement(thermal_conf) self._meas_list.add_dict("MSIC_REGISTER_STRESS", msic_reg) # check thermal capabilities only if thermal chamber is used if self.tc_module is not None: # Store various information self.__em_meas_tab.add_measurement( [self.tc_module.feed_meas_report()]) self._meas_list.add_dict("THERMAL_MSIC_REGISTER_STRESS", msic_reg) self._meas_list.add_dict("THERMAL_CONF_STRESS", thermal_conf) # get the bcu state bcu = self.em_api.get_bcu_status() # Store various information self.__em_meas_tab.add_measurement([("BCU", bcu)]) if self._load in ["HEAVY", "MEDIUM"]: # get the call state call_state = self._cell_service reg_state = self.modem_api.get_network_registration_status( ) # 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(str(error)) call_state += "_DATA_CALL_DISCONNECTED" # try to re - establish data call 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(str(error)) # get BER ber = "CANT_GET_BER" if reg_state != "unregistered": try: self._test_mode_2g.configure_ber_measurement( 200, self._cell_power) ber = self._test_mode_2g.get_ber() except TestEquipmentException as error: self._logger.error(str(error)) # Store various information self.__em_meas_tab.add_measurement([("BER", ber)]) # Store various information self.__em_meas_tab.add_measurement([ ("REGISTRATION", reg_state), ("VOICE_CALL", call_state) ]) # get multimedia info volume = self._system_api.get_specified_stream_volume( "Media") self.__em_meas_tab.add_measurement([("VOLUME", volume)]) self._meas_list.add("BER", (ber, "none")) self._meas_list.add("VOLUME", (volume, "none")) # check vibration vibration = self.phonesystem_api.get_vibration_state() self.__em_meas_tab.add_measurement([("VIBRATION", vibration)]) self._meas_list.add("VIBRATION", (vibration, "none")) # check system info brightness_level = self.phonesystem_api.get_backlight_level() cpu_freq = self.phonesystem_api.get_cpu_freq() charge_current = self.em_api.get_charger_level() self.__em_meas_tab.add_measurement([ ("BRIGHTNESS_LEVEL", brightness_level), ("CPU_FREQ", cpu_freq), ("CHARGER_CURRENT", charge_current) ]) self._meas_list.add("BRIGHTNESS_LEVEL", (brightness_level, "none")) self._meas_list.add("CPU_FREQ", (cpu_freq, "none")) if self._load in ["HEAVY"]: # check ftp xfer info wifi_transfer = self.networking_api.get_ftp_xfer_status() self.__em_meas_tab.add_measurement([("WIFI_FTP_TRANSFER", wifi_transfer)]) self._meas_list.add("WIFI_FTP_TRANSFER", (wifi_transfer, "none")) # restart wifi if necessary if wifi_transfer == "notrunning": self.networking_api.stop_ftp_xfer("id") self.networking_api.\ start_ftp_xfer(self._uecmd_types.XFER_DIRECTIONS.DL, # pylint: disable=E1101 self._ftp_ip_address, self._ftp_username, self._ftp_password, self._dlfilename, self._device.get_ftpdir_path(), True) # reset consecutive fail self.measurement_fail = 0 # TEMPS TO FORCE USB CHARGING OFF stop charging through usb self.em_api.set_usb_charging("off") self.phonesystem_api.stress_emmc("off") self.phonesystem_api.stress_emmc("on") except AcsBaseException as e: # Just log error, board will be rebooted in next iteration self._logger.error("fail to get measurement: %s" % str(e)) self.measurement_fail += 1 # stop the usecase if measurement fail several times. if self.measurement_fail >= self._consecutive_meas_error: tmp_txt = "Measurement failed after %s times, stop usecase" % \ self._consecutive_meas_error self._logger.error(tmp_txt) if self.batt_voltage > self.vbatt_mos_shutdown or \ self.batt_voltage == -1: raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt) else: self._logger.info( "battery must be empty, stop usecase") break finally: # Store various information self.__em_meas_tab.add_measurement([ self.get_time_tuple(), ("COMMENTS", "Discharging with hard stess test"), ("REBOOT", self.phone_as_reboot) ]) # generate em verdict self._em_meas_verdict.compare_list(self._meas_list, self._em_targets) self._em_meas_verdict.judge(ignore_blocked_tc=True) self._meas_list.clean() # switch to next meas self.__em_meas_tab.switch_to_next_meas() self.phone_as_reboot = False # check the board connection self.em_core_module.check_board_connection(1, False) # restart flash , audio and call try: if self.has_board_reboot(): self._device.set_filesystem_rw() # set brightness to max value self.phonesystem_api.set_display_brightness(100) # stop charging through usb self.em_api.set_usb_charging("off") self.phonesystem_api.stress_cpu("on") self.phonesystem_api.stress_emmc("on") if self._load in ["HEAVY"]: # set flash self.phonesystem_api.set_torchlight("on") # restart wifi transfer self.networking_api.\ wifi_connect(self._ssid) self.networking_api.\ start_ftp_xfer(self._uecmd_types.XFER_DIRECTIONS.DL, # pylint: disable=E1101 self._ftp_ip_address, self._ftp_username, self._ftp_password, self._dlfilename, self._device.get_ftpdir_path(), True) if self._load in ["HEAVY", "MEDIUM"]: # launch music time.sleep(self._wait_btwn_cmd) self._system_api.adjust_specified_stream_volume( "Media", self._volume) self._audio_api.play( self._multimedia_path + self._audio_file, True) # establish data call try: self._data_2g.data_call(self._data_call_mode) self._data_2g.check_data_call_connected(60) except TestEquipmentException as error: self._logger.error(str(error)) # set vibration at the end self.phonesystem_api.set_vibration("on") except AcsBaseException as e: self._logger.error("fail to relaunch uemcd : " + str(e)) return Global.SUCCESS, "No actions"
def reboot(self, mode="MOS", wait_for_transition=True, transition_timeout=None, skip_failure=False, wait_settledown_duration=False): """ Perform a SOFTWARE reboot on the device. By default will bring you to MOS and connect acs once MOS is seen. this reboot require that you are in a state where adb or fastboot command can be run. :type mode: str or list :param mode: mode to reboot in, support MOS, COS, POS, ROS. It can be a list of these modes (ie ("COS","MOS")) .. warning:: it is not always possible to reboot in a mode from another mode eg: not possible to switch from ROS to COS :type wait_for_transition: bool :param wait_for_transition: if set to true, it will wait until the wanted mode is reached :type transition_timeout: int :param transition_timeout: timeout for reaching the wanted mode by default will be equal to boot timeout set on device catalog :type skip_failure: bool :param skip_failure: skip the failure, avoiding raising exception, using this option block the returned value when it is equal to False :type wait_settledown_duration: bool :param wait_settledown_duration: if set to True, it will wait settleDownDuration seconds after reboot for Main OS only. :rtype: bool :return: return True if reboot action succeed depending of the option used, False otherwise - if wait_for_transition not used, it will return True if the reboot action has been seen by the device - if wait_for_transition used , it will return True if the reboot action has been seen by the device and the wanted reboot mode reached. """ if not isinstance(mode, (list, tuple, set, frozenset)): mode = [mode] for os_mode in mode: msg = "Undefined error while rebooting" output = Global.FAILURE transition_timeout = self._init_boot_timeout(transition_timeout) transition_timeout_next = 0 rebooted = False os_mode = os_mode.upper() # Wait for device to be ready if wait_settledown_duration: settledown_duration = self._settledown_duration else: settledown_duration = None # List here command and combo list reboot_dict = { "MOS": "adb reboot", "POS": "adb reboot bootloader", "ROS": "adb reboot recovery", "COS": self._soft_shutdown_cmd } # exist if mode is unknown if os_mode not in reboot_dict: msg = "unsupported boot mode %s" % str(os_mode) self.get_logger().error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) self.get_logger().info("Trying to reboot device in %s mode" % str(os_mode)) # get actual boot mode actual_state = self.get_boot_mode() # boot the device if actual_state != "UNKNOWN": cmd = reboot_dict[os_mode] # inject adb logs if actual_state in ["ROS", "MOS", "COS"]: self.inject_device_log( "i", "ACS", "Trying to reboot device in %s" % os_mode) # disconnect acs only if we was in MOS if actual_state == "MOS": # Stop extra threads before sending the reboot command # in case the device reboots whereas extra threads are still active self._stop_extra_threads() # overide cmd in case we are in POS elif actual_state == "POS" and os_mode == "MOS": cmd = "fastboot reboot" # override cmd in case we are in POS and we want to reboot in POS elif actual_state == "POS" and os_mode == "POS": cmd = "fastboot reboot-bootloader" # Send the reboot cmd start_time = time.time() self._logger.debug( "*** RUN reboot command: {0}, timeout={1}".format( cmd, transition_timeout)) output = self.run_cmd( cmd, transition_timeout, force_execution=True, wait_for_response=self._wait_reboot_cmd_returns) if not self._wait_reboot_cmd_returns: self.get_logger().info( "Wait soft shutdown duration (%ds)..." % self._soft_shutdown_duration) time.sleep(self._soft_shutdown_settle_down_duration) transition_timeout_next = transition_timeout - (time.time() - start_time) # Disconnect the board in if actual_state == "MOS": # Need to send the reboot cmd before disconnecting in case adb over ethernet self.disconnect_board() # Consider after reboot that we shall restart the acs agent self._acs_agent.is_started = False # check reboot result if self._wait_reboot_cmd_returns and output[ 0] == Global.FAILURE: msg = "error happen during reboot command or no reboot command reply received from the device" # Update actual device state actual_state = self.get_boot_mode() else: # waiting for transition if wait_for_transition and transition_timeout_next > 0: # Check that we boot in right mode # Handle MOS state if os_mode == "MOS": return_code, _ = self._wait_board_is_ready( boot_timeout=transition_timeout_next, settledown_duration=settledown_duration) if return_code == Global.SUCCESS: actual_state = "MOS" rebooted = True else: actual_state = self.get_boot_mode() else: # POS, ROS, COS # some time is always available to finalize boot procedure start_time = time.time() while ((time.time() - start_time) < transition_timeout_next) and not rebooted: actual_state = self.get_boot_mode( check_pos_forced=True) if os_mode == actual_state: self._logger.info( "Device has been seen booted in %s after %s seconds" % (os_mode, str((time.time() - start_time)))) rebooted = True if rebooted: # inject adb logs self.inject_device_log( "i", "ACS", "Device successfully booted in %s" % os_mode) else: # Device fail to reach the wanted mode msg = "Device fail to boot in %s before %d second(s) (current mode = %s)" \ % (os_mode, transition_timeout, actual_state) else: # We do not wait for end of reboot command or time to reboot is already completed # Get the actual state actual_state = self.get_boot_mode() # We do not check the final state but reboot command has succeed rebooted = True msg = "Device reboot command sent (mode requested = %s), " \ "we do not wait the end of reboot procedure (current mode = %s)" % (os_mode, actual_state) self.get_logger().warning(msg) # Post processing after boot procedure successful or failure if actual_state == "MOS": # connect device if mode is MOS self.connect_board() # If the Agent was previously installed, start it self.init_acs_agent() elif actual_state in ["ROS", "COS"]: # Try to enable adb root if self._enableAdbRoot: if not self.enable_adb_root(): # Only warning message as we are not in MOS self.get_logger().warning( "Device failed to enable adb root, after rebooting in %s" % os_mode) else: # exist if device state is seen as UNKNOWN msg = "Device is in mode %s, cant launch reboot" % actual_state if not rebooted: self.get_logger().error(msg) if not skip_failure: raise DeviceException(DeviceException.OPERATION_FAILED, msg) break return rebooted
def soft_discharge(self, timeout): """ stress the board during discharge """ start_time = time.time() if self._load in ["HEAVY", "MEDIUM"]: # set CMU cell phone OFF self._data_2g.set_data_cell_off() if self.is_board_and_acs_ok(): try: # try to deactivate if self._load in ["HEAVY"]: # stop to download file through ftp self.networking_api.stop_ftp_xfer("id") self.networking_api.wifi_disconnect(self._ssid) # stop all daemonized process self.phonesystem_api.clean_daemon_files() # stop charging through usb self.em_api.set_usb_charging("off") if self._load in ["HEAVY", "MEDIUM"]: # set vibration self.phonesystem_api.set_vibration("off") # stop music self._audio_api.stop() # stop stress emmc self.phonesystem_api.stress_emmc("off") # stop stress cpu self.phonesystem_api.stress_cpu("off") # wake phone self.phonesystem_api.wake_screen() # init failed measurement counter self.phone_as_reboot = False self.measurement_fail = 0 except AcsBaseException as e: self._logger.error("fail to set hard stress setup : " + str(e)) # start to discharge self._logger.info("Soft discharge cycle during %s" % timeout) while (self.batt_capacity > self.em_core_module.batt_min_capacity and ((time.time() - start_time) < timeout)): try: # try to read measurement self.__total_test += 1 self._logger.info("TEST iteration_%s" % str(self.__total_test)) # get msic registers value msic_reg = self.update_battery_info() self.__em_meas_tab.add_dict_measurement(msic_reg) # get thermal thermal_conf = self.em_api.get_thermal_sensor_info() self.__em_meas_tab.add_dict_measurement(thermal_conf) # get the bcu state bcu = self.em_api.get_bcu_status() # Store various information self.__em_meas_tab.add_measurement([("BCU", bcu)]) self._meas_list.add_dict("MSIC_REGISTER_NO_STRESS", msic_reg) if self.tc_module is not None: # Store various information self.__em_meas_tab.add_measurement( [self.tc_module.feed_meas_report()]) self._meas_list.add_dict("THERMAL_MSIC_REGISTER_NO_STRESS", msic_reg) self._meas_list.add_dict("THERMAL_CONF_NO_STRESS", thermal_conf) # reset consecutive fail self.measurement_fail = 0 # TEMPS TO FORCE USB CHARGING OFF stop charging through usb self.em_api.set_usb_charging("off") except AcsBaseException as e: # Just log error, board will be rebooted in next iteration self._logger.error("fail to get measurement: " + str(e)) self.measurement_fail += 1 # stop the usecase if measurement fail several times. if self.measurement_fail >= self._consecutive_meas_error: tmp_txt = "Measurement failed after %s times, stop usecase" % \ self._consecutive_meas_error self._logger.error(tmp_txt) if self.batt_voltage > self.vbatt_mos_shutdown or \ self.batt_voltage == -1: raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt) else: self._logger.info( "battery must be empty, stop usecase") break finally: # Store various information self.__em_meas_tab.add_measurement([ self.get_time_tuple(), ("COMMENTS", "Discharging with soft stress test"), ("REBOOT", self.phone_as_reboot) ]) # switch to next meas self.__em_meas_tab.switch_to_next_meas() self.phone_as_reboot = False # check the board connection self.em_core_module.check_board_connection(1, False) # restart flash , audio and call try: if self.has_board_reboot(): # TEMPS TO FORCE USB CHARGING OFF stop charging through usb self.em_api.set_usb_charging("off") except AcsBaseException as e: self._logger.error("fail to relaunch uemcd : " + str(e))
def run_test(self): """ Execute the test """ # pylint: disable=E1101 # Disable this pylint error due to Enum class VOICE_CALL_STATE # Call GSM VoiceCall base run_test function LabGsmVcBase.run_test(self) # Update the list of RIL Emergency Numbers on the DUT # This imperatively has to be done after settting the Flight Mode self._logger.info("Add Emergency Number in ril.ecclist list") if self._is_emergency_number: # Update the property holding the Emergency Numbers list. self._device.set_property_value( LabGsmFlightmodeEmVc.EMERGENCY_NUMBER_PROPERTY_NAME, self._phone_number) self._logger.info("Add Emergency Number in NVM:cust.emergency list " "at index %s" % self._index) #Start up the proxy for sending AT commands self.at_proxy_com_port = self._modem_flashing_api.start_at_proxy_from_mos( int(self._launch_mode)) #check serial connection self._serial_handler.set_data_analyser( ATCommandAnalyser(self._expected_result)) self._serial_handler.set_default_timeout(self._command_timeout) self._logger.info("Connecting to the port " + str(self.at_proxy_com_port)) # Connect to the at proxy self._serial_handler.connect(self.at_proxy_com_port) # Check that the modem is available modem_status = self._modem_flashing_api.ping_modem_from_serial( self._serial_handler.get_serial()) if modem_status: self._logger.info("AT Proxy correctly respond to ping command") self.modem_available = True else: raise TestEquipmentException(TestEquipmentException.CONNECTION_ERROR, "Connection to AT proxy failed") #Send AT@NVM to get initial parameters stored at index "self.index" for restore at #finalize self._logger.info("Read NVM:cust.emergency list at index %s" % self._index) inerrogate_at_nvm_command = self._command + "[" + \ str(self.index) + "]" + "?" self._logger.info("Send AT command: %s" % inerrogate_at_nvm_command) self._at_inter_nvm_em_verdict, at_nvm_params_to_be_rest_raw =\ self._serial_handler.send_at_command_and_get_result(inerrogate_at_nvm_command, self._command_timeout) at_nvm_params_to_be_rest = re.match("{*.*}", at_nvm_params_to_be_rest_raw) at_nvm_params_to_be_rest = at_nvm_params_to_be_rest.group(0) self._logger.info("Data read from NVM:cust.emergency list at index %s are: %s" % ( self._index, at_nvm_params_to_be_rest)) self.command_to_rest_em_in_nvm = "%s[%s]=%s" % (str(self._command), str(self._index), str(at_nvm_params_to_be_rest)) #Send AT@NVM to add an emergency number to NNV emergency number list self._logger.info("Add NVM:cust.emergency number \"%s\" " "at index %s" % (self._phone_number, self._index)) self._at_set_nvm_em, msg = self._serial_handler.send_at_command_and_get_result( self.command_to_add_em_in_nvm, self._command_timeout) if msg == "OK": self._logger.info("Response to AT command %s " "is: %s" % (self.command_to_add_em_in_nvm, msg)) else: raise DeviceException(DeviceException.OPERATION_SET_ERROR, "Response to AT command %s is: %s" % ( self.command_to_add_em_in_nvm, msg)) self._logger.info("Start the Emergency Call when DUT is in Flight Mode") # Release any previous call (Robustness) self._voicecall_api.release() # Enable flight mode self._networking_api.set_flight_mode("on") # Wait 30 seconds to be sure that modem is down before dialing time.sleep(30) # Wake the screen otherwise the Voice Call will not be established self._phone_system.wake_screen() self._phone_system.set_phone_lock(0) # Dial using PHONE_NUMBER parameter self._voicecall_api.dial(self._phone_number) # Check call state "CONNECTED" before callSetupTimeout seconds self._ns_voice_call_2g.check_call_connected(self._call_setup_time, blocking=False) # Wait for state "active" before callSetupTimeout seconds self._voicecall_api.wait_for_state( self._uecmd_types.VOICE_CALL_STATE.ACTIVE, self._call_setup_time) # Check call is connected for CALL_DURATION seconds self._ns_voice_call_2g.is_voice_call_connected(self._call_duration) # Mobile Release call self._voicecall_api.release() # Check voice call state is "IDLE" (8960) self._ns_voice_call_2g.check_call_state("IDLE", self._call_setup_time, blocking=False) # pylint: disable=E1101 # Disable this pylint error due to Enum class VOICE_CALL_STATE # Check voice call state is "no_call" (CDK) time.sleep(self._wait_btwn_cmd) self._voicecall_api.wait_for_state( self._uecmd_types.VOICE_CALL_STATE.NOCALL, self._call_setup_time) # pylint: enable=E1101 # Disable flight mode self._networking_api.set_flight_mode("off") return Global.SUCCESS, "No errors"
def run(self, context): """ Runs the test step @type context: TestStepContext @param context: test case context """ WifiBase.run(self, context) msg = "All parameters checked :" # # Get the check sequence (it might just be one single operation) state_sequence = split_and_strip(self._pars.state, self.STR_SEPARATOR) for current_state in state_sequence: if current_state == "CONNECTED": ssids = self._api.list_ssids("wifi", "connected") if self._pars.ssid not in ssids: msg = "SSID %s is not connected" % self._pars.ssid self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) elif current_state == "NOT_CONNECTED": ssids = self._api.list_ssids("wifi", "connected") if self._pars.ssid in ssids: msg = "SSID %s is connected" % self._pars.ssid self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) elif current_state == "REMEMBERED": ssids = self._api.list_ssids("wifi", "remembered") if self._pars.ssid not in ssids: msg = "SSID %s is not in remembered WiFi AP list" % self._pars.ssid self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) elif current_state == "NOT_REMEMBERED": ssids = self._api.list_ssids("wifi", "remembered") if self._pars.ssid in ssids: msg = "SSID %s is in remembered WiFi AP list" % self._pars.ssid self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) elif current_state == "VISIBLE": ssids = self._api.list_ssids("wifi", "visible") if self._pars.ssid not in ssids: msg = "SSID %s is not visible !" % self._pars.ssid self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) elif current_state == "NOT_VISIBLE": ssids = self._api.list_ssids("wifi", "visible") if self._pars.ssid in ssids: msg = "SSID %s is visible !" % self._pars.ssid self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) elif current_state == "ALL": ssids = self._api.list_ssids("wifi", "all") if self._pars.ssid not in ssids: msg = "SSID %s is not known - visible or remembered" % self._pars.ssid self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) else: msg = "Invalid parameter state : %s" % current_state self._logger.error(msg) raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg) # Compile verdict message msg += " - %s" % current_state self._logger.debug(msg) self.ts_verdict_msg = msg
def _delete_file_if_exists(self, file_path, fail_on_error=True): """ Deletes the given file on DUT if it exists. :type file_path: str :param file_path: the absolute path of the file to delete. :type fail_on_error: bool :param fail_on_error: [optional] a boolean indicating whether we want to raise an exception on error or not. Defaults to C{True}. """ # Force file path to a str value file_path = str(file_path) rm_cmd = "adb shell rm %s" % file_path # We go on only if the file exists on the DUT if not self._phone_system_api.check_file_exist_from_shell(file_path): self._logger.debug("No such file to delete.") return # We try to delete the file try: # Run the command to remove the file, we give it 10 seconds to run self._logger.debug("Deleting file %s." % file_path) (exit_status, _output) = internal_shell_exec(rm_cmd, 10) except (KeyboardInterrupt, SystemExit): raise # We want to trap any kind of error/exception so # we use an empty exception clause and disable the # corresponding Pylint warning. # pylint: disable=W0702 except: exit_status = Global.FAILURE traceback.print_exc() # Check the status of the command execution if exit_status != Global.SUCCESS: # Build an error message error_message = "Command execution failed (command: '%s')." % rm_cmd # Handle the error case as expected if fail_on_error: # If we have to fail, raise an exception raise DeviceException(DeviceException.OPERATION_FAILED, error_message) else: # Otherwise simply log a warning self._logger.warning(error_message) # We double-check that the file has been deleted if self._phone_system_api.check_file_exist_from_shell(file_path): # Build an error message error_message = "File deletion failed (file: '%s')." % file_path # Handle the error case as expected if fail_on_error: # If we have to fail, raise an exception raise DeviceException(DeviceException.OPERATION_FAILED, error_message) else: # Otherwise simply log a warning self._logger.warning(error_message) else: self._logger.info("File %s deleted successfully." % file_path)
def run(self, context): """ Runs the test step @type context: TestStepContext @param context: test case context """ DeviceTestStepBase.run(self, context) self._logger.debug(self._pars.id + " : Test step starting.") self._3dmark_package = "com.futuremark.dmandroid.application" self._3dmark_activity = "activity.MainActivity" # Start test control loop. # Number of seconds to run the bench mark for before restarting it. benchRun = 100 pkg_activity = self._3dmark_package + "/." + self._3dmark_activity # Making sure that 3d mark application is installed. self.app_api.launch_app(intent=pkg_activity) app_ok = self.phonesystem_api.check_process(self._3dmark_package) if app_ok: self._logger.debug(self._pars.id + " : 3D Mark is installed") self.system_api.stop_app(self._3dmark_package) else: self._logger.error(self._pars.id + " : 3D Mark is not installed.") raise DeviceException( DeviceException.OPERATION_FAILED, self._pars.id + " :3D Mark is not installed.") # Start the 3D mark test control loop. end_time = float(time.time()) + (float(self._pars.duration)) * 60 while (time.time() < end_time): # Launch the 3D mark application. self.app_api.launch_app(intent=pkg_activity) time.sleep(15) # For the drop down option by sending keyboard presses # At this point the pull down menu is showing and then selecting the run. keyevent_list = [ "DPAD_DOWN", "DPAD_RIGHT", "ENTER", "DPAD_DOWN", "DPAD_DOWN", "ENTER" ] self._keyevent_api.scenario(keyevent_list, 5) # Calculate bench mark run end time benchRunEndTime = time.time() + benchRun # Start the bench run control loop while ((benchRunEndTime > time.time()) and (end_time > time.time())): # Check the status every few seconds time.sleep(10) # Check for system UI systemui_ok = self.phonesystem_api.check_process("systemui") if systemui_ok: self._logger.debug(self._pars.id + ": Systemui is active") else: self._logger.error(self._pars.id + ": Systemui is not active.") raise DeviceException( DeviceException.OPERATION_FAILED, self._pars.id + " : Systemui is not active.") # Check that the app is still alive app_ok = self.phonesystem_api.check_process( self._3dmark_package) if app_ok: self._logger.debug(self._pars.id + " :3D Mark apk is ok") else: self._logger.error(self._pars.id + " :3D Mark apk Crashed.") raise DeviceException( DeviceException.OPERATION_FAILED, self._pars.id + " :3D Mark apk Crashed.") # Close out the application. self.system_api.stop_app(self._3dmark_package) #Sleep time for the application to close and start the application in the next iteration. time.sleep(10) self._logger.debug(self._pars.id + " : test finished.")
def run_async_uecmd(self, module_name, class_name, method_name, args, start_delay, repeat_delay="", total_duration=""): """ Starts an asynchronous uecmd and return a task id to follow the result :type module_name: str :param module_name: uecmd module :type class_name: str :param class_name: class of uecmd :type method_name: str :param method_name: uecmd function :type args: str :param args: args to pass to the uecmd :type start_delay: int :param start_delay: time in second before starting the uecmd :type repeat_delay: int :param repeat_delay: [optional] time in second before repeating the uecmd. If used, total_duration must be set too. :type total_duration: int :param total_duration: [optional] the maximum duration time in second allowed to repeat the uecmd. If used, repeat_delay must be set too. :rtype: str :return: scheduled task id """ # first check that both if is_number(repeat_delay) != is_number(total_duration): text = "repeat_delay (%s) and total_duration (%s) must be used together as valid integer" % ( repeat_delay, total_duration) self._logger.error(text) raise DeviceException(DeviceException.INVALID_PARAMETER, text) # if the var are not numbers and different from their default values, raise an error if repeat_delay in ["", None]: repeat_delay = 0 elif is_number(repeat_delay): repeat_delay = int(repeat_delay) else: text = "repeat_delay (%s) must be a valid integer" % str(repeat_delay) self._logger.error(text) raise DeviceException(DeviceException.INVALID_PARAMETER, text) if total_duration in ["", None]: total_duration = 0 elif is_number(total_duration): total_duration = int(total_duration) else: text = "total_duration (%s) must be a valid integer" % str(total_duration) self._logger.error(text) raise DeviceException(DeviceException.INVALID_PARAMETER, text) try: result = self.__windows_service.launch_async_uecmd( module_name, class_name, method_name, args, self._uecmd_default_timeout, False, int(start_delay), repeat_delay, total_duration) if result.get_verdict() != CommandResult.VERDICT_PASS or result.has_exception(): raise DeviceException(DeviceException.OPERATION_FAILED, str(result.get_verdict_message())) return result['task_id'] # catch service communication errors except CommandResultException as cre: raise DeviceException(DeviceException.INTERNAL_EXEC_ERROR, str(cre))
def _get_autolog_result(self, name): """ Internal method that get the result from autolog functions. :type name: str :param name: file which contains autolog uecmd result :type reset_logs: boolean :param reset_logs: set to true if you want to reset the logs after getting the value to avoid pulling the same data each time :rtype: list of (dict, str) :return: return a list containing tuples of (special stamp, log) special stamp contains the following keys ("AUTOLOG_HOURS", "REBOOT", "REBOOT_TIME") """ # Move import here to avoid problem on other uecmd when libxml is missing from lxml import etree from acs_test_scripts.Utilities.EMUtilities import EMConstant as CST # add a retry mechanism cmd = "adb shell cat %s/%s" % (self._autolog_folder, name) for i in range(4): if i == 3: tmp_txt = "problem to access file %s/%s, is this file existing? check if something happened before logging start or read permission on the target files" % ( self._autolog_folder, name) self._logger.error(tmp_txt) raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt) # set a big timeout to avoid timeout if file size is too big output = self._exec(cmd, timeout=300) if not self.is_shell_output_ok(output): self._logger.error("retrying getting autolog result") else: break output = output.split(self.AUTO_LOG_NEW_ENTRY_SEPARATOR) result = [] for element in output: special_dict = {} if element.find("<GLOBAL_INFO") != -1: # get the str with autolog general info element = element.strip() xml_txt = element[element.find("<GLOBAL_INFO" ):element.find("/>") + 2] document = etree.fromstring(xml_txt) for tag in [CST.AUTOLOG_TIME, CST.REBOOT, CST.REBOOT_TIME]: # check every tag tag_value = document.get(tag) if tag is not None and tag_value is not None: if tag in [CST.AUTOLOG_TIME, CST.REBOOT_TIME]: tag_value = int(tag_value) else: tag_value = str_to_bool(tag_value) special_dict.update({tag: tag_value}) # clean text from evaluate tag element = element.replace(xml_txt, "").strip() if special_dict != {}: formated_output = element.replace( self.CARRIAGE_RETURN_MARKER, "\n") result.append((special_dict, formated_output.strip())) return result
def set_up(self): """ Initialize the test """ # Call LabPwrMeasBase base Setup function EmUsecaseBase.set_up(self) # check that all necessary file exist self.__benchmark_module.setup() # init camera connection self.__temp_camera.init() # call the auto setup 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.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 cool down self._setup_camera() # wait a given time to let the board cool down self._monitor_board_temp(self.__cooldown, self.__start_temp) # 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() # 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(self): """ Execute the test """ # pylint: disable=E1101 LabWifiBase.run_test(self) # monitor wifi connection time if requested mean = -1 if self._monitor_connection_time and self.get_b2b_iteration( ) == self._current_iteration_num: # This is the last iteration of back to back test # compute standard deviation, mean and verdict mean = float(numpy.mean(self._connection_time_list)) std_deviation = float(numpy.std(self._connection_time_list)) compute_verdict(self._expected_connection_time, self._tolerance, mean, std_deviation, self._logger) # Switch OFF the AP if the TC associated parameter is enabled if self._restart_ap_radio: # Forget the SSID self._networking_api.wifi_remove_config(self._ssid) # Disable radio self._ns.init() self._ns.disable_wireless() # Restart the DUT wifi interface self._networking_api.set_wifi_power("off") time.sleep(self._wait_btwn_cmd) self._networking_api.set_wifi_power("on") time.sleep(self._wait_btwn_cmd) # Register to the "out of range" network if str(self._wrong_passphrase).lower() == 'none': self._networking_api.set_wificonfiguration( self._ssid, self._passphrase, self._security, self._ip_setting, self._ip_address, self._netmask, self._gateway, self._dns1, self._dns2) else: self._networking_api.set_wificonfiguration( self._ssid, self._wrong_passphrase, self._security, self._ip_setting, self._ip_address, self._netmask, self._gateway, self._dns1, self._dns2) self._networking_api.set_autoconnect_mode(self._ssid, AUTO_CONNECT_STATE.on) # Restart the Wifi interface if required if self._restart_dut == "INTERFACE": # Power cycle the Wifi interface self._networking_api.set_wifi_power("off") time.sleep(self._wait_btwn_cmd) self._networking_api.set_wifi_power("on") time.sleep(self._wait_btwn_cmd) elif self._restart_dut == "PHONE": # Power cycle the phone self._device.reboot() # Switch ON the AP if the TC associated parameter is enabled if self._restart_ap_radio: # enable_wireless includes a time sleep self._ns.enable_wireless() self._ns.release() if self._restart_dut == "INTERFACE" \ or self._restart_dut == "PHONE" \ or self._restart_ap_radio \ or self._mac_filter != "OFF" \ or str(self._wrong_passphrase).lower() != 'none': if str(self._wrong_passphrase).lower() == 'none' and \ not self._key_exchange_should_fail: # Wait for the connection to establish self._networking_api.check_connection_state(self._ssid) else: # Wait for the connection to try to establish self._logger.debug( "Waiting for the connection list to be updated") self._phone_system_api.display_on() time.sleep(30) self._phone_system_api.display_off() # MAC address filter management if self._mac_filter != "OFF": if self._mac_filter_parameter != "OFF": self._networking_api.wifi_disconnect(self._ssid) self._add_mac_filter_to_ap() # Try to reconnect DUT self._networking_api.wifi_connect(self._ssid, False) try: self._networking_api.check_connection_state(self._ssid, 20) except AcsBaseException as e: if not self._dut_in_mac_filter or \ e.get_generic_error_message() != DeviceException.TIMEOUT_REACHED: raise # List connected SSIDs to check if the right ssid is connected connected_wifi_list = self._networking_api.list_connected_wifi() if str(self._wrong_passphrase).lower() == 'none' and \ not self._key_exchange_should_fail and \ not self._dut_in_mac_filter: if self._ssid in connected_wifi_list: result = "Wifi connected to network %s with correct password." % str( self._ssid) if mean > 0: result += " Mean connection time is %2.2f sec" % mean if self._ip_setting_enable: if (self._ip_address == self._networking_api.get_wifi_ip_address()): result += "Static ip successfully set." else: msg = "obtained ip address is different from the " + \ "static ip address" self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) else: msg = "Wifi did not connect to network " \ + "[%s] with correct password. " % str(self._ssid) self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) else: if self._ssid not in connected_wifi_list: result = "Wifi not connected to network " \ + "%s" % str(self._ssid) if str(self._wrong_passphrase).lower() != 'none' or \ self._key_exchange_should_fail: result += ", with wrong password" if self._dut_in_mac_filter: result += ", MAC add filtered" else: msg = "Wifi connected to network " \ + "[%s]" % str(self._ssid) if str(self._wrong_passphrase).lower() != 'none' or \ self._key_exchange_should_fail: msg += ", with wrong password" if self._dut_in_mac_filter: msg += ", MAC add filtered" self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) if self._mac_filter != "OFF": if self._mac_filter_parameter != "OFF": self._networking_api.wifi_disconnect(self._ssid) # Remove MAC filter self._remove_mac_filter_on_ap() # Connect DUT self._networking_api.wifi_connect(self._ssid) return Global.SUCCESS, result
def run(self, context): """ Runs the test step @type context: TestStepContext @param context: test case context """ DeviceTestStepBase.run(self, context) self._logger.info(self._pars.id + ": Run") self.residency_api = self._device.get_uecmd("Residencies") result_file_fullpath = self._pars.csv_stored_path + "/" + self._pars.csv_file_name + ".csv" target_criteria = self._pars.target_criteria.split(";") converted_target_criteria = self.residency_api.convert_criteria_list( target_criteria) if not converted_target_criteria: msg = "run_socwatch: TARGET_CRITERIA contains invalid value" self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) target_value = self._pars.target_value.split(";") if not os.path.isfile(result_file_fullpath): msg = "run_socwatch: Could not find a SOCWatch result file {0}".format( result_file_fullpath) self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) states_title, states_info = self.residency_api.parse_socwatch_sstates_info( result_file_fullpath) if not len(states_title) is len(converted_target_criteria): msg = "run_socwatch: Length of TARGET_CRITERIA is different from expected value {0}".format( len(states_info)) self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) if not len(states_title) is len(target_value): msg = "run_socwatch: Length of TARGET_VALUE is different from expected value {0}".format( len(states_info)) self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) self._logger.info("S state residency information") self._logger.info("================================") for i in xrange(len(states_title)): self._logger.info("{0} state: {1}%".format(states_title[i], states_info[i])) for index, title in enumerate(states_title): ret_val = eval("{0} {1} {2}".format( states_info[index], converted_target_criteria[index], target_value[index])) if ret_val: self._logger.info( "Success: Reported {0} residency is {1}%. It is {2} {3} ". format(title, states_info[index], converted_target_criteria[index], target_value[index])) else: msg = "Reported {0} residency is {1}%. Different from expectation, it is not {2} {3}".format( title, states_info[index], converted_target_criteria[index], target_value[index]) self._logger.error(msg) raise DeviceException(DeviceException.OPERATION_FAILED, msg) self._logger.info(self._pars.id + ": Done")
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) # try to see what is the boot mode just after plugging cable mode = self._device.get_boot_mode() self._logger.info( "boot mode just after plugging usb pc host connection : %s" % mode) if mode == "UNKNOWN": time_to_wait = 300 # wait for a while to let the board boot self._logger.info("Waiting at most %ss to see the boot mode" % time_to_wait) start_time = time.time() while time.time() - start_time < time_to_wait: mode = self._device.get_boot_mode() if mode in ["COS", "MOS"]: self._logger.info("Board seen booted in %s after %ss" % (mode, time.time() - start_time)) break if mode != "MOS": # plug a charge and charge it for a while self._io_card.wall_charger_connector(True) time_to_wait = 1800 self._logger.info( "Board booted mode is %s waiting %ss to charge it with a wall charger" % (mode, time_to_wait)) time.sleep(time_to_wait) # 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) time.sleep(self.usb_sleep) mode = self._device.get_boot_mode() end_time = 300 self._logger.info("Waiting at most %ss to detect the boot mode" % end_time) start_time = time.time() while time.time() - start_time < end_time: mode = self._device.get_boot_mode() if mode != "UNKNOWN": self._logger.info("Board seen booted in %s after %ss" % (mode, time.time() - start_time)) 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) mode = self._device.get_boot_mode() else: # 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 a potential shutdown, last boot mode seen was %s" % mode self._logger.error(tmp_txt) raise DeviceException(DeviceException.OPERATION_FAILED, tmp_txt)