IDFDUT.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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 functools
  16. import io
  17. import os
  18. import os.path
  19. import re
  20. import subprocess
  21. import sys
  22. import tempfile
  23. import time
  24. import pexpect
  25. # python2 and python3 queue package name is different
  26. try:
  27. import Queue as _queue
  28. except ImportError:
  29. import queue as _queue # type: ignore
  30. from serial.tools import list_ports
  31. from tiny_test_fw import DUT, Utility
  32. try:
  33. import esptool
  34. except ImportError: # cheat and use IDF's copy of esptool if available
  35. idf_path = os.getenv('IDF_PATH')
  36. if not idf_path or not os.path.exists(idf_path):
  37. raise
  38. sys.path.insert(0, os.path.join(idf_path, 'components', 'esptool_py', 'esptool'))
  39. import esptool
  40. class IDFToolError(OSError):
  41. pass
  42. class IDFDUTException(RuntimeError):
  43. pass
  44. class IDFRecvThread(DUT.RecvThread):
  45. PERFORMANCE_PATTERN = re.compile(r'\[Performance]\[(\w+)]: ([^\r\n]+)\r?\n')
  46. EXCEPTION_PATTERNS = [
  47. re.compile(r"(Guru Meditation Error: Core\s+\d panic'ed \([\w].*?\))"),
  48. re.compile(r'(abort\(\) was called at PC 0x[a-fA-F\d]{8} on core \d)'),
  49. re.compile(r'(rst 0x\d+ \(TG\dWDT_SYS_RESET|TGWDT_CPU_RESET\))')
  50. ]
  51. BACKTRACE_PATTERN = re.compile(r'Backtrace:((\s(0x[0-9a-f]{8}):0x[0-9a-f]{8})+)')
  52. BACKTRACE_ADDRESS_PATTERN = re.compile(r'(0x[0-9a-f]{8}):0x[0-9a-f]{8}')
  53. def __init__(self, read, dut):
  54. super(IDFRecvThread, self).__init__(read, dut)
  55. self.exceptions = _queue.Queue()
  56. self.performance_items = _queue.Queue()
  57. def collect_performance(self, comp_data):
  58. matches = self.PERFORMANCE_PATTERN.findall(comp_data)
  59. for match in matches:
  60. Utility.console_log('[Performance][{}]: {}'.format(match[0], match[1]), color='orange')
  61. self.performance_items.put((match[0], match[1]))
  62. def detect_exception(self, comp_data):
  63. for pattern in self.EXCEPTION_PATTERNS:
  64. start = 0
  65. while True:
  66. match = pattern.search(comp_data, pos=start)
  67. if match:
  68. start = match.end()
  69. self.exceptions.put(match.group(0))
  70. Utility.console_log('[Exception]: {}'.format(match.group(0)), color='red')
  71. else:
  72. break
  73. def detect_backtrace(self, comp_data):
  74. start = 0
  75. while True:
  76. match = self.BACKTRACE_PATTERN.search(comp_data, pos=start)
  77. if match:
  78. start = match.end()
  79. Utility.console_log('[Backtrace]:{}'.format(match.group(1)), color='red')
  80. # translate backtrace
  81. addresses = self.BACKTRACE_ADDRESS_PATTERN.findall(match.group(1))
  82. translated_backtrace = ''
  83. for addr in addresses:
  84. ret = self.dut.lookup_pc_address(addr)
  85. if ret:
  86. translated_backtrace += ret + '\n'
  87. if translated_backtrace:
  88. Utility.console_log('Translated backtrace\n:' + translated_backtrace, color='yellow')
  89. else:
  90. Utility.console_log('Failed to translate backtrace', color='yellow')
  91. else:
  92. break
  93. CHECK_FUNCTIONS = [collect_performance, detect_exception, detect_backtrace]
  94. def _uses_esptool(func):
  95. """ Suspend listener thread, connect with esptool,
  96. call target function with esptool instance,
  97. then resume listening for output
  98. """
  99. @functools.wraps(func)
  100. def handler(self, *args, **kwargs):
  101. self.stop_receive()
  102. settings = self.port_inst.get_settings()
  103. try:
  104. if not self._rom_inst:
  105. self._rom_inst = esptool.ESPLoader.detect_chip(self.port_inst)
  106. self._rom_inst.connect('hard_reset')
  107. esp = self._rom_inst.run_stub()
  108. ret = func(self, esp, *args, **kwargs)
  109. # do hard reset after use esptool
  110. esp.hard_reset()
  111. finally:
  112. # always need to restore port settings
  113. self.port_inst.apply_settings(settings)
  114. self.start_receive()
  115. return ret
  116. return handler
  117. class IDFDUT(DUT.SerialDUT):
  118. """ IDF DUT, extends serial with esptool methods
  119. (Becomes aware of IDFApp instance which holds app-specific data)
  120. """
  121. # /dev/ttyAMA0 port is listed in Raspberry Pi
  122. # /dev/tty.Bluetooth-Incoming-Port port is listed in Mac
  123. INVALID_PORT_PATTERN = re.compile(r'AMA|Bluetooth')
  124. # if need to erase NVS partition in start app
  125. ERASE_NVS = True
  126. RECV_THREAD_CLS = IDFRecvThread
  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. esp = None
  145. try:
  146. esp = cls._get_rom()(port)
  147. esp.connect()
  148. return esp.read_mac()
  149. except RuntimeError:
  150. return None
  151. finally:
  152. if esp:
  153. # do hard reset after use esptool
  154. esp.hard_reset()
  155. esp._port.close()
  156. @classmethod
  157. def confirm_dut(cls, port, **kwargs):
  158. inst = None
  159. try:
  160. expected_rom_class = cls._get_rom()
  161. except NotImplementedError:
  162. expected_rom_class = None
  163. try:
  164. # TODO: check whether 8266 works with this logic
  165. # Otherwise overwrite it in ESP8266DUT
  166. inst = esptool.ESPLoader.detect_chip(port)
  167. if expected_rom_class and type(inst) != expected_rom_class:
  168. raise RuntimeError('Target not expected')
  169. return inst.read_mac() is not None, get_target_by_rom_class(type(inst))
  170. except(esptool.FatalError, RuntimeError):
  171. return False, None
  172. finally:
  173. if inst is not None:
  174. inst._port.close()
  175. def _try_flash(self, erase_nvs):
  176. """
  177. Called by start_app()
  178. :return: None
  179. """
  180. flash_files = []
  181. encrypt_files = []
  182. try:
  183. # Open the files here to prevents us from having to seek back to 0
  184. # each time. Before opening them, we have to organize the lists the
  185. # way esptool.write_flash needs:
  186. # If encrypt is provided, flash_files contains all the files to
  187. # flash.
  188. # Else, flash_files contains the files to be flashed as plain text
  189. # and encrypt_files contains the ones to flash encrypted.
  190. flash_files = self.app.flash_files
  191. encrypt_files = self.app.encrypt_files
  192. encrypt = self.app.flash_settings.get('encrypt', False)
  193. if encrypt:
  194. flash_files = encrypt_files
  195. encrypt_files = []
  196. else:
  197. flash_files = [entry
  198. for entry in flash_files
  199. if entry not in encrypt_files]
  200. flash_files = [(offs, open(path, 'rb')) for (offs, path) in flash_files]
  201. encrypt_files = [(offs, open(path, 'rb')) for (offs, path) in encrypt_files]
  202. if erase_nvs:
  203. address = self.app.partition_table['nvs']['offset']
  204. size = self.app.partition_table['nvs']['size']
  205. nvs_file = tempfile.TemporaryFile()
  206. nvs_file.write(b'\xff' * size)
  207. nvs_file.seek(0)
  208. if not isinstance(address, int):
  209. address = int(address, 0)
  210. # We have to check whether this file needs to be added to
  211. # flash_files list or encrypt_files.
  212. # Get the CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT macro
  213. # value. If it is set to True, then NVS is always encrypted.
  214. sdkconfig_dict = self.app.get_sdkconfig()
  215. macro_encryption = 'CONFIG_SECURE_FLASH_ENCRYPTION_MODE_DEVELOPMENT' in sdkconfig_dict
  216. # If the macro is not enabled (plain text flash) or all files
  217. # must be encrypted, add NVS to flash_files.
  218. if not macro_encryption or encrypt:
  219. flash_files.append((address, nvs_file))
  220. else:
  221. encrypt_files.append((address, nvs_file))
  222. self._write_flash(flash_files, encrypt_files, False, encrypt)
  223. finally:
  224. for (_, f) in flash_files:
  225. f.close()
  226. for (_, f) in encrypt_files:
  227. f.close()
  228. @_uses_esptool
  229. def _write_flash(self, esp, flash_files=None, encrypt_files=None, ignore_flash_encryption_efuse_setting=True, encrypt=False):
  230. """
  231. Try flashing at a particular baud rate.
  232. Structured this way so @_uses_esptool will reconnect each time
  233. :return: None
  234. """
  235. last_error = None
  236. for baud_rate in [921600, 115200]:
  237. try:
  238. # fake flasher args object, this is a hack until
  239. # esptool Python API is improved
  240. class FlashArgs(object):
  241. def __init__(self, attributes):
  242. for key, value in attributes.items():
  243. self.__setattr__(key, value)
  244. # write_flash expects the parameter encrypt_files to be None and not
  245. # an empty list, so perform the check here
  246. flash_args = FlashArgs({
  247. 'flash_size': self.app.flash_settings['flash_size'],
  248. 'flash_mode': self.app.flash_settings['flash_mode'],
  249. 'flash_freq': self.app.flash_settings['flash_freq'],
  250. 'addr_filename': flash_files or None,
  251. 'encrypt_files': encrypt_files or None,
  252. 'no_stub': False,
  253. 'compress': True,
  254. 'verify': False,
  255. 'encrypt': encrypt,
  256. 'ignore_flash_encryption_efuse_setting': ignore_flash_encryption_efuse_setting,
  257. 'erase_all': False,
  258. 'after': 'no_reset',
  259. })
  260. esp.change_baud(baud_rate)
  261. esptool.detect_flash_size(esp, flash_args)
  262. esptool.write_flash(esp, flash_args)
  263. break
  264. except RuntimeError as e:
  265. last_error = e
  266. else:
  267. raise last_error
  268. def image_info(self, path_to_file):
  269. """
  270. get hash256 of app
  271. :param: path: path to file
  272. :return: sha256 appended to app
  273. """
  274. old_stdout = sys.stdout
  275. new_stdout = io.StringIO()
  276. sys.stdout = new_stdout
  277. class Args(object):
  278. def __init__(self, attributes):
  279. for key, value in attributes.items():
  280. self.__setattr__(key, value)
  281. args = Args({
  282. 'chip': self.TARGET,
  283. 'filename': path_to_file,
  284. })
  285. esptool.image_info(args)
  286. output = new_stdout.getvalue()
  287. sys.stdout = old_stdout
  288. return output
  289. def start_app(self, erase_nvs=ERASE_NVS):
  290. """
  291. download and start app.
  292. :param: erase_nvs: whether erase NVS partition during flash
  293. :return: None
  294. """
  295. self._try_flash(erase_nvs)
  296. def start_app_no_enc(self):
  297. """
  298. download and start app.
  299. :param: erase_nvs: whether erase NVS partition during flash
  300. :return: None
  301. """
  302. flash_files = self.app.flash_files + self.app.encrypt_files
  303. self.write_flash(flash_files)
  304. def write_flash(self, flash_files=None, encrypt_files=None, ignore_flash_encryption_efuse_setting=True, encrypt=False):
  305. """
  306. Flash files
  307. :return: None
  308. """
  309. flash_offs_files = []
  310. encrypt_offs_files = []
  311. try:
  312. if flash_files:
  313. flash_offs_files = [(offs, open(path, 'rb')) for (offs, path) in flash_files]
  314. if encrypt_files:
  315. encrypt_offs_files = [(offs, open(path, 'rb')) for (offs, path) in encrypt_files]
  316. self._write_flash(flash_offs_files, encrypt_offs_files, ignore_flash_encryption_efuse_setting, encrypt)
  317. finally:
  318. for (_, f) in flash_offs_files:
  319. f.close()
  320. for (_, f) in encrypt_offs_files:
  321. f.close()
  322. def bootloader_flash(self):
  323. """
  324. download bootloader.
  325. :return: None
  326. """
  327. bootloader_path = os.path.join(self.app.binary_path, 'bootloader', 'bootloader.bin')
  328. offs = int(self.app.get_sdkconfig()['CONFIG_BOOTLOADER_OFFSET_IN_FLASH'], 0)
  329. flash_files = [(offs, bootloader_path)]
  330. self.write_flash(flash_files)
  331. @_uses_esptool
  332. def reset(self, esp):
  333. """
  334. hard reset DUT
  335. :return: None
  336. """
  337. # decorator `_use_esptool` will do reset
  338. # so we don't need to do anything in this method
  339. pass
  340. @_uses_esptool
  341. def erase_partition(self, esp, partition):
  342. """
  343. :param partition: partition name to erase
  344. :return: None
  345. """
  346. address = self.app.partition_table[partition]['offset']
  347. size = self.app.partition_table[partition]['size']
  348. esp.erase_region(address, size)
  349. @_uses_esptool
  350. def erase_flash(self, esp):
  351. """
  352. erase the flash completely
  353. :return: None
  354. """
  355. esp.erase_flash()
  356. @_uses_esptool
  357. def dump_flash(self, esp, output_file, **kwargs):
  358. """
  359. dump flash
  360. :param output_file: output file name, if relative path, will use sdk path as base path.
  361. :keyword partition: partition name, dump the partition.
  362. ``partition`` is preferred than using ``address`` and ``size``.
  363. :keyword address: dump from address (need to be used with size)
  364. :keyword size: dump size (need to be used with address)
  365. :return: None
  366. """
  367. if os.path.isabs(output_file) is False:
  368. output_file = os.path.relpath(output_file, self.app.get_log_folder())
  369. if 'partition' in kwargs:
  370. partition = self.app.partition_table[kwargs['partition']]
  371. _address = partition['offset']
  372. _size = partition['size']
  373. elif 'address' in kwargs and 'size' in kwargs:
  374. _address = kwargs['address']
  375. _size = kwargs['size']
  376. else:
  377. raise IDFToolError("You must specify 'partition' or ('address' and 'size') to dump flash")
  378. content = esp.read_flash(_address, _size)
  379. with open(output_file, 'wb') as f:
  380. f.write(content)
  381. @staticmethod
  382. def _sort_usb_ports(ports):
  383. """
  384. Move the usb ports to the very beginning
  385. :param ports: list of ports
  386. :return: list of ports with usb ports at beginning
  387. """
  388. usb_ports = []
  389. rest_ports = []
  390. for port in ports:
  391. if 'usb' in port.lower():
  392. usb_ports.append(port)
  393. else:
  394. rest_ports.append(port)
  395. return usb_ports + rest_ports
  396. @classmethod
  397. def list_available_ports(cls):
  398. # It will return other kinds of ports as well, such as ttyS* ports.
  399. # Give the usb ports higher priority
  400. ports = cls._sort_usb_ports([x.device for x in list_ports.comports()])
  401. espport = os.getenv('ESPPORT')
  402. if not espport:
  403. # It's a little hard filter out invalid port with `serial.tools.list_ports.grep()`:
  404. # The check condition in `grep` is: `if r.search(port) or r.search(desc) or r.search(hwid)`.
  405. # This means we need to make all 3 conditions fail, to filter out the port.
  406. # So some part of the filters will not be straight forward to users.
  407. # And negative regular expression (`^((?!aa|bb|cc).)*$`) is not easy to understand.
  408. # Filter out invalid port by our own will be much simpler.
  409. return [x for x in ports if not cls.INVALID_PORT_PATTERN.search(x)]
  410. # On MacOs with python3.6: type of espport is already utf8
  411. if isinstance(espport, type(u'')):
  412. port_hint = espport
  413. else:
  414. port_hint = espport.decode('utf8')
  415. # If $ESPPORT is a valid port, make it appear first in the list
  416. if port_hint in ports:
  417. ports.remove(port_hint)
  418. return [port_hint] + ports
  419. # On macOS, user may set ESPPORT to /dev/tty.xxx while
  420. # pySerial lists only the corresponding /dev/cu.xxx port
  421. if sys.platform == 'darwin' and 'tty.' in port_hint:
  422. port_hint = port_hint.replace('tty.', 'cu.')
  423. if port_hint in ports:
  424. ports.remove(port_hint)
  425. return [port_hint] + ports
  426. return ports
  427. def lookup_pc_address(self, pc_addr):
  428. cmd = ['%saddr2line' % self.TOOLCHAIN_PREFIX,
  429. '-pfiaC', '-e', self.app.elf_file, pc_addr]
  430. ret = ''
  431. try:
  432. translation = subprocess.check_output(cmd)
  433. ret = translation.decode()
  434. except OSError:
  435. pass
  436. return ret
  437. @staticmethod
  438. def _queue_read_all(source_queue):
  439. output = []
  440. while True:
  441. try:
  442. output.append(source_queue.get(timeout=0))
  443. except _queue.Empty:
  444. break
  445. return output
  446. def _queue_copy(self, source_queue, dest_queue):
  447. data = self._queue_read_all(source_queue)
  448. for d in data:
  449. dest_queue.put(d)
  450. def _get_from_queue(self, queue_name):
  451. self_queue = getattr(self, queue_name)
  452. if self.receive_thread:
  453. recv_thread_queue = getattr(self.receive_thread, queue_name)
  454. self._queue_copy(recv_thread_queue, self_queue)
  455. return self._queue_read_all(self_queue)
  456. def stop_receive(self):
  457. if self.receive_thread:
  458. for name in ['performance_items', 'exceptions']:
  459. source_queue = getattr(self.receive_thread, name)
  460. dest_queue = getattr(self, name)
  461. self._queue_copy(source_queue, dest_queue)
  462. super(IDFDUT, self).stop_receive()
  463. def get_exceptions(self):
  464. """ Get exceptions detected by DUT receive thread. """
  465. return self._get_from_queue('exceptions')
  466. def get_performance_items(self):
  467. """
  468. DUT receive thread will automatic collect performance results with pattern ``[Performance][name]: value\n``.
  469. This method is used to get all performance results.
  470. :return: a list of performance items.
  471. """
  472. return self._get_from_queue('performance_items')
  473. def close(self):
  474. super(IDFDUT, self).close()
  475. if not self.allow_dut_exception and self.get_exceptions():
  476. raise IDFDUTException('DUT exception detected on {}'.format(self))
  477. class ESP32DUT(IDFDUT):
  478. TARGET = 'esp32'
  479. TOOLCHAIN_PREFIX = 'xtensa-esp32-elf-'
  480. @classmethod
  481. def _get_rom(cls):
  482. return esptool.ESP32ROM
  483. class ESP32S2DUT(IDFDUT):
  484. TARGET = 'esp32s2'
  485. TOOLCHAIN_PREFIX = 'xtensa-esp32s2-elf-'
  486. @classmethod
  487. def _get_rom(cls):
  488. return esptool.ESP32S2ROM
  489. class ESP32S3DUT(IDFDUT):
  490. TARGET = 'esp32s3'
  491. TOOLCHAIN_PREFIX = 'xtensa-esp32s3-elf-'
  492. @classmethod
  493. def _get_rom(cls):
  494. return esptool.ESP32S3ROM
  495. def erase_partition(self, esp, partition):
  496. raise NotImplementedError()
  497. class ESP32C3DUT(IDFDUT):
  498. TARGET = 'esp32c3'
  499. TOOLCHAIN_PREFIX = 'riscv32-esp-elf-'
  500. @classmethod
  501. def _get_rom(cls):
  502. return esptool.ESP32C3ROM
  503. class ESP8266DUT(IDFDUT):
  504. TARGET = 'esp8266'
  505. TOOLCHAIN_PREFIX = 'xtensa-lx106-elf-'
  506. @classmethod
  507. def _get_rom(cls):
  508. return esptool.ESP8266ROM
  509. def get_target_by_rom_class(cls):
  510. for c in [ESP32DUT, ESP32S2DUT, ESP32S3DUT, ESP32C3DUT, ESP8266DUT, IDFQEMUDUT]:
  511. if c._get_rom() == cls:
  512. return c.TARGET
  513. return None
  514. class IDFQEMUDUT(IDFDUT):
  515. TARGET = None
  516. TOOLCHAIN_PREFIX = None
  517. ERASE_NVS = True
  518. DEFAULT_EXPECT_TIMEOUT = 30 # longer timeout, since app startup takes more time in QEMU (due to slow SHA emulation)
  519. QEMU_SERIAL_PORT = 3334
  520. def __init__(self, name, port, log_file, app, allow_dut_exception=False, **kwargs):
  521. self.flash_image = tempfile.NamedTemporaryFile('rb+', suffix='.bin', prefix='qemu_flash_img')
  522. self.app = app
  523. self.flash_size = 4 * 1024 * 1024
  524. self._write_flash_img()
  525. args = [
  526. 'qemu-system-xtensa',
  527. '-nographic',
  528. '-machine', self.TARGET,
  529. '-drive', 'file={},if=mtd,format=raw'.format(self.flash_image.name),
  530. '-nic', 'user,model=open_eth',
  531. '-serial', 'tcp::{},server,nowait'.format(self.QEMU_SERIAL_PORT),
  532. '-S',
  533. '-global driver=timer.esp32.timg,property=wdt_disable,value=true']
  534. # TODO(IDF-1242): generate a temporary efuse binary, pass it to QEMU
  535. if 'QEMU_BIOS_PATH' in os.environ:
  536. args += ['-L', os.environ['QEMU_BIOS_PATH']]
  537. self.qemu = pexpect.spawn(' '.join(args), timeout=self.DEFAULT_EXPECT_TIMEOUT)
  538. self.qemu.expect_exact(b'(qemu)')
  539. super(IDFQEMUDUT, self).__init__(name, port, log_file, app, allow_dut_exception=allow_dut_exception, **kwargs)
  540. def _write_flash_img(self):
  541. self.flash_image.seek(0)
  542. self.flash_image.write(b'\x00' * self.flash_size)
  543. for offs, path in self.app.flash_files:
  544. with open(path, 'rb') as flash_file:
  545. contents = flash_file.read()
  546. self.flash_image.seek(offs)
  547. self.flash_image.write(contents)
  548. self.flash_image.flush()
  549. @classmethod
  550. def _get_rom(cls):
  551. return esptool.ESP32ROM
  552. @classmethod
  553. def get_mac(cls, app, port):
  554. # TODO(IDF-1242): get this from QEMU/efuse binary
  555. return '11:22:33:44:55:66'
  556. @classmethod
  557. def confirm_dut(cls, port, **kwargs):
  558. return True, cls.TARGET
  559. def start_app(self, erase_nvs=ERASE_NVS):
  560. # TODO: implement erase_nvs
  561. # since the flash image is generated every time in the constructor, maybe this isn't needed...
  562. self.qemu.sendline(b'cont\n')
  563. self.qemu.expect_exact(b'(qemu)')
  564. def reset(self):
  565. self.qemu.sendline(b'system_reset\n')
  566. self.qemu.expect_exact(b'(qemu)')
  567. def erase_partition(self, partition):
  568. raise NotImplementedError('method erase_partition not implemented')
  569. def erase_flash(self):
  570. raise NotImplementedError('method erase_flash not implemented')
  571. def dump_flash(self, output_file, **kwargs):
  572. raise NotImplementedError('method dump_flash not implemented')
  573. @classmethod
  574. def list_available_ports(cls):
  575. return ['socket://localhost:{}'.format(cls.QEMU_SERIAL_PORT)]
  576. def close(self):
  577. super(IDFQEMUDUT, self).close()
  578. self.qemu.sendline(b'q\n')
  579. self.qemu.expect_exact(b'(qemu)')
  580. for _ in range(self.DEFAULT_EXPECT_TIMEOUT):
  581. if not self.qemu.isalive():
  582. break
  583. time.sleep(1)
  584. else:
  585. self.qemu.terminate(force=True)
  586. class ESP32QEMUDUT(IDFQEMUDUT):
  587. TARGET = 'esp32' # type: ignore
  588. TOOLCHAIN_PREFIX = 'xtensa-esp32-elf-' # type: ignore