serial_ext.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. # SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import json
  4. import os
  5. import sys
  6. import click
  7. from idf_monitor_base.output_helpers import yellow_print
  8. from idf_py_actions.errors import FatalError, NoSerialPortFoundError
  9. from idf_py_actions.global_options import global_options
  10. from idf_py_actions.tools import ensure_build_directory, get_sdkconfig_value, run_target, run_tool
  11. PYTHON = sys.executable
  12. def action_extensions(base_actions, project_path):
  13. def _get_project_desc(ctx, args):
  14. desc_path = os.path.join(args.build_dir, 'project_description.json')
  15. if not os.path.exists(desc_path):
  16. ensure_build_directory(args, ctx.info_name)
  17. with open(desc_path, 'r') as f:
  18. project_desc = json.load(f)
  19. return project_desc
  20. def _get_default_serial_port(args):
  21. # Import is done here in order to move it after the check_environment() ensured that pyserial has been installed
  22. try:
  23. import serial.tools.list_ports
  24. esptool_path = os.path.join(os.environ['IDF_PATH'], 'components/esptool_py/esptool/')
  25. sys.path.insert(0, esptool_path)
  26. import esptool
  27. ports = list(sorted(p.device for p in serial.tools.list_ports.comports()))
  28. # high baud rate could cause the failure of creation of the connection
  29. esp = esptool.get_default_connected_device(serial_list=ports, port=None, connect_attempts=4,
  30. initial_baud=115200)
  31. if esp is None:
  32. raise NoSerialPortFoundError(
  33. "No serial ports found. Connect a device, or use '-p PORT' option to set a specific port.")
  34. serial_port = esp.serial_port
  35. esp._port.close()
  36. return serial_port
  37. except NoSerialPortFoundError:
  38. raise
  39. except Exception as e:
  40. raise FatalError('An exception occurred during detection of the serial port: {}'.format(e))
  41. def _get_esptool_args(args):
  42. esptool_path = os.path.join(os.environ['IDF_PATH'], 'components/esptool_py/esptool/esptool.py')
  43. esptool_wrapper_path = os.environ.get('ESPTOOL_WRAPPER', '')
  44. if args.port is None:
  45. args.port = _get_default_serial_port(args)
  46. result = [PYTHON]
  47. if os.path.exists(esptool_wrapper_path):
  48. result += [esptool_wrapper_path]
  49. result += [esptool_path]
  50. result += ['-p', args.port]
  51. result += ['-b', str(args.baud)]
  52. with open(os.path.join(args.build_dir, 'flasher_args.json')) as f:
  53. flasher_args = json.load(f)
  54. extra_esptool_args = flasher_args['extra_esptool_args']
  55. result += ['--before', extra_esptool_args['before']]
  56. result += ['--after', extra_esptool_args['after']]
  57. result += ['--chip', extra_esptool_args['chip']]
  58. if not extra_esptool_args['stub']:
  59. result += ['--no-stub']
  60. return result
  61. def _get_commandline_options(ctx):
  62. """ Return all the command line options up to first action """
  63. # This approach ignores argument parsing done Click
  64. result = []
  65. for arg in sys.argv:
  66. if arg in ctx.command.commands_with_aliases:
  67. break
  68. result.append(arg)
  69. return result
  70. def monitor(action, ctx, args, print_filter, monitor_baud, encrypted, timestamps, timestamp_format):
  71. """
  72. Run idf_monitor.py to watch build output
  73. """
  74. project_desc = _get_project_desc(ctx, args)
  75. elf_file = os.path.join(args.build_dir, project_desc['app_elf'])
  76. if not os.path.exists(elf_file):
  77. raise FatalError("ELF file '%s' not found. You need to build & flash the project before running 'monitor', "
  78. 'and the binary on the device must match the one in the build directory exactly. '
  79. "Try '%s flash monitor'." % (elf_file, ctx.info_name), ctx)
  80. idf_monitor = os.path.join(os.environ['IDF_PATH'], 'tools/idf_monitor.py')
  81. monitor_args = [PYTHON, idf_monitor]
  82. if project_desc['target'] != 'linux':
  83. esp_port = args.port or _get_default_serial_port(args)
  84. monitor_args += ['-p', esp_port]
  85. if not monitor_baud:
  86. monitor_baud = os.getenv('IDF_MONITOR_BAUD') or os.getenv('MONITORBAUD') or project_desc['monitor_baud']
  87. monitor_args += ['-b', monitor_baud]
  88. monitor_args += ['--toolchain-prefix', project_desc['monitor_toolprefix']]
  89. coredump_decode = get_sdkconfig_value(project_desc['config_file'], 'CONFIG_ESP_COREDUMP_DECODE')
  90. if coredump_decode is not None:
  91. monitor_args += ['--decode-coredumps', coredump_decode]
  92. target_arch_riscv = get_sdkconfig_value(project_desc['config_file'], 'CONFIG_IDF_TARGET_ARCH_RISCV')
  93. monitor_args += ['--target', project_desc['target']]
  94. revision = project_desc.get('rev')
  95. if revision:
  96. monitor_args += ['--revision', revision]
  97. if target_arch_riscv:
  98. monitor_args += ['--decode-panic', 'backtrace']
  99. if print_filter is not None:
  100. monitor_args += ['--print_filter', print_filter]
  101. monitor_args += [elf_file]
  102. if encrypted:
  103. monitor_args += ['--encrypted']
  104. if timestamps:
  105. monitor_args += ['--timestamps']
  106. if timestamp_format:
  107. monitor_args += ['--timestamp-format', timestamp_format]
  108. idf_py = [PYTHON] + _get_commandline_options(ctx) # commands to re-run idf.py
  109. monitor_args += ['-m', ' '.join("'%s'" % a for a in idf_py)]
  110. if 'MSYSTEM' in os.environ:
  111. monitor_args = ['winpty'] + monitor_args
  112. run_tool('idf_monitor', monitor_args, args.project_dir)
  113. def flash(action, ctx, args):
  114. """
  115. Run esptool to flash the entire project, from an argfile generated by the build system
  116. """
  117. ensure_build_directory(args, ctx.info_name)
  118. project_desc = _get_project_desc(ctx, args)
  119. if project_desc['target'] == 'linux':
  120. yellow_print('skipping flash since running on linux...')
  121. return
  122. esp_port = args.port or _get_default_serial_port(args)
  123. run_target(action, args, {'ESPBAUD': str(args.baud), 'ESPPORT': esp_port})
  124. def erase_flash(action, ctx, args):
  125. ensure_build_directory(args, ctx.info_name)
  126. esptool_args = _get_esptool_args(args)
  127. esptool_args += ['erase_flash']
  128. run_tool('esptool.py', esptool_args, args.build_dir)
  129. def global_callback(ctx, global_args, tasks):
  130. encryption = any([task.name in ('encrypted-flash', 'encrypted-app-flash') for task in tasks])
  131. if encryption:
  132. for task in tasks:
  133. if task.name == 'monitor':
  134. task.action_args['encrypted'] = True
  135. break
  136. baud_rate = {
  137. 'names': ['-b', '--baud'],
  138. 'help': 'Baud rate for flashing.',
  139. 'scope': 'global',
  140. 'envvar': 'ESPBAUD',
  141. 'default': 460800,
  142. }
  143. port = {
  144. 'names': ['-p', '--port'],
  145. 'help': 'Serial port.',
  146. 'scope': 'global',
  147. 'envvar': 'ESPPORT',
  148. 'default': None,
  149. }
  150. serial_actions = {
  151. 'global_action_callbacks': [global_callback],
  152. 'actions': {
  153. 'flash': {
  154. 'callback': flash,
  155. 'help': 'Flash the project.',
  156. 'options': global_options + [baud_rate, port],
  157. 'order_dependencies': ['all', 'erase-flash'],
  158. },
  159. 'erase-flash': {
  160. 'callback': erase_flash,
  161. 'help': 'Erase entire flash chip. Deprecated alias: "erase_flash"',
  162. 'options': [baud_rate, port],
  163. },
  164. 'erase_flash': {
  165. 'callback': erase_flash,
  166. 'deprecated': {
  167. 'removed': 'v5.0',
  168. 'message': 'Please use "erase-flash" instead.',
  169. },
  170. 'hidden': True,
  171. 'help': 'Erase entire flash chip.',
  172. 'options': [baud_rate, port],
  173. },
  174. 'monitor': {
  175. 'callback':
  176. monitor,
  177. 'help':
  178. 'Display serial output.',
  179. 'options': [
  180. port, {
  181. 'names': ['--print-filter', '--print_filter'],
  182. 'help':
  183. ('Filter monitor output. '
  184. 'Restrictions on what to print can be specified as a series of <tag>:<log_level> items '
  185. 'where <tag> is the tag string and <log_level> is a character from the set '
  186. '{N, E, W, I, D, V, *} referring to a level. '
  187. 'For example, "tag1:W" matches and prints only the outputs written with '
  188. 'ESP_LOGW("tag1", ...) or at lower verbosity level, i.e. ESP_LOGE("tag1", ...). '
  189. 'Not specifying a <log_level> or using "*" defaults to Verbose level. '
  190. 'Please see the IDF Monitor section of the ESP-IDF documentation '
  191. 'for a more detailed description and further examples.'),
  192. 'default':
  193. None,
  194. }, {
  195. 'names': ['--monitor-baud', '-B'],
  196. 'type':
  197. click.INT,
  198. 'help': ('Baud rate for monitor. '
  199. 'If this option is not provided IDF_MONITOR_BAUD and MONITORBAUD '
  200. 'environment variables and project_description.json in build directory '
  201. "(generated by CMake from project's sdkconfig) "
  202. 'will be checked for default value.'),
  203. }, {
  204. 'names': ['--encrypted', '-E'],
  205. 'is_flag': True,
  206. 'help': ('Enable encrypted flash targets. '
  207. 'IDF Monitor will invoke encrypted-flash and encrypted-app-flash targets '
  208. 'if this option is set. This option is set by default if IDF Monitor was invoked '
  209. 'together with encrypted-flash or encrypted-app-flash target.'),
  210. }, {
  211. 'names': ['--timestamps'],
  212. 'is_flag': True,
  213. 'help': 'Print a time stamp in the beginning of each line.',
  214. }, {
  215. 'names': ['--timestamp-format'],
  216. 'help': ('Set the formatting of timestamps compatible with strftime(). '
  217. 'For example, "%Y-%m-%d %H:%M:%S".'),
  218. 'default': None
  219. }
  220. ],
  221. 'order_dependencies': [
  222. 'flash',
  223. 'encrypted-flash',
  224. 'partition-table-flash',
  225. 'bootloader-flash',
  226. 'app-flash',
  227. 'encrypted-app-flash',
  228. ],
  229. },
  230. 'partition-table-flash': {
  231. 'callback': flash,
  232. 'help': 'Flash partition table only. Deprecated alias: "partition_table-flash".',
  233. 'options': [baud_rate, port],
  234. 'order_dependencies': ['partition-table', 'erase-flash'],
  235. },
  236. 'partition_table-flash': {
  237. 'callback': flash,
  238. 'hidden': True,
  239. 'help': 'Flash partition table only.',
  240. 'options': [baud_rate, port],
  241. 'order_dependencies': ['partition-table', 'erase-flash'],
  242. },
  243. 'bootloader-flash': {
  244. 'callback': flash,
  245. 'help': 'Flash bootloader only.',
  246. 'options': [baud_rate, port],
  247. 'order_dependencies': ['bootloader', 'erase-flash'],
  248. },
  249. 'app-flash': {
  250. 'callback': flash,
  251. 'help': 'Flash the app only.',
  252. 'options': [baud_rate, port],
  253. 'order_dependencies': ['app', 'erase-flash'],
  254. },
  255. 'encrypted-app-flash': {
  256. 'callback': flash,
  257. 'help': 'Flash the encrypted app only.',
  258. 'order_dependencies': ['app', 'erase-flash'],
  259. },
  260. 'encrypted-flash': {
  261. 'callback': flash,
  262. 'help': 'Flash the encrypted project.',
  263. 'order_dependencies': ['all', 'erase-flash'],
  264. },
  265. },
  266. }
  267. return serial_actions