def start_listen(target_freq, cb, serialno=None):
     if serialno:
         Adb.execute(cmd=["logcat", "-c"], serialno=serialno)
         ToneDetector.WORK_THREAD = ToneDetectorForDeviceThread(
             serialno=serialno, target_freq=target_freq, callback=cb)
     else:
         ToneDetector.WORK_THREAD = ToneDetectorForServerThread(
             target_freq=target_freq, callback=cb)
     ToneDetector.WORK_THREAD.start()
Ejemplo n.º 2
0
def clear_and_update_music_files(serialno):
    filenames, _ = Adb.execute(cmd=["shell", "ls", DEVICE_MUSIC_DIR],
                               serialno=serialno)
    filenames = filenames.split()
    cmdprefix = [
        "shell", "am", "broadcast", "-a",
        "android.intent.action.MEDIA_SCANNER_SCAN_FILE", "-d"
    ]
    for filename in filenames:
        Adb.execute(cmd=["shell", "rm", DEVICE_MUSIC_DIR + filename],
                    serialno=serialno)
        Adb.execute(cmd=cmdprefix +
                    ["file:///mnt/" + DEVICE_MUSIC_DIR + filename],
                    serialno=serialno)

    for file_to_pushed in FILE_NAMES:
        out, _ = subprocess.Popen(["find", ROOT_DIR, "-name", file_to_pushed],
                                  stdout=subprocess.PIPE).communicate()
        file_path = out.splitlines()[0] if out else None
        if file_path:
            Adb.execute(cmd=["push", file_path, DEVICE_MUSIC_DIR],
                        serialno=serialno)
            Adb.execute(cmd=cmdprefix +
                        ["file:///mnt/" + DEVICE_MUSIC_DIR + file_to_pushed],
                        serialno=serialno)
Ejemplo n.º 3
0
def fetch_dmesg(latest_log=None, serialno=None):
    out, err = Adb.execute(["shell", "dmesg"], tolog=False, serialno=serialno)
    dmesg_entries = map(DmesgEntry, out.splitlines())
    if latest_log:
        dmesg_entries = filter(lambda x: x.timestamp > latest_log.timestamp,
                               dmesg_entries)
    return dmesg_entries
Ejemplo n.º 4
0
def get_phone_state(serialno):
    out, err = Adb.execute(["shell", "dumpsys telephony.registry"],
                           tolog=False,
                           serialno=serialno)
    out = filter(lambda x: "mCallState" in x, out.splitlines())
    if len(out) == 0:
        return None
    return int(out[0].strip()[-1])
Ejemplo n.º 5
0
 def installed(child, serialno=None, tolog=True):
     out, _ = Adb.execute(["shell", "pm list packages"],
                          serialno=serialno,
                          tolog=tolog)
     packages = [
         line.split(":")[-1].strip() for line in out.splitlines()
         if line.startswith("package:")
     ]
     return child.get_package() in packages
Ejemplo n.º 6
0
def error_handle(serialno, trial):
    out, _ = Adb.execute(["shell", "cat", "/proc/asound/cards"],
                         serialno=serialno)
    for line in out.splitlines():
        log(line)

    out, _ = Adb.execute(["shell", "lsmod"], serialno=serialno)
    for line in out.splitlines():
        log(line)

    out, _ = Adb.execute(["shell", "dmesg"], serialno=serialno)
    log_file_name = "./log/dmesg-{}-{}.txt".format(serialno,
                                                   trial.ds["timestamp"])
    with open(log_file_name, "w") as f:
        f.write(out)
    log("write the kernel log to {}".format(log_file_name))
    for line in out.splitlines():
        if "rt5514" in line or "cs35l36" in line:
            log(line)
Ejemplo n.º 7
0
 def grant_permissions(child, serialno=None, tolog=True, warning=True):
     for perm, granted in child.get_permissions(serialno=serialno,
                                                tolog=tolog).items():
         if granted or not perm.startswith("android.permission."):
             continue
         cmd = "pm grant {} {}".format(child.get_package(), perm)
         out, err = Adb.execute(["shell", cmd],
                                serialno=serialno,
                                tolog=tolog)
         if warning and len(err) > 0:
             child.log("grant permission failed: {}".format(err.strip()))
