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
  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. if os.getenv("IDF_MONITOR_BAUD"):
  72. monitor_baud = os.getenv("IDF_MONITOR_BAUD", None)
  73. elif os.getenv("MONITORBAUD"):
  74. monitor_baud = os.getenv("MONITORBAUD", None)
  75. else:
  76. monitor_baud = project_desc["monitor_baud"]
  77. monitor_args += ["-b", monitor_baud]
  78. monitor_args += ["--toolchain-prefix", project_desc["monitor_toolprefix"]]
  79. coredump_decode = get_sdkconfig_value(project_desc["config_file"], "CONFIG_ESP32_CORE_DUMP_DECODE")
  80. if coredump_decode is not None:
  81. monitor_args += ["--decode-coredumps", coredump_decode]
  82. if print_filter is not None:
  83. monitor_args += ["--print_filter", print_filter]
  84. monitor_args += [elf_file]
  85. if encrypted:
  86. monitor_args += ['--encrypted']
  87. idf_py = [PYTHON] + _get_commandline_options(ctx) # commands to re-run idf.py
  88. monitor_args += ["-m", " ".join("'%s'" % a for a in idf_py)]
  89. if "MSYSTEM" in os.environ:
  90. monitor_args = ["winpty"] + monitor_args
  91. run_tool("idf_monitor", monitor_args, args.project_dir)
  92. def flash(action, ctx, args):
  93. """
  94. Run esptool to flash the entire project, from an argfile generated by the build system
  95. """
  96. ensure_build_directory(args, ctx.info_name)
  97. if args.port is None:
  98. args.port = _get_default_serial_port()
  99. run_target(action, args, {"ESPPORT": args.port,
  100. "ESPBAUD": str(args.baud)})
  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. The default value can be set with the ESPBAUD environment variable.",
  116. "scope": "global",
  117. "envvar": "ESPBAUD",
  118. "default": 460800,
  119. }
  120. port = {
  121. "names": ["-p", "--port"],
  122. "help": "Serial port. The default value can be set with the ESPPORT environment variable.",
  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.\n"
  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.\n'
  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.\n"
  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.\n"
  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