DUT.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. import time
  35. import re
  36. import threading
  37. import copy
  38. import sys
  39. import functools
  40. import serial
  41. from serial.tools import list_ports
  42. import Utility
  43. if sys.version_info[0] == 2:
  44. import Queue as _queue
  45. else:
  46. import queue as _queue
  47. class ExpectTimeout(ValueError):
  48. """ timeout for expect method """
  49. pass
  50. class UnsupportedExpectItem(ValueError):
  51. """ expect item not supported by the expect method """
  52. pass
  53. def _expect_lock(func):
  54. @functools.wraps(func)
  55. def handler(self, *args, **kwargs):
  56. with self.expect_lock:
  57. ret = func(self, *args, **kwargs)
  58. return ret
  59. return handler
  60. def _decode_data(data):
  61. """ for python3, if the data is bytes, then decode it to string """
  62. if isinstance(data, bytes):
  63. # convert bytes to string
  64. try:
  65. data = data.decode("utf-8", "ignore")
  66. except UnicodeDecodeError:
  67. data = data.decode("iso8859-1", )
  68. return data
  69. def _pattern_to_string(pattern):
  70. try:
  71. ret = "RegEx: " + pattern.pattern
  72. except AttributeError:
  73. ret = pattern
  74. return ret
  75. class _DataCache(_queue.Queue):
  76. """
  77. Data cache based on Queue. Allow users to process data cache based on bytes instead of Queue."
  78. """
  79. def __init__(self, maxsize=0):
  80. _queue.Queue.__init__(self, maxsize=maxsize)
  81. self.data_cache = str()
  82. def _move_from_queue_to_cache(self):
  83. """
  84. move all of the available data in the queue to cache
  85. :return: True if moved any item from queue to data cache, else False
  86. """
  87. ret = False
  88. while True:
  89. try:
  90. self.data_cache += _decode_data(self.get(0))
  91. ret = True
  92. except _queue.Empty:
  93. break
  94. return ret
  95. def get_data(self, timeout=0):
  96. """
  97. get a copy of data from cache.
  98. :param timeout: timeout for waiting new queue item
  99. :return: copy of data cache
  100. """
  101. # make sure timeout is non-negative
  102. if timeout < 0:
  103. timeout = 0
  104. ret = self._move_from_queue_to_cache()
  105. if not ret:
  106. # we only wait for new data if we can't provide a new data_cache
  107. try:
  108. data = self.get(timeout=timeout)
  109. self.data_cache += _decode_data(data)
  110. except _queue.Empty:
  111. # don't do anything when on update for cache
  112. pass
  113. return copy.deepcopy(self.data_cache)
  114. def flush(self, index=0xFFFFFFFF):
  115. """
  116. flush data from cache.
  117. :param index: if < 0 then don't do flush, otherwise flush data before index
  118. :return: None
  119. """
  120. # first add data in queue to cache
  121. self.get_data()
  122. if index > 0:
  123. self.data_cache = self.data_cache[index:]
  124. class _RecvThread(threading.Thread):
  125. PERFORMANCE_PATTERN = re.compile(r"\[Performance]\[(\w+)]: ([^\r\n]+)\r?\n")
  126. def __init__(self, read, data_cache):
  127. super(_RecvThread, self).__init__()
  128. self.exit_event = threading.Event()
  129. self.setDaemon(True)
  130. self.read = read
  131. self.data_cache = data_cache
  132. # cache the last line of recv data for collecting performance
  133. self._line_cache = str()
  134. def collect_performance(self, data):
  135. """ collect performance """
  136. if data:
  137. decoded_data = _decode_data(data)
  138. matches = self.PERFORMANCE_PATTERN.findall(self._line_cache + decoded_data)
  139. for match in matches:
  140. Utility.console_log("[Performance][{}]: {}".format(match[0], match[1]),
  141. color="orange")
  142. # cache incomplete line to later process
  143. lines = decoded_data.splitlines(True)
  144. last_line = lines[-1]
  145. if last_line[-1] != "\n":
  146. if len(lines) == 1:
  147. # only one line and the line is not finished, then append this to cache
  148. self._line_cache += lines[-1]
  149. else:
  150. # more than one line and not finished, replace line cache
  151. self._line_cache = lines[-1]
  152. else:
  153. # line finishes, flush cache
  154. self._line_cache = str()
  155. def run(self):
  156. while not self.exit_event.isSet():
  157. data = self.read(1000)
  158. if data:
  159. self.data_cache.put(data)
  160. self.collect_performance(data)
  161. def exit(self):
  162. self.exit_event.set()
  163. self.join()
  164. class BaseDUT(object):
  165. """
  166. :param name: application defined name for port
  167. :param port: comport name, used to create DUT port
  168. :param log_file: log file name
  169. :param app: test app instance
  170. :param kwargs: extra args for DUT to create ports
  171. """
  172. DEFAULT_EXPECT_TIMEOUT = 5
  173. def __init__(self, name, port, log_file, app, **kwargs):
  174. self.expect_lock = threading.Lock()
  175. self.name = name
  176. self.port = port
  177. self.log_file = log_file
  178. self.app = app
  179. self.data_cache = _DataCache()
  180. self.receive_thread = None
  181. # open and start during init
  182. self.open()
  183. def __str__(self):
  184. return "DUT({}: {})".format(self.name, str(self.port))
  185. # define for methods need to be overwritten by Port
  186. @classmethod
  187. def list_available_ports(cls):
  188. """
  189. list all available ports.
  190. subclass (port) must overwrite this method.
  191. :return: list of available comports
  192. """
  193. pass
  194. def _port_open(self):
  195. """
  196. open the port.
  197. subclass (port) must overwrite this method.
  198. :return: None
  199. """
  200. pass
  201. def _port_read(self, size=1):
  202. """
  203. read form port. This method should not blocking for long time, otherwise receive thread can not exit.
  204. subclass (port) must overwrite this method.
  205. :param size: max size to read.
  206. :return: read data.
  207. """
  208. pass
  209. def _port_write(self, data):
  210. """
  211. write to port.
  212. subclass (port) must overwrite this method.
  213. :param data: data to write
  214. :return: None
  215. """
  216. pass
  217. def _port_close(self):
  218. """
  219. close port.
  220. subclass (port) must overwrite this method.
  221. :return: None
  222. """
  223. pass
  224. # methods that need to be overwritten by Tool
  225. @classmethod
  226. def confirm_dut(cls, port, app, **kwargs):
  227. """
  228. confirm if it's a DUT, usually used by auto detecting DUT in by Env config.
  229. subclass (tool) must overwrite this method.
  230. :param port: comport
  231. :param app: app instance
  232. :return: True or False
  233. """
  234. pass
  235. def start_app(self):
  236. """
  237. usually after we got DUT, we need to do some extra works to let App start.
  238. For example, we need to reset->download->reset to let IDF application start on DUT.
  239. subclass (tool) must overwrite this method.
  240. :return: None
  241. """
  242. pass
  243. # methods that features raw port methods
  244. def open(self):
  245. """
  246. open port and create thread to receive data.
  247. :return: None
  248. """
  249. self._port_open()
  250. self.receive_thread = _RecvThread(self._port_read, self.data_cache)
  251. self.receive_thread.start()
  252. def close(self):
  253. """
  254. close receive thread and then close port.
  255. :return: None
  256. """
  257. if self.receive_thread:
  258. self.receive_thread.exit()
  259. self._port_close()
  260. def write(self, data, eol="\r\n", flush=True):
  261. """
  262. :param data: data
  263. :param eol: end of line pattern.
  264. :param flush: if need to flush received data cache before write data.
  265. usually we need to flush data before write,
  266. make sure processing outputs generated by wrote.
  267. :return: None
  268. """
  269. # do flush before write
  270. if flush:
  271. self.data_cache.flush()
  272. # do write if cache
  273. if data is not None:
  274. self._port_write(data + eol if eol else data)
  275. @_expect_lock
  276. def read(self, size=0xFFFFFFFF):
  277. """
  278. read(size=0xFFFFFFFF)
  279. read raw data. NOT suggested to use this method.
  280. Only use it if expect method doesn't meet your requirement.
  281. :param size: read size. default read all data
  282. :return: read data
  283. """
  284. data = self.data_cache.get_data(0)[:size]
  285. self.data_cache.flush(size)
  286. return data
  287. # expect related methods
  288. @staticmethod
  289. def _expect_str(data, pattern):
  290. """
  291. protected method. check if string is matched in data cache.
  292. :param data: data to process
  293. :param pattern: string
  294. :return: pattern if match succeed otherwise None
  295. """
  296. index = data.find(pattern)
  297. if index != -1:
  298. ret = pattern
  299. index += len(pattern)
  300. else:
  301. ret = None
  302. return ret, index
  303. @staticmethod
  304. def _expect_re(data, pattern):
  305. """
  306. protected method. check if re pattern is matched in data cache
  307. :param data: data to process
  308. :param pattern: compiled RegEx pattern
  309. :return: match groups if match succeed otherwise None
  310. """
  311. ret = None
  312. match = pattern.search(data)
  313. if match:
  314. ret = match.groups()
  315. index = match.end()
  316. else:
  317. index = -1
  318. return ret, index
  319. EXPECT_METHOD = [
  320. [type(re.compile("")), "_expect_re"],
  321. [str, "_expect_str"],
  322. ]
  323. def _get_expect_method(self, pattern):
  324. """
  325. protected method. get expect method according to pattern type.
  326. :param pattern: expect pattern, string or compiled RegEx
  327. :return: ``_expect_str`` or ``_expect_re``
  328. """
  329. for expect_method in self.EXPECT_METHOD:
  330. if isinstance(pattern, expect_method[0]):
  331. method = expect_method[1]
  332. break
  333. else:
  334. raise UnsupportedExpectItem()
  335. return self.__getattribute__(method)
  336. @_expect_lock
  337. def expect(self, pattern, timeout=DEFAULT_EXPECT_TIMEOUT):
  338. """
  339. expect(pattern, timeout=DEFAULT_EXPECT_TIMEOUT)
  340. expect received data on DUT match the pattern. will raise exception when expect timeout.
  341. :raise ExpectTimeout: failed to find the pattern before timeout
  342. :raise UnsupportedExpectItem: pattern is not string or compiled RegEx
  343. :param pattern: string or compiled RegEx(string pattern)
  344. :param timeout: timeout for expect
  345. :return: string if pattern is string; matched groups if pattern is RegEx
  346. """
  347. method = self._get_expect_method(pattern)
  348. # non-blocking get data for first time
  349. data = self.data_cache.get_data(0)
  350. start_time = time.time()
  351. while True:
  352. ret, index = method(data, pattern)
  353. if ret is not None or time.time() - start_time > timeout:
  354. self.data_cache.flush(index)
  355. break
  356. # wait for new data from cache
  357. data = self.data_cache.get_data(time.time() + timeout - start_time)
  358. if ret is None:
  359. raise ExpectTimeout(self.name + ": " + _pattern_to_string(pattern))
  360. return ret
  361. def _expect_multi(self, expect_all, expect_item_list, timeout):
  362. """
  363. protected method. internal logical for expect multi.
  364. :param expect_all: True or False, expect all items in the list or any in the list
  365. :param expect_item_list: expect item list
  366. :param timeout: timeout
  367. :return: None
  368. """
  369. def process_expected_item(item_raw):
  370. # convert item raw data to standard dict
  371. item = {
  372. "pattern": item_raw[0] if isinstance(item_raw, tuple) else item_raw,
  373. "method": self._get_expect_method(item_raw[0] if isinstance(item_raw, tuple)
  374. else item_raw),
  375. "callback": item_raw[1] if isinstance(item_raw, tuple) else None,
  376. "index": -1,
  377. "ret": None,
  378. }
  379. return item
  380. expect_items = [process_expected_item(x) for x in expect_item_list]
  381. # non-blocking get data for first time
  382. data = self.data_cache.get_data(0)
  383. start_time = time.time()
  384. matched_expect_items = list()
  385. while True:
  386. for expect_item in expect_items:
  387. if expect_item not in matched_expect_items:
  388. # exclude those already matched
  389. expect_item["ret"], expect_item["index"] = \
  390. expect_item["method"](data, expect_item["pattern"])
  391. if expect_item["ret"] is not None:
  392. # match succeed for one item
  393. matched_expect_items.append(expect_item)
  394. # if expect all, then all items need to be matched,
  395. # else only one item need to matched
  396. if expect_all:
  397. match_succeed = len(matched_expect_items) == len(expect_items)
  398. else:
  399. match_succeed = True if matched_expect_items else False
  400. if time.time() - start_time > timeout or match_succeed:
  401. break
  402. else:
  403. data = self.data_cache.get_data(time.time() + timeout - start_time)
  404. if match_succeed:
  405. # do callback and flush matched data cache
  406. slice_index = -1
  407. for expect_item in matched_expect_items:
  408. # trigger callback
  409. if expect_item["callback"]:
  410. expect_item["callback"](expect_item["ret"])
  411. slice_index = max(slice_index, expect_item["index"])
  412. # flush already matched data
  413. self.data_cache.flush(slice_index)
  414. else:
  415. raise ExpectTimeout(self.name + ": " + str([_pattern_to_string(x) for x in expect_items]))
  416. @_expect_lock
  417. def expect_any(self, *expect_items, **timeout):
  418. """
  419. expect_any(*expect_items, timeout=DEFAULT_TIMEOUT)
  420. expect any of the patterns.
  421. will call callback (if provided) if pattern match succeed and then return.
  422. will pass match result to the callback.
  423. :raise ExpectTimeout: failed to match any one of the expect items before timeout
  424. :raise UnsupportedExpectItem: pattern in expect_item is not string or compiled RegEx
  425. :arg expect_items: one or more expect items.
  426. string, compiled RegEx pattern or (string or RegEx(string pattern), callback)
  427. :keyword timeout: timeout for expect
  428. :return: None
  429. """
  430. # to be compatible with python2
  431. # in python3 we can write f(self, *expect_items, timeout=DEFAULT_TIMEOUT)
  432. if "timeout" not in timeout:
  433. timeout["timeout"] = self.DEFAULT_EXPECT_TIMEOUT
  434. return self._expect_multi(False, expect_items, **timeout)
  435. @_expect_lock
  436. def expect_all(self, *expect_items, **timeout):
  437. """
  438. expect_all(*expect_items, timeout=DEFAULT_TIMEOUT)
  439. expect all of the patterns.
  440. will call callback (if provided) if all pattern match succeed and then return.
  441. will pass match result to the callback.
  442. :raise ExpectTimeout: failed to match all of the expect items before timeout
  443. :raise UnsupportedExpectItem: pattern in expect_item is not string or compiled RegEx
  444. :arg expect_items: one or more expect items.
  445. string, compiled RegEx pattern or (string or RegEx(string pattern), callback)
  446. :keyword timeout: timeout for expect
  447. :return: None
  448. """
  449. # to be compatible with python2
  450. # in python3 we can write f(self, *expect_items, timeout=DEFAULT_TIMEOUT)
  451. if "timeout" not in timeout:
  452. timeout["timeout"] = self.DEFAULT_EXPECT_TIMEOUT
  453. return self._expect_multi(True, expect_items, **timeout)
  454. class SerialDUT(BaseDUT):
  455. """ serial with logging received data feature """
  456. DEFAULT_UART_CONFIG = {
  457. "baudrate": 115200,
  458. "bytesize": serial.EIGHTBITS,
  459. "parity": serial.PARITY_NONE,
  460. "stopbits": serial.STOPBITS_ONE,
  461. "timeout": 0.05,
  462. "xonxoff": False,
  463. "rtscts": False,
  464. }
  465. def __init__(self, name, port, log_file, app, **kwargs):
  466. self.port_inst = None
  467. self.serial_configs = self.DEFAULT_UART_CONFIG.copy()
  468. self.serial_configs.update(kwargs)
  469. super(SerialDUT, self).__init__(name, port, log_file, app, **kwargs)
  470. @staticmethod
  471. def _format_data(data):
  472. """
  473. format data for logging. do decode and add timestamp.
  474. :param data: raw data from read
  475. :return: formatted data (str)
  476. """
  477. timestamp = time.time()
  478. timestamp = "[{}:{}]".format(time.strftime("%m-%d %H:%M:%S", time.localtime(timestamp)),
  479. str(timestamp % 1)[2:5])
  480. formatted_data = timestamp.encode() + b"\r\n" + data + b"\r\n"
  481. return formatted_data
  482. def _port_open(self):
  483. self.port_inst = serial.Serial(self.port, **self.serial_configs)
  484. def _port_close(self):
  485. self.port_inst.close()
  486. def _port_read(self, size=1):
  487. data = self.port_inst.read(size)
  488. if data:
  489. with open(self.log_file, "ab+") as _log_file:
  490. _log_file.write(self._format_data(data))
  491. return data
  492. def _port_write(self, data):
  493. if isinstance(data, str):
  494. data = data.encode()
  495. self.port_inst.write(data)
  496. @classmethod
  497. def list_available_ports(cls):
  498. return [x.device for x in list_ports.comports()]