IDFDUT.py 15 KB

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