class Monitor():
    def __init__(self):
        self.serial = self._get_serial()
        self.automation_handle = Device(self.serial)
        self.name = self._get_monitor_name()


    def _get_serial(self):
        output = subprocess.check_output(["adb", "devices"])
        starting_time = time.time()
        while "offline" in output and time.time() < starting_time + 20:
            subprocess.check_output(["adb", "kill-server"])
            time.sleep(1)
            subprocess.check_output(["adb", "start-server"])
            time.sleep(5)
            output = subprocess.check_output(["adb", "devices"])

        serial = output.rsplit("\n")[1].rsplit("\t")[0].strip()
        print "Device serial: %s" % serial
        return serial


    def _get_monitor_name(self):
        output = subprocess.check_output(["adb", "shell", "dumpsys", "|", "findstr", "wifiP2pDevice=Device"], shell=True)
        start_index = output.rfind('Device: ', 0)
        start_index = start_index + 8
        end_index = output.rfind("\n", 0)
        name = output[start_index : end_index].strip()
        return name


    def is_mac_address(self, address):
        boo = False
        boo = self.automation_handle.exists(description='VideoView ' + address)
        return boo


    def reboot(self):
        checkBootComp = subprocess.check_output('adb {} shell getprop sys.boot_completed'.format(self.serial))
        print('start rebbot monitor')
        os.system('adb {} reboot'.format(self.serial))
        self.is_boot_completed(checkBootComp)
        print('reboot monitor completed')


    def is_boot_completed(self , bootCompCmd):
        screenUp = '-1'
        while screenUp != bootCompCmd:
            time.sleep(1)
            try:
                screenUp = subprocess.check_output('adb {} shell getprop sys.boot_completed'.format(self.serial))
            except Exception:
                print('waiting for monitor' )
        print('Screen up and fully loaded')
        return True
Esempio n. 2
0
class AndroidDevice(object):
    '''
    wrapper for android uiautomator-server binding(pip install uiautomator).
    provide android device event inject, ui object inspect and image comparison.
    '''
    def __init__(self, seral=None):
        '''
        create device instance.
        '''
        self.serial = os.environ[ANDROID_SERIAL] if os.environ.has_key(
            ANDROID_SERIAL) else None
        self.working_dir_path = WORKING_DIR_PATH
        self.report_dir_path = REPORT_DIR_PATH
        self.right_dir_path = WORKING_DIR_PATH
        self._internal_storage_dir = DEFAULT_DEVICE_INTERNAL_STORAGE
        self.d = Device(self.serial)
        #try:
        #    if int(self.d.info['sdkInt']) <= 17:
        #        self.d.screenshot = self.screenshot_common
        #except:
        #    pass

    def set_internal_storage_dir(self, path):
        self._internal_storage_dir = path

    def __getattr__(self, attr):
        '''
        forward method/attrbuite to uiautomator device if method support by uiautomator.
        '''
        if hasattr(self.d, attr):
            #if attr == 'screenshot':
            #    return self.screenshot_common
            m = getattr(self.d, attr)
            if inspect.ismethod(m):

                def wrapper(*args, **kwargs):
                    return m(*args, **kwargs)

                return wrapper
            else:
                return m
        raise AttributeError(attr)

    def __call__(self, *args, **kwargs):
        '''
        selector support:
        d(text="Settings").click()
        '''
        return self.d(*args, **kwargs)

    @property
    def orientation(self):
        return self.d.orientation

    @orientation.setter
    def orientation(self, v):
        self.d.orientation = v

    def serial(self):
        '''
        device serial number from $ANDROID_SERIAL
        '''
        return self.serial

    def sleep(self, sec):
        time.sleep(sec)

    #device event inject
    def start_activity(self, *argv, **intent_params):
        '''
        Starts an Activity on the device by sending an Intent which constructed from the specified parameters. 
        The params of Intent supported from adb docs:
        <INTENT> specifications include these flags:
            [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
            [-c <CATEGORY> [-c <CATEGORY>] ...]
            [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
            [--esn <EXTRA_KEY> ...]
            [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
            [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
            [-n <COMPONENT>] [-f <FLAGS>]
            [<URI>]
        example: 
           start avtivity as new task:
           start_activity('--activity-clear-task', component='com.android.settings/.Settings')

        @type argv: string
        @param argv: specify the rule of how to start acitivty. the value of argv show as below:
           [--grant-read-uri-permission] [--grant-write-uri-permission]
           [--debug-log-resolution] [--exclude-stopped-packages]
           [--include-stopped-packages]
           [--activity-brought-to-front] [--activity-clear-top]
           [--activity-clear-when-task-reset] [--activity-exclude-from-recents]
           [--activity-launched-from-history] [--activity-multiple-task]
           [--activity-no-animation] [--activity-no-history]
           [--activity-no-user-action] [--activity-previous-is-top]
           [--activity-reorder-to-front] [--activity-reset-task-if-needed]
           [--activity-single-top] [--activity-clear-task]
           [--activity-task-on-home]
           [--receiver-registered-only] [--receiver-replace-pending]

        @type intent_params: dictionary 
        @param intent_params: the properties of an Intent. 
                              property support: component/action/data/mimetype/categories/extras/flags/uri
        @rtype: AndroidDevice
        @return: a instance of AndroidDevice.
        '''
        #d.server.adb.cmd('shell','am', 'start', '-a', 'android.intent.action.DIAL','tel:13581739891').communicate()
        #sys.stderr.write(str(intent_params))
        keys = intent_params.keys()
        shellcmd = ['shell', 'am', 'start']
        if 'component' in keys:
            shellcmd.append('-n')
            shellcmd.append(intent_params['component'])

        if 'action' in keys:
            shellcmd.append('-a')
            shellcmd.append(intent_params['action'])

        if 'data' in keys:
            shellcmd.append('-d')
            shellcmd.append(intent_params['data'])

        if 'mimetype' in keys:
            shellcmd.append('-t')
            shellcmd.append(intent_params['mimetype'])

        if 'categories' in keys:
            for category in intent_params['categories']:
                shellcmd.append('-c')
                shellcmd.append(category)

        if 'extras' in keys:
            for extra_key, extra_value in intent_params['extras'].items():
                str_value = ''
                arg = ''
                if isinstance(extra_value, types.IntType):
                    str_value = str(extra_value)
                    arg = '--ei'
                elif isinstance(extra_value, types.BooleanType):
                    str_value = str(extra_value)
                    arg = '--ez'
                else:
                    str_value = str(extra_value)
                    arg = '--es'
                shellcmd.append(arg)
                shellcmd.append(extra_key)
                shellcmd.append(str_value)

        if 'flags' in keys:
            shellcmd.append('-f')
            shellcmd.append(str(intent_params['flags']))

        if 'uri' in keys:
            shellcmd.append(intent_params['uri'])

        if 'package' in keys:
            shellcmd.append(intent_params['package'])
        #sys.stderr.write(str(shellcmd))
        if argv:
            shellcmd.append(*argv)
        self.d.server.adb.cmd(*shellcmd).communicate()
        return self

    def instrument(self, **kwargs):
        '''
        Run the specified package with instrumentation and return the output it generates. 
        Use this to run a test package using InstrumentationTestRunner.
        Typically this target <COMPONENT> is the form <TEST_PACKAGE>/<RUNNER_CLASS>. 
        Options are:
        -w: wait for instrumentation to finish before returning. Required for test runners.
        -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT).
            Use with [-e perf true] to generate raw output for performance measurements.
        -e <NAME> <VALUE>: set argument <NAME> to <VALUE>.
            For test runners a common form is [-e <testrunner_flag> <value>[,<value>...]].
        -p <FILE>: write profiling data to <FILE>
        --user <USER_ID> | current: Specify user instrumentation runs in; current user if not specified.
        --no-window-animation: turn off window animations will running.

        @type intent_params: dictionary 
        @param intent_params: the properties of an instrumentation testing. 
                              property support: packagename, <NAME> to <VALUE>.
        @rtype: AndroidDevice
        @return: a instance of AndroidDevice.
        '''
        keys = kwargs.keys()
        shellcmd = ['shell', 'am', 'instrument', '-w', '-r']
        pkgname = kwargs.pop('packagename')
        for k, v in kwargs.items():
            if k and v:
                shellcmd.append('-e')
                shellcmd.append(k)
                shellcmd.append(str(v))
        shellcmd.append(pkgname)
        result = self.d.server.adb.cmd(*shellcmd).communicate()
        return result

    def click(self, *args, **kwargs):
        '''
        example:
         click(x,y)
         Click the screen location specified by x and y.
         Format: (x,y) the screen location specified by x and y.
         x   The horizontal position of the touch in actual device pixels, starting from the left of the screen in its current orientation.
         y   The vertical position of the touch in actual device pixels, starting from the top of the screen in its current orientation.
        
        click('phone_app.png', rotation=90)
        
        Perform a click event on the center point on the expected screen region.
        If the screen region want to click not found in the current screen snapshot will do nothing
        rotation: 0, 90, 180, 270
        '''
        if args:
            if isinstance(args[0], types.IntType):
                self.__click_point(*args, **kwargs)
                return self
            if isinstance(args[0], types.StringType):
                self.__click_image(*args, **kwargs)
                return self

    def __click_point(self, x, y, waittime=1):
        '''
        click x,y
        '''
        self.d.click(x, y)
        time.sleep(waittime)

    def __click_image(self, imagename, waittime=1, threshold=0.01, rotation=0):
        '''
        if the wanted image found on current screen click it.
        if the wanted image not found raise exception and set test to be failure.
        '''
        expect_image_path = None
        current_image_path = None
        if os.path.isabs(imagename):
            expect_image_path = imagename
            current_image_path = join(self.report_dir_path,
                                      os.path.basename(imagename))
        else:
            expect_image_path = join(self.right_dir_path, imagename)
            current_image_path = join(self.report_dir_path, imagename)

        assert os.path.exists(
            expect_image_path
        ), 'the local expected image %s not found!' % expect_image_path

        self.d.screenshot(current_image_path)
        assert os.path.exists(
            current_image_path
        ), 'fetch current screen shot image %s failed!' % imagename
        pos = getMatchedCenterOffset(subPath=expect_image_path,
                                     srcPath=current_image_path,
                                     threshold=0.01,
                                     rotation=rotation)
        if not pos:
            reason = 'Fail Reason: The wanted image \'%s\' not found on screen!' % imagename
            raise ExpectException(expect_image_path, current_image_path,
                                  reason)
        self.d.click(pos[0], pos[1])
        time.sleep(waittime)

    def screenshot_common(self, filename):
        '''
        if SK version <= 16
        Capture the screenshot via adb and store it in the specified location.
        '''
        png = os.path.basename(filename)
        if self.serial:
            shell('adb -s %s shell screencap %s%s' %
                  (self.serial, self._internal_storage_dir, png))
            shell('adb -s %s pull %s%s %s' %
                  (self.serial, self._internal_storage_dir, png, filename))
        else:
            shell('adb shell screencap %s%s' %
                  (self._internal_storage_dir, png))
            shell('adb pull %s%s %s' %
                  (self._internal_storage_dir, png, filename))
        return True

    #inspect
    def exists(self, **kwargs):
        '''
        if the expected component exists on current screen layout return true else return false.
        @rtype: boolean
        @return:  return True f the expected component exists on current screen layout, else return false.
        '''
        return self.d.exists(**kwargs)

    def expect(self, imagename, interval=2, timeout=4, threshold=0.01, msg=''):
        '''
        if the expected image found on current screen return self 
        else raise exception. set test to be failure.
        @type imagename: sting
        @param imagename: the name of picture which expected to find in current screenshot.
        @type interval: int
        @param iinterval: the value of interval time
        @type timeout: int
        @param timeout: the value of timeout
        @type threshold: float
        @param threshold: the value of threshold. 0.0~1.0
        @type msg: string
        @param msg: the prompt message content when the expected image not found on current screenshot
        '''
        expect_image_path = None
        current_image_path = None
        if os.path.isabs(imagename):
            expect_image_path = imagename
            current_image_path = join(self.report_dir_path,
                                      os.path.basename(imagename))
        else:
            expect_image_path = join(self.right_dir_path, imagename)
            current_image_path = join(self.report_dir_path, imagename)

        assert os.path.exists(
            expect_image_path
        ), 'the local expected image %s not found!' % expect_image_path
        begin = time.time()
        while (time.time() - begin < timeout):
            self.d.screenshot(current_image_path)
            if isMatch(expect_image_path, current_image_path, threshold):
                return self
            time.sleep(interval)
        reason = msg if msg else 'Fail Reason: Image \'%s\' not found on screen!' % imagename
        raise ExpectException(expect_image_path, current_image_path, reason)

    def find(self, imagename, interval=2, timeout=4, threshold=0.01):
        '''
        if the expected image found on current screen return true else return false

        @type imagename: sting
        @param imagename: the name of picture which expected to find in current screenshot.
        @type interval: int
        @param iinterval: the value of interval time
        @type timeout: int
        @param timeout: the value of timeout
        @type threshold: float
        @param threshold: the value of threshold. 0.0~1.0
        @type msg: string
        @param msg: the prompt message content when the expected image not found on current screenshot
        @rtype: boolean
        @return:  return True f the expected image found exists on current screenshot, else return false.
        '''
        expect_image_path = None
        current_image_path = None
        if os.path.isabs(imagename):
            expect_image_path = imagename
            current_image_path = join(self.report_dir_path,
                                      os.path.basename(imagename))
        else:
            expect_image_path = join(self.right_dir_path, imagename)
            current_image_path = join(self.report_dir_path, imagename)

        assert os.path.exists(
            expect_image_path
        ), 'the local expected image %s not found!' % expect_image_path

        begin = time.time()
        isExists = False
        while (time.time() - begin < timeout):
            #time.sleep(interval)
            self.d.screenshot(current_image_path)
            isExists = isMatch(expect_image_path, current_image_path,
                               threshold)
            if not isExists:
                time.sleep(interval)
                continue
            break
        return isExists

    def TODOinstallPackage(self, **kwargs):
        pass

    def TODOremovePackage(self, **kwargs):
        pass
