Esempio n. 1
0
def run(dir_path):
    json_files = subprocess.Popen("ls {} | grep json".format(dir_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].split()
    trials = []
    for jf in json_files:
        trials += TrialHelper.load("{}/{}".format(dir_path, jf))
    for t in trials:
        t.pass_check = lambda t: t.ds["extra"]["elapsed"] > 0 or "msg" in t.ds["extra"]
        if t.ds["status"] == "invalid" and "msg" in t.ds["extra"].keys() and "bugreport" in t.ds["extra"].keys():
            bugreport_file = subprocess.Popen(
                "find {}/ssr_report-bugreport/ -name {}".format(ROOT_DIR, t.ds["extra"]["bugreport"]),
                shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].strip()
            if len(bugreport_file) > 0:
                os.system("rm -f {}".format(bugreport_file))

    tt = len(trials)
    trials = filter(lambda t: t.ds["status"] == "valid", trials)
    print("valid trials: {}/{}".format(len(trials), tt))
    trials = filter(lambda t: t.ds["status"] == "valid", trials)
    trials = TrialHelper.categorize_in(trials, cat_func=lambda t: t.ds["task"])

    for taskname, results in trials.items():
        print("pass in task[{}]: {}/{}".format(taskname, len([t for t in results if t.is_pass()]), len(results)))

    for taskname, results in trials.items():
        print("failed cases in task[{}]".format(taskname))
        print(TrialHelper.to_json([t for t in results if not t.is_pass()]))
Esempio n. 2
0
def run(num_iter=1):
    AudioFunction.init()
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    os.system("mkdir -p {}/ssr_report > /dev/null".format(ROOT_DIR))
    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)

    package = "com.htc.audiofunctionsdemo"
    activity = ".activities.MainActivity"
    component = package + "/" + activity

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)
    wake_device(device, serialno)
    SSRDumpListener.init(device, serialno)

    # keymap reference:
    #   https://github.com/dtmilano/AndroidViewClient/blob/master/src/com/dtmilano/android/adb/androidkeymap.py
    device.press("HOME")
    time.sleep(1)
    device.startActivity(component=component)
    time.sleep(1)

    trials = []
    batch_count = 1
    while num_iter > 0:
        log("-------- batch_run #{} --------".format(batch_count))
        trials_batch = []
        trials_batch += playback_task_run(device,
                                          serialno,
                                          num_iter=min([num_iter, BATCH_SIZE]))
        trials_batch += record_task_run(device,
                                        serialno,
                                        num_iter=min([num_iter, BATCH_SIZE]))
        trials_batch += voip_task_run(device,
                                      serialno,
                                      num_iter=min([num_iter, BATCH_SIZE]))

        map(lambda trial: trial.put_extra(name="batch_id", value=batch_count),
            trials_batch)
        trials += trials_batch
        with open("{}/ssr_report/{}".format(ROOT_DIR, filename), "w") as f:
            f.write(TrialHelper.to_json(trials))

        num_iter -= BATCH_SIZE
        batch_count += 1

    AudioFunction.finalize()
    Logger.finalize()
    SSRDumpListener.finalize()
    device.press("HOME")
Esempio n. 3
0
def run(num_iter=1):
    # initail componet
    AudioFunction.init()
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    if PLATFORM == WINDOWS:
        os.system("mkdir {}/{} ".format(ROOT_DIR, REPORT_DIR))
    elif PLATFORM == LINUX:
        os.system("mkdir -p {}/{} ".format(ROOT_DIR, REPORT_DIR))

    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)
    wake_device(device, serialno)

    # keymap reference:
    #   https://github.com/dtmilano/AndroidViewClient/blob/master/src/com/dtmilano/android/adb/androidkeymap.py
    device.press("HOME")
    time.sleep(0.5)

    trials = []
    batch_count = 1
    while num_iter > 0:
        log("-------- batch_run #{} --------".format(batch_count))
        trials_batch = []
        trials_batch += record_task_run(device,
                                        serialno,
                                        num_iter=min([num_iter, BATCH_SIZE]))
        #trials_batch += recordHD_task_run(device, serialno, num_iter=min([num_iter, BATCH_SIZE]))
        trials_batch += record_VoiceRecord_run(device,
                                               serialno,
                                               num_iter=min(
                                                   [num_iter, BATCH_SIZE]))

        map(lambda trial: trial.put_extra(name="batch_id", value=batch_count),
            trials_batch)
        trials += trials_batch
        with open("{}/{}/{}".format(ROOT_DIR, REPORT_DIR, filename), "w") as f:
            f.write(TrialHelper.to_json(trials))

        num_iter -= BATCH_SIZE
        batch_count += 1

    device.press("HOME")

    AudioFunction.finalize()
    Logger.finalize()
