serial_ext.py 10 KB

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