예제 #1
0
def playback_GoogleMusic_run(device, serialno, num_iter=1):
    # Google Music
    # play
    # pause
    # resume
    # seek
    # forward
    log("GoogleMusic playback++")
    
    packageGM = "com.google.android.music"
    activityGM = "com.android.music.activitymanagement.TopLevelActivity"
    componentGM = packageGM + "/" + activityGM
    
    cmd = " ".join(["am", "force-stop", packageGM])
    
    freq = 440
    
    trials = []
    
    th = DetectionStateChangeListenerThread()
    th.start()
    
    for i in range(num_iter):
        trial = Trial(taskname="GoogleMusic playback")
        trial.put_extra(name="iter_id", value=i+1)

        # start google music
        device.wake() 
        time.sleep(1)
        device.startActivity(componentGM)
        log("-> GoogleMusic start")

        # into Music list
        log("-> GoogleMusic into Music list")
        vc, key = get_MusicList_id(device, serialno)
        if vc is None:
            log("can't find Music list")
            trial.invalidate(errormsg="can't find Music list")
            trials.append(trial)
            device.shell(cmd)
            continue

        log("find the Music list")
        control_Btn(vc, key)    

        # find 440Hz in list
        log("-> GoogleMusic find 440Hz in list")
        vc = ViewClient(device, serialno)
        view = get_fragment_list_view(device, serialno)
        uis = UiScrollable(view)

        for i in range(3):
            vc, key = get_File_id(device, serialno)
            if key is None:
                log("scroll")
                uis.flingForward()
                continue
            else:
                control_Btn(vc, key)
                break;

        # into art pager interface
        log("-> GoogleMusic into art pager")
        vc, key = get_ArtPager_id(device, serialno)
        if vc is None:
            log("can't find Art Pager")
            trial.invalidate(errormsg="GoogleMusic can't find Art Pager")
            trials.append(trial)
            device.shell(cmd)
            continue

        log("find the Art Pager")
        control_Btn(vc, key)  

        log("ToneDetector.start_listen(target_freq={})".format(freq))
        ToneDetector.start_listen(target_freq=freq, cb=lambda event: th.tone_detected_event_cb(event))

        th.reset()

        # the music already start, so detect it...
        log("-> GoogleMusic start function:")
        if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE, timeout=5) < 0:
            log("the tone was not detected, abort the iteration this time...")

            trial.invalidate(errormsg="GoogleMusic start play fail")
            trials.append(trial)
            device.shell(cmd)
            continue
        else:
            log("-> GoogleMusic start function: pass")
            trial.put_extra(name="GoogleMusic start", value="pass")    

        pop = AudioFunction.get_pop()
        if pop:
            log("pop detect")
            trial.put_extra(name="playback start", value="pop")
                    
        # pause
        log("-> GoogleMusic pause function:")
        vc, key = get_play_pause_id(device, serialno)
        if vc is None:
            log("can't find pause btn")
            trial.invalidate(errormsg="can't find pause btn")
            trials.append(trial)
            device.shell(cmd)
            continue

        log("find the pause btn")
        control_Btn(vc, key)

        if th.wait_for_event(DetectionStateChangeListenerThread.Event.FALLING_EDGE, timeout=5) < 0:
            log("the tone was not pause...")

            trial.invalidate(errormsg="GoogleMusic pause fail")
            trials.append(trial)
            device.shell(cmd)
            continue
        else:
            log("-> GoogleMusic pause function: pass")
            trial.put_extra(name="GoogleMusic pause", value="pass")

        pop = AudioFunction.get_pop()
        if pop:
            log("pop detect")
            trial.put_extra(name="playback start", value="pop")
            
        # resume
        log("-> GoogleMusic resume function:")
        vc, key = get_play_pause_id(device, serialno)
        if vc is None:
            log("can't find resume btn")
            trial.invalidate(errormsg="can't find resume btn")
            trials.append(trial)
            device.shell(cmd)
            continue

        pop = AudioFunction.get_pop()
        if pop:
            log("pop detect")
            trial.put_extra(name="playback start", value="pop")
            
        log("find the resume btn")
        control_Btn(vc, key)

        if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE, timeout=5) < 0:
            log("the tone was not resume...")

            trial.invalidate(errormsg="GoogleMusic resume fail")
            trials.append(trial)
            device.shell(cmd)
            continue
        else:
            log("-> GoogleMusic resume function: pass")
            trial.put_extra(name="GoogleMusic resume", value="pass")

        pop = AudioFunction.get_pop()
        if pop:
            log("pop detect")
            trial.put_extra(name="playback start", value="pop")
        
        time.sleep(1)
        
        # seek
        log("-> GoogleMusic seek function:")
        vc, key = get_progress_id(device, serialno)
        if vc is None:
            log("can't find seek btn")
            trial.invalidate(errormsg="can't find seek btn")
            trials.append(trial)
            device.shell(cmd)
            continue

        log("find the seek btn")
        control_Btn(vc, key)

        if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE, timeout=5) < 0:
            log("seek fail...")

            trial.invalidate(errormsg="GoogleMusic seek fail")
            trials.append(trial)
            device.shell(cmd)
            continue
        else:
            log("-> GoogleMusic seek function: pass")
            trial.put_extra(name="GoogleMusic seek", value="pass")

        pop = AudioFunction.get_pop()
        if pop:
            log("pop detect")
            trial.put_extra(name="playback start", value="pop")
        
        time.sleep(1)
        
        # next
        log("-> GoogleMusic next function:")
        vc, key = get_next_id(device, serialno)
        if vc is None:
            log("can't find next btn")
            trial.invalidate(errormsg="can't find next btn")
            trials.append(trial)
            device.shell(cmd)
            continue

        log("find the next btn")
        control_Btn(vc, key)

        if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE, timeout=5) < 0:
            log("next fail...")

            trial.invalidate(errormsg="GoogleMusic next fail")
            trials.append(trial)
            device.shell(cmd)
            continue
        else:
            log("-> GoogleMusic next function: pass")
            trial.put_extra(name="GoogleMusic next", value="pass")

        pop = AudioFunction.get_pop()
        if pop:
            log("pop detect")
            trial.put_extra(name="playback start", value="pop")
        
        time.sleep(1)
        
        # pause
        log("-> GoogleMusic pause function:")
        vc, key = get_play_pause_id(device, serialno)
        if vc is None:
            log("can't find pause btn")
            trial.invalidate(errormsg="can't find pause btn")
            trials.append(trial)
            device.shell(cmd)
            continue

        log("find the pause btn")
        control_Btn(vc, key)

        if th.wait_for_event(DetectionStateChangeListenerThread.Event.FALLING_EDGE, timeout=5) < 0:
            log("pause fail...")

            trial.invalidate(errormsg="GoogleMusic pause fail")
            trials.append(trial)
            device.shell(cmd)
            continue
        else:
            log("-> GoogleMusic pause function: pass")
            trial.put_extra(name="GoogleMusic pause", value="pass")    

        pop = AudioFunction.get_pop()
        if pop:
            log("pop detect")
            trial.put_extra(name="playback start", value="pop")
        
        time.sleep(1)
        
        device.shell(cmd)
        
    time.sleep(2)
    log("ToneDetector.stop_listen()")
    ToneDetector.stop_listen()
    
    device.shell(cmd)
    th.join()
    
    log("GoogleMusic playback--")
    return trials