Esempio n. 3
0
class ModelInfo():
    '''
    classdocs
    '''
    
    def __init__(self, deviceserial):
        '''
        Constructor
        '''
    
    #sndLog = CLS("test", "test")
        self.osType = sys.platform
        
        self.mstrInfo = {}
        
        #self.devSerials = self.instAdb.device_serial()
        self.mstrDevice = Device(deviceserial)
        self.mstrInfo = self.mstrDevice.info
    
    '''
        DEVICE Infoamtions
        { u'displayRotation': 0,
          u'displaySizeDpY': 640,
          u'displaySizeDpX': 360,
          u'currentPackageName': u'com.android.launcher',
          u'productName': u'takju',
          u'displayWidth': 720,
          u'sdkInt': 18,
          u'displayHeight': 1184,
          u'naturalOrientation': True
        }
    '''        
    def getCurrntProductInfo(self):
        return self.mstrInfo
        
    def getProductNmae(self):
        return self.mstrInfo['productName']
        
    def getCurrntPkg(self):
        return self.mstrInfo['currentPackageName']
    
    def getSDKInt(self):
            return self.mstrInfo['sdkInt']
        
    def getRotation(self):
        return self.mstrInfo['displayRotation']
    
    
    def getNaturalOri(self):
        return self.mstrInfo['naturalOrientation']
    
    def getDisplayState(self):
        return self.mstrDevice.screen
                
    def setReflash(self):
        pass
    
    #define Key activity
    def setDevScrnOn(self):
        self.mstrDevice.screen.on()
    
    
    def setMstDevScrnOff(self):
        self.mstrDevice.screen.off()

            
    def setWakeup(self):
        self.mstrDevice.wakeup()
            
    def setSleep(self):
        self.mstrDevice.sleep()
            
     #Hard key Soft key       
    def pressHome(self):
        return self.mstrDevice.press.home()
    
    def pressBack(self):
        return self.mstrDevice.press.back()
        
    
    ######################################################################
    
    def pressLeft(self):
        return self.mstrDevice.press.left()
        
    def pressRight(self):
        return self.mstrDevice.press.right()
    
    def pressUp(self):
        return self.mstrDevice.press.up()
        
    def pressDown(self):
        return self.mstrDevice.press.down()
        
    def pressCenter(self):
        return self.mstrDevice.press.center()
    
    ######################################################################    
        
    def pressMenu(self):
        return self.mstrDevice.press.menu()
        
    def pressSearch(self):
        return self.mstrDevice.press.search()
           
    def pressEnter(self):
        return self.mstrDevice.press.enter()
            
    def pressDelete(self):
        return self.mstrDevice.press.delete() # or del
        
    def pressRecent(self):
        return self.mstrDevice.press.recent()
            
    def pressVol_Up(self):
        return self.mstrDevice.press.volume_up()
            
    def pressVol_Down(self):
        return self.mstrDevice.press.volume_down()
            
    def pressVol_Mute(self):
        return self.mstrDevice.press.volume_mute()
            
    def pressPower(self):
        return self.mstrDevice.press.power()
            
    def clik(self, x, y):
        return self.mstrDevice.click(x, y)
            
    def longClik(self,x, y):
        '''
            Description:
                
            param:
                x, y : start first point x, y
                
            return : Boolean
        '''
        return self.mstrDevice.long_click(x, y)
            
    def swipe(self, sx, sy, ex, ey, steps=10):
        '''
            Description:
                
            param:
                sx, xy : start first x, y
                ex, ey : move to x, y
            return : Boolean
        '''
        return self.mstrDevice.swipe(sx, sy, ex, ey, steps)
           
    def drage(self,sx, sy, ex, ey, steps=10):
        '''
            Description:
                
            param:
                sx, xy : start first x, y
                ex, ey : move to x, y
            return : Boolean
        '''
        return self.mstrDevice.drag(sx, sy, ex, ey, steps)
       
    #screen action of the device   
    def setOrientation(self,scrAct='natural', choiceDevice='mstr'):
        '''
            Description
                
            param
                d.orientation = 'l' or 'left'
                d.orientation = 'r' or 'right'
                d.orientation = 'n' or 'natural'
            return : None
        '''
        self.mstrDevice.orientation = scrAct
    
    def setFreezeRotation(self,condition=False,choiceDevice='mstr'):
        '''
            param:
                condition : False un-freeze rotation
            return : None
        '''
        self.mstrDevice.freeze_rotation(condition)
    
    
            
    def takeScreenShot(self, choiceDevice = 'mstr'):
        '''
            Description:
                take screenshot and save to local file 'home.png' can work until android 4.2
            param
                image name
        '''
        
    def dumpWindowHeirarchy(self,filename='./log/hierachy.xml'):
        return self.mstrDevice.dump(filename)
        
    def dumpWindowHeirarchyStream(self):
        return self.mstrDevice.dump()
        
    def notification(self):
        '''
            Open notification, can not work until android 4.3
            return : Boolean
        '''
        return self.mstrDevice.open.Notification()
    
    def quickSettings(self):
        '''
            open quick settins, can not work until android 4.3
            return : Boolean 
        '''
        return self.mstrDevice.open.quick_settings()
    def waitidle(self):
        '''
            wait for current window to idle
            return : None
        '''
        self.mstrDevice.wait.idle()
        
    def waitWindowUpdate(self):
        '''
            wait until window upate event occurs
            return : Boolean
        '''
        self.mstrDevice.wait.update()
        
    def getCurrentActivityInfo(self, text):
        '''
          INFOMATION:
              { u'contentDescription': u'',
              u'checked': False,
              u'scrollable': False,
              u'text': u'Settings',
              u'packageName': u'com.android.launcher',
              u'selected': False,
              u'enabled': True,
              u'bounds': {u'top': 385,
                          u'right': 360,
                          u'bottom': 585,
                          u'left': 200},
              u'className': u'android.widget.TextView',
              u'focused': False,
              u'focusable': True,
              u'clickable': True,
              u'chileCount': 0,
              u'longClickable': True,
              u'visibleBounds': {u'top': 385,
                                 u'right': 360,
                                 u'bottom': 585,
                                 u'left': 200},
              u'checkable': False
            }
        '''  
        return self.mstrDevice(text).info
    
    def uiObjExist(self,text):
        '''
            ture if exists, else False
        '''
        return self.mstrDevice.exists(text)
    
    def watcher(self):
        pass
    def handler(self):
        pass
    def selector(self):
        pass
        
    def __del__(self):
        pass    
