serial_ext.py 10.0 KB

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