예제 #2
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()
예제 #3
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()
예제 #4
0
def playback_format_task_run(device, num_iter=1):
    log("playback_format_task_run++")

    package = "com.htc.audiofunctionsdemo"
    activity = ".activities.MainActivity"
    component = package + "/" + activity     
    
    trials = []
    
    device.startActivity(component=component)
    
    th = DetectionStateChangeListenerThread()
    th.start()

    funcs = {
        "nonoffload": AATApp.playback_nonoffload
    }
    
    formats = {
        "1k_Stereo_48k_16bits_aac.aac": 1000,
        "1k_Stereo_48k_16bits_wav.wav": 1000,
        "1k_Stereo_96k_24bits_flac.flac": 1000
    }

    # force stop app string
    cmd = " ".join(["am", "force-stop", package])
    
    for i in range(num_iter):
        log("-------- playback_format_task #{} --------".format(i+1))
        for name, func in funcs.items():
            log("dev_playback_{}_start".format(name))
            
            for file, freq in formats.items():
                
                trial = Trial(taskname="playback_{}_{}".format(name, file))
                trial.put_extra(name="iter_id", value=i+1)
            
                log("playback_file_{}".format(file))
                
                log("ToneDetector.start_listen(target_freq={})".format(freq))
                ToneDetector.start_listen(target_freq=freq, cb=lambda event: th.tone_detected_event_cb(event))  
                
                time.sleep(1)
                th.reset()
                log("reset DetectionStateChangeListener")
                
                func(device, file)

                log("-> playback start function:")
                if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE, timeout=5) < 0:
                    log("the tone was not detected, abort the iteration this time...")
                    AATApp.playback_stop(device)
                    trial.invalidate(errormsg="start play fail")
                    trials.append(trial)
                    continue
                else:
                    log("-> playback start function: pass")
                    trial.put_extra(name="playback start", value="pass")
                
                pop = AudioFunction.get_pop()
                if pop:
                    log("pop detect")
                    trial.put_extra(name="playback start", value="pop")
                    
                time.sleep(0.5)

                log("-> playback pause function:")
                th.reset()
                
                AATApp.playback_pause_resume(device)
                #time.sleep(1)
                if th.wait_for_event(DetectionStateChangeListenerThread.Event.INACTIVE, timeout=5) < 0:
                    log("the tone was not detected, abort the iteration this time...")
                    AATApp.playback_stop(device)
                    trial.invalidate(errormsg="pause fail")
                    trials.append(trial)
                    continue
                else:
                    log("-> playback pause function: pass")
                    trial.put_extra(name="playback pause", value="pass")
                
                pop = AudioFunction.get_pop()
                if pop:
                    log("pop detect")
                    trial.put_extra(name="playback start", value="pop")
                    
                time.sleep(1)

                log("-> playback resume function:")
                th.reset()
                AATApp.playback_pause_resume(device)
                if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE, timeout=5) < 0:
                    log("the tone was not detected, abort the iteration this time...")
                    AATApp.playback_stop(device)
                    trial.invalidate(errormsg="resume fail")
                    trials.append(trial)
                    continue
                else:
                    log("-> playback resume: pass")
                    trial.put_extra(name="playback resume", value="pass")

                pop = AudioFunction.get_pop()
                if pop:
                    log("pop detect")
                    trial.put_extra(name="playback start", value="pop")
                    
                time.sleep(1)

                log("-> playback seek function:")
                th.reset()
                AATApp.playback_seek(device)
                if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE, timeout=5) < 0:
                    log("the tone was not detected, abort the iteration this time...")
                    AATApp.playback_stop(device)
                    trial.invalidate(errormsg="seek fail")
                    trials.append(trial)
                    continue
                else:
                    log("-> playback seek: pass")
                    trial.put_extra(name="playback seek", value="pass")
                
                pop = AudioFunction.get_pop()
                if pop:
                    log("pop detect")
                    trial.put_extra(name="playback start", value="pop")
                    
                time.sleep(2)

                log("-> playback forward function:")
                th.reset()
                AATApp.playback_forward(device)
                if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE, timeout=5) < 0:
                    log("the tone was not detected, abort the iteration this time...")
                    AATApp.playback_stop(device)
                    trial.invalidate(errormsg="forward fail")
                    trials.append(trial)
                    continue
                else:
                    log("-> playback forward function: pass")
                    trial.put_extra(name="playback forward", value="pass")
                
                pop = AudioFunction.get_pop()
                if pop:
                    log("pop detect")
                    trial.put_extra(name="playback start", value="pop")
                time.sleep(2)

                th.reset()
                AATApp.playback_stop(device)
                log("dev_playback_stop")

                elapsed = th.wait_for_event(DetectionStateChangeListenerThread.Event.INACTIVE, timeout=5)
                
                trial.put_extra(name="elapsed", value=elapsed)
                
                pop = AudioFunction.get_pop()
                if pop:
                    log("pop detect")
                    trial.put_extra(name="playback start", value="pop")
                    
                trials.append(trial)

    log("ToneDetector.stop_listen()")
    ToneDetector.stop_listen()
    th.join()
    device.shell(cmd)
    
    log("playback_task_run--")
    return trials