Esempio n. 4
0
def run(num_iter=1):
    AudioFunction.init()
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    os.system("mkdir -p {}{}{} > {}".format(ROOT_DIR, SEP, REPORT_DIR, STDNUL))
    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)

    device.press("HOME")
    time.sleep(1)

    gmhandler = GoogleMusicApp(device, serialno)
    log("gmhandler.to_top()")
    gmhandler.to_top()
    clear_and_update_music_files(serialno)
    time.sleep(10)

    trials = []
    batch_count = 1
    while num_iter > 0:
        log("-------- batch_run #{} --------".format(batch_count))
        trials_batch = []
        trials_batch += playback_task_run(num_iter=min([num_iter, BATCH_SIZE]),
                                          num_seek_test=5,
                                          gmhandler=gmhandler)
        trials_batch += record_task_run(device,
                                        serialno,
                                        num_iter=min([num_iter, BATCH_SIZE]),
                                        num_freqs=5)

        map(lambda trial: trial.put_extra(name="batch_id", value=batch_count),
            trials_batch)
        trials += trials_batch

        with open(
                "{}{}{}{}{}".format(ROOT_DIR, SEP, REPORT_DIR, SEP, filename),
                "w") as f:
            f.write(TrialHelper.to_json(trials))

        for taskname, tasktrials in TrialHelper.categorize_in(
                trials, lambda t: t.ds["task"]).items():
            valid_trials = zip(
                tasktrials,
                TrialHelper.pass_fail_list(
                    tasktrials, lambda t: t.ds["status"] == "valid"))
            valid_trials = [
                trial for trial, isvalid in valid_trials if isvalid
            ]
            num_valid = len(valid_trials)
            num_pass = len(
                filter(lambda x: x, TrialHelper.pass_fail_list(valid_trials)))
            log("task[{}] valid trials: {}/{}, pass trials: {}/{}".format(
                taskname, num_valid, len(tasktrials), num_pass, num_valid))

        num_iter -= BATCH_SIZE
        batch_count += 1

    AudioFunction.finalize()
    Logger.finalize()
