serial_ext.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. # SPDX-FileCopyrightText: 2021-2023 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import json
  4. import os
  5. import shlex
  6. import signal
  7. import sys
  8. from typing import Any, Dict, List, Optional
  9. import click
  10. from idf_py_actions.global_options import global_options
  11. from idf_py_actions.tools import (PropertyDict, RunTool, ensure_build_directory, get_default_serial_port,
  12. get_sdkconfig_value, run_target)
  13. PYTHON = sys.executable
  14. BAUD_RATE = {
  15. 'names': ['-b', '--baud'],
  16. 'help': 'Baud rate for flashing. It can imply monitor baud rate as well if it hasn\'t been defined locally.',
  17. 'scope': 'global',
  18. 'envvar': 'ESPBAUD',
  19. 'default': 460800,
  20. }
  21. PORT = {
  22. 'names': ['-p', '--port'],
  23. 'help': 'Serial port.',
  24. 'scope': 'global',
  25. 'envvar': 'ESPPORT',
  26. 'type': click.Path(),
  27. 'default': None,
  28. }
  29. def yellow_print(message, newline='\n'): # type: (str, Optional[str]) -> None
  30. """Print a message to stderr with yellow highlighting """
  31. sys.stderr.write('%s%s%s%s' % ('\033[0;33m', message, '\033[0m', newline))
  32. sys.stderr.flush()
  33. def action_extensions(base_actions: Dict, project_path: str) -> Dict:
  34. def _get_project_desc(ctx: click.core.Context, args: PropertyDict) -> Any:
  35. desc_path = os.path.join(args.build_dir, 'project_description.json')
  36. if not os.path.exists(desc_path):
  37. ensure_build_directory(args, ctx.info_name)
  38. with open(desc_path, 'r') as f:
  39. project_desc = json.load(f)
  40. return project_desc
  41. def _get_esptool_args(args: PropertyDict) -> List:
  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()
  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: click.core.Context) -> List:
  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: str, ctx: click.core.Context, args: PropertyDict, print_filter: str, monitor_baud: str, encrypted: bool,
  71. no_reset: bool, timestamps: bool, timestamp_format: str, force_color: bool) -> None:
  72. """
  73. Run esp_idf_monitor to watch build output
  74. """
  75. project_desc = _get_project_desc(ctx, args)
  76. elf_file = os.path.join(args.build_dir, project_desc['app_elf'])
  77. idf_monitor = os.path.join(os.environ['IDF_PATH'], 'tools/idf_monitor.py')
  78. monitor_args = [PYTHON, idf_monitor]
  79. if project_desc['target'] != 'linux':
  80. if no_reset and args.port is None:
  81. msg = ('WARNING: --no-reset is ignored. '
  82. 'Please specify the port with the --port argument in order to use this option.')
  83. yellow_print(msg)
  84. no_reset = False
  85. args.port = args.port or get_default_serial_port()
  86. monitor_args += ['-p', args.port]
  87. baud = monitor_baud or os.getenv('IDF_MONITOR_BAUD') or os.getenv('MONITORBAUD')
  88. if baud is None:
  89. # Baud hasn't been changed locally (by local baud argument nor by environment variables)
  90. #
  91. # Use the global baud rate if it has been changed by the command line.
  92. # Use project_desc['monitor_baud'] as the last option.
  93. global_baud_defined = ctx._parameter_source['baud'] == click.core.ParameterSource.COMMANDLINE
  94. baud = args.baud if global_baud_defined else project_desc['monitor_baud']
  95. monitor_args += ['-b', baud]
  96. monitor_args += ['--toolchain-prefix', project_desc['monitor_toolprefix']]
  97. coredump_decode = get_sdkconfig_value(project_desc['config_file'], 'CONFIG_ESP_COREDUMP_DECODE')
  98. if coredump_decode is not None:
  99. monitor_args += ['--decode-coredumps', coredump_decode]
  100. target_arch_riscv = get_sdkconfig_value(project_desc['config_file'], 'CONFIG_IDF_TARGET_ARCH_RISCV')
  101. monitor_args += ['--target', project_desc['target']]
  102. revision = project_desc.get('min_rev')
  103. if revision:
  104. monitor_args += ['--revision', revision]
  105. if target_arch_riscv:
  106. monitor_args += ['--decode-panic', 'backtrace']
  107. if print_filter is not None:
  108. monitor_args += ['--print_filter', print_filter]
  109. if elf_file:
  110. monitor_args += [elf_file]
  111. if encrypted:
  112. monitor_args += ['--encrypted']
  113. if no_reset:
  114. monitor_args += ['--no-reset']
  115. if timestamps:
  116. monitor_args += ['--timestamps']
  117. if timestamp_format:
  118. monitor_args += ['--timestamp-format', timestamp_format]
  119. if force_color or os.name == 'nt':
  120. monitor_args += ['--force-color']
  121. idf_py = [PYTHON] + _get_commandline_options(ctx) # commands to re-run idf.py
  122. monitor_args += ['-m', ' '.join("'%s'" % a for a in idf_py)]
  123. hints = not args.no_hints
  124. # Temporally ignore SIGINT, which is used in idf_monitor to spawn gdb.
  125. old_handler = signal.getsignal(signal.SIGINT)
  126. signal.signal(signal.SIGINT, signal.SIG_IGN)
  127. try:
  128. RunTool('idf_monitor', monitor_args, args.project_dir, build_dir=args.build_dir, hints=hints, interactive=True, convert_output=True)()
  129. finally:
  130. signal.signal(signal.SIGINT, old_handler)
  131. def flash(action: str, ctx: click.core.Context, args: PropertyDict, force: bool, extra_args: str) -> None:
  132. """
  133. Run esptool to flash the entire project, from an argfile generated by the build system
  134. """
  135. ensure_build_directory(args, ctx.info_name)
  136. project_desc = _get_project_desc(ctx, args)
  137. if project_desc['target'] == 'linux':
  138. yellow_print('skipping flash since running on linux...')
  139. return
  140. args.port = args.port or get_default_serial_port()
  141. extra = list()
  142. if force:
  143. extra.append('--force')
  144. if extra_args:
  145. extra += shlex.split(extra_args)
  146. env = {'ESPBAUD': str(args.baud), 'ESPPORT': args.port, 'SERIAL_TOOL_EXTRA_ARGS': ';'.join(extra)}
  147. run_target(action, args, env, force_progression=True)
  148. def erase_flash(action: str, ctx: click.core.Context, args: PropertyDict) -> None:
  149. ensure_build_directory(args, ctx.info_name)
  150. esptool_args = _get_esptool_args(args)
  151. esptool_args += ['erase_flash']
  152. RunTool('esptool.py', esptool_args, args.build_dir, hints=not args.no_hints)()
  153. def global_callback(ctx: click.core.Context, global_args: Dict, tasks: PropertyDict) -> None:
  154. encryption = any([task.name in ('encrypted-flash', 'encrypted-app-flash') for task in tasks])
  155. if encryption:
  156. for task in tasks:
  157. if task.name == 'monitor':
  158. task.action_args['encrypted'] = True
  159. break
  160. def ota_targets(target_name: str, ctx: click.core.Context, args: PropertyDict) -> None:
  161. """
  162. Execute the target build system to build target 'target_name'.
  163. Additionally set global variables for baud and port.
  164. Calls ensure_build_directory() which will run cmake to generate a build
  165. directory (with the specified generator) as needed.
  166. """
  167. args.port = args.port or get_default_serial_port()
  168. ensure_build_directory(args, ctx.info_name)
  169. run_target(target_name, args, {'ESPBAUD': str(args.baud), 'ESPPORT': args.port})
  170. BAUD_AND_PORT = [BAUD_RATE, PORT]
  171. flash_options = BAUD_AND_PORT + [
  172. {
  173. 'names': ['--force'],
  174. 'is_flag': True,
  175. 'help': 'Force write, skip security and compatibility checks. Use with caution!',
  176. },
  177. {
  178. 'names': ['--extra-args'],
  179. 'help': (
  180. 'Pass extra arguments to esptool separated by space. For more details see `esptool.py write_flash --help`. '
  181. 'For example to compress and verify data use: `idf.py flash --extra-args="--compress --verify"`. Use with caution!'
  182. )
  183. }
  184. ]
  185. serial_actions = {
  186. 'global_action_callbacks': [global_callback],
  187. 'actions': {
  188. 'flash': {
  189. 'callback': flash,
  190. 'help': 'Flash the project.',
  191. 'options': global_options + flash_options,
  192. 'order_dependencies': ['all', 'erase-flash'],
  193. },
  194. 'erase-flash': {
  195. 'callback': erase_flash,
  196. 'help': 'Erase entire flash chip.',
  197. 'options': BAUD_AND_PORT,
  198. },
  199. 'erase_flash': {
  200. 'callback': erase_flash,
  201. 'deprecated': {
  202. 'since': 'v4.4',
  203. 'removed': 'next major release',
  204. 'message': 'Have you wanted to run "erase-flash" instead?',
  205. },
  206. 'hidden': True,
  207. 'help': 'Erase entire flash chip.',
  208. 'options': BAUD_AND_PORT,
  209. },
  210. 'monitor': {
  211. 'callback':
  212. monitor,
  213. 'help':
  214. 'Display serial output.',
  215. 'options': [
  216. PORT, {
  217. 'names': ['--print-filter', '--print_filter'],
  218. 'help':
  219. ('Filter monitor output. '
  220. 'Restrictions on what to print can be specified as a series of <tag>:<log_level> items '
  221. 'where <tag> is the tag string and <log_level> is a character from the set '
  222. '{N, E, W, I, D, V, *} referring to a level. '
  223. 'For example, "tag1:W" matches and prints only the outputs written with '
  224. 'ESP_LOGW("tag1", ...) or at lower verbosity level, i.e. ESP_LOGE("tag1", ...). '
  225. 'Not specifying a <log_level> or using "*" defaults to Verbose level. '
  226. 'Please see the IDF Monitor section of the ESP-IDF documentation '
  227. 'for a more detailed description and further examples.'),
  228. 'default':
  229. None,
  230. }, {
  231. 'names': ['--monitor-baud', '-b'],
  232. 'type':
  233. click.INT,
  234. 'help': ('Baud rate for monitor. '
  235. 'If this option is not provided IDF_MONITOR_BAUD and MONITORBAUD '
  236. 'environment variables, global baud rate and project_description.json in build directory '
  237. "(generated by CMake from project's sdkconfig) "
  238. 'will be checked for default value.'),
  239. }, {
  240. 'names': ['--encrypted', '-E'],
  241. 'is_flag': True,
  242. 'help': ('Enable encrypted flash targets. '
  243. 'IDF Monitor will invoke encrypted-flash and encrypted-app-flash targets '
  244. 'if this option is set. This option is set by default if IDF Monitor was invoked '
  245. 'together with encrypted-flash or encrypted-app-flash target.'),
  246. }, {
  247. 'names': ['--no-reset'],
  248. 'is_flag': True,
  249. 'help': ('Disable reset on monitor startup. '
  250. 'IDF Monitor will not reset the MCU target by toggling DTR/RTS lines on startup '
  251. 'if this option is set.'),
  252. }, {
  253. 'names': ['--timestamps'],
  254. 'is_flag': True,
  255. 'help': 'Print a time stamp in the beginning of each line.',
  256. }, {
  257. 'names': ['--timestamp-format'],
  258. 'help': ('Set the formatting of timestamps compatible with strftime(). '
  259. 'For example, "%Y-%m-%d %H:%M:%S".'),
  260. 'default': None
  261. }, {
  262. 'names': ['--force-color'],
  263. 'is_flag': True,
  264. 'help': 'Always print ANSI for colors',
  265. }
  266. ],
  267. 'order_dependencies': [
  268. 'flash',
  269. 'encrypted-flash',
  270. 'partition-table-flash',
  271. 'bootloader-flash',
  272. 'app-flash',
  273. 'encrypted-app-flash',
  274. ],
  275. },
  276. 'partition-table-flash': {
  277. 'callback': flash,
  278. 'help': 'Flash partition table only.',
  279. 'options': flash_options,
  280. 'order_dependencies': ['partition-table', 'erase-flash'],
  281. },
  282. 'bootloader-flash': {
  283. 'callback': flash,
  284. 'help': 'Flash bootloader only.',
  285. 'options': flash_options,
  286. 'order_dependencies': ['bootloader', 'erase-flash'],
  287. },
  288. 'app-flash': {
  289. 'callback': flash,
  290. 'help': 'Flash the app only.',
  291. 'options': flash_options,
  292. 'order_dependencies': ['app', 'erase-flash'],
  293. },
  294. 'encrypted-app-flash': {
  295. 'callback': flash,
  296. 'help': 'Flash the encrypted app only.',
  297. 'options': flash_options,
  298. 'order_dependencies': ['app', 'erase-flash'],
  299. },
  300. 'encrypted-flash': {
  301. 'callback': flash,
  302. 'help': 'Flash the encrypted project.',
  303. 'options': flash_options,
  304. 'order_dependencies': ['all', 'erase-flash'],
  305. },
  306. 'erase-otadata': {
  307. 'callback': ota_targets,
  308. 'help': 'Erase otadata partition.',
  309. 'options': global_options + BAUD_AND_PORT,
  310. },
  311. 'read-otadata': {
  312. 'callback': ota_targets,
  313. 'help': 'Read otadata partition.',
  314. 'options': global_options + BAUD_AND_PORT,
  315. },
  316. },
  317. }
  318. return serial_actions