IDFDUT.py 13 KB

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