예제 #5
0
def record_task_run(device, serialno, num_iter=1):
    log("record_task_run++")

    trials = []

    log("dev_record_start")
    AATApp.record_start(device)
    time.sleep(2)

    stm = DetectionStateListener()

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

    time.sleep(3)
    for i in range(num_iter):
        log("-------- record_task #{} --------".format(i + 1))

        trial = Trial(taskname="record",
                      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=TAG,
                         log="record_task #{}".format(i + 1))

        ToneDetector.WORK_THREAD.clear_dump()
        stm.reset()
        if stm.wait_for_event(DetectionStateListener.Event.ACTIVE,
                              timeout=5) < 0:
            log("the tone was not detected, abort the iteration this time...")
            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.invalidate(
                errormsg="early return, possible reason: tx no sound")
            trials.append(trial)

            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))
            continue

        log("trigger_ssr()")
        AATApp.trigger_ssr(device)

        if PARTIAL_RAMDUMP_ENABLED:
            handle_ssr_ui()

        log("Waiting for SSR recovery")
        elapsed = stm.wait_for_event(DetectionStateListener.Event.RISING_EDGE,
                                     timeout=10)
        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=5) < 0:
                log("The tone is not detected")
            else:
                log("The tone is detected, please also check the device log for confirming if it is a false alarm"
                    )

            log("start dumping the process during capturing the frequency...")
            ToneDetector.WORK_THREAD.dump()

        log("elapsed: {} ms".format(elapsed))

        if elapsed < 0:
            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("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"]))

        if PARTIAL_RAMDUMP_ENABLED:
            log("Waiting for the partial ramdump completed")
            handle_ssr_ui()

        if elapsed >= 0 and not PARTIAL_RAMDUMP_ENABLED:
            time.sleep(10 - elapsed / 1000.0)

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

    log("-------- record_task done --------")
    log("AudioFunction.stop_audio()")
    AudioFunction.stop_audio()

    log("dev_record_stop")
    AATApp.record_stop(device)
    time.sleep(5)
    log("ToneDetector.stop_listen()")
    ToneDetector.stop_listen()

    log("record_task_run--")
    return trials
