DUT.py 27 KB

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