IDFDUT.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. """ DUT for IDF applications """
  15. import os
  16. import os.path
  17. import sys
  18. import re
  19. import functools
  20. import tempfile
  21. import subprocess
  22. # python2 and python3 queue package name is different
  23. try:
  24. import Queue as _queue
  25. except ImportError:
  26. import queue as _queue
  27. from serial.tools import list_ports
  28. from tiny_test_fw import DUT, Utility
  29. try:
  30. import esptool
  31. except ImportError: # cheat and use IDF's copy of esptool if available
  32. idf_path = os.getenv("IDF_PATH")
  33. if not idf_path or not os.path.exists(idf_path):
  34. raise
  35. sys.path.insert(0, os.path.join(idf_path, "components", "esptool_py", "esptool"))
  36. import esptool
  37. class IDFToolError(OSError):
  38. pass
  39. class IDFDUTException(RuntimeError):
  40. pass
  41. class IDFRecvThread(DUT.RecvThread):
  42. PERFORMANCE_PATTERN = re.compile(r"\[Performance]\[(\w+)]: ([^\r\n]+)\r?\n")
  43. EXCEPTION_PATTERNS = [
  44. re.compile(r"(Guru Meditation Error: Core\s+\d panic'ed \([\w].*?\))"),
  45. re.compile(r"(abort\(\) was called at PC 0x[a-fA-F\d]{8} on core \d)"),
  46. re.compile(r"(rst 0x\d+ \(TG\dWDT_SYS_RESET|TGWDT_CPU_RESET\))")
  47. ]
  48. BACKTRACE_PATTERN = re.compile(r"Backtrace:((\s(0x[0-9a-f]{8}):0x[0-9a-f]{8})+)")
  49. BACKTRACE_ADDRESS_PATTERN = re.compile(r"(0x[0-9a-f]{8}):0x[0-9a-f]{8}")
  50. def __init__(self, read, dut):
  51. super(IDFRecvThread, self).__init__(read, dut)
  52. self.exceptions = _queue.Queue()
  53. self.performance_items = _queue.Queue()
  54. def collect_performance(self, comp_data):
  55. matches = self.PERFORMANCE_PATTERN.findall(comp_data)
  56. for match in matches:
  57. Utility.console_log("[Performance][{}]: {}".format(match[0], match[1]),
  58. color="orange")
  59. self.performance_items.put((match[0], match[1]))
  60. def detect_exception(self, comp_data):
  61. for pattern in self.EXCEPTION_PATTERNS:
  62. start = 0
  63. while True:
  64. match = pattern.search(comp_data, pos=start)
  65. if match:
  66. start = match.end()
  67. self.exceptions.put(match.group(0))
  68. Utility.console_log("[Exception]: {}".format(match.group(0)), color="red")
  69. else:
  70. break
  71. def detect_backtrace(self, comp_data):
  72. start = 0
  73. while True:
  74. match = self.BACKTRACE_PATTERN.search(comp_data, pos=start)
  75. if match:
  76. start = match.end()
  77. Utility.console_log("[Backtrace]:{}".format(match.group(1)), color="red")
  78. # translate backtrace
  79. addresses = self.BACKTRACE_ADDRESS_PATTERN.findall(match.group(1))
  80. translated_backtrace = ""
  81. for addr in addresses:
  82. ret = self.dut.lookup_pc_address(addr)
  83. if ret:
  84. translated_backtrace += ret + "\n"
  85. if translated_backtrace:
  86. Utility.console_log("Translated backtrace\n:" + translated_backtrace, color="yellow")
  87. else:
  88. Utility.console_log("Failed to translate backtrace", color="yellow")
  89. else:
  90. break
  91. CHECK_FUNCTIONS = [collect_performance, detect_exception, detect_backtrace]
  92. def _uses_esptool(func):
  93. """ Suspend listener thread, connect with esptool,
  94. call target function with esptool instance,
  95. then resume listening for output
  96. """
  97. @functools.wraps(func)
  98. def handler(self, *args, **kwargs):
  99. self.stop_receive()
  100. settings = self.port_inst.get_settings()
  101. try:
  102. if not self._rom_inst:
  103. self._rom_inst = esptool.ESPLoader.detect_chip(self.port_inst)
  104. self._rom_inst.connect('hard_reset')
  105. esp = self._rom_inst.run_stub()
  106. ret = func(self, esp, *args, **kwargs)
  107. # do hard reset after use esptool
  108. esp.hard_reset()
  109. finally:
  110. # always need to restore port settings
  111. self.port_inst.apply_settings(settings)
  112. self.start_receive()
  113. return ret
  114. return handler
  115. class IDFDUT(DUT.SerialDUT):
  116. """ IDF DUT, extends serial with esptool methods
  117. (Becomes aware of IDFApp instance which holds app-specific data)
  118. """
  119. # /dev/ttyAMA0 port is listed in Raspberry Pi
  120. # /dev/tty.Bluetooth-Incoming-Port port is listed in Mac
  121. INVALID_PORT_PATTERN = re.compile(r"AMA|Bluetooth")
  122. # if need to erase NVS partition in start app
  123. ERASE_NVS = True
  124. RECV_THREAD_CLS = IDFRecvThread
  125. def __init__(self, name, port, log_file, app, allow_dut_exception=False, **kwargs):
  126. super(IDFDUT, self).__init__(name, port, log_file, app, **kwargs)
  127. self.allow_dut_exception = allow_dut_exception
  128. self.exceptions = _queue.Queue()
  129. self.performance_items = _queue.Queue()
  130. self._rom_inst = None
  131. @classmethod
  132. def _get_rom(cls):
  133. raise NotImplementedError("This is an abstraction class, method not defined.")
  134. @classmethod
  135. def get_mac(cls, app, port):
  136. """
  137. get MAC address via esptool
  138. :param app: application instance (to get tool)
  139. :param port: serial port as string
  140. :return: MAC address or None
  141. """
  142. esp = None
  143. try:
  144. esp = cls._get_rom()(port)
  145. esp.connect()
  146. return esp.read_mac()
  147. except RuntimeError:
  148. return None
  149. finally:
  150. if esp:
  151. # do hard reset after use esptool
  152. esp.hard_reset()
  153. esp._port.close()
  154. @classmethod
  155. def confirm_dut(cls, port, **kwargs):
  156. inst = None
  157. try:
  158. expected_rom_class = cls._get_rom()
  159. except NotImplementedError:
  160. expected_rom_class = None
  161. try:
  162. # TODO: check whether 8266 works with this logic
  163. # Otherwise overwrite it in ESP8266DUT
  164. inst = esptool.ESPLoader.detect_chip(port)
  165. if expected_rom_class and type(inst) != expected_rom_class:
  166. raise RuntimeError("Target not expected")
  167. return inst.read_mac() is not None, get_target_by_rom_class(type(inst))
  168. except(esptool.FatalError, RuntimeError):
  169. return False, None
  170. finally:
  171. if inst is not None:
  172. inst._port.close()
  173. @_uses_esptool
  174. def _try_flash(self, esp, erase_nvs, baud_rate):
  175. """
  176. Called by start_app() to try flashing at a particular baud rate.
  177. Structured this way so @_uses_esptool will reconnect each time
  178. """
  179. flash_files = []
  180. try:
  181. # note: opening here prevents us from having to seek back to 0 each time
  182. flash_files = [(offs, open(path, "rb")) for (offs, path) in self.app.flash_files]
  183. if erase_nvs:
  184. address = self.app.partition_table["nvs"]["offset"]
  185. size = self.app.partition_table["nvs"]["size"]
  186. nvs_file = tempfile.TemporaryFile()
  187. nvs_file.write(b'\xff' * size)
  188. nvs_file.seek(0)
  189. flash_files.append((int(address, 0), nvs_file))
  190. # fake flasher args object, this is a hack until
  191. # esptool Python API is improved
  192. class FlashArgs(object):
  193. def __init__(self, attributes):
  194. for key, value in attributes.items():
  195. self.__setattr__(key, value)
  196. flash_args = FlashArgs({
  197. 'flash_size': self.app.flash_settings["flash_size"],
  198. 'flash_mode': self.app.flash_settings["flash_mode"],
  199. 'flash_freq': self.app.flash_settings["flash_freq"],
  200. 'addr_filename': flash_files,
  201. 'no_stub': False,
  202. 'compress': True,
  203. 'verify': False,
  204. 'encrypt': self.app.flash_settings.get("encrypt", False),
  205. 'erase_all': False,
  206. })
  207. esp.change_baud(baud_rate)
  208. esptool.detect_flash_size(esp, flash_args)
  209. esptool.write_flash(esp, flash_args)
  210. finally:
  211. for (_, f) in flash_files:
  212. f.close()
  213. def start_app(self, erase_nvs=ERASE_NVS):
  214. """
  215. download and start app.
  216. :param: erase_nvs: whether erase NVS partition during flash
  217. :return: None
  218. """
  219. for baud_rate in [921600, 115200]:
  220. try:
  221. self._try_flash(erase_nvs, baud_rate)
  222. break
  223. except RuntimeError:
  224. continue
  225. else:
  226. raise IDFToolError()
  227. @_uses_esptool
  228. def reset(self, esp):
  229. """
  230. hard reset DUT
  231. :return: None
  232. """
  233. # decorator `_use_esptool` will do reset
  234. # so we don't need to do anything in this method
  235. pass
  236. @_uses_esptool
  237. def erase_partition(self, esp, partition):
  238. """
  239. :param partition: partition name to erase
  240. :return: None
  241. """
  242. raise NotImplementedError() # TODO: implement this
  243. # address = self.app.partition_table[partition]["offset"]
  244. size = self.app.partition_table[partition]["size"]
  245. # TODO can use esp.erase_region() instead of this, I think
  246. with open(".erase_partition.tmp", "wb") as f:
  247. f.write(chr(0xFF) * size)
  248. @_uses_esptool
  249. def dump_flush(self, esp, output_file, **kwargs):
  250. """
  251. dump flush
  252. :param output_file: output file name, if relative path, will use sdk path as base path.
  253. :keyword partition: partition name, dump the partition.
  254. ``partition`` is preferred than using ``address`` and ``size``.
  255. :keyword address: dump from address (need to be used with size)
  256. :keyword size: dump size (need to be used with address)
  257. :return: None
  258. """
  259. if os.path.isabs(output_file) is False:
  260. output_file = os.path.relpath(output_file, self.app.get_log_folder())
  261. if "partition" in kwargs:
  262. partition = self.app.partition_table[kwargs["partition"]]
  263. _address = partition["offset"]
  264. _size = partition["size"]
  265. elif "address" in kwargs and "size" in kwargs:
  266. _address = kwargs["address"]
  267. _size = kwargs["size"]
  268. else:
  269. raise IDFToolError("You must specify 'partition' or ('address' and 'size') to dump flash")
  270. content = esp.read_flash(_address, _size)
  271. with open(output_file, "wb") as f:
  272. f.write(content)
  273. @classmethod
  274. def list_available_ports(cls):
  275. ports = [x.device for x in list_ports.comports()]
  276. espport = os.getenv('ESPPORT')
  277. if not espport:
  278. # It's a little hard filter out invalid port with `serial.tools.list_ports.grep()`:
  279. # The check condition in `grep` is: `if r.search(port) or r.search(desc) or r.search(hwid)`.
  280. # This means we need to make all 3 conditions fail, to filter out the port.
  281. # So some part of the filters will not be straight forward to users.
  282. # And negative regular expression (`^((?!aa|bb|cc).)*$`) is not easy to understand.
  283. # Filter out invalid port by our own will be much simpler.
  284. return [x for x in ports if not cls.INVALID_PORT_PATTERN.search(x)]
  285. # On MacOs with python3.6: type of espport is already utf8
  286. if isinstance(espport, type(u'')):
  287. port_hint = espport
  288. else:
  289. port_hint = espport.decode('utf8')
  290. # If $ESPPORT is a valid port, make it appear first in the list
  291. if port_hint in ports:
  292. ports.remove(port_hint)
  293. return [port_hint] + ports
  294. # On macOS, user may set ESPPORT to /dev/tty.xxx while
  295. # pySerial lists only the corresponding /dev/cu.xxx port
  296. if sys.platform == 'darwin' and 'tty.' in port_hint:
  297. port_hint = port_hint.replace('tty.', 'cu.')
  298. if port_hint in ports:
  299. ports.remove(port_hint)
  300. return [port_hint] + ports
  301. return ports
  302. def lookup_pc_address(self, pc_addr):
  303. cmd = ["%saddr2line" % self.TOOLCHAIN_PREFIX,
  304. "-pfiaC", "-e", self.app.elf_file, pc_addr]
  305. ret = ""
  306. try:
  307. translation = subprocess.check_output(cmd)
  308. ret = translation.decode()
  309. except OSError:
  310. pass
  311. return ret
  312. @staticmethod
  313. def _queue_read_all(source_queue):
  314. output = []
  315. while True:
  316. try:
  317. output.append(source_queue.get(timeout=0))
  318. except _queue.Empty:
  319. break
  320. return output
  321. def _queue_copy(self, source_queue, dest_queue):
  322. data = self._queue_read_all(source_queue)
  323. for d in data:
  324. dest_queue.put(d)
  325. def _get_from_queue(self, queue_name):
  326. self_queue = getattr(self, queue_name)
  327. if self.receive_thread:
  328. recv_thread_queue = getattr(self.receive_thread, queue_name)
  329. self._queue_copy(recv_thread_queue, self_queue)
  330. return self._queue_read_all(self_queue)
  331. def stop_receive(self):
  332. if self.receive_thread:
  333. for name in ["performance_items", "exceptions"]:
  334. source_queue = getattr(self.receive_thread, name)
  335. dest_queue = getattr(self, name)
  336. self._queue_copy(source_queue, dest_queue)
  337. super(IDFDUT, self).stop_receive()
  338. def get_exceptions(self):
  339. """ Get exceptions detected by DUT receive thread. """
  340. return self._get_from_queue("exceptions")
  341. def get_performance_items(self):
  342. """
  343. DUT receive thread will automatic collect performance results with pattern ``[Performance][name]: value\n``.
  344. This method is used to get all performance results.
  345. :return: a list of performance items.
  346. """
  347. return self._get_from_queue("performance_items")
  348. def close(self):
  349. super(IDFDUT, self).close()
  350. if not self.allow_dut_exception and self.get_exceptions():
  351. Utility.console_log("DUT exception detected on {}".format(self), color="red")
  352. raise IDFDUTException()
  353. class ESP32DUT(IDFDUT):
  354. TARGET = "esp32"
  355. TOOLCHAIN_PREFIX = "xtensa-esp32-elf-"
  356. @classmethod
  357. def _get_rom(cls):
  358. return esptool.ESP32ROM
  359. class ESP32S2DUT(IDFDUT):
  360. TARGET = "esp32s2beta"
  361. TOOLCHAIN_PREFIX = "xtensa-esp32s2-elf-"
  362. @classmethod
  363. def _get_rom(cls):
  364. return esptool.ESP32S2ROM
  365. class ESP8266DUT(IDFDUT):
  366. TARGET = "esp8266"
  367. TOOLCHAIN_PREFIX = "xtensa-lx106-elf-"
  368. @classmethod
  369. def _get_rom(cls):
  370. return esptool.ESP8266ROM
  371. def get_target_by_rom_class(cls):
  372. for c in [ESP32DUT, ESP32S2DUT, ESP8266DUT]:
  373. if c._get_rom() == cls:
  374. return c.TARGET
  375. return None