Ejemplo n.º 8
0
    def get_permissions(child, serialno=None, tolog=True):
        if not child.installed(serialno=serialno, tolog=tolog):
            child.log("{} should be installed on the device.".format(
                child.TAG))
            return None

        out, _ = Adb.execute(
            ["shell", "dumpsys package {}".format(child.get_package())],
            serialno=serialno,
            tolog=tolog)
        lines = out.splitlines()
        requested_perm_idx = [idx for idx, line in enumerate(lines) \
            if "requested permissions:" == line.strip()][0]
        install_perm_idx = [idx for idx, line in enumerate(lines) \
            if "install permissions:" == line.strip()][0]
        install_perm_idx_end = [idx for idx, line in enumerate(lines[install_perm_idx+1:]) \
            if not "android.permission." in line][0] + install_perm_idx + 1

        runtime_perm_idx = [idx for idx, line in enumerate(lines) \
            if "runtime permissions:" == line.strip()][0]
        runtime_perm_idx_end = [idx for idx, line in enumerate(lines[runtime_perm_idx+1:]) \
            if not "android.permission." in line][0] + runtime_perm_idx + 1

        requested_perms = [
            line.strip()
            for line in lines[requested_perm_idx + 1:install_perm_idx]
        ]
        install_perms = [
            line.strip()
            for line in lines[install_perm_idx + 1:install_perm_idx_end]
        ]
        runtime_perms = [
            line.strip()
            for line in lines[runtime_perm_idx + 1:runtime_perm_idx_end]
        ]

        perms = {}
        for perm in requested_perms:
            perms[perm.split(":")[0]] = False
        for perm in install_perms:
            if not "granted=" in perm:
                continue
            perms[perm.split(":")[0]] = perm.split(
                "granted=")[-1].lower() == "true"
        for perm in runtime_perms:
            if not "granted=" in perm:
                continue
            perms[perm.split(":")[0]] = perm.split(":")[-1].split(
                ",")[0].split("granted=")[-1].lower() == "true"

        return perms
Ejemplo n.º 9
0
def wait_for_device(serialno):
    cnt = 0
    start = datetime.datetime.now()
    while True:
        out, _ = Adb.execute(["devices"], tolog=False)
        if serialno in out:
            log("adb device '{}' available".format(serialno))
            return
        wait_time = (datetime.datetime.now() - start).total_seconds()
        if int(wait_time) % 5 == 0:
            if int(wait_time) / 5 > cnt:
                log("wait_for_device('{}'): {} secs".format(
                    serialno, wait_time))
                cnt += 1
Ejemplo n.º 10
0
def wait_for_snd_card(serialno, timeout):
    start = datetime.datetime.now()
    while True:
        wait_time = (datetime.datetime.now() - start).total_seconds()
        if wait_time > timeout:
            return -1

        out, _ = Adb.execute(["shell", "cat", "/proc/asound/cards"],
                             serialno=serialno,
                             tolog=False)
        if len(out.splitlines()) > 1:
            log("<soundcard name>")
            for line in out.splitlines():
                log(line)
            return wait_time * 1000
        time.sleep(0.02)
Ejemplo n.º 11
0
def push_files_if_needed(serialno):
    out, _ = Adb.execute(cmd=["shell", "ls", DEVICE_MUSIC_DIR], serialno=serialno)

    # The command "adb shell ls" might return several lines of strings where each line lists multiple file names
    # Then the result should be handled line by line:
    #           map function for split with spaces and reduce function for concatenate the results of each line
    files = reduce(lambda x, y: x+y, map(lambda s: s.split(), out.splitlines())) if out else []

    for file_to_pushed in FILE_NAMES:
        if file_to_pushed in files:
            continue
        out, _ = subprocess.Popen(["find", ROOT_DIR, "-name", file_to_pushed], stdout=subprocess.PIPE).communicate()
        file_path = out.splitlines()[0] if out else None
        if file_path:
            os.system("adb -s {} push {} {} > {}".format(serialno, file_path, DEVICE_MUSIC_DIR, STDNUL))
        else:
            raise ValueError("Cannot find the file \"{}\", please place it under the project tree.".format(file_to_pushed))