Esempio n. 4
0
class AndroidDevice(object):
    '''
    wrapper for android uiautomator-server binding(pip install uiautomator).
    provide android device event inject, ui object inspect and image comparison.
    '''

    def __init__(self, seral=None):
        '''
        create device instance.
        '''
        self.serial = os.environ[ANDROID_SERIAL] if os.environ.has_key(ANDROID_SERIAL) else None
        self.working_dir_path = WORKING_DIR_PATH
        self.report_dir_path = REPORT_DIR_PATH
        self.right_dir_path = WORKING_DIR_PATH
        self._internal_storage_dir = DEFAULT_DEVICE_INTERNAL_STORAGE
        self.d = Device(self.serial)
        #try:
        #    if int(self.d.info['sdkInt']) <= 17:
        #        self.d.screenshot = self.screenshot_common
        #except:
        #    pass

    def set_internal_storage_dir(self, path):
        self._internal_storage_dir = path

    def __getattr__(self, attr):
        '''
        forward method/attrbuite to uiautomator device if method support by uiautomator.
        '''
        if hasattr(self.d, attr):
            if attr == 'screenshot':
                return self.screenshot_common
            m =  getattr(self.d, attr)
            if inspect.ismethod(m):
                def wrapper(*args, **kwargs):
                    return m(*args, **kwargs)
                return wrapper
            else:
                return m
        raise AttributeError(attr)

    def __call__(self, *args, **kwargs):
        '''
        selector support:
        d(text="Settings").click()
        '''
        return self.d(*args, **kwargs)

    @property
    def orientation(self):
        return self.d.orientation

    @orientation.setter
    def orientation(self, v):
        self.d.orientation = v

    def serial(self):
        '''
        device serial number from $ANDROID_SERIAL
        '''
        return self.serial

    def sleep(self, sec):
        time.sleep(sec)

    #device event inject
    def start_activity(self, **intent_params):
        '''
        Starts an Activity on the device by sending an Intent which constructed from the specified parameters.     
        The params of Intent supported from adb docs:
        <INTENT> specifications include these flags:
            [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
            [-c <CATEGORY> [-c <CATEGORY>] ...]
            [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
            [--esn <EXTRA_KEY> ...]
            [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
            [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
            [-n <COMPONENT>] [-f <FLAGS>]
            [<URI>]
        @type intent_params: dictionary 
        @param intent_params: the properties of an Intent. 
                              property support: component/action/data/mimetype/categories/extras/flags/uri
        @rtype: AndroidDevice
        @return: a instance of AndroidDevice.
        '''
        
        #d.server.adb.cmd('shell','am', 'start', '-a', 'android.intent.action.DIAL','tel:13581739891').communicate()
        #sys.stderr.write(str(intent_params))
        keys = intent_params.keys()
        shellcmd = ['shell', 'am', 'start']
        if 'component' in keys:
            shellcmd.append('-n')
            shellcmd.append(intent_params['component'])

        if 'action' in keys:  
            shellcmd.append('-a')
            shellcmd.append(intent_params['action'])

        if 'data' in keys:
            shellcmd.append('-d')
            shellcmd.append(intent_params['data'])

        if 'mimetype' in keys:
            shellcmd.append('-t')
            shellcmd.append(intent_params['mimetype'])

        if 'categories' in keys:
            for category in intent_params['categories']:
                shellcmd.append('-c')
                shellcmd.append(category)
        
        if 'extras' in keys:
            for extra_key, extra_value in intent_params['extras'].items():
                str_value = ''
                arg = ''
                if isinstance(extra_value, types.IntType):
                    str_value = str(extra_value)
                    arg = '--ei'
                elif isinstance(extra_value, types.BooleanType):
                    str_value = str(extra_value)
                    arg = '--ez'
                else:
                    str_value = str(extra_value)
                    arg = '--es'
                shellcmd.append(arg)
                shellcmd.append(extra_key)
                shellcmd.append(str_value)
                
        if 'flags' in keys:
            shellcmd.append('-f')
            shellcmd.append(str(intent_params['flags']))

        if 'uri' in keys:
            shellcmd.append(intent_params['uri'])

        if 'package' in keys:
            shellcmd.append(intent_params['package'])
        #sys.stderr.write(str(shellcmd))            
        self.d.server.adb.cmd(*shellcmd).communicate()
        return self

    def instrument(self, **kwargs):
        '''
        Run the specified package with instrumentation and return the output it generates. 
        Use this to run a test package using InstrumentationTestRunner.
        Typically this target <COMPONENT> is the form <TEST_PACKAGE>/<RUNNER_CLASS>. 
        Options are:
        -w: wait for instrumentation to finish before returning. Required for test runners.
        -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT).
            Use with [-e perf true] to generate raw output for performance measurements.
        -e <NAME> <VALUE>: set argument <NAME> to <VALUE>.
            For test runners a common form is [-e <testrunner_flag> <value>[,<value>...]].
        -p <FILE>: write profiling data to <FILE>
        --user <USER_ID> | current: Specify user instrumentation runs in; current user if not specified.
        --no-window-animation: turn off window animations will running.

        @type intent_params: dictionary 
        @param intent_params: the properties of an instrumentation testing. 
                              property support: packagename, <NAME> to <VALUE>.
        @rtype: AndroidDevice
        @return: a instance of AndroidDevice.
        '''
        keys = kwargs.keys()
        shellcmd = ['shell', 'am', 'instrument', '-w', '-r']
        pkgname = kwargs.pop('packagename')
        for k, v in kwargs.items():
            if k and v:
                shellcmd.append('-e')
                shellcmd.append(k)
                shellcmd.append(str(v))
        shellcmd.append(pkgname)
        result = self.d.server.adb.cmd(*shellcmd).communicate()
        return result

    def click(self, *args, **kwargs):
        '''
        example:
         click(x,y)
         Click the screen location specified by x and y.
         Format: (x,y) the screen location specified by x and y.
         x   The horizontal position of the touch in actual device pixels, starting from the left of the screen in its current orientation.
         y   The vertical position of the touch in actual device pixels, starting from the top of the screen in its current orientation.
        
        click('phone_app.png', rotation=90)
        
        Perform a click event on the center point on the expected screen region.
        If the screen region want to click not found in the current screen snapshot will do nothing
        rotation: 0, 90, 180, 270
        '''
        if args:
            if isinstance(args[0], types.IntType):
                self.__click_point(*args, **kwargs)
                return self
            if isinstance(args[0], types.StringType):
                self.__click_image(*args, **kwargs)
                return self

    def __click_point(self, x, y, waittime=1):
        '''
        click x,y
        '''
        self.d.click(x, y)
        time.sleep(waittime)

    def __click_image(self, imagename, waittime=1, threshold=0.01, rotation=0):
        '''
        if the wanted image found on current screen click it.
        if the wanted image not found raise exception and set test to be failure.
        '''
        expect_image_path = None
        current_image_path = None
        if os.path.isabs(imagename):
            expect_image_path = imagename
            current_image_path = join(self.report_dir_path, os.path.basenme(imagename))
        else:
            expect_image_path = join(self.right_dir_path, imagename)
            current_image_path = join(self.report_dir_path, imagename)       

        assert os.path.exists(expect_image_path), 'the local expected image %s not found!' % expect_image_path

        self.d.screenshot(current_image_path)
        assert os.path.exists(current_image_path), 'fetch current screen shot image %s failed!' % imagename
        pos = getMatchedCenterOffset(subPath=expect_image_path, srcPath=current_image_path, threshold=0.01, rotation=rotation)
        if not pos:
            reason = 'Fail Reason: The wanted image \'%s\' not found on screen!' % imagename
            raise ExpectException(expect_image_path, current_image_path, reason)
        self.d.click(pos[0], pos[1])
        time.sleep(waittime)

    def screenshot_common(self, filename):
        '''
        if SK version <= 16
        Capture the screenshot via adb and store it in the specified location.
        '''
        png = os.path.basename(filename)
        if self.serial:
            shell('adb -s %s shell screencap %s%s' % (self.serial, self._internal_storage_dir, png))
            shell('adb -s %s pull %s%s %s' % (self.serial, self._internal_storage_dir, png, filename))
        else:
            shell('adb shell screencap %s%s' % (self._internal_storage_dir, png))
            shell('adb pull %s%s %s' % (self._internal_storage_dir, png, filename))
        return True

    #inspect
    def exists(self, **kwargs):
        '''
        if the expected component exists on current screen layout return true else return false.
        '''
        return self.d.exists(**kwargs)

    def expect(self, imagename, interval=2, timeout=4, threshold=0.01, msg=''):
        '''
        if the expected image found on current screen return self 
        else raise exception. set test to be failure.
        '''
        expect_image_path = None
        current_image_path = None
        if os.path.isabs(imagename):
            expect_image_path = imagename
            current_image_path = join(self.report_dir_path, os.path.basenme(imagename))
        else:
            expect_image_path = join(self.right_dir_path, imagename)
            current_image_path = join(self.report_dir_path, imagename)       

        assert os.path.exists(expect_image_path), 'the local expected image %s not found!' % expect_image_path
        begin = time.time()
        while (time.time() - begin < timeout):
            self.d.screenshot(current_image_path)
            if isMatch(expect_image_path , current_image_path , threshold):
                return self
            time.sleep(interval)
        reason = msg if msg else 'Fail Reason: Image \'%s\' not found on screen!' % imagename
        raise ExpectException(expect_image_path, current_image_path, reason)

    def find(self, imagename, interval=2, timeout=4, threshold=0.01):
        '''
        if the expected image found on current screen return true else return false
        '''
        expect_image_path = None
        current_image_path = None
        if os.path.isabs(imagename):
            expect_image_path = imagename
            current_image_path = join(self.report_dir_path, os.path.basenme(imagename))
        else:
            expect_image_path = join(self.right_dir_path, imagename)
            current_image_path = join(self.report_dir_path, imagename)       

        assert os.path.exists(expect_image_path), 'the local expected image %s not found!' % expect_image_path

        begin = time.time()
        isExists = False
        while (time.time() - begin < timeout):
            time.sleep(interval)
            self.d.screenshot(current_image_path)
            isExists = isMatch(expect_image_path , current_image_path , threshold)
            if not isExists:
                time.sleep(interval)
                continue
        return isExists

    def TODOinstallPackage(self, **kwargs):
        pass

    def TODOremovePackage(self, **kwargs):
        pass
