def detect_port(self, port, timeout=2000, logmsg="logmsg"): """ Detect the serial port Examples: detect_port("/dev/acis/DUT1/AT") Args: port : the serial port you want to detect. Kwargs: timeout : detect port timeout logmsg: logmsg, peer with log message.\n debug, peer with log and debug message.\n nologmsg, peer without any message. \n Returns: none. """ start_time = datetime.now() flag_linebreak = 0 while 1: try: s = serial.Serial(port, baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, writeTimeout=None, dsrdtr=False) if logmsg == "logmsg": if flag_linebreak: peer("") peer(port + " - port found") # display time spent in receive diff_time = datetime.now() - start_time diff_time_ms = diff_time.seconds * 1000 + diff_time.microseconds / 1000 if logmsg == "logmsg": peer(" <" + str(timeout) + " @" + str(diff_time_ms) + "ms") s.close() break except serial.SerialException: pass time.sleep(1) sys.stdout.write("*") flag_linebreak = 1 # Count timeout diff_time = datetime.now() - start_time diff_time_ms = diff_time.seconds * 1000 + diff_time.microseconds / 1000 if diff_time_ms > timeout: if logmsg == "logmsg": if flag_linebreak: peer("") peer(port + " - port not found" + " <" + str(timeout) + " ms") break
def __init__(self, conf): """ _AT constructor function, init and open serial port Args: conf : The com serial config Returns: none """ self.conf = conf self.port_link = conf["dev_link"] self.reset_mark = False # AT Send receive time stamp self.SndRcvTimestamp = False self.RcvTimespent = False #Variable for status self.statOfItem = 'OK' # Variable for log self.numOfSuccessfulResponse = 0.0 #list of opened COM ports self.uartbuffer = {} self.open(port=self.port_link) peer(self)
def register_port(self, port_names): """ Register the port. Examples: register_port('AT..DUT1') Args: port_names: the port name you want to register. Returns: none. """ self.mPort = Port() port_names = self.order_port_list(port_names) for backend_cookie in port_names: peer("\n\n Loop is <{}>".format(backend_cookie)) backend = self.mPort.match(backend_cookie) if backend.name == 'AT': self.at = backend elif backend.name == "ADB": self.adb = backend else: pass
def send_cmd(self, cmd, printmode="symbol"): """ Sends an AT command to a serial port. Examples: send_cmd("ATE0\r") Args: cmd: the AT command you want to send. Kwargs: printmode: the log print mode(symbol, hexstring, raw) Returns: none. """ if not self.hCom.is_open: self.hCom.open() self.hCom.write(cmd.encode('utf-8')) if re.search('AT!RESET', cmd): #self.hCom.close() self.reset_mark = True time.sleep(0.1) timestamp = "" if self.SndRcvTimestamp: timestamp = self.timeDisplay() + " " LogMsg = timestamp + "Snd COM " + self.hCom.port + " [" + self.ascii2print( cmd, printmode) + "]" peer(LogMsg)
def __init__(self): """ the ACISMiscer class constructor function, init necessary conditions Args: none Returns: none """ self.limit_name = 'testcases' # Maybe get this var from environment better. try: self.prefix = os.environ["REPORT_PATH"] + '/' \ + os.environ["PLATFORM"] + '/' \ + os.environ["ACIS_DIFF"] except KeyError as e: peer( "Can't get vaild environments from master. \nStack info: \n<{}>.\nSo switch to default branch." .format(e)) if not os.path.exists('/tmp/acis/testlog/' + self.limit_name): os.makedirs('/tmp/acis/testlog/' + self.limit_name, mode=0o744) self.prefix = '/tmp/acis/testlog' self.at = None self.adb = None self.envs = {}
def __narrow_config(self): """ the method purpose to drop self.configs items that without in devices. Args: none Returns: none """ try: output = subprocess.check_output('adb devices', shell = True).decode('utf-8').strip() except subprocess.CalledProcessError as err: raise err else: # devices = [ 'serial_id_1', 'serial_id_2', ...] devices = [] for line in output.split('\n'): g = re.match('\s*?(.*)\s*device$', line) if g: devices.append(g.group(1).strip()) pop = [] for i in self.configs: if self.configs[i]['serial'] not in devices: pop.append(i) for item in pop: peer("Narrowing - Drop item: {}".format(self.configs.pop(item))) peer("Final <configs> : {}".format(self.configs))
def match(self, aka_name): """ The method to match the port object. Examples: match("AT..DUT1") Args: aka_name: The port object you want to match Returns: return the matched port object(adb/AT). """ backend_name, type_name = self.name_split(aka_name) backend_name = backend_name.upper() if type_name != 'any': type_name = type_name.upper() conf = self.parser.get_conf(backend_name, type_name) peer(conf) if backend_name == "AT": self.at = self.factory.which_backend(backend_name, type_name, conf) return self.at elif backend_name == "ADB": self.adb = self.factory.which_backend(backend_name, type_name, conf) return self.adb
def _pick_info(self,_file): """ The method to Pick some information from udev file 'self.configs' content: eg.\n { "DUT1" : { "serial" : xxx, "link" : xxx, << acis/DUT1 "AT" : xxx, << acis/DUT1/AT "DM" : xxx},<< acis/DUT1/DM "DUT2" : { "serial" : xxx, "link" : xxx, << acis/DUT2 "AT" : xxx, << acis/DUT2/AT "DM" : xxx},<< acis/DUT2/DM } Examples: _pick_info('/etc/udev/rules.d/11-acis.rules') Args: _file: the udev file you want to pick information Returns: none. """ if not os.path.exists(_file): raise AcisRuleFileNotExist() with open(_file, mode = 'r') as f: for line in f: g = re.match(r'\s*ATTRS{serial}=="(.*)",\s*GOTO="(.*)\s*"', line) if g: if g.group(2) == "acis_DUT1": self.configs["DUT1"] = {"serial" : g.group(1) } elif g.group(2) == "acis_DUT2": self.configs["DUT2"] = {"serial" : g.group(1) } g = re.match(r"\s*SUBSYSTEMS==\"usb\",\s*DRIVERS==\"GobiSerial\",\s*SYMLINK\+=\"(acis/(.*))/(.*)\",\s*ATTRS{bInterfaceNumber}==\"(.*)\"\s*", line) if g: if g.group(2) == "DUT1": self.configs["DUT1"]["link"] = g.group(1) if g.group(4) == "03": self.configs["DUT1"]["AT"] = g.group(1) + '/' + g.group(3) if g.group(4) == "00": self.configs["DUT1"]["DM"] = g.group(1) + '/' + g.group(3) elif g.group(2) == "DUT2" : self.configs["DUT2"]["link"] = g.group(1) if g.group(4) == "03": self.configs["DUT2"]["AT"] = g.group(1) + '/' + g.group(3) if g.group(4) == "00": self.configs["DUT2"]["DM"] = g.group(1) + '/' + g.group(3) peer("<Rules> configs: {}".format(self.configs)) self.__narrow_config()
def __init__(self, serial_id): """ _ADB constructor function, init adb port,get serial_id Args: serial_id: the DUT serial_id. Returns: none """ self.serial_id = serial_id peer(self)
def get_ini_value(file_path, sections, name): """ It be used to parse the fields in the INI file. Examples: get_ini_value( sim_ini + '/ATT_9331.ini', 'Identification', 'VoiceNumber') Args: file_path: the file path. sections: the file sections name: the name you want to get the config Returns: return the string value. """ if os.path.isfile(file_path): peer("\nRead %s:%s from %s\n" % (sections, name, file_path)) Parser = configparser.RawConfigParser() found = Parser.read(file_path) if not Parser.has_section(sections): peer("\nNo Section %s in %s !!!" % (str(sections), file_path)) if not Parser.has_option(sections, name): peer("\nNo Name %s udner %s in %s !!!" % (name, str(sections), file_path)) Parser = configparser.ConfigParser() found = Parser.read(file_path) value = Parser.get(sections, name) return value.strip("\"'") else: peer("\%s NOT exits !!!\n" % file_path) return ''
def register_mail(self, mail_to): """ Register mail(It's not used now) Examples: register_mail("*****@*****.**") Args: mail_to: mail address Returns: none. """ peer("[Mail] From: {}".format(mail_to))
def sleep(self, millisecond, silent=False): """ Call the time module and execute sleep function. Examples: sleep(1000) Args: millisecond : sleep time(ms). Kwargs: silent: It's a bool flag to control whether to print sleep time log or not Returns: none """ try: if not (silent): peer("SLEEP: Start sleep for %d milliseconds" % millisecond) time.sleep(millisecond / 1000.0) if not (silent): peer("SLEEP: End sleep") except SystemExit: raise SystemExit except Exception as e: peer(e)
def deal_log_path(self, case_file): """ Deal and provide the log path, the testcase log will saved in the path. Examples: deal_log_path('/home/jenkins/tmp/loop_test/testcases/Driver/LowSpeedBus/ACIS_A_D_LSBUS_SPI_TEST.py') Args: case_file: the case path, it will be made for the log. Returns: the log path("/tmp/acis/testlog/testcases/Driver/LowSpeedBus/*"). """ dname, fname = os.path.split(case_file) dname = dname.split(self.limit_name + '/')[1] mprefix = self.prefix + '/' + self.limit_name + '/' + dname + '/' self.which_log = mprefix + fname.replace('.py', '.log') self.case_output = mprefix + fname.replace('.py', '') if not os.path.exists(self.case_output): os.makedirs(self.case_output, mode=0o755) peer("Case Log Location: {}".format(self.which_log)) return self.which_log
def clean_buffer(self): """ The method clears the input buffer of serial port instance Examples: clean_buffer() Args: none Returns: none. """ try: self.hCom.flushInput() except SystemExit: raise SystemExit except Exception as e: self.hCom.close() peer("CLEAR_BUFFER: Error!") peer(e)
def close(self): """ The method will close and release the occupation of the port. Examples: close() Args: none Returns: none """ try: self.hCom.close() peer("CLOSE: Close the " + self.hCom.port) except Exception as e: peer(e) peer("CLOSE: Error for " + self.hCom.port)
def open(self, port=None, baudrate=115200, bytesize=8, parity='N', stopbits=1, rtscts=False, OpenPortTimeout=2000, timeout=1, dsrdtr=False, xonxoff=False, interCharTimeout=None, write_timeout=None): """ Open AT port, maybe you shouldn't use it, because the initialization of the port is already ready before running the case. Examples: open("/dev/acis/DUT1/AT") Kwargs: port : the AT serial port baudrate : the baudrate of the port bytesize : the bytesize of the port parity : the parity of the port stopbits : the stopbits of the port rtscts : I/o for request/clear to send signal OpenPortTimeout: detect port timeout timeout: Read timeout dsrdtr: I/O for Data ready signal xonxoff: software flow control interCharTimeout: Character interval timeout write_timeout: write timeout Returns: return serial port instance. """ # validate parameter - rtscts flowcontrol = "Hardware" if type(rtscts) == type("string"): if rtscts not in ["Hardware", "None"]: peer("Invalid parameter for AcisOpen() - rtscts") peer("Option:") peer("\"Hardware\"" + "\"None\"") peer("") rtscts = 1 flowcontrol = "Hardware" if rtscts == "Hardware": rtscts = 1 flowcontrol = "Hardware" if rtscts == "None": rtscts = 0 flowcontrol = "None" self.detect_port(port, OpenPortTimeout, "nologmsg") try: hCom = None hCom = serial.Serial(port, baudrate, bytesize, parity, stopbits, timeout, xonxoff, rtscts, write_timeout, dsrdtr, interCharTimeout) peer("{} OPEN: Open the ".format(hCom) + hCom.port + " @" + str(baudrate) + " " + str(bytesize) + str(parity) + str(stopbits) + " " + str(flowcontrol)) time.sleep(1) self.uartbuffer[hCom.port] = "" self.hCom = hCom _AT.objs[self.conf["serial_id"]] = self.hCom return hCom except serial.SerialException as val: peer(val) if ("%s" % val).startswith("could not open port "): peer("ERROR Could not open COM%d !" % (port)) peer("hCom" + str(hCom)) else: peer("ERROR : %s" % val) except AttributeError: peer("OPEN: Busy for " + hCom.port + "!")
def waitn_match_resp(self, waitpattern, timeout, condition="wildcard", update_result="critical", log_msg="logmsg", printmode="symbol"): """ Parses the contents of the serial buffer and provide some specified filtering conditions. Examples: waitn_match_resp(["*\r\nOK\r\n"], 4000) Args: waitpattern: the matching pattern for the received data timeout: timeout value in second Kwargs: update_result: critical, update result to global variable statOfItem \n not_critical, do nothing for the result \n condition: matching condition log_msg: logmsg, peer with log message.\n debug, peer with log and debug message.\n nologmsg, peer without any message. \n printmode: the log print mode(symbol, hexstring, raw) Returns: match result. """ #myColor = colorLsit[8] # validate parameter - condition if condition not in ["wildcard"]: peer("Invalid parameter for AcisWaitnMatchResp() - condition") peer("Option:") peer("\"wildcard\"") peer("") peer( "AcisWaitnMatchResp() only support \"wildcard\" in \"condition\"" ) peer("") condition = "wildcard" AcisWaitResp_response = self.wait_resp(waitpattern, timeout, log_msg, printmode) match_result = self.match_resp(AcisWaitResp_response, waitpattern, condition, update_result, log_msg, printmode) if self.reset_mark: self.hCom.close() self.reset_mark = False return match_result
def match_resp(self, resp, keywords, condition="wildcard", update_result="critical", log_msg="logmsg", printmode="symbol"): """ The method compares the received command response to the expected command response and display the comparison result,maybe you should use waitn_match_resp instead of this. Args: resp : Response object or a string keywords: expected response Kwargs: condition : matching condition update_result: critical, update result to global variable statOfItem \n not_critical, do nothing for the result\n log_msg: logmsg, peer with log message\n debug, peer with log and debug message\n nologmsg, peer without any message\n printmode: the log print mode(symbol, hexstring, raw) Returns: Boolean >> True:response matched, False:repsonse mis-matched" """ #myColor = colorLsit[8] if not self.hCom.is_open: self.hCom.open() # If resp is Response() >> assign .tabData to resp if type(resp) != type("string"): #peer "This is not a string" resp = resp.tabData # If keywords is None >> assign empty string if keywords == None: keywords = [""] # validate parameter - condition if condition not in [ "wildcard", "match_all_order", "match_all_disorder", "contain_all_order", "contain_all_disorder", "contain_anyone", "not_contain_anyone" ]: peer("Invalid parameter for AcisMatchResp() - condition") peer("Option:") peer("\"wildcard\"" + "\"match_all_order\"" + "\"match_all_disorder\"" + "\"contain_all_order\"" + "\"contain_all_disorder\"" + "\"contain_anyone\"" + "\"not_contain_anyone\"") peer("") condition = "wildcard" # validate parameter - update_result if update_result not in ["critical", "not_critical"]: peer("Invalid parameter for AcisMatchResp() - update_result") peer("Option:") peer("\"critical\"" + "\"not_critical\"") peer("") update_result = "critical" # validate parameter - log_msg if log_msg not in ["logmsg", "nologmsg", "debug"]: peer("Invalid parameter for AcisMatchResp() - log_msg") peer("Option:") peer("\"logmsg\"" + "\"nologmsg\"" + "\"debug\"") peer("") log_msg = "logmsg" # 1 # Default - matching with wildcard character if condition == "wildcard": flag_matchstring = False matched = False for (each_elem) in keywords: receivedResp = resp expectedResp = each_elem if fnmatch.fnmatchcase(receivedResp, expectedResp): flag_matchstring = True matched = True break if matched == 0: if log_msg == "logmsg" or log_msg == "debug": if len(keywords) == 1: peer("") peer("Expected Response: %s" % self.ascii2print(expectedResp, printmode).replace( "<CR>", "\\r").replace("<LF>", "\\n")) peer("Received Response: %s" % self.ascii2print(receivedResp, printmode).replace( "<CR>", "\\r").replace("<LF>", "\\n")) peer("") if len(keywords) > 1: peer("") peer("Expected Response: %s" % self.ascii2print(keywords[0], printmode).replace( "<CR>", "\\r").replace("<LF>", "\\n")) for (i, each_elem) in enumerate(keywords): if i == 0: pass if i > 0: SafePrintLog("Expected Response: %s" % self.ascii2print( each_elem, printmode).replace( "<CR>", "\\r").replace( "<LF>", "\\n")) SafePrintLog( "Received Response: %s" % self.ascii2print(receivedResp, printmode).replace( "<CR>", "\\r").replace("<LF>", "\\n")) SafePrintLog("") # 2 if condition == "match_all_order": if log_msg == "debug": peer( "Check if response match all keywords in order: ( match without extra char. )" ) receivedResp = resp expectedResp = "" for (i, each_keyword) in enumerate(keywords): expectedResp += keywords[i] matched = fnmatch.fnmatchcase(receivedResp, expectedResp) if matched == 0: if log_msg == "logmsg" or log_msg == "debug": peer("") peer("No Match!! (match_all_order)") peer("") peer("Expected Response: %s" % self.ascii2print(expectedResp, printmode).replace( "<CR>", "\\r").replace("<LF>", "\\n")) peer("Received Response: %s" % self.ascii2print(receivedResp, printmode).replace( "<CR>", "\\r").replace("<LF>", "\\n")) peer("") # 3 if condition == "match_all_disorder": debug_msg = "" debug_msg += "Check if response contains all keywords ( without extra character, dis-order ): \n" # differcuit to code , code later itemlist = keywords #itemlist = ["A","B","C"] permutation_list = list( itertools.permutations(itemlist, len(itemlist))) permutation_concat_list = [] for each_elem in permutation_list: tempstring = "" for eachchar in each_elem: tempstring += eachchar permutation_concat_list.append(tempstring) debug_msg += "\nConbination of keywords: \n" for (i, each_conbination) in enumerate(permutation_concat_list): # peer i+1, ascii2print(each_conbination,printmode).replace("<CR>","\\r").replace("<LF>","\\n") receivedResp = resp expectedResp = each_conbination matched = fnmatch.fnmatchcase(receivedResp, expectedResp) # debug message if matched == 0: debug_msg += str(i + 1) + " " + self.ascii2print( each_conbination, printmode).replace("<CR>", "\\r").replace( "<LF>", "\\n") + " <-- no match\n" else: debug_msg += str(i + 1) + " " + self.ascii2print( each_conbination, printmode).replace("<CR>", "\\r").replace( "<LF>", "\\n") + " <-- matched\n" # break in normal mode when result matched # normal mode >> matched result and break, debug mode >> list all conbination and result if matched == 1: if log_msg != "debug": break # display "No Match" when matching failed if matched == 1: if log_msg == "debug": peer(debug_msg) else: if log_msg == "logmsg" or log_msg == "debug": peer("") peer("No Match!! (match_all_disorder)") peer("") peer(debug_msg) # 4 if condition == "contain_all_order": debug_msg = "" debug_msg += "Check if response contains all keywords in order:" receivedResp = resp expectedResp = "*" for (i, each_keyword) in enumerate(keywords): if i == 0: expectedResp += keywords[i] else: expectedResp += "*" + keywords[i] expectedResp += "*" matched = fnmatch.fnmatchcase(receivedResp, expectedResp) if matched == 1: if log_msg == "debug": peer("") peer(debug_msg) peer("Expected Response: %s" % self.ascii2print(expectedResp, printmode).replace( "<CR>", "\\r").replace("<LF>", "\\n")) peer("") else: if log_msg == "logmsg" or log_msg == "debug": peer("") peer("No Match!! (contain_all_order)") peer("") peer("Expected Response: %s" % self.ascii2print(expectedResp, printmode).replace( "<CR>", "\\r").replace("<LF>", "\\n")) peer("Received Response: %s" % self.ascii2print(receivedResp, printmode).replace( "<CR>", "\\r").replace("<LF>", "\\n")) peer("") # 5 if condition == "contain_all_disorder": debug_msg = "" debug_msg += "\nCheck if response contains all keywords without order:\n\n" #for (i,each_keyword) in enumerate(keywords) : # peer ascii2print(keywords[i],printmode).replace("<CR>","\\r").replace("<LF>","\\n") receivedResp = resp expectedResp = "" debug_msg += "Response: " + self.ascii2print( receivedResp, printmode).replace("<CR>", "\\r").replace( "<LF>", "\\n") + "\n" debug_msg += "Keywords:\n" flag_notfound = 0 matched = 1 for (i, each_keyword) in enumerate(keywords): if resp.find(keywords[i]) >= 0: debug_msg += self.ascii2print( keywords[i], printmode).replace("<CR>", "\\r").replace( "<LF>", "\\n") + " <-- found\n" else: debug_msg += self.ascii2print( keywords[i], printmode).replace("<CR>", "\\r").replace( "<LF>", "\\n") + " <-- not found\n" flag_notfound = 1 if flag_notfound == 0: matched = 1 if log_msg == "debug": peer(debug_msg) if flag_notfound == 1: matched = 0 if log_msg == "logmsg" or log_msg == "debug": peer("") peer("No Match!! (contain_all_disorder)") peer("") peer(debug_msg) # 6 if condition == "contain_anyone": debug_msg = "" debug_msg += "\nCheck if response contains anyone of keywords: \n\n" #for (i,each_keyword) in enumerate(keywords) : # peer ascii2print(keywords[i],printmode).replace("<CR>","\\r").replace("<LF>","\\n") receivedResp = resp expectedResp = "" debug_msg += "Response: " + self.ascii2print( receivedResp, printmode).replace("<CR>", "\\r").replace( "<LF>", "\\n") + "\n" debug_msg += "Keywords:\n" flag_found = 0 matched = 0 for (i, each_keyword) in enumerate(keywords): if resp.find(keywords[i]) >= 0: debug_msg += self.ascii2print( keywords[i], printmode).replace("<CR>", "\\r").replace( "<LF>", "\\n") + " <-- found\n" flag_found = 1 else: debug_msg += self.ascii2print( keywords[i], printmode).replace("<CR>", "\\r").replace( "<LF>", "\\n") + " <-- not found\n" if flag_found == 1: matched = 1 if log_msg == "debug": peer(debug_msg) if flag_found == 0: matched = 0 if log_msg == "logmsg" or log_msg == "debug": peer("") peer("No Match!! (contain_anyone)") peer("") peer(debug_msg) # 7 if condition == "not_contain_anyone": debug_msg = "" debug_msg += "\nCheck that response do not contains anyone of keywords: \n\n" #for (i,each_keyword) in enumerate(keywords) : # peer ascii2print(keywords[i],printmode).replace("<CR>","\\r").replace("<LF>","\\n") receivedResp = resp expectedResp = "" debug_msg += "Response: " + self.ascii2print( receivedResp, printmode).replace("<CR>", "\\r").replace( "<LF>", "\\n") + "\n" debug_msg += "Keywords:\n" flag_found = 0 matched = 1 for (i, each_keyword) in enumerate(keywords): if resp.find(keywords[i]) >= 0: debug_msg += self.ascii2print( keywords[i], printmode).replace("<CR>", "\\r").replace( "<LF>", "\\n") + " <-- found\n" flag_found = 1 else: debug_msg += self.ascii2print( keywords[i], printmode) + " <-- not found\n" if flag_found == 0: matched = 1 if log_msg == "debug": peer(debug_msg) if flag_found == 1: matched = 0 if log_msg == "logmsg" or log_msg == "debug": peer("") peer("No Match!! (not_contain_anyone)") peer("") peer(debug_msg) # udpate result to statOfItem if update_result == "critical": if matched == 0: self.statOfItem = 'NOK' raise Exception( "<Critical> Exception: reason is NOT match Response.") else: self.numOfSuccessfulResponse += 1.0 pass else: if log_msg == "logmsg": peer("\nNot Critical command\n") return matched
def get_conf(self, backend_name, type_name): """ The method to get the port object config. Examples: get_conf("AT", "DUT1") Args: backend_name: The port name(AT/adb). type_name: The DUT name(DUT1/DUT2/any) Returns: return the port object config. Examples: 'type_name' : >> 'DUT1' or 'DUT2' or 'any' \n 'mapto' : >> only 'any' has this prop. \n 'backend' : >> 'AT' or 'ADB' \n 'dev_link' : >> eg: AT > /dev/acis/DUT1/AT \n 'serial_id' : >> adb serial id. """ if type_name == "DUT1": if "DUT1" not in self.configs: raise NotFindTypeNameInRule("Can NOT find type name <{}> in udev-rules file.".format(type_name)) if backend_name == "AT": if not subprocess.call("lsof {where}".format(where = '/dev/' + self.configs[type_name][backend_name]), shell=True): raise ATportBusyErr("AT port is using.") if subprocess.call('ls {where}'.format(where = '/dev/' + self.configs[type_name][backend_name]), shell=True): raise ATdevLinkNotExist("Can NOT find dev-link [{}] for test.".format('/dev/'+self.configs[type_name][backend_name])) return { 'type_name' : type_name, 'mapto' : type_name, 'backend' : backend_name, 'dev_link' : '/dev/' + self.configs[type_name][backend_name], 'serial_id' : self.configs[type_name]["serial"]} elif backend_name == "DM": raise UnsupportBackendErr("NOT support backend <{backend}>.".format(backend = backend_name)) elif backend_name == "ADB": return { 'type_name' : type_name, 'mapto' : type_name, 'backend' : backend_name, 'serial_id' : self.configs[type_name]["serial"]} elif type_name == "DUT2": if "DUT2" not in self.configs: raise NotFindTypeNameInRule("Can NOT find type name <{}> in udev-rules file.".format(type_name)) if backend_name == "AT": if not subprocess.call("lsof {where}".format(where = '/dev/' + self.configs[type_name][backend_name]), shell=True): raise ATportBusyErr("AT port is using.") if subprocess.call('ls {where}'.format(where = '/dev/' + self.configs[type_name][backend_name]), shell=True): raise ATdevLinkNotExist("Can NOT find dev-link [{}] for test.".format('/dev/'+self.configs[type_name][backend_name])) return { 'type_name' : type_name, 'mapto' : type_name, 'backend' : backend_name, 'dev_link' : '/dev/' + self.configs[type_name][backend_name], 'serial_id' : self.configs[type_name]["serial"]} elif backend_name == "DM": raise UnsupportBackendErr("NOT support backend <{backend}>.".format(backend = backend_name)) elif backend_name == "ADB": return { 'type_name' : type_name, 'mapto' : type_name, 'backend' : backend_name, 'serial_id' : self.configs[type_name]["serial"]} elif type_name == "any": if not self.configs: raise NotFindTypeNameInRule("Can NOT find any type names <DUT2 or DUT1> in udev-rules file.") if len(self.configs) == 2: if backend_name == "AT": sel = choice(["DUT1", "DUT2"]) peer("First get type is {name}".format(name = sel)) if not subprocess.call("lsof {where}".format(where = '/dev/' + self.configs[sel][backend_name]), shell=True): peer("Port Busy! Try another...") for another in ["DUT1", "DUT2"]: if sel != another: if not subprocess.call("lsof {where}".format(where = '/dev/' + self.configs[another][backend_name]), shell=True): raise ATportBusyErr("Double AT ports had been using.") else: if subprocess.call('ls {where}'.format(where = '/dev/' + self.configs[sel][backend_name]), shell=True): raise ATdevLinkNotExist("Can NOT find dev-link [{}] for test.".format('/dev/'+self.configs[sel][backend_name])) self.any_conf[type_name] = another return { 'type_name' : type_name, 'mapto' : self.any_conf[type_name], 'backend' : backend_name, 'dev_link' : '/dev/' + self.configs[self.any_conf[type_name]][backend_name], 'serial_id' : self.configs[self.any_conf[type_name]]["serial"]} else: if subprocess.call('ls {where}'.format(where = '/dev/' + self.configs[sel][backend_name]), shell=True): raise ATdevLinkNotExist("Can NOT find dev-link [{}] for test.".format('/dev/'+self.configs[sel][backend_name])) self.any_conf[type_name] = sel return {'type_name' : type_name, 'mapto' : self.any_conf[type_name], 'backend' : backend_name, 'dev_link' : '/dev/' + self.configs[self.any_conf[type_name]][backend_name], 'serial_id' : self.configs[self.any_conf[type_name]]["serial"]} elif backend_name == "DM": raise UnsupportBackendErr("NOT support backend <{backend}>.".format(backend = backend_name)) elif backend_name == "ADB": return {'type_name' : type_name, 'mapto' : self.any_conf[type_name], 'backend' : backend_name, 'serial_id' : self.configs[self.any_conf[type_name]]["serial"]} elif len(self.configs) == 1: if 'DUT1' in self.configs: if backend_name == "AT": sel = 'DUT1' if not subprocess.call("lsof {where}".format(where = '/dev/' + self.configs[sel][backend_name]), shell=True): raise ATportBusyErr("Only one module register to udev-rules: <{name}>, but this port is using.".format(name = sel)) else: if subprocess.call('ls {where}'.format(where = '/dev/' + self.configs[sel][backend_name]), shell=True): raise ATdevLinkNotExist("Can NOT find dev-link [{}] for test.".format('/dev/'+self.configs[sel][backend_name])) self.any_conf[type_name] = sel return { 'type_name' : type_name, 'mapto' : self.any_conf[type_name], 'backend' : backend_name, 'dev_link' : '/dev/' + self.configs[self.any_conf[type_name]][backend_name], 'serial_id' : self.configs[self.any_conf[type_name]]["serial"]} elif backend_name == "DM": raise UnsupportBackendErr("NOT support backend <{backend}>.".format(backend = backend_name)) elif backend_name == "ADB": return {'type_name' : type_name, 'mapto' : self.any_conf[type_name], 'backend' : backend_name, 'serial_id' : self.configs[self.any_conf[type_name]]["serial"]} elif 'DUT2' in self.configs: if backend_name == "AT": sel = 'DUT2' if not subprocess.call("lsof {where}".format(where = '/dev/' + self.configs[sel][backend_name]), shell=True): raise ATportBusyErr("Only one module register to udev-rules: <{name}>, but this port is using.".format(name = sel)) else: if subprocess.call('ls {where}'.format(where = '/dev/' + self.configs[sel][backend_name]), shell=True): raise ATdevLinkNotExist("Can NOT find dev-link [{}] for test.".format('/dev/'+self.configs[sel][backend_name])) self.any_conf[type_name] = sel return { 'type_name' : type_name, 'mapto' : self.any_conf[type_name], 'backend' : backend_name, 'dev_link' : '/dev/' + self.configs[self.any_conf[type_name]][backend_name], 'serial_id' : self.configs[self.any_conf[type_name]]["serial"]} elif backend_name == "DM": raise UnsupportBackendErr("NOT support backend <{backend}>.".format(backend = backend_name)) elif backend_name == "ADB": return {'type_name' : type_name, 'mapto' : self.any_conf[type_name], 'backend' : backend_name, 'serial_id' : self.configs[self.any_conf[type_name]]["serial"]} else: raise UnsupportTypeErr("This type that your input [{}] is NOT support now.".format(type_name))
def info(self): peer("My name is : {name}\n- conf:\n{conf}".format(name = ADB.name, conf = self.conf))
def wait_resp(self, waitpattern, timeout=60000, log_msg="logmsg", printmode="symbol"): """ The method waits for the data received from serial port. Examples: wait_resp(["*\r\nOK\r\n"], 4000) Args: waitpattern : the matching pattern for the received data. Kwargs: timeout : timeout between each received packet log_msg : option for log message printmode: the log print mode(symbol, hexstring, raw) Returns: Received data (String). """ if not self.hCom.is_open: self.hCom.open() start_time = datetime.now() com_port_name = self.hCom.port if log_msg == "debug": peer(start_time) flag_matchrsp = False flag_matchstring = False flag_timeout = False flag_wait_until_timeout = False flag_printline = False LogMsg = "" timestamp = "" # wait until timeout mode if waitpattern == None or waitpattern[0] == "": flag_wait_until_timeout = True waitpattern = [""] peer("") peer("Wait responses in %s ms" % str(timeout)) peer("") displaybuffer = "" displaypointer = 0 while 1: # Read data from UART Buffer if int(self.hCom.in_waiting) > 0: self.uartbuffer[self.hCom.port] += self.hCom.read( self.hCom.in_waiting).decode('utf-8', 'ignore') if log_msg == "debug": #myColor = colorLsit[7] #peer "Read data from UART buffer:", self.uartbuffer[self.hCom.port].replace("\r","<CR>").replace("\n","<LF>") #peer "Read data from UART buffer:", self.ascii2print(self.uartbuffer[self.hCom.port],printmode) LogMsg = "Read data from UART buffer: " + self.ascii2print( self.uartbuffer[self.hCom.port], printmode) peer(LogMsg) # Match response # Loop for each character for (i, each_char) in enumerate(self.uartbuffer[self.hCom.port]): if log_msg == "debug": #myColor = colorLsit[7] #peer i, self.uartbuffer[self.hCom.port][:i+1].replace("\r","<CR>").replace("\n","<LF>").replace("\n","<LF>") #peer i, ascii2print(self.uartbuffer[self.hCom.port][:i+1],printmode) LogMsg = str(i) + " " + self.ascii2print( self.uartbuffer[self.hCom.port][:i + 1], printmode) peer(LogMsg) # display if matched with a line syntax displaybuffer = self.uartbuffer[ self.hCom.port][displaypointer:i + 1] line_syntax1 = "*\r\n*\r\n" line_syntax2 = "+*\r\n" line_syntax3 = "\r\n> " if fnmatch.fnmatchcase(displaybuffer, line_syntax1) or \ fnmatch.fnmatchcase(displaybuffer, line_syntax2) or \ fnmatch.fnmatchcase(displaybuffer, line_syntax3) : # display timestamp if self.SndRcvTimestamp: timestamp = self.timeDisplay() + " " # display data #myColor = colorLsit[7] #received_data = displaybuffer.replace("\r","<CR>").replace("\n","<LF>").replace("\x15","<NAK>").replace("\x06","<ACK>").replace("\x00","<NULL>") received_data = self.ascii2print(displaybuffer, printmode) #peer timestamp+"Rcv COM", com_port_name, "["+received_data+"]", LogMsg = timestamp + "Rcv COM " + com_port_name + " [" + received_data + "] " displaypointer = i + 1 flag_printline = True # match received response with waitpattern for (each_elem) in waitpattern: receivedResp = self.uartbuffer[self.hCom.port][:i + 1] expectedResp = each_elem if fnmatch.fnmatchcase(receivedResp, expectedResp): flag_matchstring = True break if flag_matchstring: # display the remaining matched response when waitpettern is found displaybuffer = self.uartbuffer[ self.hCom.port][displaypointer:i + 1] if len(displaybuffer) > 0: # display timestamp if self.SndRcvTimestamp: timestamp = self.timeDisplay() + " " # display data #myColor = colorLsit[7] #received_data = displaybuffer.replace("\r","<CR>").replace("\n","<LF>").replace("\x15","<NAK>").replace("\x06","<ACK>").replace("\x00","<NULL>") received_data = self.ascii2print( displaybuffer, printmode) #peer "Rcv COM", com_port_name, "["+received_data+"]", LogMsg = timestamp + "Rcv COM " + str( com_port_name) + " [" + received_data + "] " pass # display time spent in receive if self.RcvTimespent: diff_time = datetime.now() - start_time diff_time_ms = diff_time.seconds * 1000 + diff_time.microseconds / 1000 #peer " <"+str(timeout), " @"+str(diff_time_ms), "ms", LogMsg += " <" + str(timeout) + " @" + str( diff_time_ms) + " ms " flag_printline = True # clear matched resposne in UART Buffer self.uartbuffer[self.hCom.port] = self.uartbuffer[ self.hCom.port][i + 1:] flag_matchrsp = True # break for Match response flag_matchrsp = True # peer linebreak for EOL if flag_printline: flag_printline = False #peer "" peer(LogMsg) # break for Match response if flag_matchrsp: break # Count timeout diff_time = datetime.now() - start_time diff_time_ms = diff_time.seconds * 1000 + diff_time.microseconds / 1000 if diff_time_ms > timeout: if log_msg == "debug": #peer "Timeout: ", diff_time, "diff_time_ms:", diff_time_ms LogMsg = "Timeout: " + str( diff_time) + " diff_time_ms: " + str(diff_time_ms) peer(LogMsg) # display the remaining response when timeout displaybuffer = self.uartbuffer[ self.hCom.port][displaypointer:] if len(displaybuffer) > 0: # display timestamp if self.SndRcvTimestamp: #myColor = colorLsit[7] #peer TimeDisplay(), timestamp = self.timeDisplay() + " " # display data #myColor = colorLsit[7] #received_data = receivedResp.replace("\r","<CR>").replace("\n","<LF>").replace("\x15","<NAK>").replace("\x06","<ACK>").replace("\x00","<NULL>") received_data = self.ascii2print(receivedResp, printmode) #peer "Rcv COM", com_port_name, " ["+received_data+"]" LogMsg = "Rcv COM " + str( com_port_name) + " [" + received_data + "]" peer(LogMsg) pass # clear all resposne in UART Buffer #myColor = colorLsit[8] receivedResp = self.uartbuffer[self.hCom.port] if flag_wait_until_timeout != True: if log_msg == "logmsg" or log_msg == "debug": if len(receivedResp) > 0: #peer "\nNo Match! "+"@COM"+com_port_name+ " <"+str(timeout)+" ms\n" LogMsg = "\nNo Match! " + "@COM" + com_port_name + " <" + str( timeout) + " ms\n" peer(LogMsg) if len(receivedResp) == 0: #peer "\nNo Response! "+"@COM"+com_port_name+ " <"+str(timeout)+" ms\n" LogMsg = "\nNo Response! " + "@COM" + com_port_name + " <" + str( timeout) + " ms\n" peer(LogMsg) self.uartbuffer[self.hCom.port] = "" flag_timeout = True if flag_matchrsp: break if flag_timeout: break if log_msg == "debug": peer("") peer(str(len(self.uartbuffer[self.hCom.port]))) LogMsg = "The remaining data in uartbuffer " + str( (self.hCom.port + 1)) + " : [", self.ascii2print( self.uartbuffer[self.hCom.port], printmode), "]" peer(LogMsg) return receivedResp
def send_cmd(self, command, timeout=30): """ Send ADB commands with adb -s serial_id command. Examples: send_cmd('shell "echo %s >/dev/ttyHS0" ' % string) send_cmd('shell "cat /dev/ttyHS0>/tmp/at.txt" ', timeout = 60) Args: command: the adb command you want to send. Kwargs: timeout: adb command timeout Returns: return the command output. """ try: start_time = datetime.now() dt = datetime.now() timeDisplay = "(%0.2d:%0.2d:%0.2d:%0.3d) Snd"%(dt.hour, dt.minute, dt.second, dt.microsecond/1000) cmd = 'adb -s %s %s' % (self.serial_id, command) peer(timeDisplay + " ADB " + self.serial_id + " ["+ cmd + "]") #p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines = True) # > 'exec ' + cmd can FIX the process kill issue p = subprocess.Popen("exec " + cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines = True) t = threading.Timer(timeout, self.__killSubProcess, args = (p,)) t.start() output = p.communicate()[0] if command.strip() in ("shell init 6", "shell init 0", "shell \"poweroff\"", "reboot-bootloader", "reboot"): peer("framework hook <Module reboot> commands [{}]".format(command.strip())) _AT.objs[self.serial_id].close() try: if t is not None: if t.isAlive(): peer("Terminate the monitoring process") t.cancel() peer("%s : Timer is cancelled" % datetime.now().strftime("%y/%m/%d %H:%M:%S")) else: peer("Monitoring process expired, actively kill the thread.") else: peer("Timer NOT set.") except Exception as e: peer(e) traceback.print_exc() peer("---->Problem when terminating mornitor process !!!") timeDisplay = "(%0.2d:%0.2d:%0.2d:%0.3d) Rcv"%(dt.hour, dt.minute, dt.second, dt.microsecond/1000) diff_time = datetime.now() - start_time diff_time_ms = diff_time.seconds * 1000 + diff_time.microseconds / 1000 for each_line in output.split('\n'): peer(timeDisplay + " ADB "+ self.serial_id + " ["+ each_line.replace("\r","<CR>").replace("\n","<CR>") +"]"+" @"+str(diff_time_ms)+" ms ") return output except Exception as e: peer(e) peer("----->Problem: Exception comes up when send command !!!") return "\r\nERROR\r\n"
def info(self): peer("My name is : {name}\n- conf:\n<{conf}>".format(name=AT.name, conf=self.conf))