Ejemplo n.º 12
0
def run(num_iter=1, serialno=None):
    num_iter = int(num_iter)
    Adb.init()
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT, prefix="quick-start")

    check_props = {
        "Device name": "ro.product.model",
        "Project": "ro.build.product",
        "ROM": "ro.product.build.fingerprint",
    }

    passed = True
    for tag, prop in check_props.items():
        out, err = Adb.execute(["shell", "getprop {}".format(prop)],
                               serialno=serialno)
        passed &= len(err) == 0
        out = out.strip()
        Logger.log(LOGGER_TAG, "{}: {}".format(tag, out))

    Logger.log(LOGGER_TAG,
               "result: {}".format("passed" if passed else "failed"))
    Logger.finalize()
Ejemplo n.º 13
0
def fetch_setmode_events(serialno):
    out, err = Adb.execute(["shell", "dumpsys", "audio"],
                           tolog=False,
                           serialno=serialno)
    setmode_events = filter(lambda x: "setMode" in x, out.splitlines())
    return map(SetModeEvent, setmode_events)
Ejemplo n.º 14
0
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()
Ejemplo n.º 15
0
def main():
    Logger.init(Logger.Mode.STDOUT)
    Adb.init()

    trial_num = 1
    pass_trial_num = 0
    try:
        while True:
            Adb.execute(["shell", "input", "keyevent", "POWER"])
            Adb.execute([
                "shell", AATApp.INTENT_PREFIX,
                AATApp.HTC_INTENT_PREFIX + "record.start"
            ])
            time.sleep(2)
            log("play 220Hz_44100Hz_15secs_2ch.wav")
            os.system(
                "adb shell tinyplay /data/220Hz_44100Hz_15secs_2ch.wav > /dev/null &"
            )
            retry = 5
            detected = False
            while retry > 0:
                out, err = Adb.execute([
                    "shell", "cat",
                    "/storage/emulated/0/AudioFunctionsDemo-record-prop.txt"
                ],
                                       tolog=False)
                try:
                    out = float(out.split(",")[0])
                except:
                    out = 0.0

                if out > 200.0 and out < 240.0:
                    log("detected tones.")
                    detected = True
                    break

                time.sleep(0.1)

            time.sleep(1)

            log("turn off the screen.")
            Adb.execute(["shell", "input", "keyevent", "POWER"])

            time.sleep(2)

            retry = 5
            detected = False
            detected_cnt = 0
            while retry > 0:
                out, err = Adb.execute([
                    "shell", "cat",
                    "/storage/emulated/0/AudioFunctionsDemo-record-prop.txt"
                ],
                                       tolog=False)
                try:
                    out = float(out.split(",")[0])
                except:
                    out = 0.0

                if out > 200.0 and out < 240.0:
                    log("detected tones.")
                    detected_cnt += 1
                    if detected_cnt == 10:
                        log("detected for a sufficient times.")
                        detected = True
                        break

                time.sleep(0.1)

            if detected:
                pass_trial_num += 1
                log("trial #{}: passed. ({}/{})".format(
                    trial_num, pass_trial_num, trial_num))
            else:
                log("trial #{}: failed. ({}/{})".format(
                    trial_num, pass_trial_num, trial_num))

            trial_num += 1
            time.sleep(15)

    except:
        pass

    Logger.finalize()