예제 #6
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()

    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))

    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=TAG,
                         log="voip_rx_task #{}".format(i + 1))

        time.sleep(1)
        stm.reset()

        if stm.wait_for_event(DetectionStateListener.Event.ACTIVE,
                              timeout=5) < 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_ssr()")
        AATApp.trigger_ssr(device)

        if PARTIAL_RAMDUMP_ENABLED:
            handle_ssr_ui()

        log("Waiting for SSR recovery")
        elapsed = stm.wait_for_event(DetectionStateListener.Event.RISING_EDGE,
                                     timeout=10)
        log("elapsed: {} ms".format(elapsed))

        if PARTIAL_RAMDUMP_ENABLED:
            log("Waiting for the partial ramdump completed")
            handle_ssr_ui()

        if elapsed >= 0 and not PARTIAL_RAMDUMP_ENABLED:
            time.sleep(10 - elapsed / 1000.0)

        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, None))
    ToneDetector.start_listen(
        serialno=serialno,
        target_freq=None,
        cb=lambda event: stm.tone_detected_event_cb(event))

    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=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=5) < 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_ssr()")
        AATApp.trigger_ssr(device)

        if PARTIAL_RAMDUMP_ENABLED:
            handle_ssr_ui()

        log("Waiting for SSR recovery")
        elapsed = stm.wait_for_event(DetectionStateListener.Event.RISING_EDGE,
                                     timeout=10)
        log("elapsed: {} ms".format(elapsed))

        if PARTIAL_RAMDUMP_ENABLED:
            log("Waiting for the partial ramdump completed")
            handle_ssr_ui()

        if elapsed >= 0 and not PARTIAL_RAMDUMP_ENABLED:
            time.sleep(10 - elapsed / 1000.0)

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

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

    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--")
    return trials
