def find_cleware4_names(): """docstring for find_cleware4s""" p = '.*Switch1.*version:.(29|512),.*serial number:.([0-9]{6,7})' cleware4s = [find_pattern(p, s, groupindex=2) for s in check_output('clewarecontrol -l', shell=True).split('\n') if find_pattern(p, s)] logging.debug('cleware4 cutters : {0}'.format(cleware4s)) return cleware4s
def _current_uart_status(self): """docstring for _current_uart_status""" self._flush_uart_buffer() for loop in range(3): self._write_uart(b'') readdata = self._read_uart(500) if find_pattern(self._pattern_bootprompt, readdata): return 'BOOT_PROMPT' if find_pattern(self._pattern_shellprompt, readdata): return 'LOGGED_IN' else: return 'NOT_LOGGED_IN'
def recognize_device(self, config, uart): """docstring for recognize_device""" for l in self.devcatalog: logging.debug('Is {}'.format(l['dev_type'].upper())) uart.flushInput() time.sleep(0.1) uart.flushOutput() time.sleep(0.5) uart.flush() time.sleep(0.1) uart.write(l['cmd'].encode() + b'\r') time.sleep(0.5) buf = uart.read(5000) if find_pattern(l['pattern'], decode(buf)): logging.debug('Yes') name = '{0}_{1:0>3}'.format(l['dev_type'].upper(), l['index']) cfg = {'name': name, 'dev_type': l['dev_type'], 'uart_port': uart.name } l['index'] += 1 return cfg
def _set_sdb_deviceid(self): """docstring for _set_sdb_deviceid""" usb0_path = b'/sys/class/usb_mode/usb0' pattern = '.*{0}'.format(self.get_id()) def set_serialnumber(deviceid): """docstring for set_serialnumber""" self._write_uart(b''.join([b'echo 0 > ', usb0_path, b'/enable'])) time.sleep(0.3) self._write_uart(b''.join( [b'echo ', b'-n ', deviceid, b' > ', usb0_path, b'/iSerial'])) time.sleep(0.3) self._write_uart(b''.join([b'echo 1 > ', usb0_path, b'/enable'])) time.sleep(0.3) self._write_uart(b''.join([b'cat ', usb0_path, b'/enable'])) time.sleep(0.3) def get_serialnumber(): """docstring for get_serialnumber""" self._write_uart(b''.join([b'cat ', usb0_path, b'/iSerial'])) time.sleep(0.3) return self._read_uart(1000) retrycnt = 0 while retrycnt < 10: set_serialnumber(deviceid=self.get_id().encode()) serialnumber = get_serialnumber() if find_pattern(pattern, serialnumber): return retrycnt += 1 else: raise Exception('Can\'t configure sdb deviceid')
def _get_display_server_type(self): """docstring for get_display_server_type""" res = self.run_cmd('ls /usr/lib', timeout=10) if find_pattern('.*libX11.*', res): return 'X11' else: return 'WAYLAND'
def _find_device_id(self): """docstring for _find_device_id""" self.start_sdb_server() outs = check_output(['sdb', 'devices'], timeout=10) pattern = '.*List of devices attached \n([a-zA-Z0-9]*).*device.*' found = find_pattern(pattern, outs, groupindex=1) if found: return found
def is_on(self): """docstring for is_on""" super(cuttercleware4, self).is_on() c = self._getstatuscmd.format(cport=self._cport, cindex=self._cindex) out = check_output(c, shell=True, timeout=10) if find_pattern(pattern=r'On', data=out): return True else: return False
def is_on(self, uart): """docstring for is_on""" p = r'.*echo.*' uart.flushInput() time.sleep(0.1) uart.flushOutput() time.sleep(0.1) uart.flush() time.sleep(0.1) uart.write(b'echo\r') time.sleep(0.1) data = decode(b' '.join(uart.readlines(500))) return find_pattern(p, data)
def is_on(self): """docstring for is_on""" super(cuttersmartpower, self).is_on() c = self._getstatuscmd.format(cport=self._cport) out = check_output(c, shell=True, stderr=subprocess.DEVNULL, timeout=10) if find_pattern(pattern=r'[0-9].[0-9]{3}W', data=out): return True else: return False
def _attach_sdb(self): """docstring for _attach_sdb""" # start sdb server if it is not started. call('sdb start-server'.split(), timeout=10) retry_attempt = 0 pattern = r'{}.*device.*\t.*'.format(self.get_id()) while retry_attempt < self._max_attempt_attach_sdb: for l in range(self._retrycnt_at_a_time_sdb): outs = check_output('sdb devices'.split(), timeout=10) logging.debug(outs) if find_pattern(pattern, outs): logging.debug('found {}.'.format(self.get_id())) return time.sleep(0.2) retry_attempt += 1 else: raise Exception('Can\'t find device.')
def _wait_uart_shell_login_prompt(self): """docstring for _wait_uart_shell_login_prompt""" logging.debug('===============Print boot logs===============') start_time = time.perf_counter() wait_time = 0 while wait_time < self._boot_timeout: if self._uart.inWaiting: buf = self._read_uart(1000) if find_pattern(self._pattern_loginprompt, data=buf): logging.debug('Found login shell pattern from uart log') logging.debug('wait_time : {}'.format(wait_time)) return elif len(buf) == 0: self._write_uart(b'') time.sleep(0.01) wait_time = time.perf_counter() - start_time else: raise Exception('Boot timeout : {}s'.format(wait_time))
def is_on(self): """ Return whether device is turned on or not. Example: >>> dut.on() >>> dut.is_on() True >>> dut.off() >>> dut.is_on() False :returns boolean: true if device is turned on, false otherwise. """ pattern = '.*{}'.format(self.get_id()) outs = check_output('sdb devices'.split(), timeout=10) if find_pattern(pattern, outs): return True else: return False
def find_smartpower_names(): """docstring for find_smartpowers""" p = '.*Microchip Technology.*' try: smartpower_names = ['/dev/{}'.format(s) for s in check_output('ls /dev ' '| grep hidraw', shell=True).split() if find_pattern(p, check_output(['cat', '/sys/' 'class/' 'hidraw/' '{}/' 'device/' 'uevent' .format(s) ]))] except AttributeError: smartpower_names = [] logging.debug('smart powers : {0}'.format(smartpower_names)) return smartpower_names
def _screenshot_wayland(self, filename): """docstring for _screenshot_wayland""" # Find all viewable window id p_winid = '.*(0x[a-zA-Z0-9]{8})\s+\d+\s+\d+\s+\d+' \ '\s+\d+\s+(\d+)\s+(\d+).*[0]{1}\s+\d+\s+[NV]{1}.*' winids = find_all_pattern( p_winid, self.run_cmd('enlightenment_info -topvwins', timeout=20)) if winids: # Dump windows outs = self.run_cmd('cd /tmp; enlightenment_info -dump_topvwins', timeout=20) dirn = find_pattern('directory:\s(.*)', outs, groupindex=1).rstrip() # Create tempdir and pull dump files tmpdir = tempfile.mkdtemp() self.pull_file(dirn, tmpdir, timeout=20) # If dump does not exist then remove winid from list winids = [ winid for winid in winids if os.path.exists(os.path.join(tmpdir, winid[0] + '_0.png')) ] # Base image bg = Image.new('RGB', (self._screen_width, self._screen_height)) # Merge images for winid in reversed(winids): try: fg = Image.open(os.path.join(tmpdir, winid[0] + '_0.png')) bg.paste(fg, (int(winid[1]), int(winid[2])), fg) except FileNotFoundError: pass # Save merged image bg.save(filename) # Remove tempdir call(['rm', '-rf', tmpdir], timeout=10)
def _login_uart_shell(self): """docstring for _login_uart_shell""" logging.debug('===============Login UART shell===============') retrycnt = 0 while retrycnt < self._max_attempt_login_uart_shell: if self._username: self._write_uart(self._username) time.sleep(0.5) if self._password: self._write_uart(self._password) time.sleep(1.5) self._flush_uart_buffer() self._write_uart(b'dmesg -n 1') time.sleep(0.5) readdata = self._read_uart(2000) if find_pattern(self._pattern_shellprompt, readdata): return else: logging.debug('Login failed. retry.') self._write_uart(b'') time.sleep(2) retrycnt += 1 else: raise Exception('Can\'t login uart shell.')
def tizen_snapshot_downloader(url, pattern_bin='tar.gz$', username='', password='', pattern_version='tizen[a-zA-Z0-9-_.^/]' '*[0-9]{8}.[0-9]{1,2}', version=None, timeout=10, maxretry=20, waiting_for_retry=10): """ Download snapshot images from web server. :param str url: url for downloading binaries. This has to include \ 'latest' string :param str pattern_bin: filename pattern to find correct binary \ under the url :param str username: username to access http server :param str password: password to access http server :param str pattern_version: pattern of tizen snapshot version string :param str version: specific version string of tizen snapshot \ what you want to download :param float timeout: timeout :param int maxretry: max retry count to attempt the url for downloading :param float waiting_for_retry: delay for each retry Example: >>> from litmus.helper.helper import tizen_snapshot_downloader >>> tizen_snapshot_downloader( url='http://download.tizen.org/snapshots/tizen/tv/latest/images/arm-wayland/tv-wayland-armv7l-odroidu3/') [\'tizen-tv_20160516.2_tv-wayland-armv7l-odroidu3.tar.gz\'] :returns list: filenames of downloaded binaries """ logging.debug('============Download binaries from server===========') # convert latest url to actual url url_to_find_latest_version_number = url.split('latest')[0] for loop in range(maxretry): try: f = requests.get(url_to_find_latest_version_number, auth=(username, password), timeout=timeout) if f.status_code == 200: break time.sleep(waiting_for_retry) except requests.exceptions.Timeout as e: logging.debug(e) continue except requests.exceptions.ConnectionError as e: logging.debug(e) continue except Exception as e: logging.debug(e) raise Exception('Can\'t open url {0}'.format(url)) else: raise Exception('Can\'t open url {0}'.format(url)) latest_version = find_all_pattern(pattern_version, f.text)[-1] url = url.replace('latest', latest_version) if version: pattern_version_number = '[0-9]{8}.[0-9]{1,2}' found = find_pattern(pattern_version_number, url) url = url.replace(found, version) # get data from actual url and download binaries for loop in range(maxretry): try: f = requests.get(url, auth=(username, password), timeout=timeout) if f.status_code != 200: continue soup = BeautifulSoup(f.text, 'html.parser') filenames = [] for l in soup.findAll('a', attrs={'href': re.compile(pattern_bin)}): filename = l['href'] fileurl = urllib.parse.urljoin(url, filename) logging.debug(fileurl) with open(filename, 'wb') as f: logging.debug('Downloading {}'.format(filename)) resp = requests.get(fileurl, auth=(username, password), stream=True) total_length = resp.headers.get('Content-Length') cs = 1024 * 1024 if total_length is None: f.write(resp.content) else: downloaded_data = 0 total_length = int(total_length) for download_data in resp.iter_content(chunk_size=cs): downloaded_data += len(download_data) f.write(download_data) done = int(50 * downloaded_data / total_length) sys.stdout.write('\r[{0}{1}]'.format('#'*done, ' '*(50-done) )) sys.stdout.flush() logging.debug('') filenames.append(filename) if filenames: break else: logging.debug('There\'s no binary for downloading. Retry.') time.sleep(waiting_for_retry) except requests.exceptions.Timeout as e: logging.debug(e) continue except requests.exceptions.ConnectionError as e: logging.debug(e) continue except Exception as e: logging.debug(e) raise Exception('Can\'t open url {0}'.format(url)) else: raise Exception('Can\'t open url {0}'.format(url)) return filenames