Esempio n. 5
0
class AndroidDevice(object):
    '''
    wrapper for android uiautomator(pip install uiautomator) and image comparision(pip install imglib)
    to provide android device event inject and ui object inspect and image comparison.
    '''

    def __init__(self):
        self.serial = configer.env[ANDROID_SERIAL] if configer.env.has_key(ANDROID_SERIAL) else None
        self.d = Device(self.serial)
    
    def __getattr__(self, method):
        '''
        forward method to uiautomator device if method support by uiautomator.
        '''
        if hasattr(self.d, method):
            def wrapper(*args, **kwargs):
                return getattr(self.d, method)(*args, **kwargs)
            return wrapper
        raise AttributeError(method)


    def serial(self):
        '''device serial number from $ANDROID_SERIAL '''
        return self.serial

    def info(self):
        '''retrieve the device info'''
        return self.d.info
   
    def sleep(self, seconds):
        time.sleep(seconds)
        return self

    #device event inject
    def start_activity(self, **kwargs):
        '''launch application from android shell am start: component, flag
        // from adb docs:
        //<INTENT> specifications include these flags:
        //    [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
        //    [-c <CATEGORY> [-c <CATEGORY>] ...]
        //    [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
        //    [--esn <EXTRA_KEY> ...]
        //    [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
        //    [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
        //    [-n <COMPONENT>] [-f <FLAGS>]
        //    [<URI>]
        '''
        #d.server.adb.cmd('shell','am', 'start', '-a', 'android.intent.action.DIAL','tel:13581739891').communicate()
        #sys.stderr.write(str(kwargs))
        keys = kwargs.keys()
        shellcmd = ['shell', 'am', 'start']
        if 'component' in keys:
            shellcmd.append('-n')
            shellcmd.append(kwargs['component'])

        if 'action' in keys:  
            shellcmd.append('-a')
            shellcmd.append(kwargs['action'])

        if 'data' in keys:
            shellcmd.append('-d')
            shellcmd.append(kwargs['data'])

        if 'mimetype' in keys:
            shellcmd.append('-t')
            shellcmd.append(kwargs['mimetype'])

        if 'categories' in keys:
            for category in kwargs['categories']:
                shellcmd.append('-c')
                shellcmd.append(category)
        
        if 'extras' in keys:
            for extra_key, extra_value in kwargs['extras'].items():
                str_value = ''
                arg = ''
                if isinstance(extra_value, types.IntType):
                    str_value = str(extra_value)
                    arg = '--ei'
                elif isinstance(extra_value, types.BooleanType):
                    str_value = str(extra_value)
                    arg = '--ez'
                else:
                    str_value = str(extra_value)
                    arg = '--es'
                shellcmd.append(arg)
                shellcmd.append(extra_key)
                shellcmd.append(str_value)
                
        if 'flags' in keys:
            shellcmd.append('-f')
            shellcmd.append(str(kwargs['flags']))

        if 'uri' in keys:
            shellcmd.append(kwargs['uri'])
        #sys.stderr.write(str(shellcmd))            
        self.d.server.adb.cmd(*shellcmd).communicate()
        return self

    def instrument(self, **kwargs):
        keys = kwargs.keys()
        shellcmd = ['shell', 'am', 'instrument', '-w', '-r']
        pkgname = kwargs.pop('packagename')
        for k, v in kwargs.items():
            if k and v:
                shellcmd.append('-e')
                shellcmd.append(k)
                shellcmd.append(str(v))
        shellcmd.append(pkgname)
        result = self.d.server.adb.cmd(*shellcmd).communicate()
        return result

    def TODOinstallPackage(self, **kwargs):
        pass

    def TODOremovePackage(self, **kwargs):
        pass

    def press(self, keyname, waittime=1):
        #hard, soft key: home,back,up,down,right,left,center,menu,power or ANDROID_KEYEVENT
        self.d.press(keyname)
        time.sleep(waittime)
        return self

    def click(self, x, y, waittime=1):
        self.d.click(x, y)
        time.sleep(waittime)
        return self

    def click_image(self, imagename, waittime=1, threshold=0.01):
        '''
        if the wanted image found on current screen click it.
        if the wanted image not found raise exception and set test to be failure.
        '''
        expect_image_path = os.path.join(configer['right_dir_path'], imagename)
        assert os.path.exists(expect_image_path), 'the local expected image %s not found!' % imagename
        current_image_path = os.path.join(configer['report_dir_path'], imagename)
        self.d.screenshot(current_image_path)
        assert os.path.exists(current_image_path), 'fetch current screen shot image %s failed!' % imagename
        pos = getMatchedCenterOffset(expect_image_path, current_image_path, threshold)
        assert pos, 'Fail Reason: The wanted image \'%s\' not found on screen!' % imagename
        self.d.click(pos[0], pos[1])
        time.sleep(waittime)
        return self

    def swipe(self, sx, sy, ex, ey, steps=100, waittime=1):
        self.d.swipe(sx, sy, ex, ey, steps)
        time.sleep(waittime)
        return self

    def drag(self, sx, sy, ex, ey, steps=100, waittime=1):
        self.d.drag(sx, sy, ex, ey, steps)
        time.sleep(waittime)
        return self

    #inspect
    def exists(self, **kwargs):
        '''
        if the expected component exists on current screen layout return true else return false.
        '''
        return self.d.exists(**kwargs)

    #device snapshot
    def screenshot(self, filename, waittime=1):
        path = os.path.join(configer['report_dir_path'], filename)
        self.d.screenshot(path)
        return self

    def expect(self, imagename, interval=2, timeout=4, threshold=0.01, msg=''):
        '''
        if the expected image found on current screen return self 
        else raise exception. set test to be failure.
        '''
        expect_image_path = os.path.join(configer['right_dir_path'], imagename)
        assert os.path.exists(expect_image_path)
        current_image_path = os.path.join(configer['report_dir_path'], imagename)
        begin = time.time()
        while (time.time() - begin < timeout):
            self.d.screenshot(current_image_path)
            if isMatch(expect_image_path , current_image_path , threshold):
                return self
            time.sleep(interval)
        name, ext = os.path.splitext(os.path.basename(imagename))
        shutil.copyfile(expect_image_path, os.path.join(configer['report_dir_path'], '%s%s%s' % (name, '_expect', ext)))
        reason = msg if not msg else 'Fail Reason: Image \'%s\' not found on screen!' % imagename
        assert False, reason

    def find(self, imagename, interval=2, timeout=4, threshold=0.01):
        '''
        if the expected image found on current screen return true else return false
        '''
        expect_image_path = os.path.join(configer['right_dir_path'], imagename)
        assert os.path.exists(expect_image_path)
        current_image_path = os.path.join(configer['report_dir_path'], imagename)
        begin = time.time()
        isExists = False
        while (time.time() - begin < timeout):
            time.sleep(interval)
            self.d.screenshot(current_image_path)
            isExists = isMatch(expect_image_path , current_image_path , threshold)
            if not isExists:
                time.sleep(interval)
                continue
        return isExists