Ejemplo n.º 16
0
def run(num_iter, serialno1, phoneno1, serialno2, phoneno2):
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    # Logger.init(Logger.Mode.STDOUT)
    Adb.init()

    for serialno in [serialno1, serialno2]:
        Adb.execute(["root"], serialno=serialno)
        Adb.execute(["shell", "'echo \'related\' > msm_subsys'"], serialno=serialno)
        Adb.execute(["shell", "svc", "power", "stayon", "true"], serialno=serialno)

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

    latest_dmesg1 = fetch_dmesg(serialno=serialno1)
    latest_dmesg2 = fetch_dmesg(serialno=serialno2)
    latest_dmesg1 = latest_dmesg1[0] if len(latest_dmesg1) > 0 else None
    latest_dmesg2 = latest_dmesg2[0] if len(latest_dmesg2) > 0 else None

    phone_dict = {
        serialno1: phoneno1,
        serialno2: phoneno2
    }
    last_dmesg_dict = {
        serialno1: latest_dmesg1,
        serialno2: latest_dmesg2
    }
    mt_serialno = serialno1
    mo_serialno = serialno2

    pass_trial_cnt = 0
    total_trial_cnt = 0
    invalid_trial_cnt = 0
    failed_trial_cnt = 0

    try:
        for i in range(int(num_iter)):
            log("-------------------- Dual-CS-call-test #{} --------------------".format(i+1))

            log("{} makes call to {} ({})".format(mo_serialno, mt_serialno, phone_dict[mt_serialno]))
            start_cs_call(tel=phone_dict[mt_serialno], serialno=mo_serialno)
            if not wait_for_phone_state(state=1, timeout=30, serialno=mt_serialno):
                log("There is no incoming call to {}, next trial".format(mt_serialno))
                end_cs_call(serialno=mo_serialno)
                end_cs_call(serialno=mt_serialno)
                invalid_trial_cnt += 1
                continue

            log("{} picks up the call".format(mt_serialno))
            pick_cs_call(serialno=mt_serialno)
            if not wait_for_phone_state(state=2, timeout=10, serialno=mo_serialno):
                log("{} is not in phone state 'MODE_INCALL', next trial".format(mo_serialno))
                end_cs_call(serialno=mo_serialno)
                end_cs_call(serialno=mt_serialno)
                invalid_trial_cnt += 1
                continue
            if not wait_for_phone_state(state=2, timeout=10, serialno=mt_serialno):
                log("{} is not in phone state 'MODE_INCALL', next trial".format(mt_serialno))
                end_cs_call(serialno=mo_serialno)
                end_cs_call(serialno=mt_serialno)
                invalid_trial_cnt += 1
                continue

            log("To check if ADSP crashes during the CS call")
            is_passed = True
            pass_trial_cnt += 1
            total_trial_cnt += 1
            retry = 15
            while retry > 0:
                for serialno in [mt_serialno, mo_serialno]:
                    latest_dmesg = last_dmesg_dict[serialno]
                    new_dmesgs = fetch_dmesg(latest_dmesg, serialno=serialno)
                    if len(new_dmesgs) > 0:
                        last_dmesg_dict[serialno] = new_dmesgs[-1]
                        adsp_ssr_demsgs = filter(lambda x: "Restart sequence requested for adsp" in x.raw, new_dmesgs)
                        if len(adsp_ssr_demsgs) > 0:
                            for dmesg in adsp_ssr_demsgs:
                                log("SSR log detected in {}: '{}'".format(serialno, dmesg.raw))
                            is_passed = False
                            break

                    phone_state = get_phone_state(serialno=serialno)
                    if phone_state == None:
                        log("the phone state of {} is unobtainable, something wrong".format(serialno))
                        is_passed = False
                        break
                    if phone_state == 0:
                        log("the phone state of {} is in idle, the call might be dropped".format(serialno))
                        is_passed = False
                        break

                if not is_passed:
                    for serialno in [mt_serialno, mo_serialno]:
                        out, err = Adb.execute(["bugreport"], serialno)
                        log("bugreport to '{}'".format(out.strip()))
                    pass_trial_cnt -= 1
                    failed_trial_cnt += 1
                    for serialno in [mt_serialno, mo_serialno]:
                        end_cs_call(serialno=serialno)
                    break

                if retry % 5 == 0:
                    log("{} switches path to '{}'".format(mo_serialno, "speaker" if retry/5 % 2 == 1 else "receiver"))
                    Adb.execute(["shell", "input", "tap", "1000", "1000"], tolog=False, serialno=mo_serialno)

                retry -= 1
                time.sleep(1)

            log("result: {} ({}/{})".format("pass" if retry == 0 else "fail", pass_trial_cnt, total_trial_cnt))
            log("pass: {}% ({}/{}), fail: {}% ({}/{}), invalid: {}% ({}/{})".format(
                    pass_trial_cnt*100.0/total_trial_cnt, pass_trial_cnt, total_trial_cnt,
                    failed_trial_cnt*100.0/total_trial_cnt, failed_trial_cnt, total_trial_cnt,
                    invalid_trial_cnt*100.0/(i+1), invalid_trial_cnt, i+1))
            for serialno in [mo_serialno, mt_serialno]:
                end_cs_call(serialno=serialno)
                wait_for_phone_state(state=0, timeout=10, serialno=serialno)
            time.sleep(5)
    except:
        pass

    for serialno in [serialno1, serialno2]:
        end_cs_call(serialno=serialno)
        Adb.execute(["shell", "svc", "power", "stayon", "false"], serialno=serialno)
    Logger.finalize()
Ejemplo n.º 17
0
 def launch_app(child, device=None, serialno=None):
     Adb.execute(
         ["shell", "am start -n {}".format(child.get_launch_component())],
         serialno=serialno)