Esempio n. 5
0
def run(test_type, num_iter=1, serialno=None):
    num_iter = int(num_iter)
    GLOBAL["test_config"] = test_type
    GLOBAL["tag"] = GLOBAL["tag"].format(GLOBAL["test_config"])
    AudioFunction.init()
    Adb.init()

    os.system("mkdir -p {}{}{}_report > {}".format(ROOT_DIR, SEP,
                                                   GLOBAL["test_config"],
                                                   STDNUL))
    os.system("mkdir -p {}{}{}_report-bugreport > {}".format(
        ROOT_DIR, SEP, GLOBAL["test_config"], STDNUL))
    t = datetime.datetime.now()
    postfix = "{}{:02d}{:02d}_{:02d}{:02d}{:02d}".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)
    filename = "report_{}.json".format(postfix)
    os.system("mkdir -p {}{}{}_report-bugreport/{} > {}".format(
        ROOT_DIR, SEP, GLOBAL["test_config"], postfix, STDNUL))

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=serialno)
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT,
                prefix="{}-{}".format(GLOBAL["test_config"], serialno))
    push_files(serialno)

    Adb.execute(["shell", "svc", "power", "stayon", "true"], serialno=serialno)
    Adb.execute(["root"], serialno=serialno)

    out, _ = Adb.execute(["shell", "getprop", "ro.vendor.build.fingerprint"],
                         serialno=serialno)
    out = out.strip()
    log("build number: '{}'".format(out))

    # keymap reference:
    #   https://github.com/dtmilano/AndroidViewClient/blob/master/src/com/dtmilano/android/adb/androidkeymap.py
    # device.press("HOME")
    # time.sleep(1)
    relaunch_app(device)
    # time.sleep(5)

    function_items = [
        lambda x: playback_task_run(
            device, serialno, num_iter=x, postfix=postfix),
        lambda x: record_task_run(device, serialno, num_iter=x),
        lambda x: voip_task_run(device, serialno, num_iter=x)
    ]

    trials = []
    batch_count = 1
    temp = num_iter
    while num_iter > 0:
        log("-------- batch_run #{} --------".format(batch_count))
        AATApp.print_log(
            device,
            severity="i",
            tag=GLOBAL["tag"],
            log="-------- batch_run #{} --------".format(batch_count))
        trials_batch = []
        # trials_batch += playback_task_run(device, num_iter=min([num_iter, BATCH_SIZE]))
        # trials_batch += record_task_run(device, serialno, num_iter=min([num_iter, BATCH_SIZE]))
        # trials_batch += voip_task_run(device, serialno, num_iter=min([num_iter, BATCH_SIZE]))
        need_to_reboot = False
        for test_item in function_items:
            test_results = test_item(min([num_iter, BATCH_SIZE]))
            trials_batch += test_results
            if len(filter(lambda t: t.ds["status"] == "valid",
                          test_results)) == 0:
                log("Function failed after {} trials...".format(temp -
                                                                num_iter))
                need_to_reboot = True

        for trial in trials_batch:
            trial.put_extra(name="batch_id", value=batch_count)
        trials += trials_batch
        with open(
                "{}{}{}_report{}{}".format(ROOT_DIR, SEP,
                                           GLOBAL["test_config"], SEP,
                                           filename), "w") as f:
            f.write(TrialHelper.to_json(trials))

        for taskname, tasktrials in TrialHelper.categorize_in(
                trials, lambda t: t.ds["task"]).items():
            valid_trials = zip(
                tasktrials,
                TrialHelper.pass_fail_list(
                    tasktrials, lambda t: t.ds["status"] == "valid"))
            valid_trials = [
                trial for trial, isvalid in valid_trials if isvalid
            ]
            num_valid = len(valid_trials)
            num_pass = len(
                filter(lambda x: x, TrialHelper.pass_fail_list(valid_trials)))
            log("task[{}] valid trials: {}/{}, pass trials: {}/{}".format(
                taskname, num_valid, len(tasktrials), num_pass, num_valid))

        if need_to_reboot:
            AudioFunction.stop_audio()
            log("No valid trials, might be some problems!")
            log("trigger bugreport!")
            trigger_bugreport(device)
            log("Try to reboot the device")
            if not try_to_reboot_device(serialno, timeout=300):
                log("reboot failed!")
                os.system(
                    "mv bugreport*.zip {}{}{}_report-bugreport{}{}{}".format(
                        ROOT_DIR, SEP, GLOBAL["test_config"], SEP, postfix,
                        SEP))
                os.system("mv {}-*.png {}{}{}_report-bugreport{}{}{}".format(
                    postfix, ROOT_DIR, SEP, GLOBAL["test_config"], SEP,
                    postfix, SEP))
                break
            else:
                time.sleep(5)
                device, serialno = ViewClient.connectToDeviceOrExit(
                    serialno=serialno)

        os.system("mv bugreport*.zip {}{}{}_report-bugreport{}{}{}".format(
            ROOT_DIR, SEP, GLOBAL["test_config"], SEP, postfix, SEP))

        num_iter -= BATCH_SIZE
        batch_count += 1
        time.sleep(5)

    AudioFunction.finalize()
    Logger.finalize()