Esempio n. 6
0
class ModelInfo():
    '''
    classdocs
    '''
    def __init__(self, deviceserial):
        '''
        Constructor
        '''

        #sndLog = CLS("test", "test")
        self.osType = sys.platform

        self.mstrInfo = {}

        #self.devSerials = self.instAdb.device_serial()
        self.mstrDevice = Device(deviceserial)
        self.mstrInfo = self.mstrDevice.info

    '''
        DEVICE Infoamtions
        { u'displayRotation': 0,
          u'displaySizeDpY': 640,
          u'displaySizeDpX': 360,
          u'currentPackageName': u'com.android.launcher',
          u'productName': u'takju',
          u'displayWidth': 720,
          u'sdkInt': 18,
          u'displayHeight': 1184,
          u'naturalOrientation': True
        }
    '''

    def getCurrntProductInfo(self):
        return self.mstrInfo

    def getProductNmae(self):
        return self.mstrInfo['productName']

    def getCurrntPkg(self):
        return self.mstrInfo['currentPackageName']

    def getSDKInt(self):
        return self.mstrInfo['sdkInt']

    def getRotation(self):
        return self.mstrInfo['displayRotation']

    def getNaturalOri(self):
        return self.mstrInfo['naturalOrientation']

    def getDisplayState(self):
        return self.mstrDevice.screen

    def setReflash(self):
        pass

    #define Key activity
    def setDevScrnOn(self):
        self.mstrDevice.screen.on()

    def setMstDevScrnOff(self):
        self.mstrDevice.screen.off()

    def setWakeup(self):
        self.mstrDevice.wakeup()

    def setSleep(self):
        self.mstrDevice.sleep()

    #Hard key Soft key
    def pressHome(self):
        return self.mstrDevice.press.home()

    def pressBack(self):
        return self.mstrDevice.press.back()

    ######################################################################

    def pressLeft(self):
        return self.mstrDevice.press.left()

    def pressRight(self):
        return self.mstrDevice.press.right()

    def pressUp(self):
        return self.mstrDevice.press.up()

    def pressDown(self):
        return self.mstrDevice.press.down()

    def pressCenter(self):
        return self.mstrDevice.press.center()

    ######################################################################

    def pressMenu(self):
        return self.mstrDevice.press.menu()

    def pressSearch(self):
        return self.mstrDevice.press.search()

    def pressEnter(self):
        return self.mstrDevice.press.enter()

    def pressDelete(self):
        return self.mstrDevice.press.delete()  # or del

    def pressRecent(self):
        return self.mstrDevice.press.recent()

    def pressVol_Up(self):
        return self.mstrDevice.press.volume_up()

    def pressVol_Down(self):
        return self.mstrDevice.press.volume_down()

    def pressVol_Mute(self):
        return self.mstrDevice.press.volume_mute()

    def pressPower(self):
        return self.mstrDevice.press.power()

    def clik(self, x, y):
        return self.mstrDevice.click(x, y)

    def longClik(self, x, y):
        '''
            Description:
                
            param:
                x, y : start first point x, y
                
            return : Boolean
        '''
        return self.mstrDevice.long_click(x, y)

    def swipe(self, sx, sy, ex, ey, steps=10):
        '''
            Description:
                
            param:
                sx, xy : start first x, y
                ex, ey : move to x, y
            return : Boolean
        '''
        return self.mstrDevice.swipe(sx, sy, ex, ey, steps)

    def drage(self, sx, sy, ex, ey, steps=10):
        '''
            Description:
                
            param:
                sx, xy : start first x, y
                ex, ey : move to x, y
            return : Boolean
        '''
        return self.mstrDevice.drag(sx, sy, ex, ey, steps)

    #screen action of the device
    def setOrientation(self, scrAct='natural', choiceDevice='mstr'):
        '''
            Description
                
            param
                d.orientation = 'l' or 'left'
                d.orientation = 'r' or 'right'
                d.orientation = 'n' or 'natural'
            return : None
        '''
        self.mstrDevice.orientation = scrAct

    def setFreezeRotation(self, condition=False, choiceDevice='mstr'):
        '''
            param:
                condition : False un-freeze rotation
            return : None
        '''
        self.mstrDevice.freeze_rotation(condition)

    def takeScreenShot(self, choiceDevice='mstr'):
        '''
            Description:
                take screenshot and save to local file 'home.png' can work until android 4.2
            param
                image name
        '''

    def dumpWindowHeirarchy(self, filename='./log/hierachy.xml'):
        return self.mstrDevice.dump(filename)

    def dumpWindowHeirarchyStream(self):
        return self.mstrDevice.dump()

    def notification(self):
        '''
            Open notification, can not work until android 4.3
            return : Boolean
        '''
        return self.mstrDevice.open.Notification()

    def quickSettings(self):
        '''
            open quick settins, can not work until android 4.3
            return : Boolean 
        '''
        return self.mstrDevice.open.quick_settings()

    def waitidle(self):
        '''
            wait for current window to idle
            return : None
        '''
        self.mstrDevice.wait.idle()

    def waitWindowUpdate(self):
        '''
            wait until window upate event occurs
            return : Boolean
        '''
        self.mstrDevice.wait.update()

    def getCurrentActivityInfo(self, text):
        '''
          INFOMATION:
              { u'contentDescription': u'',
              u'checked': False,
              u'scrollable': False,
              u'text': u'Settings',
              u'packageName': u'com.android.launcher',
              u'selected': False,
              u'enabled': True,
              u'bounds': {u'top': 385,
                          u'right': 360,
                          u'bottom': 585,
                          u'left': 200},
              u'className': u'android.widget.TextView',
              u'focused': False,
              u'focusable': True,
              u'clickable': True,
              u'chileCount': 0,
              u'longClickable': True,
              u'visibleBounds': {u'top': 385,
                                 u'right': 360,
                                 u'bottom': 585,
                                 u'left': 200},
              u'checkable': False
            }
        '''
        return self.mstrDevice(text).info

    def uiObjExist(self, text):
        '''
            ture if exists, else False
        '''
        return self.mstrDevice.exists(text)

    def watcher(self):
        pass

    def handler(self):
        pass

    def selector(self):
        pass

    def __del__(self):
        pass