Ejemplo n.º 18
0
    def run(self):
        shared_vars = {"start_time": None, "last_event": None, "last_freq": -1}

        self.extra = {}
        self.extra["adb-read-prop-max-elapsed"] = -1
        self.extra["freq-cb-max-elapsed"] = -1
        self.extra["dump"] = []
        self.extra["dump-lock"] = threading.Lock()

        def freq_cb(msg):
            line = msg.splitlines()[0]
            strs = line.split()
            freq, amp_db = list(map(float, strs[-1].split(",")))
            the_date, the_time = strs[:2]

            time_str = the_date + " " + the_time

            if shared_vars["last_freq"] != freq:
                self.push_to_dump( \
                    "the detected freq has been changed from {} to {} Hz".format(shared_vars["last_freq"], freq))
                shared_vars["last_freq"] = freq

            thresh = 10 if self.target_freq else 1
            if super(AATAppToneDetectorThread, self).target_detected(freq):
                self.event_counter += 1
                if self.event_counter == 1:
                    shared_vars["start_time"] = time_str
                if self.event_counter == thresh:
                    if not shared_vars["last_event"] or shared_vars[
                            "last_event"] != ToneDetector.Event.TONE_DETECTED:
                        Logger.log(
                            self.get_tag(),
                            "send_cb({}, TONE_DETECTED)".format(
                                shared_vars["start_time"]))
                        self.cb((shared_vars["start_time"],
                                 ToneDetector.Event.TONE_DETECTED))
                        shared_vars[
                            "last_event"] = ToneDetector.Event.TONE_DETECTED

            else:
                if self.event_counter > thresh:
                    shared_vars["start_time"] = None
                    self.push_to_dump(
                        "the tone is not detected and the event_counter is over the threshold"
                    )
                    self.push_to_dump("last_event: \"{}\"".format(
                        shared_vars["last_event"]))
                if not shared_vars["last_event"] or shared_vars[
                        "last_event"] != ToneDetector.Event.TONE_MISSING:
                    Logger.log(self.get_tag(),
                               "send_cb({}, TONE_MISSING)".format(time_str))
                    self.cb((time_str, ToneDetector.Event.TONE_MISSING))
                    shared_vars["last_event"] = ToneDetector.Event.TONE_MISSING
                self.event_counter = 0

            if self.event_counter <= thresh:
                self.push_to_dump("event_counter: {}".format(
                    self.event_counter))

        # Adb.execute(cmd= \
        #     ["shell", "am", "broadcast", "-a", "audio.htc.com.intent.print.properties.enable", "--ez", "v", "1"], \
        #     serialno=self.serialno)

        from libs.timeutils import TicToc, TimeUtils
        freq_cb_tictoc = TicToc()
        adb_tictoc = TicToc()

        tcount = 0
        freq_cb_tictoc.tic()
        while not self.stoprequest.isSet():
            adb_tictoc.tic()
            msg, _ = Adb.execute(cmd=["shell", "cat", "sdcard/AudioFunctionsDemo-record-prop.txt"], \
                serialno=self.serialno, tolog=False)
            elapsed = adb_tictoc.toc()
            if tcount == 0:
                Adb.execute(cmd=["shell", "rm", "-f", "sdcard/AudioFunctionsDemo-record-prop.txt"], \
                    serialno=self.serialno, tolog=False)

            if not "," in msg:
                msg = "0,-30"

            if elapsed > self.extra["adb-read-prop-max-elapsed"]:
                self.extra["adb-read-prop-max-elapsed"] = elapsed

            if "," in msg:
                msg = msg.replace("\n", "")
                import datetime
                msg = "{} {}".format(TimeUtils.now_str(), msg)

                try:
                    self.push_to_dump("{} (adb-shell elapsed: {} ms)".format(
                        msg, elapsed))
                    freq_cb(msg)
                except Exception as e:
                    Logger.log(self.get_tag(),
                               "crashed in freq_cb('{}')".format(msg))
                    print(e)

                elapsed = freq_cb_tictoc.toc()
                if elapsed > self.extra["freq-cb-max-elapsed"]:
                    self.extra["freq-cb-max-elapsed"] = elapsed

            time.sleep(0.01)
            tcount += 1
            tcount %= 10
