1# Copyright 2015 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import re
16import subprocess
17import sys
18import time
19
20DISPLAY_LEVEL = 96  # [0:255] Depends on tablet model. Adjust for best result.
21DISPLAY_CMD_WAIT = 0.5  # seconds. Screen commands take time to have effect
22DISPLAY_TIMEOUT = 1800000  # ms
23
24
25def main():
26    """Power up and unlock screen as needed."""
27    screen_id = None
28    for s in sys.argv[1:]:
29        if s[:7] == 'screen=' and len(s) > 7:
30            screen_id = s[7:]
31
32    if not screen_id:
33        print 'Error: need to specify screen serial'
34        assert False
35
36    # turn on screen if necessary and unlock
37    cmd = ('adb -s %s shell dumpsys display | egrep "mScreenState"'
38           % screen_id)
39    process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
40    cmd_ret = process.stdout.read()
41    screen_state = re.split(r'[s|=]', cmd_ret)[-1]
42    power_event = ('adb -s %s shell input keyevent POWER' % screen_id)
43    subprocess.Popen(power_event.split())
44    time.sleep(DISPLAY_CMD_WAIT)
45    if 'ON' in screen_state:
46        print 'Screen was ON. Toggling to refresh.'
47        subprocess.Popen(power_event.split())
48        time.sleep(DISPLAY_CMD_WAIT)
49    else:
50        print 'Screen was OFF. Powered ON.'
51    unlock = ('adb -s %s wait-for-device shell wm dismiss-keyguard'
52              % screen_id)
53    subprocess.Popen(unlock.split())
54    time.sleep(DISPLAY_CMD_WAIT)
55
56    # set brightness
57    print 'Tablet display brightness set to %d' % DISPLAY_LEVEL
58    bright = ('adb -s %s shell settings put system screen_brightness %d'
59              % (screen_id, DISPLAY_LEVEL))
60    subprocess.Popen(bright.split())
61    time.sleep(DISPLAY_CMD_WAIT)
62
63    # set screen to dim at max time (30min)
64    stay_bright = ('adb -s %s shell settings put system screen_off_timeout %d'
65                   % (screen_id, DISPLAY_TIMEOUT))
66    subprocess.Popen(stay_bright.split())
67    time.sleep(DISPLAY_CMD_WAIT)
68
69if __name__ == '__main__':
70    main()
71