예제 #7
0
def record_VoiceRecord_run(device, serialno, num_iter=1):
    # Google Music
    # play
    # pause
    # resume
    # seek
    # forward
    # offload/non-offload
    log("VoiceReocrd record_task_run++")

    packageVR = "com.htc.soundrecorder"
    activityVR = ".SoundRecorderBG"
    componentVR = packageVR + "/" + activityVR
    cmd = " ".join(["am", "force-stop", packageVR])

    trials = []

    for i in range(num_iter):
        trial = Trial(taskname="VoiceRecord record")
        trial.put_extra(name="iter_id", value=i + 1)

        device.wake()
        log("wake")
        time.sleep(1)
        device.startActivity(componentVR)
        log("startActivity")

        time.sleep(1)

        # more option
        vc, key = get_menu_id(device=device, serialno=serialno)
        if vc is None:
            log("can't find more option")
            trial.invalidate(errormsg="can't find more option")
            trials.append(trial)
            device.shell(cmd)
            continue
        control_Btn(vc, key)

        # settings
        vc, key = get_setting_id(device=device, serialno=serialno)
        if vc is None:
            log("can't find setting")
            trial.invalidate(errormsg="can't find setting")
            trials.append(trial)
            device.shell(cmd)
            continue
        control_Btn(vc, key)

        # (ask to name check)

        # encoding format
        vc, key = get_encode_id(device=device, serialno=serialno)
        if vc is None:
            log("can't find encode")
            trial.invalidate(errormsg="can't find encode")
            trials.append(trial)
            device.shell(cmd)
            continue
        control_Btn(vc, key)

        # flac
        vc, key = get_flac_id(device=device, serialno=serialno)
        if vc is None:
            log("can't find .flac format")
            trial.invalidate(errormsg="can't find .flac format")
            trials.append(trial)
            device.shell(cmd)
            continue
        control_Btn(vc, key)

        # back
        vc, key = get_back_id(device=device, serialno=serialno)
        if vc is None:
            log("can't find back key")
            trial.invalidate(errormsg="can't find back key")
            trials.append(trial)
            device.shell(cmd)
            continue
        control_Btn(vc, key)

        # start record
        vc, key = get_record_id(device=device, serialno=serialno)
        if vc is None:
            log("can't find start record")
            trial.invalidate(errormsg="can't find start record")
            trials.append(trial)
            device.shell(cmd)
            continue
        control_Btn(vc, key)

        log("AudioFunction.play_sound(out_freq={})".format(OUT_FREQ))
        AudioFunction.play_sound(out_freq=OUT_FREQ)
        time.sleep(10)

        # stop record
        vc, key = get_stop_id(device=device, serialno=serialno)
        if vc is None:
            log("can't find stop record")
            trial.invalidate(errormsg="can't find stop record")
            trials.append(trial)
            device.shell(cmd)
            continue
        control_Btn(vc, key)

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

        # rename
        vc, key = get_rename_edit_id(device=device, serialno=serialno)
        if vc is None:
            log("can't find rename edit")
            trial.invalidate(errormsg="can't find rename edit")
            trials.append(trial)
            device.shell(cmd)
            continue
        control_Edit(vc, key, "VRecordHD")
        time.sleep(1)

        #save
        vc, key = get_save_id(device=device, serialno=serialno)
        if vc is None:
            log("can't find save file btn")
            trial.invalidate(errormsg="can't find save file btn")
            trials.append(trial)
            device.shell(cmd)
            continue
        control_Btn(vc, key)

        # pull file
        pull_files(serialno, voice_path_1)

        # judge_record
        ret = judge_recordV(voice_name, thresh=80)
        if ret:
            log("-> VoiceReocrd record HD function: pass")
            trial.put_extra(name="VoiceReocrd record HD", value="pass")
        else:
            log("-> VoiceReocrd record HD function: fail")
            trial.invalidate(errormsg="VoiceReocrd record HD fail")
            trials.append(trial)

        trials.append(trial)

        delete_file(serialno, voice_name, voice_path_2)

    device.shell(cmd)
    log("VoiceReocrd record_task_run--")
    return trials
예제 #8
0
def record_task_run(device, serialno, num_iter=1):
    log("record_task_run++")

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

    trials = []
    cmd = " ".join(["am", "force-stop", package])

    device.startActivity(component=component)
    time.sleep(1)

    log("dev_record_start")
    AATApp.record_start(device)
    time.sleep(2)

    th = DetectionStateChangeListenerThread()
    th.start()

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

    time.sleep(3)
    for i in range(num_iter):
        log("-------- record_task #{} --------".format(i + 1))

        trial = Trial(taskname="record")
        trial.put_extra(name="iter_id", value=i + 1)

        th.reset()
        if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE,
                             timeout=5) < 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
        else:
            log("-> record function: pass")
            trial.put_extra(name="record", value="pass")

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

    log("dev_record_stop")
    AATApp.record_stop(device)
    time.sleep(5)
    log("ToneDetector.stop_listen()")
    ToneDetector.stop_listen()
    th.join()

    device.shell(cmd)
    log("record_task_run--")
    return trials