Ejemplo n.º 19
0
def trigger_asr(serialno):
    Adb.execute(["shell", "killall", "audioserver"], serialno=serialno)
Ejemplo n.º 20
0
 def stop_app(child, device=None, serialno=None):
     Adb.execute(["shell", "am force-stop {}".format(child.get_package())],
                 serialno=serialno)
Ejemplo n.º 21
0
def trigger_ssr(serialno):
    Adb.execute(["shell", "crash_adsp"], serialno=serialno)
Ejemplo n.º 22
0
 def clear_data(child, serialno=None, tolog=True):
     Adb.execute(["shell", "pm clear {}".format(child.PACKAGE)],
                 serialno=serialno,
                 tolog=tolog)
Ejemplo n.º 23
0
def end_cs_call(serialno):
    Adb.execute(["shell", "input", "keyevent", "KEYCODE_ENDCALL"],
                serialno=serialno)
Ejemplo n.º 24
0
 def install(child, grant=False, serialno=None, tolog=True):
     params = ["-r", "-d"]
     if grant:
         params.append("-g")
     params.append(child.get_apk_path())
     Adb.execute(["install"] + params, serialno=serialno, tolog=tolog)
Ejemplo n.º 25
0
 def uninstall(child, serialno=None, tolog=True):
     Adb.execute(["uninstall", child.get_package()],
                 serialno=serialno,
                 tolog=tolog)
Ejemplo n.º 26
0
def start_cs_call(tel, serialno):
    Adb.execute([
        "shell", "am", "start", "-a", "android.intent.action.CALL", "-d",
        "tel:{}".format(tel)
    ],
                serialno=serialno)
Ejemplo n.º 27
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()
Ejemplo n.º 28
0
def run(num_iter, serialno):
    Logger.init(Logger.Mode.BOTH_FILE_AND_STDOUT)
    # Logger.init(Logger.Mode.STDOUT)
    Adb.init()

    Adb.execute(["root"], serialno=serialno)
    Adb.execute(["shell", "'echo \'related\' > msm_subsys'"],
                serialno=serialno)
    Adb.execute(["shell", "svc", "power", "stayon", "true"], serialno=serialno)

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

    latest_dmesg = fetch_dmesg(serialno=serialno)
    latest_dmesg = latest_dmesg[0] if len(latest_dmesg) > 0 else None

    pass_trial_cnt = 0

    try:
        for i in range(num_iter):
            log("-------------------- CS call test #{} --------------------".
                format(i + 1))

            events = fetch_setmode_events(serialno=serialno)
            latest_event = events[-1] if len(events) > 0 else None
            log("The latest setMode event: '{}'".format(
                latest_event.raw if latest_event else "None"))

            log("Make call to 0988102544")
            start_cs_call(tel="0988102544", serialno=serialno)
            log("Waiting to the mode 'MODE_IN_CALL'")
            if not wait_for_phone_state(state=2, timeout=10,
                                        serialno=serialno):
                log("The phone state never turns in 'MODE_IN_CALL', ignore this trial"
                    )
                continue

            log("To check if ADSP crashes during the CS call")
            is_passed = True
            pass_trial_cnt += 1
            retry = 15
            while retry > 0:
                new_dmesgs = fetch_dmesg(latest_dmesg, serialno=serialno)
                if len(new_dmesgs) > 0:
                    latest_dmesg = new_dmesgs[-1]
                    adsp_ssr_demsgs = filter(
                        lambda x: "Restart sequence requested for adsp" in x.
                        raw, new_dmesgs)
                    if len(adsp_ssr_demsgs) > 0:
                        for dmesg in adsp_ssr_demsgs:
                            log("SSR log detected: '{}'".format(dmesg.raw))
                        is_passed = False

                phone_state = get_phone_state(serialno=serialno)
                if phone_state == None:
                    log("the phone state is unobtainable, something wrong")
                    is_passed = False
                if phone_state == 0:
                    log("the phone state is in idle, the call might be dropped"
                        )
                    is_passed = False

                if not is_passed:
                    out, err = Adb.execute(["bugreport"])
                    log("bugreport to '{}'".format(out.strip()))
                    pass_trial_cnt -= 1
                    break

                if retry % 5 == 0:
                    log("switch path to '{}'".format("speaker" if retry / 5 %
                                                     2 == 1 else "receiver"))
                    Adb.execute(["shell", "input", "tap", "1000", "1000"],
                                tolog=False,
                                serialno=serialno)

                retry -= 1
                time.sleep(1)

            log("result: {} ({}/{})".format("pass" if retry == 0 else "fail",
                                            pass_trial_cnt, i + 1))
            end_cs_call(serialno=serialno)
            time.sleep(10)
    except:
        pass

    Adb.execute(["shell", "svc", "power", "stayon", "false"],
                serialno=serialno)
    Logger.finalize()
