DUT.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. # Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http:#www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. DUT provides 3 major groups of features:
  16. * DUT port feature, provide basic open/close/read/write features
  17. * DUT tools, provide extra methods to control the device, like download and start app
  18. * DUT expect method, provide features for users to check DUT outputs
  19. The current design of DUT have 3 classes for one DUT: BaseDUT, DUTPort, DUTTool.
  20. * BaseDUT class:
  21. * defines methods DUT port and DUT tool need to overwrite
  22. * provide the expect methods and some other methods based on DUTPort
  23. * DUTPort class:
  24. * inherent from BaseDUT class
  25. * implements the port features by overwriting port methods defined in BaseDUT
  26. * DUTTool class:
  27. * inherent from one of the DUTPort class
  28. * implements the tools features by overwriting tool methods defined in BaseDUT
  29. * could add some new methods provided by the tool
  30. This module implements the BaseDUT class and one of the port class SerialDUT.
  31. User should implement their DUTTool classes.
  32. If they using different port then need to implement their DUTPort class as well.
  33. """
  34. from __future__ import print_function
  35. import time
  36. import re
  37. import sys
  38. import threading
  39. import copy
  40. import functools
  41. # python2 and python3 queue package name is different
  42. try:
  43. import Queue as _queue
  44. except ImportError:
  45. import queue as _queue
  46. import serial
  47. from serial.tools import list_ports
  48. from . import Utility
  49. class ExpectTimeout(ValueError):
  50. """ timeout for expect method """
  51. pass
  52. class UnsupportedExpectItem(ValueError):
  53. """ expect item not supported by the expect method """
  54. pass
  55. def _expect_lock(func):
  56. @functools.wraps(func)
  57. def handler(self, *args, **kwargs):
  58. with self.expect_lock:
  59. ret = func(self, *args, **kwargs)
  60. return ret
  61. return handler
  62. def _decode_data(data):
  63. """ for python3, if the data is bytes, then decode it to string """
  64. if isinstance(data, bytes):
  65. # convert bytes to string. This is a bit of a hack, we know that we want to log this
  66. # later so encode to the stdout encoding with backslash escapes for anything non-encodable
  67. try:
  68. return data.decode(sys.stdout.encoding, "backslashreplace")
  69. except UnicodeDecodeError: # Python <3.5 doesn't support backslashreplace
  70. return data.decode(sys.stdout.encoding, "replace")
  71. return data
  72. def _pattern_to_string(pattern):
  73. try:
  74. ret = "RegEx: " + pattern.pattern
  75. except AttributeError:
  76. ret = pattern
  77. return ret
  78. class _DataCache(_queue.Queue):
  79. """
  80. Data cache based on Queue. Allow users to process data cache based on bytes instead of Queue."
  81. """
  82. def __init__(self, maxsize=0):
  83. _queue.Queue.__init__(self, maxsize=maxsize)
  84. self.data_cache = str()
  85. def _move_from_queue_to_cache(self):
  86. """
  87. move all of the available data in the queue to cache
  88. :return: True if moved any item from queue to data cache, else False
  89. """
  90. ret = False
  91. while True:
  92. try:
  93. self.data_cache += _decode_data(self.get(0))
  94. ret = True
  95. except _queue.Empty:
  96. break
  97. return ret
  98. def get_data(self, timeout=0.0):
  99. """
  100. get a copy of data from cache.
  101. :param timeout: timeout for waiting new queue item
  102. :return: copy of data cache
  103. """
  104. # make sure timeout is non-negative
  105. if timeout < 0:
  106. timeout = 0
  107. ret = self._move_from_queue_to_cache()
  108. if not ret:
  109. # we only wait for new data if we can't provide a new data_cache
  110. try:
  111. data = self.get(timeout=timeout)
  112. self.data_cache += _decode_data(data)
  113. except _queue.Empty:
  114. # don't do anything when on update for cache
  115. pass
  116. return copy.deepcopy(self.data_cache)
  117. def flush(self, index=0xFFFFFFFF):
  118. """
  119. flush data from cache.
  120. :param index: if < 0 then don't do flush, otherwise flush data before index
  121. :return: None
  122. """
  123. # first add data in queue to cache
  124. self.get_data()
  125. if index > 0:
  126. self.data_cache = self.data_cache[index:]
  127. class _LogThread(threading.Thread, _queue.Queue):
  128. """
  129. We found some SD card on Raspberry Pi could have very bad performance.
  130. It could take seconds to save small amount of data.
  131. If the DUT receives data and save it as log, then it stops receiving data until log is saved.
  132. This could lead to expect timeout.
  133. As an workaround to this issue, ``BaseDUT`` class will create a thread to save logs.
  134. Then data will be passed to ``expect`` as soon as received.
  135. """
  136. def __init__(self):
  137. threading.Thread.__init__(self, name="LogThread")
  138. _queue.Queue.__init__(self, maxsize=0)
  139. self.setDaemon(True)
  140. self.flush_lock = threading.Lock()
  141. def save_log(self, filename, data):
  142. """
  143. :param filename: log file name
  144. :param data: log data. Must be ``bytes``.
  145. """
  146. self.put({"filename": filename, "data": data})
  147. def flush_data(self):
  148. with self.flush_lock:
  149. data_cache = dict()
  150. while True:
  151. # move all data from queue to data cache
  152. try:
  153. log = self.get_nowait()
  154. try:
  155. data_cache[log["filename"]] += log["data"]
  156. except KeyError:
  157. data_cache[log["filename"]] = log["data"]
  158. except _queue.Empty:
  159. break
  160. # flush data
  161. for filename in data_cache:
  162. with open(filename, "ab+") as f:
  163. f.write(data_cache[filename])
  164. def run(self):
  165. while True:
  166. time.sleep(1)
  167. self.flush_data()
  168. class RecvThread(threading.Thread):
  169. CHECK_FUNCTIONS = []
  170. """ DUT subclass can define a few check functions to process received data. """
  171. def __init__(self, read, dut):
  172. super(RecvThread, self).__init__()
  173. self.exit_event = threading.Event()
  174. self.setDaemon(True)
  175. self.read = read
  176. self.dut = dut
  177. self.data_cache = dut.data_cache
  178. self.recorded_data = dut.recorded_data
  179. self.record_data_lock = dut.record_data_lock
  180. self._line_cache = str()
  181. def _line_completion(self, data):
  182. """
  183. Usually check functions requires to check for one complete line.
  184. This method will do line completion for the first line, and strip incomplete last line.
  185. """
  186. ret = self._line_cache
  187. decoded_data = _decode_data(data)
  188. # cache incomplete line to later process
  189. lines = decoded_data.splitlines(True)
  190. last_line = lines[-1]
  191. if last_line[-1] != "\n":
  192. if len(lines) == 1:
  193. # only one line and the line is not finished, then append this to cache
  194. self._line_cache += lines[-1]
  195. ret = str()
  196. else:
  197. # more than one line and not finished, replace line cache
  198. self._line_cache = lines[-1]
  199. ret += "".join(lines[:-1])
  200. else:
  201. # line finishes, flush cache
  202. self._line_cache = str()
  203. ret += decoded_data
  204. return ret
  205. def run(self):
  206. while not self.exit_event.isSet():
  207. raw_data = self.read(1000)
  208. if raw_data:
  209. with self.record_data_lock:
  210. self.data_cache.put(raw_data)
  211. for capture_id in self.recorded_data:
  212. self.recorded_data[capture_id].put(raw_data)
  213. # we need to do line completion before call check functions
  214. comp_data = self._line_completion(raw_data)
  215. for check_function in self.CHECK_FUNCTIONS:
  216. check_function(self, comp_data)
  217. def exit(self):
  218. self.exit_event.set()
  219. self.join()
  220. class BaseDUT(object):
  221. """
  222. :param name: application defined name for port
  223. :param port: comport name, used to create DUT port
  224. :param log_file: log file name
  225. :param app: test app instance
  226. :param kwargs: extra args for DUT to create ports
  227. """
  228. DEFAULT_EXPECT_TIMEOUT = 10
  229. MAX_EXPECT_FAILURES_TO_SAVED = 10
  230. RECV_THREAD_CLS = RecvThread
  231. TARGET = None
  232. """ DUT subclass can specify RECV_THREAD_CLS to do add some extra stuff when receive data.
  233. For example, DUT can implement exception detect & analysis logic in receive thread subclass. """
  234. LOG_THREAD = _LogThread()
  235. LOG_THREAD.start()
  236. def __init__(self, name, port, log_file, app, **kwargs):
  237. self.expect_lock = threading.Lock()
  238. self.name = name
  239. self.port = port
  240. self.log_file = log_file
  241. self.app = app
  242. self.data_cache = _DataCache()
  243. # the main process of recorded data are done in receive thread
  244. # but receive thread could be closed in DUT lifetime (tool methods)
  245. # so we keep it in BaseDUT, as their life cycle are same
  246. self.recorded_data = dict()
  247. self.record_data_lock = threading.RLock()
  248. self.receive_thread = None
  249. self.expect_failures = []
  250. self._port_open()
  251. self.start_receive()
  252. def __str__(self):
  253. return "DUT({}: {})".format(self.name, str(self.port))
  254. def _save_expect_failure(self, pattern, data, start_time):
  255. """
  256. Save expect failure. If the test fails, then it will print the expect failures.
  257. In some cases, user will handle expect exceptions.
  258. The expect failures could be false alarm, and test case might generate a lot of such failures.
  259. Therefore, we don't print the failure immediately and limit the max size of failure list.
  260. """
  261. self.expect_failures.insert(0, {"pattern": pattern, "data": data,
  262. "start": start_time, "end": time.time()})
  263. self.expect_failures = self.expect_failures[:self.MAX_EXPECT_FAILURES_TO_SAVED]
  264. def _save_dut_log(self, data):
  265. """
  266. Save DUT log into file using another thread.
  267. This is a workaround for some devices takes long time for file system operations.
  268. See descriptions in ``_LogThread`` for details.
  269. """
  270. self.LOG_THREAD.save_log(self.log_file, data)
  271. # define for methods need to be overwritten by Port
  272. @classmethod
  273. def list_available_ports(cls):
  274. """
  275. list all available ports.
  276. subclass (port) must overwrite this method.
  277. :return: list of available comports
  278. """
  279. pass
  280. def _port_open(self):
  281. """
  282. open the port.
  283. subclass (port) must overwrite this method.
  284. :return: None
  285. """
  286. pass
  287. def _port_read(self, size=1):
  288. """
  289. read form port. This method should not blocking for long time, otherwise receive thread can not exit.
  290. subclass (port) must overwrite this method.
  291. :param size: max size to read.
  292. :return: read data.
  293. """
  294. pass
  295. def _port_write(self, data):
  296. """
  297. write to port.
  298. subclass (port) must overwrite this method.
  299. :param data: data to write
  300. :return: None
  301. """
  302. pass
  303. def _port_close(self):
  304. """
  305. close port.
  306. subclass (port) must overwrite this method.
  307. :return: None
  308. """
  309. pass
  310. # methods that need to be overwritten by Tool
  311. @classmethod
  312. def confirm_dut(cls, port, **kwargs):
  313. """
  314. confirm if it's a DUT, usually used by auto detecting DUT in by Env config.
  315. subclass (tool) must overwrite this method.
  316. :param port: comport
  317. :return: tuple of result (bool), and target (str)
  318. """
  319. pass
  320. def start_app(self):
  321. """
  322. usually after we got DUT, we need to do some extra works to let App start.
  323. For example, we need to reset->download->reset to let IDF application start on DUT.
  324. subclass (tool) must overwrite this method.
  325. :return: None
  326. """
  327. pass
  328. # methods that features raw port methods
  329. def start_receive(self):
  330. """
  331. Start thread to receive data.
  332. :return: None
  333. """
  334. self.receive_thread = self.RECV_THREAD_CLS(self._port_read, self)
  335. self.receive_thread.start()
  336. def stop_receive(self):
  337. """
  338. stop the receiving thread for the port
  339. :return: None
  340. """
  341. if self.receive_thread:
  342. self.receive_thread.exit()
  343. self.LOG_THREAD.flush_data()
  344. self.receive_thread = None
  345. def close(self):
  346. """
  347. permanently close the port
  348. """
  349. self.stop_receive()
  350. self._port_close()
  351. @staticmethod
  352. def u_to_bytearray(data):
  353. """
  354. if data is not bytearray then it tries to convert it
  355. :param data: data which needs to be checked and maybe transformed
  356. """
  357. if isinstance(data, type(u'')):
  358. try:
  359. data = data.encode('utf-8')
  360. except Exception as e:
  361. print(u'Cannot encode {} of type {}'.format(data, type(data)))
  362. raise e
  363. return data
  364. def write(self, data, eol="\r\n", flush=True):
  365. """
  366. :param data: data
  367. :param eol: end of line pattern.
  368. :param flush: if need to flush received data cache before write data.
  369. usually we need to flush data before write,
  370. make sure processing outputs generated by wrote.
  371. :return: None
  372. """
  373. # do flush before write
  374. if flush:
  375. self.data_cache.flush()
  376. # do write if cache
  377. if data is not None:
  378. self._port_write(self.u_to_bytearray(data) + self.u_to_bytearray(eol) if eol else self.u_to_bytearray(data))
  379. @_expect_lock
  380. def read(self, size=0xFFFFFFFF):
  381. """
  382. read(size=0xFFFFFFFF)
  383. read raw data. NOT suggested to use this method.
  384. Only use it if expect method doesn't meet your requirement.
  385. :param size: read size. default read all data
  386. :return: read data
  387. """
  388. data = self.data_cache.get_data(0)[:size]
  389. self.data_cache.flush(size)
  390. return data
  391. def start_capture_raw_data(self, capture_id="default"):
  392. """
  393. Sometime application want to get DUT raw data and use ``expect`` method at the same time.
  394. Capture methods provides a way to get raw data without affecting ``expect`` or ``read`` method.
  395. If you call ``start_capture_raw_data`` with same capture id again, it will restart capture on this ID.
  396. :param capture_id: ID of capture. You can use different IDs to do different captures at the same time.
  397. """
  398. with self.record_data_lock:
  399. try:
  400. # if start capture on existed ID, we do flush data and restart capture
  401. self.recorded_data[capture_id].flush()
  402. except KeyError:
  403. # otherwise, create new data cache
  404. self.recorded_data[capture_id] = _DataCache()
  405. def stop_capture_raw_data(self, capture_id="default"):
  406. """
  407. Stop capture and get raw data.
  408. This method should be used after ``start_capture_raw_data`` on the same capture ID.
  409. :param capture_id: ID of capture.
  410. :return: captured raw data between start capture and stop capture.
  411. """
  412. with self.record_data_lock:
  413. try:
  414. ret = self.recorded_data[capture_id].get_data()
  415. self.recorded_data.pop(capture_id)
  416. except KeyError as e:
  417. e.message = "capture_id does not exist. " \
  418. "You should call start_capture_raw_data with same ID " \
  419. "before calling stop_capture_raw_data"
  420. raise e
  421. return ret
  422. # expect related methods
  423. @staticmethod
  424. def _expect_str(data, pattern):
  425. """
  426. protected method. check if string is matched in data cache.
  427. :param data: data to process
  428. :param pattern: string
  429. :return: pattern if match succeed otherwise None
  430. """
  431. index = data.find(pattern)
  432. if index != -1:
  433. ret = pattern
  434. index += len(pattern)
  435. else:
  436. ret = None
  437. return ret, index
  438. @staticmethod
  439. def _expect_re(data, pattern):
  440. """
  441. protected method. check if re pattern is matched in data cache
  442. :param data: data to process
  443. :param pattern: compiled RegEx pattern
  444. :return: match groups if match succeed otherwise None
  445. """
  446. ret = None
  447. if isinstance(pattern.pattern, type(u'')):
  448. pattern = re.compile(BaseDUT.u_to_bytearray(pattern.pattern))
  449. if isinstance(data, type(u'')):
  450. data = BaseDUT.u_to_bytearray(data)
  451. match = pattern.search(data)
  452. if match:
  453. ret = tuple(None if x is None else x.decode() for x in match.groups())
  454. index = match.end()
  455. else:
  456. index = -1
  457. return ret, index
  458. EXPECT_METHOD = [
  459. [type(re.compile("")), "_expect_re"],
  460. [type(b''), "_expect_str"], # Python 2 & 3 hook to work without 'from builtins import str' from future
  461. [type(u''), "_expect_str"],
  462. ]
  463. def _get_expect_method(self, pattern):
  464. """
  465. protected method. get expect method according to pattern type.
  466. :param pattern: expect pattern, string or compiled RegEx
  467. :return: ``_expect_str`` or ``_expect_re``
  468. """
  469. for expect_method in self.EXPECT_METHOD:
  470. if isinstance(pattern, expect_method[0]):
  471. method = expect_method[1]
  472. break
  473. else:
  474. raise UnsupportedExpectItem()
  475. return self.__getattribute__(method)
  476. @_expect_lock
  477. def expect(self, pattern, timeout=DEFAULT_EXPECT_TIMEOUT, full_stdout=False):
  478. """
  479. expect(pattern, timeout=DEFAULT_EXPECT_TIMEOUT)
  480. expect received data on DUT match the pattern. will raise exception when expect timeout.
  481. :raise ExpectTimeout: failed to find the pattern before timeout
  482. :raise UnsupportedExpectItem: pattern is not string or compiled RegEx
  483. :param pattern: string or compiled RegEx(string pattern)
  484. :param timeout: timeout for expect
  485. :param full_stdout: return full stdout until meet expect string/pattern or just matched string
  486. :return: string if pattern is string; matched groups if pattern is RegEx
  487. """
  488. method = self._get_expect_method(pattern)
  489. stdout = ''
  490. # non-blocking get data for first time
  491. data = self.data_cache.get_data(0)
  492. start_time = time.time()
  493. while True:
  494. ret, index = method(data, pattern)
  495. if ret is not None:
  496. self.data_cache.flush(index)
  497. break
  498. time_remaining = start_time + timeout - time.time()
  499. if time_remaining < 0:
  500. break
  501. # wait for new data from cache
  502. data = self.data_cache.get_data(time_remaining)
  503. stdout = data
  504. if ret is None:
  505. pattern = _pattern_to_string(pattern)
  506. self._save_expect_failure(pattern, data, start_time)
  507. raise ExpectTimeout(self.name + ": " + pattern)
  508. return stdout if full_stdout else ret
  509. def _expect_multi(self, expect_all, expect_item_list, timeout):
  510. """
  511. protected method. internal logical for expect multi.
  512. :param expect_all: True or False, expect all items in the list or any in the list
  513. :param expect_item_list: expect item list
  514. :param timeout: timeout
  515. :return: None
  516. """
  517. def process_expected_item(item_raw):
  518. # convert item raw data to standard dict
  519. item = {
  520. "pattern": item_raw[0] if isinstance(item_raw, tuple) else item_raw,
  521. "method": self._get_expect_method(item_raw[0] if isinstance(item_raw, tuple)
  522. else item_raw),
  523. "callback": item_raw[1] if isinstance(item_raw, tuple) else None,
  524. "index": -1,
  525. "ret": None,
  526. }
  527. return item
  528. expect_items = [process_expected_item(x) for x in expect_item_list]
  529. # non-blocking get data for first time
  530. data = self.data_cache.get_data(0)
  531. start_time = time.time()
  532. matched_expect_items = list()
  533. while True:
  534. for expect_item in expect_items:
  535. if expect_item not in matched_expect_items:
  536. # exclude those already matched
  537. expect_item["ret"], expect_item["index"] = \
  538. expect_item["method"](data, expect_item["pattern"])
  539. if expect_item["ret"] is not None:
  540. # match succeed for one item
  541. matched_expect_items.append(expect_item)
  542. # if expect all, then all items need to be matched,
  543. # else only one item need to matched
  544. if expect_all:
  545. match_succeed = len(matched_expect_items) == len(expect_items)
  546. else:
  547. match_succeed = True if matched_expect_items else False
  548. time_remaining = start_time + timeout - time.time()
  549. if time_remaining < 0 or match_succeed:
  550. break
  551. else:
  552. data = self.data_cache.get_data(time_remaining)
  553. if match_succeed:
  554. # sort matched items according to order of appearance in the input data,
  555. # so that the callbacks are invoked in correct order
  556. matched_expect_items = sorted(matched_expect_items, key=lambda it: it["index"])
  557. # invoke callbacks and flush matched data cache
  558. slice_index = -1
  559. for expect_item in matched_expect_items:
  560. # trigger callback
  561. if expect_item["callback"]:
  562. expect_item["callback"](expect_item["ret"])
  563. slice_index = max(slice_index, expect_item["index"])
  564. # flush already matched data
  565. self.data_cache.flush(slice_index)
  566. else:
  567. pattern = str([_pattern_to_string(x["pattern"]) for x in expect_items])
  568. self._save_expect_failure(pattern, data, start_time)
  569. raise ExpectTimeout(self.name + ": " + pattern)
  570. @_expect_lock
  571. def expect_any(self, *expect_items, **timeout):
  572. """
  573. expect_any(*expect_items, timeout=DEFAULT_TIMEOUT)
  574. expect any of the patterns.
  575. will call callback (if provided) if pattern match succeed and then return.
  576. will pass match result to the callback.
  577. :raise ExpectTimeout: failed to match any one of the expect items before timeout
  578. :raise UnsupportedExpectItem: pattern in expect_item is not string or compiled RegEx
  579. :arg expect_items: one or more expect items.
  580. string, compiled RegEx pattern or (string or RegEx(string pattern), callback)
  581. :keyword timeout: timeout for expect
  582. :return: None
  583. """
  584. # to be compatible with python2
  585. # in python3 we can write f(self, *expect_items, timeout=DEFAULT_TIMEOUT)
  586. if "timeout" not in timeout:
  587. timeout["timeout"] = self.DEFAULT_EXPECT_TIMEOUT
  588. return self._expect_multi(False, expect_items, **timeout)
  589. @_expect_lock
  590. def expect_all(self, *expect_items, **timeout):
  591. """
  592. expect_all(*expect_items, timeout=DEFAULT_TIMEOUT)
  593. expect all of the patterns.
  594. will call callback (if provided) if all pattern match succeed and then return.
  595. will pass match result to the callback.
  596. :raise ExpectTimeout: failed to match all of the expect items before timeout
  597. :raise UnsupportedExpectItem: pattern in expect_item is not string or compiled RegEx
  598. :arg expect_items: one or more expect items.
  599. string, compiled RegEx pattern or (string or RegEx(string pattern), callback)
  600. :keyword timeout: timeout for expect
  601. :return: None
  602. """
  603. # to be compatible with python2
  604. # in python3 we can write f(self, *expect_items, timeout=DEFAULT_TIMEOUT)
  605. if "timeout" not in timeout:
  606. timeout["timeout"] = self.DEFAULT_EXPECT_TIMEOUT
  607. return self._expect_multi(True, expect_items, **timeout)
  608. @staticmethod
  609. def _format_ts(ts):
  610. return "{}:{}".format(time.strftime("%m-%d %H:%M:%S", time.localtime(ts)), str(ts % 1)[2:5])
  611. def print_debug_info(self):
  612. """
  613. Print debug info of current DUT. Currently we will print debug info for expect failures.
  614. """
  615. Utility.console_log("DUT debug info for DUT: {}:".format(self.name), color="orange")
  616. for failure in self.expect_failures:
  617. Utility.console_log(u"\t[pattern]: {}\r\n\t[data]: {}\r\n\t[time]: {} - {}\r\n"
  618. .format(failure["pattern"], failure["data"],
  619. self._format_ts(failure["start"]), self._format_ts(failure["end"])),
  620. color="orange")
  621. class SerialDUT(BaseDUT):
  622. """ serial with logging received data feature """
  623. DEFAULT_UART_CONFIG = {
  624. "baudrate": 115200,
  625. "bytesize": serial.EIGHTBITS,
  626. "parity": serial.PARITY_NONE,
  627. "stopbits": serial.STOPBITS_ONE,
  628. "timeout": 0.05,
  629. "xonxoff": False,
  630. "rtscts": False,
  631. }
  632. def __init__(self, name, port, log_file, app, **kwargs):
  633. self.port_inst = None
  634. self.serial_configs = self.DEFAULT_UART_CONFIG.copy()
  635. for uart_config_name in self.serial_configs.keys():
  636. if uart_config_name in kwargs:
  637. self.serial_configs[uart_config_name] = kwargs[uart_config_name]
  638. super(SerialDUT, self).__init__(name, port, log_file, app, **kwargs)
  639. def _format_data(self, data):
  640. """
  641. format data for logging. do decode and add timestamp.
  642. :param data: raw data from read
  643. :return: formatted data (str)
  644. """
  645. timestamp = "[{}]".format(self._format_ts(time.time()))
  646. formatted_data = timestamp.encode() + b"\r\n" + data + b"\r\n"
  647. return formatted_data
  648. def _port_open(self):
  649. self.port_inst = serial.serial_for_url(self.port, **self.serial_configs)
  650. def _port_close(self):
  651. self.port_inst.close()
  652. def _port_read(self, size=1):
  653. data = self.port_inst.read(size)
  654. if data:
  655. self._save_dut_log(self._format_data(data))
  656. return data
  657. def _port_write(self, data):
  658. if isinstance(data, str):
  659. data = data.encode()
  660. self.port_inst.write(data)
  661. @classmethod
  662. def list_available_ports(cls):
  663. return [x.device for x in list_ports.comports()]