def run(num_iter, serialno):
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    out, err = Adb.execute(["shell", "getprop", "ro.vendor.build.fingerprint"],
                           serialno=serialno)
    log("build number: '{}'".format(out.strip()))

    report_file_name = "./log/test_report_{}.json".format(serialno)

    try:
        trials = TrialHelper.load(report_file_name)

    except:
        trials = []

    if len(trials) > 0:
        pass_cnt = len(
            filter(
                lambda x: x,
                TrialHelper.pass_fail_list(
                    trials, check_func=lambda x: not x.ds["error-msg"])))
        fail_cnt = len(trials) - pass_cnt
    else:
        pass_cnt, fail_cnt = 0, 0

    try:
        for i in range(int(num_iter)):
            log("-------------------- reboot-snd-card-test #{} --------------------"
                .format(i + 1))
            trial = Trial(taskname="reboot-snd-card-test",
                          pass_check=lambda x: not x.ds["error-msg"])

            log("reboot the device")
            _, err = Adb.execute(["reboot"], serialno=serialno)
            if len(err) > 0:
                log("adb error: '{}'".format(err.strip()))
                time.sleep(5)
                continue

            time.sleep(5)
            try:
                wait_for_device(serialno=serialno)
            except:
                break

            log("now checking the snd card")
            elapsed = wait_for_snd_card(serialno=serialno, timeout=30)
            if elapsed < 0:
                fail_cnt += 1
                trial.invalidate(errormsg="no sound card")
                error_handle(serialno=serialno, trial=trial)
            else:
                pass_cnt += 1
                log("elapsed: {} ms".format(elapsed))
                trial.put_extra("elapsed", elapsed)

            trials.append(trial)
            with open(report_file_name, "w") as f:
                f.write(TrialHelper.to_json(trials))

            log("pass/fail/total: {}/{}/{}".format(pass_cnt, fail_cnt,
                                                   pass_cnt + fail_cnt))

            time.sleep(20)
    except:
        pass

    Logger.finalize()
Esempio n. 7
0
def run(num_iter=1):
    AudioFunction.init()
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    os.system("mkdir -p {}{}ssr_report > {}".format(ROOT_DIR, SEP, STDNUL))
    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)
    push_files(serialno)
    wake_device(device, serialno)
    SSRDumpListener.init(device, serialno)

    # keymap reference:
    #   https://github.com/dtmilano/AndroidViewClient/blob/master/src/com/dtmilano/android/adb/androidkeymap.py
    device.press("HOME")
    time.sleep(1)
    AATApp.launch_app(device)
    time.sleep(1)

    trials = []
    batch_count = 1
    while num_iter > 0:
        log("-------- batch_run #{} --------".format(batch_count))
        AATApp.print_log(
            device,
            severity="i",
            tag=TAG,
            log="-------- batch_run #{} --------".format(batch_count))
        trials_batch = []
        trials_batch += playback_task_run(device,
                                          num_iter=min([num_iter, BATCH_SIZE]))
        trials_batch += record_task_run(device,
                                        serialno,
                                        num_iter=min([num_iter, BATCH_SIZE]))
        trials_batch += voip_task_run(device,
                                      serialno,
                                      num_iter=min([num_iter, BATCH_SIZE]))

        map(lambda trial: trial.put_extra(name="batch_id", value=batch_count),
            trials_batch)
        trials += trials_batch
        with open("{}{}ssr_report{}{}".format(ROOT_DIR, SEP, SEP, filename),
                  "w") as f:
            f.write(TrialHelper.to_json(trials))

        for taskname, tasktrials in TrialHelper.categorize_in(
                trials, lambda t: t.ds["task"]).items():
            valid_trials = zip(
                tasktrials,
                TrialHelper.pass_fail_list(
                    tasktrials, lambda t: t.ds["status"] == "valid"))
            valid_trials = [
                trial for trial, isvalid in valid_trials if isvalid
            ]
            num_valid = len(valid_trials)
            num_pass = len(
                filter(lambda x: x, TrialHelper.pass_fail_list(valid_trials)))
            log("task[{}] valid trials: {}/{}, pass trials: {}/{}".format(
                taskname, num_valid, len(tasktrials), num_pass, num_valid))

        num_iter -= BATCH_SIZE
        batch_count += 1

    AudioFunction.finalize()
    Logger.finalize()
    SSRDumpListener.finalize()
