serial_ext.py 15 KB

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