Esempio n. 1
0
def wait_for_event(event, expected_state, timeout=20):
    if event == "battery presence":
        get_method = get_battery_presence
    elif event == "power status":
        get_method = get_charging_status
    elif event == "charger online":
        get_method = get_online_status
    else:
        print "Unknown event: '{}'!!!".format(event)
        exit_test()
    start = time.time()
    while time.time() - start < timeout:
        found_state = get_method()
        if isinstance(expected_state, basestring):
            comparison = found_state == expected_state
        elif isinstance(expected_state, list):
            comparison = found_state in expected_state
        else:
            comparison = False
        if comparison:
            print_to_console_and_logcat("Found {}: '{}'".format(
                event, found_state))
            return True
    print_to_console_and_logcat("Timeout waiting for '{}' to be '{}'".format(
        event, expected_state))
    return False
Esempio n. 2
0
def get_charger_info(info_string):
    component_json = {}
    global driver_name
    info_string = info_string.replace("\"", "")
    info_string = info_string.replace("\'", "\"")
    try:
        component_json = json.loads(info_string)
        driver_name = component_json['driver']['name']
    except:
        print("Failed to get charger info!!!")
        exit_test()
    return component_json
Esempio n. 3
0
def get_property(prop):
    global driver_name
    location = '/sys/class/power_supply/'

    proc = subprocess.Popen(['adb', 'shell', 'ls ' + location],
                            stdout=subprocess.PIPE)
    available_drivers = proc.stdout.read().split()
    if not available_drivers:
        print "Did not find any files in '{}' on the android device".format(
            location)
        exit_test()

    # The driver name is not necessarily equal to the driver filename found in the .desc file
    if driver_name not in available_drivers:
        if driver_name.replace('_', '-') in available_drivers:
            driver_name = driver_name.replace('_', '-')
        else:
            max_ratio = -1
            matched_item = None
            for found_driver in available_drivers:
                match_ratio = difflib.SequenceMatcher(None, driver_name,
                                                      found_driver).ratio()
                if match_ratio > max_ratio:
                    max_ratio = match_ratio
                    matched_item = found_driver
                # if name is similar or it is the only available power_supply driver, we select it
                if max_ratio > 0.6 or len(available_drivers) == 1:
                    driver_name = matched_item
                else:
                    print "Found available drivers: {}".format(
                        available_drivers)
                    print "Did not find driver with similar name with '{}'".format(
                        driver_name)
                    print "Warning: Choosing driver '{}' but it may not be the correct one".format(
                        matched_item, driver_name)
                    driver_name = matched_item

    prop_file = os.path.join(location, driver_name, prop)

    proc = subprocess.Popen(['adb', 'shell', 'cat ' + prop_file],
                            stdout=subprocess.PIPE)
    output = proc.stdout.read().strip("\r\n")

    if "No such file or directory" in output:
        print "Did not find file '{}' present on the android device".format(
            prop_file)
        exit_test()

    return output
Esempio n. 4
0
def poll_for_events(sensor_id,
                    sensor_frequency,
                    timeout,
                    seconds=0,
                    nr_events=0):
    cmd = ['adb', 'shell', 'sens2', 'poll']
    if sensor_id != None:
        id_freq = str(sensor_id)
        #hardcoded for emulator
        if sensor_frequency == 0 or sensor_frequency > 30:
            sensor_frequency = 30
        if sensor_frequency > 0:
            id_freq += "," + str(sensor_frequency)
        cmd.append(id_freq)
    try:
        timestamp_int = math.pow(10, 9) * seconds
        aux_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        proc = subprocess.Popen(['tee', sens2_out],
                                stdin=aux_proc.stdout,
                                stdout=subprocess.PIPE)
        timer = Timer(timeout, aux_proc.kill)
        timer.start()
        events = []
        index = 0
        for line in iter(proc.stdout.readline, ''):
            parsed_json = json.loads(line.rstrip())
            events.append(parsed_json)
            index = index + 1
            if (nr_events != 0 and index >= nr_events or seconds != 0 and index > 0 and \
                            events[index - 1]["timestamp"] - events[0]["timestamp"] > timestamp_int):
                if timer.is_alive():
                    timer.cancel()
                aux_proc.kill()
                return events
        if (seconds != 0 and nr_events == 0 and index == 1):
            return events
        return []
    except:
        if aux_proc:
            aux_proc.kill()
        exit_test()