Esempio n. 8
0
def run(num_iter=1, is_MO=False):
    # initail componet
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    if PLATFORM == WINDOWS:
        os.system("mkdir {}/{} ".format(ROOT_DIR, REPORT_DIR))
    elif PLATFORM == LINUX:
        os.system("mkdir -p {}/{} ".format(ROOT_DIR, REPORT_DIR))
    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)

    trials = []

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)

    log(serialno)
    time.sleep(1)
    wake_device(device, serialno)
    time.sleep(1)
    device.press("HOME")

    if is_MO:
        log("This test is running as MO call")
        notAnsweredTimes = 0
        test_count = 0
        while num_iter > 0 and notAnsweredTimes <= 5:
            num_iter -= 1
            test_count += 1
            # target control_MO_phone out phone
            log("start target MO")
            ret = control_MO_phone(device, serialno, True)
            if ret is False:
                log("can't out phone call")
                control_Stop_Call(device, serialno)
                continue
            else:
                log("phone call out: TX test")

            time.sleep(1)
            # phone call start
            timeout = 30
            isCallAnswered = False
            log("Waiting target answer our call in {} secs".format(timeout))

            while (timeout > 0):
                if (get_callDuration_id(device, serialno)):
                    log("Target has answered our call!")
                    isCallAnswered = True
                    break
                else:
                    log("Target not yet answered... {}".format(timeout))
                    timeout -= 3

            if (isCallAnswered):
                log("-------- batch_run #{} --------".format(test_count))
                phone_call_tx_task(device, serialno)
            else:
                log("Timeout: 30 secs")
                log("Target didn't answer our call...")
                control_Stop_Call(device, serialno)
                notAnsweredTimes += 1
            if not detect_DQ_stop(device, serialno):
                log("can't detect DQ log stop")
                continue

    else:
        log("This test is running as MT call")
        batch_count = 0
        while True:
            trials_batch = []

            # test control_MT_phone then recive phone
            ret = control_MT_phone(device, serialno)
            if ret is False:
                log("Timeout: no phone call comming")
                Logger.finalize()
                return
            else:
                log("Detected: answer the call")
                log("Phone call start: RX test")
                batch_count += 1

            # phone call start
            log("-------- batch_run #{} --------".format(batch_count))
            log("phone_call_task_rx_run++")
            trials_batch += phone_call_rx_task()

            map(
                lambda trial: trial.put_extra(name="batch_id",
                                              value=batch_count), trials_batch)
            trials += trials_batch
            with open("{}/{}/{}".format(ROOT_DIR, REPORT_DIR, filename),
                      "w") as f:
                f.write(TrialHelper.to_json(trials))

            control_Stop_Call(device, serialno)
            log("phone_call_task_rx_run--")

    Logger.finalize()