예제 #9
0
def record_task_run(device, serialno, num_iter=1):
    log("record_task_run++")

    trials = []

    log("dev_record_start")
    AATApp.record_start(device)
    time.sleep(2)

    th = DetectionStateChangeListenerThread()
    th.start()

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

    time.sleep(3)
    for i in range(num_iter):
        log("-------- record_task #{} --------".format(i + 1))

        trial = Trial(taskname="record")
        trial.put_extra(name="iter_id", value=i + 1)

        th.reset()
        if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE,
                             timeout=5) < 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
        else:
            log("--> ssr test record: active pass")

        log("trigger_ssr()")
        AATApp.trigger_ssr(device)

        if PARTIAL_RAMDUMP_ENABLED:
            handle_ssr_ui()

        log("Waiting for SSR recovery")
        elapsed = th.wait_for_event(
            DetectionStateChangeListenerThread.Event.RISING_EDGE, timeout=10)
        log("elapsed: {} ms".format(elapsed))

        if elapsed >= 0:
            log("--> ssr test record: rising pass")

        if PARTIAL_RAMDUMP_ENABLED:
            log("Waiting for the partial ramdump completed")
            handle_ssr_ui()

        if elapsed >= 0 and not PARTIAL_RAMDUMP_ENABLED:
            time.sleep(10 - elapsed / 1000.0)

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

    log("-------- record_task done --------")
    log("AudioFunction.stop_audio()")
    AudioFunction.stop_audio()

    log("dev_record_stop")
    AATApp.record_stop(device)
    time.sleep(5)
    log("ToneDetector.stop_listen()")
    ToneDetector.stop_listen()
    th.join()

    log("record_task_run--")
    return trials