Ejemplo n.º 29
0
def voip_task_run(device, serialno, num_iter=1):
    log("voip_task_run++")

    trials = []

    # AATApp.voip_use_speaker(device)
    time.sleep(2)

    stm = DetectionStateListener()

    out_freq = OUT_FREQ
    log("ToneDetector.start_listen(target_freq={})".format(serialno, out_freq))
    ToneDetector.start_listen(
        target_freq=out_freq,
        cb=lambda event: stm.tone_detected_event_cb(event))

    has_triggered_bugreport = False

    Adb.execute(cmd=["shell", "rm", "-f", "sdcard/AudioFunctionsDemo-record-prop.txt"], \
                serialno=serialno)
    AATApp.voip_start(device)
    for i in range(num_iter):
        log("-------- dev_voip_rx_task #{} --------".format(i + 1))

        trial = Trial(taskname="voip_rx",
                      pass_check=lambda t: t.ds["extra"]["elapsed"] > 0)
        trial.put_extra(name="iter_id", value=i + 1)

        AATApp.print_log(device,
                         severity="i",
                         tag=GLOBAL["tag"],
                         log="voip_rx_task #{}".format(i + 1))

        time.sleep(1)
        stm.reset()

        if stm.wait_for_event(DetectionStateListener.Event.ACTIVE,
                              timeout=10) < 0:
            log("the tone was not detected, abort the iteration this time...")
            trial.invalidate(
                errormsg="early return, possible reason: rx no sound")
            trials.append(trial)
            continue
        time.sleep(1)

        log("trigger_{}()".format(GLOBAL["test_config"]))
        if GLOBAL["test_config"] == "ssr":
            trigger_ssr(serialno)
        else:
            trigger_asr(serialno)

        log("Waiting for {} recovery".format("SSR" if GLOBAL["test_config"] ==
                                             "ssr" else "ASR"))
        elapsed = stm.wait_for_event(DetectionStateListener.Event.RISING_EDGE,
                                     timeout=15)
        log("elapsed: {} ms".format(elapsed))

        if elapsed < 0:
            log("Timeout in waiting for rising event, possibly caused by missing event not being caught"
                )
            log("Waiting for the tone being detected")
            if stm.wait_for_event(DetectionStateListener.Event.ACTIVE,
                                  timeout=10) < 0:
                log("The tone is not detected")
                if not has_triggered_bugreport:
                    log("get bugreport...")
                    p = trigger_bugreport(device)
                    trial.put_extra("bugreport", p)
                    has_triggered_bugreport = True
            else:
                log("The tone is detected, please also check the device log for confirming if it is a false alarm"
                    )
                trial.put_extra(name="msg", value="possible false alarm")
            AATApp.voip_stop(device)
            time.sleep(5)
            AATApp.voip_start(device)
        else:
            AATApp.voip_stop(device)
            time.sleep(30 - elapsed / 1000.)
            AATApp.voip_start(device)

        trial.put_extra(name="elapsed", value=elapsed)
        trials.append(trial)

    log("-------- dev_voip_rx_task done --------")
    log("ToneDetector.stop_listen()")
    ToneDetector.stop_listen()

    stm = DetectionStateListener()

    time.sleep(2)
    AATApp.voip_mute_output(device)
    time.sleep(10)
    log("ToneDetector.start_listen(serialno={}, target_freq={})".format(
        serialno, out_freq))

    listen_params = {
        "serialno": serialno,
        "target_freq": out_freq,
        "cb": lambda event: stm.tone_detected_event_cb(event),
        "dclass": ToneDetectorForDeviceThread
    }
    try:
        ToneDetector.start_listen(**listen_params)
    except:

        def voip_parse_detector(voip_info):
            import json
            info = voip_info[2]
            for chandle in info:
                info[chandle] = json.loads(info[chandle])
            return info

        listen_params["params"] = {
            "detector_reg_func": AATApp.voip_detector_register,
            "detector_unreg_func": AATApp.voip_detector_unregister,
            "detector_setparams_func": AATApp.voip_detector_set_params,
            "info_func": AATApp.voip_info,
            "parse_detector_func": voip_parse_detector
        }
        ToneDetector.start_listen(**listen_params)

    has_triggered_bugreport = False

    for i in range(num_iter):
        log("-------- dev_voip_tx_task #{} --------".format(i + 1))

        trial = Trial(taskname="voip_tx",
                      pass_check=lambda t: t.ds["extra"]["elapsed"] > 0)
        trial.put_extra(name="iter_id", value=i + 1)

        AATApp.print_log(device,
                         severity="i",
                         tag=GLOBAL["tag"],
                         log="voip_tx_task #{}".format(i + 1))

        time.sleep(2)

        log("AudioFunction.play_sound(out_freq={})".format(out_freq))
        AudioFunction.play_sound(out_freq=out_freq)

        stm.reset()
        if stm.wait_for_event(DetectionStateListener.Event.ACTIVE,
                              timeout=10) < 0:
            log("the tone was not detected, abort the iteration this time...")
            trial.invalidate(
                errormsg="early return, possible reason: tx no sound")
            trials.append(trial)
            continue
        time.sleep(2)

        log("trigger_{}()".format(GLOBAL["test_config"]))
        if GLOBAL["test_config"] == "ssr":
            trigger_ssr(serialno)
        else:
            trigger_asr(serialno)

        log("waiting for inactive....")
        stm.wait_for_event(DetectionStateListener.Event.INACTIVE, timeout=10)
        Adb.execute(cmd=[
            "shell", "rm", "-f", "sdcard/AudioFunctionsDemo-record-prop.txt"
        ],
                    serialno=serialno)

        log("Waiting for {} recovery".format("SSR" if GLOBAL["test_config"] ==
                                             "ssr" else "ASR"))
        elapsed = stm.wait_for_event(DetectionStateListener.Event.RISING_EDGE,
                                     timeout=15)
        log("elapsed: {} ms".format(elapsed))

        if elapsed < 0:
            log("Timeout in waiting for rising event, possibly caused by missing event not being caught"
                )
            log("Waiting for the tone being detected")
            if stm.wait_for_event(DetectionStateListener.Event.ACTIVE,
                                  timeout=10) < 0:
                log("The tone is not detected")
                if not has_triggered_bugreport:
                    AudioFunction.stop_audio()
                    log("get bugreport...")
                    p = trigger_bugreport(device)
                    trial.put_extra("bugreport", p)
                    has_triggered_bugreport = True

                now = "_".join("{}".format(datetime.datetime.now()).split())
                log("dump the recorded pcm to \"sdcard/PyAAT/dump_{}\"".format(
                    now))
                AATApp.record_dump(device, "sdcard/PyAAT/dump_{}".format(now))

                log("start dumping the process during capturing the frequency..."
                    )
                ToneDetector.WORK_THREAD.dump()
            else:
                log("The tone is detected, please also check the device log for confirming if it is a false alarm"
                    )
                trial.put_extra(name="msg", value="possible false alarm")

        log("AudioFunction.stop_audio()")
        AudioFunction.stop_audio()

        log("ToneDetectorForDeviceThread.adb-read-prop-max-elapsed: {} ms".format( \
            ToneDetector.WORK_THREAD.extra["adb-read-prop-max-elapsed"]))
        log("ToneDetectorForDeviceThread.freq-cb-max-elapsed: {} ms".format( \
            ToneDetector.WORK_THREAD.extra["freq-cb-max-elapsed"]))

        trial.put_extra(name="elapsed", value=elapsed)
        trials.append(trial)

        import random
        out_freq = OUT_FREQ * 2**(random.randint(0, 12) / 12.)
        ToneDetector.set_target_frequency(target_freq=out_freq)
        log("ToneDetector.set_target_frequency(serialno={}, target_freq={})".
            format(serialno, out_freq))

        if elapsed > 0:
            time.sleep(30 - elapsed / 1000.)

    log("-------- dev_voip_tx_task done --------")
    log("dev_voip_stop")
    AATApp.voip_stop(device)
    time.sleep(5)
    log("ToneDetector.stop_listen()")
    ToneDetector.stop_listen()

    log("voip_task_run--")
    relaunch_app(device)
    return trials