Esempio n. 7
0
class Networking(NetworkingKK):
    """
    Class that handle all networking operations
    """
    def __init__(self, phone):
        """
        Constructor
        """
        NetworkingKK.__init__(self, phone)
        self._device_serial_number = phone.retrieve_serial_number()
        self.dut = None

    def load_wpa_certificate(self,
                             certificate_name=None,
                             certificate_file=None,
                             eap_password=None,
                             credential_password=None):
        """
        Load the WPA certificate file from the SDCARD
        Prerequisite: A certificate file ".p12" should have been pushed into
        the folder /sdcard/.
        Warning, only 1 .p12 file must be present on the SDCARD
        Warning 2: if a credential password is set, it should be the PIN code
                    specified in the benchConfig (Credential_password)

        :type certificate_name: str
        :param certificate_name: Name to give to the certificate after loading

        :type certificate_file: str
        :param certificate_file: Name of the certificate file to load

        :type eap_password: str
        :param eap_password: password to open the certificate file

        :type credential_password: str
        :param credential_password: password to set for the Android credential
                                    passwords

        :return: None
        """
        # uiautomator is imported here to avoid crashes when uiautomator is not installed on the computer
        # uiautomator is not in the ACS installer for the moment
        # Should be removed when uiautomator will be installed by ACS installer
        from uiautomator import Device
        if self.dut is None:
            self.dut = Device(self._device_serial_number)

        display = self._device.get_uecmd("Display")
        """
        On ICS, credential password is linked to screen phone lock password.
        Which was not the case on GingerBread.
        This make the UI script for loading the certificate much more complicate.
        This UI script should work in every circomstances:
        - With a certificate already loaded (so with a pin code set - we assume
         that this PIN code is the credential password mentionned in BencConfig)
        - With no certificate loaded and no pin code set to lock screen phone.
        - With no certificate but with PIN code to lock screen phone (We assume
         that this PIN code is the credential password mentionned in BencConfig)
        """

        # Unlock the device
        self._phone_system.set_phone_screen_lock_on(1)
        self._phone_system.set_phone_lock(0)

        # Force the screen orientation to portrait
        display.set_display_orientation("portrait")

        # Step 1: Remove potential existing certificate
        self._exec(
            "adb shell am start -n com.android.settings/.SecuritySettings")
        time.sleep(1)

        self.dut(scrollable=True).scroll.to(text="Clear credentials")
        if self.dut(text="Clear credentials").enabled:
            msg = "Removing old Certificate"
            self._logger.info(msg)
            self.dut(text="Clear credentials").click()
            self.dut(text="OK").click()

        self.dut(scrollable=True).scroll.to(text="Screen lock")

        if self.dut.exists(text="PIN"):
            msg = "PIN CODE already set"
            self._logger.info(msg)

        else:
            # set PIN CODE
            self.dut(text="Screen lock").click()
            self.dut(text="PIN").click()
            if self.dut(text="No thanks").exists:
                # since LLP, Pin code can be required for starting up
                self.dut(text="No thanks").click()
                self.dut(text="Continue").click()
            # setting Pin code
            self.dut(text="Choose your PIN").set_text(credential_password)
            self.dut(text="Continue").click()
            self.dut(text="Choose your PIN").set_text(credential_password)
            self.dut(text="OK").click()
            if self.dut(text="Don't show notifications at all").exists:
                self.dut(text="Don't show notifications at all").click()
                self.dut(text="Done").click()
            self.dut.press.back()
            self.dut.press.back()

        self._phone_system.set_phone_lock(1)
        time.sleep(1)
        # Load the certificate
        self._phone_system.set_phone_lock(0)

        self._exec("adb shell am force-stop com.android.settings")
        time.sleep(3)
        self._exec(
            "adb shell am start -n com.android.settings/.SecuritySettings")
        time.sleep(2)

        self.dut(scrollable=True).scroll.to(text="Clear credentials")

        # Specific to platforms ( internal storage or sd card need to be chosen)
        if self.dut(text="Install from storage").exists:
            self.dut(text="Install from storage").click()
        elif self.dut(text="Install from SD card").exists:
            self.dut(text="Install from SD card").click()
        else:
            raise DeviceException(
                DeviceException.OPERATION_FAILED,
                "install from storage or from sd card is not available, possible api changes"
            )
        time.sleep(2)

        # after first certificate installation this window disappear
        if self.dut(text="Internal storage").exists:
            self.dut(text="Internal storage").click()

        if self.dut(text=certificate_file).exists:
            self.dut(text=certificate_file).click()

        else:
            try:
                # try to scroll to search for certificate file
                self._logger.info(
                    "the certificat %s does not exisit on display trying to scroll"
                    % certificate_file)
                self.dut(scrollable=True).scroll.to(text=certificate_file)
                self.dut(text=certificate_file).click()
            except Exception as error:
                # raise execption for cetifcate file not found
                raise DeviceException(
                    DeviceException.OPERATION_FAILED,
                    "Error %s : Certificate file %s not found on DUT " %
                    (str(error), certificate_file))
        time.sleep(2)
        self.dut(text="Extract certificate").set_text(eap_password)
        self.dut(text="OK").click()
        self.dut(text="Certificate name:").set_text(certificate_name)
        if self.dut(text="VPN and apps").exists:
            self.dut(text="VPN and apps").click()
            self.dut(text="Wi-Fi").click()
            self.dut(text="OK").click()
            if self.dut(text="Confirm your PIN").exists:
                # sometimes need to confirm PIN CODE
                self.dut(text="Confirm your PIN").set_text(credential_password)
                if self.dut(text="Next").exists:
                    self.dut(text="Next").click()
                elif self.dut(text="Continue").exists:
                    self.dut(text="Continue").click()
                else:
                    raise DeviceException(
                        DeviceException.OPERATION_FAILED,
                        "Unable to confirm PIN CODE , check if display has been modified "
                    )

        elif self.dut(text="Wi-Fi").exists:
            self.dut(text="OK").click()

        else:
            msg = "Credential use not supported"
            raise DeviceException(DeviceException.OPERATION_FAILED,
                                  "Credential use not supported ")

        self.dut(scrollable=True).scroll.to(text="Clear credentials")
        if self.dut(text="Clear credentials").enabled:
            msg = "Wifi Certifiacte is successfully installed"
            self._logger.info(msg)
        else:
            raise DeviceException(
                DeviceException.OPERATION_FAILED,
                "Wifi Certifiacte is not successfully installed")

        # Re-allow phone locking
        self._phone_system.set_phone_lock(1)
        self._phone_system.set_phone_screen_lock_on(0)
        display.set_display_orientation("auto")

    def open_web_browser(self,
                         website_url,
                         browser_type="chrome",
                         timeout=None,
                         skip_eula=False):
        """
        Open the Android Browser on the web page
        passed as parameter.

        :type website_url: str
        :param website_url: URL to open

        :type browser_type: str
        :param browser_type: "native" will open the default browser,
                             "acs_agent" will use the browser of the acs agent

        :type timeout: int
        :param timeout: timeout to open the page

        :type skip_eula: boolean
        :param skip_eula: skip EULA on 1st start

        :rtype: tuple
        :return: operation status & output log
        """
        if browser_type == "chrome" or browser_type == "acs_agent":
            error_code, error_msg = NetworkingKK.open_web_browser(
                self, website_url, browser_type, timeout, skip_eula)
            return error_code, error_msg
        else:
            error_msg = "Unsupported browser type : %s" % str(browser_type)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     error_msg)

    def close_web_browser(self, browser_type="chrome"):
        """
        Close the Android Browser.

        :type browser_type: str
        :param browser_type: "native" will open the default browser,
            other type can be added depending on the os

        :return: None
        """
        self._logger.info("Closing the %s web browser" % str(browser_type))
        if browser_type == "chrome" or browser_type == "acs_agent":
            NetworkingKK.close_web_browser(self, browser_type)
        else:
            error_msg = "Unsupported browser type : %s" % str(browser_type)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER,
                                     error_msg)

    def set_wifi_scan_always_available(self, mode):
        """
        Set the WiFi Scan always available option in WiFi settings menu.
        WARNING : this function use UI !

        :type mode: str
        :param mode: mode to set. Possible values : "ON", "OFF"
        """
        KEYCODE_DPAD_DOWN = "20"
        KEYCODE_MOVE_HOME = "122"
        KEYCODE_ENTER = "66"

        if mode not in ["ON", "OFF"]:
            msg = "Invalid parameter mode : %s" % mode
            self._logger.error(msg)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg)

        if self.get_wifi_scan_always_available() == mode:
            self._logger.debug("WiFi Scan Always Available is already %s" %
                               mode)
            return

        # Go to WiFi Advanced Settings Menu
        self.wifi_menu_advanced_settings()

        # Switch WiFi Scan always available option
        self._exec("adb shell input keyevent " + KEYCODE_MOVE_HOME)
        self._exec("adb shell input keyevent " + KEYCODE_DPAD_DOWN)
        self._exec("adb shell input keyevent " + KEYCODE_ENTER)

    def delete_apn(self, apn_name):
        """
        Deletes the APN with the given name.

        :type apn_name: str
        :param apn_name: the name of the APN to delete

        :rtype: None
        """
        # Initialize some local variables
        method = "deleteApn"
        args = "--es name \"%s\"" % apn_name
        # Execute the command
        self._internal_exec_v2(self._cellular_networking_module,
                               method,
                               args,
                               is_system=True)

    def update_apn(self, new_parameters):
        """
        Updates the APN configuration with the given new parameters.

        :type new_parameters: dict
        :param new_parameters: the key/value mapping of the parameters
            to update

        :rtype: None
        """
        # Initialize some local variables
        method = "updateApnWithParameters"
        args = ""
        # Update the command arguments
        for parameter_name in new_parameters:
            value = new_parameters[parameter_name]
            args = "%s %s \"%s\" \"%s\"" % (args, "--es", parameter_name,
                                            value)
        # Execute the command
        self._internal_exec_v2(self._cellular_networking_module,
                               method,
                               args,
                               is_system=True)

    def wifi_remove_config(self, ssid):
        """
        Remove a wifi configuration for the device (screen will be awaken during the process).

        :type ssid: str
        :param ssid: the ssid of the wifi configuration to be removed or "all"
        """
        # retrieve the initial wifi power status
        wifi_initial_status = self.get_wifi_power_status()

        # Enable wifi if necessary, to remove a known wifi network
        if wifi_initial_status == 0:
            self._logger.info("In order to remove remembered wifi " +
                              "networks, we must power on the wifi")
            self.set_wifi_power("on")

        # Wake up screen
        self._phone_system_api = self._device.get_uecmd("PhoneSystem")
        self._phone_system_api.wake_screen()

        # Remove the requested SSID
        self._logger.info("Trying to remove wifi config [%s]" % ssid)
        method = "removeWifiConfig"
        cmd_args = "--es ssid %s" % ssid
        self._internal_exec_v2(self._wifi_module,
                               method,
                               cmd_args,
                               is_system=True)

        # reset wifi state to its original state
        if wifi_initial_status == 0:
            self._logger.info("Set the wifi power to its original state")
            self.set_wifi_power("off")

    def usb_tether(self, wifi_off, unplug_usb, use_flight_mode):
        """
        push and run a script that will execute the test in adb disconnected mode

        :type wifi_off: int
        :param wifi_off: 1 to turn wifi off during usb tethering

        :type unplug_usb: int
        :param unplug_usb: 1 to unplug usb during usb tethering

        :type use_flight_mode: int
        :param use_flight_mode: 1 to turn on flight mode during usb tethering

        :return: None
        """
        script_name = "/data/usb_tether.sh"
        script_output = "/data/usb_tether.log"

        if wifi_off:
            # case 3: activate tethering, ping AP, turn wifi off
            # ping AP (fail) turn wifi on, ping AP, deactivate
            # tethering
            script_data = \
                """#!/system/bin/sh
sleep 10
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setUsbTethering --es switch on -e opcode %s
sleep 60
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setWifiPower --ei mode 0 -e opcode %s
sleep 30
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setWifiPower --ei mode 1 -e opcode %s
sleep 30
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setUsbTethering --es switch off -e opcode %s
sleep 30
""" \
                % (self._tethering_module, self._generate_key(),
                   self._wifi_module, self._generate_key(),
                   self._wifi_module, self._generate_key(),
                   self._tethering_module, self._generate_key())
        elif unplug_usb:
            # case 2: activate tethering, ping AP, unplug USB
            # ping AP (fail) plug USB, ping AP (fail), deactivate
            # tethering
            script_data = \
                """#!/system/bin/sh
sleep 10
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setUsbTethering --es switch on -e opcode %s
sleep 120
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setUsbTethering --es switch off -e opcode %s
sleep 30
""" \
                % (self._tethering_module, self._generate_key(),
                   self._tethering_module, self._generate_key())
        elif not use_flight_mode:
            # case 1: activate tethering, ping AP, activate flight mode
            # ping AP (fail) deactivate flight mode, ping AP, deactivate
            # tethering
            script_data = \
                """#!/system/bin/sh
sleep 10
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setUsbTethering  --es switch on -e opcode %s
sleep 60
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setFlightMode --ei mode 1 -e opcode %s
sleep 30
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setFlightMode --ei mode 0 -e opcode %s
sleep 30
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setUsbTethering  --es switch off -e opcode %s
sleep 30
""" \
                % (self._tethering_module, self._generate_key(),
                   self._connectivity_module, self._generate_key(),
                   self._connectivity_module, self._generate_key(),
                   self._tethering_module, self._generate_key())
        else:
            # case 0: activate tethering, ping AP, deactivate tethering
            script_data = \
                """#!/system/bin/sh
sleep 10
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setUsbTethering --es switch on -e opcode %s
sleep 60
am broadcast -a intel.intent.action.acs.cmd.system --es class %s --es method setUsbTethering --es switch off -e opcode %s
sleep 30
""" \
                % (self._tethering_module, self._generate_key(),
                   self._tethering_module, self._generate_key())

        # Copy the script file on DUT file system
        tmp_file = tempfile.NamedTemporaryFile(mode="w+b", delete=False)
        tmp_file.write(script_data)
        tmp_file.flush()
        tmp_file.close()
        cmd = "adb push %s %s" % (tmp_file.name, script_name)
        self._exec(cmd)
        os.unlink(tmp_file.name)

        # Set execution permissions
        cmd = "adb shell chmod 777 %s" % script_name
        self._exec(cmd)

        # Run script detached on DUT
        cmd = "adb shell exec nohup %s > %s && echo -n" \
              % (script_name, script_output)
        self._exec(cmd, wait_for_response=False)

    def set_preferred_network_mode(self, preferred_mode):
        """
        Sets the Preferred Network Type on user menu .

        :type preferred_mode:  str
        :param preferred_mode: can be:
            "2G_ONLY"       for # 1: "GSM_ONLY",
            "3G_PREF"       for # 0: "WCDMA_PREF",
            "4G_PREF"       for # 9: "LTE_GSM_WCDMA",
            "3G_ONLY"       for # 2: "WCDMA_ONLY",
            "2G_3G"         for # 3: "GSM_UMTS",
            "CDMA_PREF"     for # 4: "CDMA",
            "CDMA_ONLY"     for # 5: "CDMA_NO_EVDO"
            "EVDO_ONLY"     for # 6: "EVDO_NO_CDMA"
            "GLOBAL"        for # 7: "GLOBAL",
            "4G_PREF_US"    for # 8: "LTE_CDMA_EVDO",
            "WORLD_MODE"    for # 10: "LTE_CMDA_EVDO_GSM_WCDMA"
            "4G_ONLY"       for # 11: "LTE_ONLY"

        :return: None
        """
        self._logger.info("Set preferred network type on dut ...")
        current_mode = self.get_preferred_network_type()
        if current_mode == preferred_mode:
            warning_msg = "the preferred network '%s' type is already enabled" % str(
                preferred_mode)
            self._logger.info(warning_msg)
        else:
            preferred_mode = get_dict_key_from_value(
                self.NETWORK_TYPE_CONVERSION_TABLE, preferred_mode)
            self._logger.info(
                "Setting the wanted preferred network type: '%s' " %
                str(preferred_mode))
            method = "setPreferredNetworkMode"
            cmd = " --ei networkMode %d" \
                  % preferred_mode
            self._internal_exec_v2(self.network_type_module,
                                   method,
                                   cmd,
                                   is_system=True)

            self._logger.info(
                "Update preferred network mode (%d) to database ..." %
                int(preferred_mode))
            self._set_preferred_network_db_value(preferred_mode)

    @need('wifi')
    def set_regulatorydomain(self, regulatory_domain, interface="wlan0"):
        """
        Set the Wifi Regulatory Domain

        :type regulatory_domain: String
        :param regulatory_domain: the regulatory domain to set (FR, GB, US...)

        :type interface: str
        :param interface: interface name (wlan0/wlan1 etc...)
        """
        if regulatory_domain.lower() == "none":
            regulatory_domain = "00"

        # Force the root because sometimes it is lost and the set regulatory domain command fails.
        self._exec("adb root", force_execution=True, timeout=10)
        time.sleep(2)

        wifi_chipset = self._get_wifi_chipset_manufacturer()

        if wifi_chipset == self.CHIPSET_INTEL:

            # Check Wifi chipset is ready to be set
            self.get_regulatorydomain()

            cmd = "adb shell iw reg set %s" % regulatory_domain
            output = self._exec(cmd)
            if "failed" in output.lower():
                msg = "Unable to set regulatory domain - %s" % str(output)
                self._logger.error(msg)
                raise DeviceException(DeviceException.OPERATION_FAILED, msg)
        else:
            NetworkingKK.set_regulatorydomain(self, regulatory_domain,
                                              interface)

        # Store set value for later restoration.
        self.__last_set_reg_domain = regulatory_domain

        # Control the value set
        value_set = self.get_regulatorydomain()

        if value_set != regulatory_domain:
            msg = "Regulatory domain set fails. Try to set: %s. Read: %s" \
                % (regulatory_domain, value_set)
            self._logger.warning(msg)

    def remove_wpa_certificates(self,
                                credential_password=None,
                                pin_code_removal=False):
        """
        Remove wpa certificates already installed on device.
        Possibility to remove pin code already set.

        :type pin_code_removal: boolean
        :param pin_code_removal: Remove Pin Code

        :return: None
        """
        # uiautomator is imported here to avoid crashes when uiautomator is not installed on the computer
        # uiautomator is not in the ACS installer for the moment
        # Should be removed when uiautomator will be installed by ACS installer
        from uiautomator import Device
        if self.dut is None:
            self.dut = Device(self._device_serial_number)

        display = self._device.get_uecmd("Display")
        """
        On ICS, credential password is linked to screen phone lock password.
        Which was not the case on GingerBread.
        This make the UI script for loading the certificate much more complicate.
        This UI script should work in every circomstances:
        - With a certificate already loaded (so with a pin code set - we assume
         that this PIN code is the credential password mentionned in BencConfig)
        - With no certificate loaded and no pin code set to lock screen phone.
        - With no certificate but with PIN code to lock screen phone (We assume
         that this PIN code is the credential password mentionned in BencConfig)
        """

        # Unlock the device
        self._phone_system.set_phone_screen_lock_on(1)
        self._phone_system.set_phone_lock(0)

        # Force the screen orientation to portrait
        display.set_display_orientation("portrait")

        # Step 1: Remove potential existing certificate
        self._exec(
            "adb shell am start -n com.android.settings/.SecuritySettings")
        time.sleep(1)
        self.dut(scrollable=True).scroll.to(text="Clear credentials")
        if self.dut(text="Clear credentials").enabled:
            msg = "Removing old Certificate"
            self._logger.info(msg)
            self.dut(text="Clear credentials").click()
            self.dut(text="OK").click()

        if pin_code_removal:
            # Remove Pin CODE
            msg = "Trying to remove PIN CODE on Device"
            self._logger.info(msg)
            # Step 2: Reset current screen phone lock PIN code if exists
            self._phone_system.set_phone_lock(0)
            self._exec(
                "adb shell am start -n com.android.settings/.SecuritySettings")
            time.sleep(1)

            self.dut(scrollable=True).scroll.to(text="Screen lock")

            if self.dut.exists(text="PIN"):
                msg = "Removing PIN CODE already set"
                self._logger.info(msg)
                self.dut(text="Screen lock").click()
                # setting Pin code
                self.dut(text="Confirm your PIN").set_text(credential_password)
                if self.dut(text="Next").exists:
                    self.dut(text="Next").click()
                elif self.dut(text="Continue").exists:
                    self.dut(text="Continue").click()
                else:
                    raise DeviceException(
                        DeviceException.OPERATION_FAILED,
                        "Unable to confirm PIN CODE , check if display has been modified "
                    )

                self.dut(text="Swipe").click()
                self.dut(text="OK").click()
                if self.dut.exists(text="Swipe"):
                    msg = "PIN CODE successfully removed"
                    self._logger.info(msg)

                else:
                    msg = "PIN CODE was not successfully removed"
                    self._logger.error(msg)

                self.dut.press.back()
                self.dut.press.back()

            else:
                # Remove Pin CODE
                msg = "PIN CODE is already not set"
                self._logger.info(msg)

        # Re-allow phone locking
        self._phone_system.set_phone_lock(1)
        self._phone_system.set_phone_screen_lock_on(0)
        display.set_display_orientation("auto")

    @need('wifi')
    def set_wifi_frequency_band(self,
                                freq_band,
                                silent_mode=False,
                                interface="wlan0"):
        """
        Set the Wifi Frequency Band

        :type freq_band: String
        :param freq_band: Frequency Band to set (auto, 2.4GHz, 5GHz)

        :type silent_mode: boolean
        :param silent_mode: if True, do not raise an exception
                            if the device does not support this method

        :type interface: str
        :param interface: interface name (wlan0/wlan1 etc...)
        """
        self._logger.info("Set Wifi frequency band to: %s" % str(freq_band))
        # Send the intent to set the Wifi Frequency Band selection
        if freq_band not in self.SUPPORTED_WIFI_BANDS:
            msg = "Invalid value for frequency band"
            self._logger.error(msg)
            raise AcsConfigException(AcsConfigException.INVALID_PARAMETER, msg)

        method = "setWifiFrequencyBand"
        cmd_args = "--ei wifi_frequency_band %s" % self.SUPPORTED_WIFI_BANDS[
            freq_band]
        self._internal_exec_v2(self._wifi_module,
                               method,
                               cmd_args,
                               is_system=True)

    @need('wifi')
    def get_wifi_frequency_band(self, silent_mode=False, interface="wlan0"):
        """
        Gets the band selection (bands of frequencies)
        0 means dual
        1 means 5Ghz
        2 means 2.4Ghz

        :type silent_mode: boolean
        :param silent_mode: if True, do not raise an exception if the device does not support this method
        :type interface: str
        :param interface: interface name (wlan0/wlan1 etc...)

        :rtype: String
        :return: The band text (JB or later).
        """
        method = "getWifiFrequencyBand"
        output = self._internal_exec_v2(self._wifi_module,
                                        method,
                                        is_system=True)

        status = int(output.get("wifi_frequency_band", None))
        self._logger.debug("STATUS VALUE = %s" % status)

        match = [
            k for k, v in self.SUPPORTED_WIFI_BANDS.iteritems() if v == status
        ]
        if match:
            result = match[0]
        else:
            result = None

        self._logger.debug("Wifi frequency band: %s" % str(result))
        return result