예제 #10
0
def run(num_iter=1):
    AudioFunction.init()
    Logger.init(Logger.Mode.STDOUT)

    Logger.log(TAG, "delete the existed dump folder...")
    subprocess.Popen(["rm", "-rf", "./record-dump"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

    audiodump = AudioSignalFrameLogger()
    databuff = queue.Queue()
    th_tictoc = TicToc()
    push_tictoc = TicToc()
    push_tictoc.extra = {
        "initialized": False,
        "max_period": -1,
        "avg_period": -1,
        "push_count": 0,
        "max_snr": None,
        "min_snr": None,
        "avg_snr": -1
    }
    def process_buff():
        th_tictoc.tic()
        try:
            data = databuff.get(timeout=FRAMEMILLIS*.1/1000.)
            if push_tictoc.extra["initialized"]:
                elapsed = push_tictoc.toc()
                push_tictoc.extra["max_period"] = max([push_tictoc.extra["max_period"], elapsed])
                push_tictoc.extra["avg_period"] *= push_tictoc.extra["push_count"]
                push_tictoc.extra["avg_period"] += elapsed
                push_tictoc.extra["avg_period"] /= float(push_tictoc.extra["push_count"]+1)
            else:
                push_tictoc.tic()
                push_tictoc.extra["initialized"] = True

            push_tictoc.extra["push_count"] += 1

            audiodump.push(name="signal", fs=FS, values=data)
            nfft = np.ceil(np.log2(data.shape[0]))
            nfft = int(2**nfft)
            spectrum = np.abs(fft(data.flatten(), nfft))
            audiodump.push(name="spectrum", fs=-1, values=spectrum)

            spectrum = spectrum[:nfft/2]
            unit_freq = FS*1./nfft
            spectrum = map(lambda x: (x[0]*unit_freq, -x[1]), sort_values(-spectrum))
            signal_spectrum = filter(lambda x: target_detected(freq=x[0], target_freq=FREQ), spectrum)
            noise_spectrum = filter(lambda x: not target_detected(freq=x[0], target_freq=FREQ), spectrum)
            if len(signal_spectrum) > 0 and len(noise_spectrum) > 0:
                snr = np.mean(map(lambda x: x[1], signal_spectrum)) / np.mean(map(lambda x: x[1], noise_spectrum))
                snr = 20*np.log10(snr)
                if target_detected(freq=spectrum[0][0], target_freq=FREQ):
                    if push_tictoc.extra["max_snr"] == None or push_tictoc.extra["max_snr"][0] < snr:
                        push_tictoc.extra["max_snr"] = [snr, push_tictoc.extra["push_count"]-1]
                    if push_tictoc.extra["min_snr"] == None or push_tictoc.extra["min_snr"][0] > snr:
                        push_tictoc.extra["min_snr"] = [snr, push_tictoc.extra["push_count"]-1]
                    push_tictoc.extra["avg_snr"] *= (push_tictoc.extra["push_count"]-1)
                    push_tictoc.extra["avg_snr"] += snr
                    push_tictoc.extra["avg_snr"] /= float(push_tictoc.extra["push_count"])

            sleeptime = max([FRAMEMILLIS - th_tictoc.toc(), 0])
            time.sleep(sleeptime * .99/1000.)
        except queue.Empty:
            pass

    def threadloop():
        while True:
            process_buff()

    def record_cb(indata):
        databuff.put(indata)

    record_cmd = RawRecordCommand(config=AudioConfig(fs=FS, ch=1, dtype="float32", cb=record_cb), framemillis=FRAMEMILLIS)
    AudioFunction.COMMAND.cmd = record_cmd
    AudioFunction.WORK_THREAD.push(AudioFunction.COMMAND.cmd)
    Logger.log(TAG, "start recording on the server...")

    time.sleep(1)
    Logger.log(TAG, "start processing the data buffers...")
    th = threading.Thread(target=threadloop)
    th.daemon = True
    th.start()

    time.sleep(10)

    AudioFunction.stop_audio()
    Logger.log(TAG, "stop recording on the server...")
    audiodump.dump(path="./record-dump")

    Logger.log(TAG, "------------------------ profiling in process_buff ------------------------")
    Logger.log(TAG, "max period: {}".format(push_tictoc.extra["max_period"]))
    Logger.log(TAG, "avg period: {}".format(push_tictoc.extra["avg_period"]))
    Logger.log(TAG, "push count: {}".format(push_tictoc.extra["push_count"]))
    Logger.log(TAG, "max SNR   : {}".format(push_tictoc.extra["max_snr"]))
    Logger.log(TAG, "min SNR   : {}".format(push_tictoc.extra["min_snr"]))
    Logger.log(TAG, "avg SNR   : {}".format(push_tictoc.extra["avg_snr"]))

    AudioFunction.finalize()
    Logger.finalize()
예제 #11
0
def voip_task_run(device, serialno, num_iter=1):
    log("voip_task_run++")

    trials = []

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

    th = DetectionStateChangeListenerThread()
    th.start()

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

    AATApp.voip_start(device)
    for i in range(num_iter):
        log("-------- dev_voip_rx_task #{} --------".format(i+1))

        trial = Trial(taskname="voip_rx")
        trial.put_extra(name="iter_id", value=i+1)

        time.sleep(1)
        th.reset()

        if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE, timeout=5) < 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
        else:
            log("--> VOIP: rx pass")
        time.sleep(1)

        trials.append(trial)

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

    th = DetectionStateChangeListenerThread()
    th.start()

    time.sleep(2)
    log("-> VOIP: mute output")
    AATApp.voip_mute_output(device)
    time.sleep(10)
    log("ToneDetector.start_listen(serialno={}, target_freq={})".format(serialno, None))
    ToneDetector.start_listen(serialno=serialno, target_freq=None, cb=lambda event: th.tone_detected_event_cb(event))

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

        trial = Trial(taskname="voip_tx")
        trial.put_extra(name="iter_id", value=i+1)

        time.sleep(2)

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

        th.reset()
        if th.wait_for_event(DetectionStateChangeListenerThread.Event.ACTIVE, timeout=5) < 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
        else:
            log("--> VOIP: tx pass")
        time.sleep(2)

        trials.append(trial)
        
        log("AudioFunction.stop_audio()")
        AudioFunction.stop_audio()

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

    log("voip_task_run--")
    return trials