Esempio n. 9
0
def run(num_iter=1, serialno1=None, serialno2=None):
    '''
    # initail componet
    AudioFunction.init()
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    os.system("mkdir -p {}/{} > /dev/null".format(ROOT_DIR, REPORT_DIR))  # windows need modified
    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(t.year, t.month, t.day, t.hour, t.minute, t.second)

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)
    wake_device(device, serialno)
    # keymap reference:
    #   https://github.com/dtmilano/AndroidViewClient/blob/master/src/com/dtmilano/android/adb/androidkeymap.py
    device.press("HOME")
    time.sleep(0.5)

    trials = []
    batch_count = 1
    while num_iter > 0:
        log("-------- batch_run #{} --------".format(batch_count))
        trials_batch = []
        trials_batch += playback_task_run(device, num_iter=min([num_iter, BATCH_SIZE]))
        trials_batch += playback_format_task_run(device, num_iter=min([num_iter, BATCH_SIZE]))
        trials_batch += playback_GoogleMusic_run(device, serialno, num_iter=min([num_iter, BATCH_SIZE]))

        map(lambda trial: trial.put_extra(name="batch_id", value=batch_count), trials_batch)
        trials += trials_batch
        with open("{}/{}/{}".format(ROOT_DIR, REPORT_DIR, filename), "w") as f:
            f.write(TrialHelper.to_json(trials))

        num_iter -= BATCH_SIZE
        batch_count += 1

    AudioFunction.finalize()
    Logger.finalize()
    '''

    # initail componet
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    if PLATFORM == WINDOWS:
        os.system("mkdir {}/{} ".format(ROOT_DIR, REPORT_DIR))
    elif PLATFORM == LINUX:
        os.system("mkdir -p {}/{} ".format(ROOT_DIR, REPORT_DIR))
    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)

    trials = []

    if serialno1:
        device1, serialno1 = ViewClient.connectToDeviceOrExit(
            serialno=serialno1)
        target_sn = serialno1
        log(serialno1)

    if serialno2:
        device2, serialno2 = ViewClient.connectToDeviceOrExit(
            serialno=serialno2)
        test_sn = serialno2
        log(serialno2)

    if serialno1 is None or serialno2 is None:
        log("please input 2 phone serialno")
        return

    time.sleep(1)
    wake_device(device1, serialno1)
    time.sleep(1)
    wake_device(device2, serialno2)
    time.sleep(1)
    device1.press("HOME")
    device2.press("HOME")
    time.sleep(1)

    original = get_Auto_Mute_Mode()
    #disable_Auto_Mute_Mode()

    batch_count = 1
    while num_iter > 0:
        trials_batch = []

        # target control_MO_phone out phone
        log("start target MO")
        ret = control_MO_phone(device1, serialno1, True)
        if ret is False:
            log("can't out phone call")
            control_Stop_Call(device1, serialno1)
            continue
        else:
            log("phone call out: TX test")

        # test   control_MT_phone then recive phone
        ret = control_MT_phone(device2, serialno2)
        if ret is False:
            log("can't answer phone call")
            control_Stop_Call(device1, serialno1)
            continue
        else:
            log("phone call start: TX test")

        if not detect_DQ_start(device1, serialno1):
            log("can't detect DQ log start")
            # add trials for DQ
            continue

        log("-------- batch_run #{} --------".format(batch_count))
        # phone call start

        trials_batch += phone_call_tx_task()
        time.sleep(2)
        trials_batch += phone_call_rx_task()

        control_Stop_Call(device1, serialno1)
        if not detect_DQ_stop(device1, serialno1):
            log("can't detect DQ log stop")
            continue

        map(lambda trial: trial.put_extra(name="batch_id", value=batch_count),
            trials_batch)
        trials += trials_batch
        with open("{}/{}/{}".format(ROOT_DIR, REPORT_DIR, filename), "w") as f:
            f.write(TrialHelper.to_json(trials))

        num_iter -= BATCH_SIZE
        batch_count += 1

    #######

    change_soundcard_setting(0)
    set_Auto_Mute_Mode(original)
    log("-------- set_Auto_Mute_Mode --------")

    Logger.finalize()