Esempio n. 5
0
    def run(self):
        try:
            self.values = []
            self.aux_proc = subprocess.Popen(
                ['adb', 'shell', 'sens2', 'poll',
                 str(self.id)],
                stdout=subprocess.PIPE)
            self.proc = subprocess.Popen(['tee', sens2_out],
                                         stdin=self.aux_proc.stdout,
                                         stdout=subprocess.PIPE)

            for line in iter(self.proc.stdout.readline, ''):
                parsed_json = json.loads(line.rstrip())
                if parsed_json['type'] == self.type:
                    sys.stdout.write(
                        str(parsed_json['data'][self.axes]) + " \r")
                    self.values.append(float(parsed_json['data'][self.axes]))

        except Exception as e:
            print_to_console_and_logcat("Exception in PollThread's run")
            exit_test()
from util import menu
from util import print_to_console_and_logcat
from util import exit_test

VERDICT = FAILURE
OUTPUT = ""
BRIGHTNESS_CHANGE = TC_PARAMETERS('BRIGHTNESS')
check_brightness_message = "Please check the brightness of the display."
if (BRIGHTNESS_CHANGE == "INCREASE"):
    order = 1
elif (BRIGHTNESS_CHANGE == "DECREASE"):
    order = -1
else:
    OUTPUT = "Wrong parameter. BRIGHTNESS value should be MAX or MIN"
    print_to_console_and_logcat(OUTPUT)
    exit_test()

brightness_max = 255
brightness_min = 0
step = 15
white_color = 4
white_timeout = 10
validation_message = "Did you observe a gradually " + BRIGHTNESS_CHANGE.lower() + \
                     " of the display brightness? (y/n)"


def check_brightness(arguments):
    global VERDICT, OUTPUT
    # add step to brightness_max in order to have a closed range
    values_range = xrange(brightness_min, brightness_max + step, step)
    if order == -1:
def check_sleep(arguments):
    global VERDICT
    global OUTPUT
    VERDICT = FAILURE

    start = time.time()
    timestamp_vector = []
    first_touch = sys.float_info.max
    q.queue.clear()

    while True:

        # Exit if there are no touch events when timeout is reached
        if len(timestamp_vector) == 0 and time.time() - start > touch_timeout:
            print_to_console_and_logcat("Failure. Did not detect any touch events")
            OUTPUT = "Did not detect any touch events"
            return
        # Exit if we reach sleep timeout
        if time.time() - first_touch > max_sleep_duration:
            break
        # Exit if we reach a number of sufficient touch events
        elif len(timestamp_vector) > sufficient_events:
            break

        try:
            line = q.get_nowait()
        except Queue.Empty:
            continue

        match = json.loads(line)
        timestamp_vector.append(match["motion"]["timestamp"] / scale)
        if len(timestamp_vector) == 5:
            first_touch = time.time()
            print_to_console_and_logcat("Putting the device to sleep")

            for cmd in suspend_to_ram:
                p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
                out, err = p.communicate()
                if out:
                    print_to_console_and_logcat("Received error when trying to put device into sleep " + out)
                    exit_test()

    dev_state = subprocess.check_output(["adb get-state"], shell=True)
    if dev_state.strip("\n") != "device":
        print_to_console_and_logcat("Failure. Device did not recover; found device state: {}".format(dev_state))
        OUTPUT = "Failure. Adb state after sleep is: " + str(dev_state)
        exit_test()

    if len(timestamp_vector) < minimum_events:
        print_to_console_and_logcat("Failure. Not enough touch events were detected")
        OUTPUT = "Failure. Didn't receive enought touch events"
        return

    consecutive_elem_diff = [t - s for s, t in zip(timestamp_vector, timestamp_vector[1:])]
    time_diff_peak = max(consecutive_elem_diff)
    consecutive_elem_diff.remove(time_diff_peak)
    avg = numpy.mean(consecutive_elem_diff)
    std = numpy.std(consecutive_elem_diff)

    exp_max_std = 0.02
    exp_max_avg = 0.015
    avg_to_sleep_ratio = 200

    if (std < exp_max_std) and (avg < exp_max_avg) and (avg_to_sleep_ratio * avg < time_diff_peak):
        print_to_console_and_logcat("Successfully received poll events after sleep")
        VERDICT = SUCCESS
        OUTPUT = "Success"
    else:
        print_to_console_and_logcat("Did not detect sleep conditions. Average time diff between events: " +
                                    str(avg) + " Peak time difference: " + str(time_diff_peak) +
                                    " Standard deviation:" + str(std))
        OUTPUT = "Failure. Did not detect sleep conditions"