DUT.py 27 KB

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