def run(num_iter=1, is_MO=False):
    # initail componet
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    Adb.init()

    if PLATFORM == WINDOWS:
        os.system("mkdir {}/{} ".format(ROOT_DIR, REPORT_DIR))
    elif PLATFORM == LINUX:
        os.system("mkdir -p {}/{} ".format(ROOT_DIR, REPORT_DIR))
    t = datetime.datetime.now()
    filename = "report_{}{:02d}{:02d}_{:02d}{:02d}{:02d}.json".format(
        t.year, t.month, t.day, t.hour, t.minute, t.second)

    trials = []

    device, serialno = ViewClient.connectToDeviceOrExit(serialno=None)

    log(serialno)
    time.sleep(1)
    wake_device(device, serialno)
    time.sleep(1)
    device.press("HOME")

    if is_MO:
        log("This test is running as MO call")
        notAnsweredTimes = 0
        test_count = 0

        #start to test MO call tx
        log("===== Now is running as MO tx test for {} times =====".format(
            num_iter))
        while test_count < num_iter and notAnsweredTimes <= 5:
            # MO start to call target
            log("MO start to call target ({})".format(test_count + 1))
            ret = control_MO_phone(device, serialno, True)
            if ret is False:
                log("control_MO_phone failed: cannot dial out")
                control_Stop_Call(device, serialno)
                continue
            else:
                log("MO call: dial out success!")

            time.sleep(1)
            # Waiting target answer the call
            timeout = 30
            isCallAnswered = False
            log("Waiting target answer our call in {} secs".format(timeout))

            while (timeout > 0):
                if (get_callDuration_id(device, serialno)):
                    log("Target has answered our call!")
                    isCallAnswered = True
                    break
                else:
                    log("Target not yet answered... {}".format(timeout))
                    timeout -= 3

            if (isCallAnswered):
                test_count += 1
                log("-------- batch_run #{} --------".format(test_count))
                play_sound_and_wait_cut(device, serialno)
            else:
                log("Timeout: 30 secs")
                log("Target didn't answer our call...")
                control_Stop_Call(device, serialno)
                notAnsweredTimes += 1
            if not detect_DQ_stop(device, serialno):
                log("can't detect DQ log stop")
                continue

        #start to test MO call rx
        #reset test_count
        test_count = 0
        log("===== Now is running as MO rx test for {} times =====".format(
            num_iter))
        while test_count < num_iter and notAnsweredTimes <= 5:
            trials_batch = []
            # MO start to call target
            log("MO start to call target ({})".format(test_count + 1))
            ret = control_MO_phone(device, serialno, True)
            if ret is False:
                log("control_MO_phone failed: cannot dial out")
                control_Stop_Call(device, serialno)
                continue
            else:
                log("MO call: dial out success")

            time.sleep(1)
            # phone call start
            timeout = 30
            isCallAnswered = False
            log("Waiting target answer our call in {} secs".format(timeout))

            while (timeout > 0):
                if (get_callDuration_id(device, serialno)):
                    log("Target has answered our call!")
                    isCallAnswered = True
                    break
                else:
                    log("Target not yet answered... {}".format(timeout))
                    timeout -= 3

            if (isCallAnswered):
                test_count += 1
                log("-------- batch_run #{} --------".format(test_count))
                trials_batch += detect_sound_task()
                map(
                    lambda trial: trial.put_extra(name="batch_id",
                                                  value=test_count),
                    trials_batch)
                trials += trials_batch
                with open("{}/{}/{}".format(ROOT_DIR, REPORT_DIR, filename),
                          "w") as f:
                    f.write(TrialHelper.to_json(trials))
                log("MO hang up the call...")
                control_Stop_Call(device, serialno)
            else:
                log("Timeout: 30 secs")
                log("Target didn't answer our call...")
                control_Stop_Call(device, serialno)
                notAnsweredTimes += 1
            if not detect_DQ_stop(device, serialno):
                log("can't detect DQ log stop")
                continue

    else:
        log("This test is running as MT call")
        log("===== Now is running as MT rx test for {} times =====".format(
            num_iter))
        test_count = 0
        #start to test MT call rx
        while test_count < num_iter:
            trials_batch = []

            # test control_MT_phone then recive phone
            ret = control_MT_phone(device, serialno)
            if ret is False:
                log("Timeout: no phone call comming")
                Logger.finalize()
                return

            # phone call start
            log("Detected: answer the call")
            log("Phone call start: MT detect sound")
            test_count += 1

            log("-------- batch_run #{} --------".format(test_count))
            log("phone_call_task_rx_run++")
            trials_batch += detect_sound_task()

            map(
                lambda trial: trial.put_extra(name="batch_id",
                                              value=test_count), trials_batch)
            trials += trials_batch
            with open("{}/{}/{}".format(ROOT_DIR, REPORT_DIR, filename),
                      "w") as f:
                f.write(TrialHelper.to_json(trials))
            log("MT hang up the call...")
            control_Stop_Call(device, serialno)
            log("phone_call_task_rx_run--")

        #start to test MT call tx
        #reset test_count
        test_count = 0
        log("===== Now is running as MT tx test for {} times =====".format(
            num_iter))
        while test_count < num_iter:
            # test control_MT_phone then recive phone
            ret = control_MT_phone(device, serialno)
            if ret is False:
                log("Timeout: no phone call comming")
                Logger.finalize()
                return

            # phone call start
            log("Detected: answer the call")
            log("Phone call start: MT play sound")
            test_count += 1

            log("-------- batch_run #{} --------".format(test_count))
            log("MT_call_play_sound_task++")
            play_sound_and_wait_cut(device, serialno)

            log("MT_call_play_sound_task--")

    Logger.finalize()