Esempio n. 8
0
class Monitor:
    def __init__(self, environment, monitor_serial):

        self.monitor_serial = monitor_serial
        self.specifying_monitor = '-s {}'.format(self.monitor_serial)
        self.device = Device(self.monitor_serial)
        self.build_location ="mon_test\Apps\monitor_build\dev-dell-release-SINK-0.0.3143.7736342\system"
        self.build_version = self.get_build_version()
        self.monitor_name = self.get_monitor_name_by_ui()
        self.find_command = " | findstr" if platform.platform() == "Windows" else "| grep"
        print 'Monitor:init - orientation=%s' % self.device.orientation

    def auto_approve_connection(self):
        print('changing to auto aprrove in monitor : {}'.format(self.monitor_name))
        self.device(resourceId="com.screenovate.dell.monitorserver:id/settings").click()
        self.device(resourceId="com.screenovate.dell.monitorserver:id/security_settings").click()
        self.device(text="Auto Approve").click()
        self.device(resourceId="android:id/button1").click()



    def approve_connection(self):
        os.system('adb -s {} shell am broadcast -a com.screenovate.sink.action.ACCEPT_PAIR'.format(self.monitor_serial))

    def decline_connection(self):
        os.system('adb -s {} shell am broadcast -a com.screenovate.sink.action.DECLINE_PAIR'.format(self.monitor_serial))

    def start_intent_of_approve(self):
        os.system('adb -s {} shell am broadcast -a com.screenovate.intent.action.P2P_DIALOG_REQUEST'.format(self.monitor_serial))

    def get_screen_size(self):
        size = "adb -s {} shell wm size".format(self.monitor_serial)
        output = subprocess.check_output([s for s in size.split()])
        return output.split(':')[1].strip()

    def install_build(self):
        os.system("adb -s {} root".format(self.monitor_serial))
        os.system("adb -s {} wait-for-device remount".format(self.monitor_serial))
        time.sleep(6)
        commandToExecute = ("adb -s {} push {} /system/".format(self.monitor_serial, self.build_location))
        os.system(commandToExecute)
        time.sleep(1)
        self.reboot_mon()

    def reboot_mon(self):
        checkBootComp = 'adb {} shell getprop sys.boot_completed'.format(self.specifying_monitor)
        output = subprocess.check_output([c for c in checkBootComp.split()])
        print('start rebbot monitor')
        os.system('adb {} reboot'.format(self.specifying_monitor))
        self.is_boot_completed(output)
        print('reboot monitor completed')

    def is_boot_completed(self, bootCompCmd):
        output = '-1'
        while output != bootCompCmd:
            time.sleep(1)
            try:
                screenUp = 'adb {} shell getprop sys.boot_completed'.format(self.specifying_monitor)
                output = subprocess.check_output([s for s in screenUp.split()])
            except Exception:
                print('waiting for monitor')
        print('Screen up and fully loaded')
        return True

    def do_factory_reset(self):
        checkBootComp = 'adb {} shell getprop sys.boot_completed'.format(self.specifying_monitor)
        output = subprocess.check_output([c for c in checkBootComp.split()])
        print('Start doing reboot to the monitor')
        self.device(resourceId="com.screenovate.dell.monitorserver:id/settings").click()
        self.device(resourceId="com.screenovate.dell.monitorserver:id/reset").click()
        self.device(resourceId="com.screenovate.dell.monitorserver:id/reset_ok").click()
        print('Start doing factory rest...')
        os.system("adb {} logcat".format(self.specifying_monitor))
        self.is_boot_completed(output)

    def set_wifi_channel(self, channel):
        print('Setting wifi channel to {} '.format(channel))
        self.device(resourceId="com.screenovate.dell.monitorserver:id/settings").click()
        self.device(resourceId="com.screenovate.dell.monitorserver:id/set_wifi_channel").click()
        auto_is_checked = self.device(resourceId="com.screenovate.dell.monitorserver:id/channel_auto_checkbox").info['checked']
        channel_24_is_checked = self.device(resourceId="com.screenovate.dell.monitorserver:id/channel_auto24_checkbox").info['checked']
        channel_5_is_checked = self.device(resourceId="com.screenovate.dell.monitorserver:id/channel_auto5_checkbox").info['checked']
        if auto_is_checked or channel_5_is_checked or channel_24_is_checked:
            self.device(resourceId="com.screenovate.dell.monitorserver:id/show_advanced").click()
            self.device(resourceId="com.screenovate.dell.monitorserver:id/channel_custom_checkbox").click()
        self.device(text=channel, className="android.widget.TextView").click()
        self.device(resourceId="com.screenovate.dell.monitorserver:id/channel_ok").click()


    def get_build_version(self):
        build_name = self.build_location
        return build_name[build_name.find('K-') + 2:build_name.find("/sys")]

    def check_build_version(self):
        print('checking version of the build')
        build_version = 'adb {} shell dumpsys package com.screenovate.dell.monitorserver'.format(
            self.specifying_monitor)
        output = subprocess.check_output([b for b in build_version.split()])
        return ("versionName={}".format(self.build_version) in output)



    def get_monitor_name_by_adb(self):
        dumpsys = "adb shell dumpsys | {} wifiP2pDevice=Device".format(self.find_command)
        output = subprocess.check_output([c for c in dumpsys.split()])
        start_index = output.rfind('Device: ', 0)
        start_index = start_index + 8
        end_index = output.rfind("\n", 0)
        name = output[start_index: end_index].strip()
        return name

    def verify_nothing_connected(self):
        print('verifying nothing connected')
        if self.device.exists(resourceId="com.screenovate.dell.monitorserver:id/video_view"):
            print('some device connected to monitor , stsrt rebooting monitor')
            self.reboot_mon()
        print('no device currently connected to monitor')

    def get_monitor_name_by_ui(self):
        self.verify_nothing_connected()
        print("get name from " + self.monitor_serial)
        self.monitor_name = self.device(resourceId="com.screenovate.dell.monitorserver:id/ssid").info[
            "text"]
        return self.monitor_name

    def screen_on(self):
        print("turning monitor screen on")
        os.system("adb {} shell input keyevent 82".format(self.specifying_monitor))



    def take_screenshot_test(self):
        self.device.screenshot("pictures-test/monitor.png")