idf_monitor.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. #!/usr/bin/env python
  2. #
  3. # esp-idf serial output monitor tool. Does some helpful things:
  4. # - Looks up hex addresses in ELF file with addr2line
  5. # - Reset ESP32 via serial RTS line (Ctrl-T Ctrl-R)
  6. # - Run flash build target to rebuild and flash entire project (Ctrl-T Ctrl-F)
  7. # - Run app-flash build target to rebuild and flash app only (Ctrl-T Ctrl-A)
  8. # - If gdbstub output is detected, gdb is automatically loaded
  9. # - If core dump output is detected, it is converted to a human-readable report
  10. # by espcoredump.py.
  11. #
  12. # SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  13. # SPDX-License-Identifier: Apache-2.0
  14. #
  15. # Contains elements taken from miniterm "Very simple serial terminal" which
  16. # is part of pySerial. https://github.com/pyserial/pyserial
  17. # (C)2002-2015 Chris Liechti <cliechti@gmx.net>
  18. #
  19. # Originally released under BSD-3-Clause license.
  20. #
  21. import codecs
  22. import io
  23. import os
  24. import queue
  25. import re
  26. import shlex
  27. import subprocess
  28. import sys
  29. import threading
  30. import time
  31. from builtins import bytes
  32. from typing import Any, List, Optional, Type, Union
  33. import serial
  34. import serial.tools.list_ports
  35. # Windows console stuff
  36. from idf_monitor_base.ansi_color_converter import get_converter
  37. from idf_monitor_base.argument_parser import get_parser
  38. from idf_monitor_base.console_parser import ConsoleParser
  39. from idf_monitor_base.console_reader import ConsoleReader
  40. from idf_monitor_base.constants import (CTRL_C, CTRL_H, DEFAULT_PRINT_FILTER, DEFAULT_TOOLCHAIN_PREFIX,
  41. ESPPORT_ENVIRON, EVENT_QUEUE_TIMEOUT, GDB_EXIT_TIMEOUT,
  42. GDB_UART_CONTINUE_COMMAND, LAST_LINE_THREAD_INTERVAL, MAKEFLAGS_ENVIRON,
  43. PANIC_DECODE_DISABLE, PANIC_IDLE, TAG_CMD, TAG_KEY, TAG_SERIAL,
  44. TAG_SERIAL_FLUSH)
  45. from idf_monitor_base.coredump import COREDUMP_DECODE_INFO, CoreDump
  46. from idf_monitor_base.exceptions import SerialStopException
  47. from idf_monitor_base.gdbhelper import GDBHelper
  48. from idf_monitor_base.line_matcher import LineMatcher
  49. from idf_monitor_base.logger import Logger
  50. from idf_monitor_base.output_helpers import normal_print, yellow_print
  51. from idf_monitor_base.serial_handler import SerialHandler, SerialHandlerNoElf, run_make
  52. from idf_monitor_base.serial_reader import LinuxReader, SerialReader
  53. from idf_monitor_base.web_socket_client import WebSocketClient
  54. from serial.tools import miniterm
  55. key_description = miniterm.key_description
  56. class Monitor:
  57. """
  58. Monitor application base class.
  59. This was originally derived from miniterm.Miniterm, but it turned out to be easier to write from scratch for this
  60. purpose.
  61. Main difference is that all event processing happens in the main thread, not the worker threads.
  62. """
  63. def __init__(
  64. self,
  65. serial_instance, # type: serial.Serial
  66. elf_file, # type: str
  67. print_filter, # type: str
  68. make='make', # type: str
  69. encrypted=False, # type: bool
  70. reset=True, # type: bool
  71. toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, # type: str
  72. eol='CRLF', # type: str
  73. decode_coredumps=COREDUMP_DECODE_INFO, # type: str
  74. decode_panic=PANIC_DECODE_DISABLE, # type: str
  75. target='esp32', # type: str
  76. websocket_client=None, # type: Optional[WebSocketClient]
  77. enable_address_decoding=True, # type: bool
  78. timestamps=False, # type: bool
  79. timestamp_format='', # type: str
  80. force_color=False # type: bool
  81. ):
  82. self.event_queue = queue.Queue() # type: queue.Queue
  83. self.cmd_queue = queue.Queue() # type: queue.Queue
  84. self.console = miniterm.Console()
  85. # if the variable is set ANSI will be printed even if we do not print to terminal
  86. sys.stderr = get_converter(sys.stderr, decode_output=True, force_color=force_color)
  87. self.console.output = get_converter(self.console.output, force_color=force_color)
  88. self.console.byte_output = get_converter(self.console.byte_output, force_color=force_color)
  89. self.elf_file = elf_file or ''
  90. self.elf_exists = os.path.exists(self.elf_file)
  91. self.logger = Logger(self.elf_file, self.console, timestamps, timestamp_format, b'', enable_address_decoding,
  92. toolchain_prefix)
  93. self.coredump = CoreDump(decode_coredumps, self.event_queue, self.logger, websocket_client,
  94. self.elf_file) if self.elf_exists else None
  95. # allow for possibility the "make" arg is a list of arguments (for idf.py)
  96. self.make = make if os.path.exists(make) else shlex.split(make) # type: Any[Union[str, List[str]], str]
  97. self.target = target
  98. # testing hook - data from serial can make exit the monitor
  99. if isinstance(self, SerialMonitor):
  100. socket_mode = serial_instance.port.startswith('socket://')
  101. self.serial = serial_instance
  102. self.serial_reader = SerialReader(self.serial, self.event_queue, reset)
  103. self.gdb_helper = GDBHelper(toolchain_prefix, websocket_client, self.elf_file, self.serial.port,
  104. self.serial.baudrate) if self.elf_exists else None
  105. else:
  106. socket_mode = False
  107. self.serial = subprocess.Popen([self.elf_file], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  108. stderr=subprocess.STDOUT)
  109. self.serial_reader = LinuxReader(self.serial, self.event_queue)
  110. self.gdb_helper = None
  111. cls = SerialHandler if self.elf_exists else SerialHandlerNoElf
  112. self.serial_handler = cls(b'', socket_mode, self.logger, decode_panic, PANIC_IDLE, b'', target,
  113. False, False, self.serial, encrypted, reset, self.elf_file)
  114. self.console_parser = ConsoleParser(eol)
  115. self.console_reader = ConsoleReader(self.console, self.event_queue, self.cmd_queue, self.console_parser,
  116. socket_mode)
  117. self._line_matcher = LineMatcher(print_filter)
  118. # internal state
  119. self._invoke_processing_last_line_timer = None # type: Optional[threading.Timer]
  120. def __enter__(self) -> None:
  121. """ Use 'with self' to temporarily disable monitoring behaviour """
  122. self.serial_reader.stop()
  123. self.console_reader.stop()
  124. def __exit__(self, exc_type, exc_val, exc_tb) -> None: # type: ignore
  125. raise NotImplementedError
  126. def run_make(self, target: str) -> None:
  127. with self:
  128. run_make(target, self.make, self.console, self.console_parser, self.event_queue, self.cmd_queue,
  129. self.logger)
  130. def _pre_start(self) -> None:
  131. self.console_reader.start()
  132. self.serial_reader.start()
  133. def main_loop(self) -> None:
  134. self._pre_start()
  135. try:
  136. while self.console_reader.alive and self.serial_reader.alive:
  137. try:
  138. self._main_loop()
  139. except KeyboardInterrupt:
  140. yellow_print('To exit from IDF monitor please use \"Ctrl+]\". Alternatively, you can use Ctrl-T Ctrl-X to exit.')
  141. self.serial_write(codecs.encode(CTRL_C))
  142. except SerialStopException:
  143. normal_print('Stopping condition has been received\n')
  144. except KeyboardInterrupt:
  145. pass
  146. finally:
  147. try:
  148. self.console_reader.stop()
  149. self.serial_reader.stop()
  150. self.logger.stop_logging()
  151. # Cancelling _invoke_processing_last_line_timer is not
  152. # important here because receiving empty data doesn't matter.
  153. self._invoke_processing_last_line_timer = None
  154. except Exception: # noqa
  155. pass
  156. normal_print('\n')
  157. def serial_write(self, *args: str, **kwargs: str) -> None:
  158. raise NotImplementedError
  159. def check_gdb_stub_and_run(self, line: bytes) -> None:
  160. raise NotImplementedError
  161. def invoke_processing_last_line(self) -> None:
  162. self.event_queue.put((TAG_SERIAL_FLUSH, b''), False)
  163. def _main_loop(self) -> None:
  164. try:
  165. item = self.cmd_queue.get_nowait()
  166. except queue.Empty:
  167. try:
  168. item = self.event_queue.get(timeout=EVENT_QUEUE_TIMEOUT)
  169. except queue.Empty:
  170. return
  171. event_tag, data = item
  172. if event_tag == TAG_CMD:
  173. self.serial_handler.handle_commands(data, self.target, self.run_make, self.console_reader,
  174. self.serial_reader)
  175. elif event_tag == TAG_KEY:
  176. self.serial_write(codecs.encode(data))
  177. elif event_tag == TAG_SERIAL:
  178. self.serial_handler.handle_serial_input(data, self.console_parser, self.coredump,
  179. self.gdb_helper, self._line_matcher,
  180. self.check_gdb_stub_and_run)
  181. if self._invoke_processing_last_line_timer is not None:
  182. self._invoke_processing_last_line_timer.cancel()
  183. self._invoke_processing_last_line_timer = threading.Timer(LAST_LINE_THREAD_INTERVAL,
  184. self.invoke_processing_last_line)
  185. self._invoke_processing_last_line_timer.start()
  186. # If no further data is received in the next short period
  187. # of time then the _invoke_processing_last_line_timer
  188. # generates an event which will result in the finishing of
  189. # the last line. This is fix for handling lines sent
  190. # without EOL.
  191. # finalizing the line when coredump is in progress causes decoding issues
  192. # the espcoredump loader uses empty line as a sign for end-of-coredump
  193. # line is finalized only for non coredump data
  194. elif event_tag == TAG_SERIAL_FLUSH:
  195. self.serial_handler.handle_serial_input(data, self.console_parser, self.coredump,
  196. self.gdb_helper, self._line_matcher,
  197. self.check_gdb_stub_and_run,
  198. finalize_line=not self.coredump or not self.coredump.in_progress)
  199. else:
  200. raise RuntimeError('Bad event data %r' % ((event_tag, data),))
  201. class SerialMonitor(Monitor):
  202. def __exit__(self, exc_type, exc_val, exc_tb) -> None: # type: ignore
  203. """ Use 'with self' to temporarily disable monitoring behaviour """
  204. self.console_reader.start()
  205. if self.elf_exists:
  206. self.serial_reader.gdb_exit = self.gdb_helper.gdb_exit # write gdb_exit flag
  207. self.serial_reader.start()
  208. def _pre_start(self) -> None:
  209. super()._pre_start()
  210. if self.elf_exists:
  211. self.gdb_helper.gdb_exit = False
  212. self.serial_handler.start_cmd_sent = False
  213. def serial_write(self, *args: str, **kwargs: str) -> None:
  214. self.serial: serial.Serial
  215. try:
  216. self.serial.write(*args, **kwargs)
  217. except serial.SerialException:
  218. pass # this shouldn't happen, but sometimes port has closed in serial thread
  219. except UnicodeEncodeError:
  220. pass # this can happen if a non-ascii character was passed, ignoring
  221. def check_gdb_stub_and_run(self, line: bytes) -> None: # type: ignore # The base class one is a None value
  222. if self.gdb_helper and self.gdb_helper.check_gdb_stub_trigger(line):
  223. with self: # disable console control
  224. self.gdb_helper.run_gdb()
  225. def _main_loop(self) -> None:
  226. if self.elf_exists and self.gdb_helper.gdb_exit:
  227. self.gdb_helper.gdb_exit = False
  228. time.sleep(GDB_EXIT_TIMEOUT)
  229. # Continue the program after exit from the GDB
  230. self.serial_write(codecs.encode(GDB_UART_CONTINUE_COMMAND))
  231. self.serial_handler.start_cmd_sent = True
  232. super()._main_loop()
  233. class LinuxMonitor(Monitor):
  234. def __exit__(self, exc_type, exc_val, exc_tb) -> None: # type: ignore
  235. """ Use 'with self' to temporarily disable monitoring behaviour """
  236. self.console_reader.start()
  237. self.serial_reader.start()
  238. def serial_write(self, *args: str, **kwargs: str) -> None:
  239. self.serial.stdin.write(*args, **kwargs)
  240. def check_gdb_stub_and_run(self, line: bytes) -> None:
  241. return # fake function for linux target
  242. def main() -> None:
  243. parser = get_parser()
  244. args = parser.parse_args()
  245. # The port name is changed in cases described in the following lines. Use a local argument and
  246. # avoid the modification of args.port.
  247. port = args.port
  248. # GDB uses CreateFile to open COM port, which requires the COM name to be r'\\.\COMx' if the COM
  249. # number is larger than 10
  250. if os.name == 'nt' and port.startswith('COM'):
  251. port = port.replace('COM', r'\\.\COM')
  252. yellow_print('--- WARNING: GDB cannot open serial ports accessed as COMx')
  253. yellow_print('--- Using %s instead...' % port)
  254. elif port.startswith('/dev/tty.') and sys.platform == 'darwin':
  255. port = port.replace('/dev/tty.', '/dev/cu.')
  256. yellow_print('--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.')
  257. yellow_print('--- Using %s instead...' % port)
  258. if isinstance(args.elf_file, io.BufferedReader):
  259. elf_file = args.elf_file.name
  260. args.elf_file.close() # don't need this as a file
  261. else:
  262. elf_file = args.elf_file
  263. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  264. # parent make is only running 1 job (monitor), so we can re-spawn
  265. # all of the child makes we need (the -j argument remains part of
  266. # MAKEFLAGS)
  267. try:
  268. makeflags = os.environ[MAKEFLAGS_ENVIRON]
  269. makeflags = re.sub(r'--jobserver[^ =]*=[0-9,]+ ?', '', makeflags)
  270. os.environ[MAKEFLAGS_ENVIRON] = makeflags
  271. except KeyError:
  272. pass # not running a make jobserver
  273. ws = WebSocketClient(args.ws) if args.ws else None
  274. try:
  275. cls: Type[Monitor]
  276. if args.target == 'linux':
  277. serial_instance = None
  278. cls = LinuxMonitor
  279. yellow_print('--- idf_monitor on linux ---')
  280. else:
  281. serial_instance = serial.serial_for_url(port, args.baud, do_not_open=True)
  282. serial_instance.dtr = False
  283. serial_instance.rts = False
  284. # Pass the actual used port to callee of idf_monitor (e.g. idf.py/cmake) through `ESPPORT` environment
  285. # variable.
  286. # Note that the port must be original port argument without any replacement done in IDF Monitor (idf.py
  287. # has a check for this).
  288. # To make sure the key as well as the value are str type, by the requirements of subprocess
  289. espport_val = str(args.port)
  290. os.environ.update({ESPPORT_ENVIRON: espport_val})
  291. cls = SerialMonitor
  292. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(p=serial_instance))
  293. monitor = cls(serial_instance,
  294. elf_file,
  295. args.print_filter,
  296. args.make,
  297. args.encrypted,
  298. not args.no_reset,
  299. args.toolchain_prefix,
  300. args.eol,
  301. args.decode_coredumps,
  302. args.decode_panic,
  303. args.target,
  304. ws,
  305. not args.disable_address_decoding,
  306. args.timestamps,
  307. args.timestamp_format,
  308. args.force_color)
  309. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  310. key_description(monitor.console_parser.exit_key),
  311. key_description(monitor.console_parser.menu_key),
  312. key_description(monitor.console_parser.menu_key),
  313. key_description(CTRL_H)))
  314. if args.print_filter != DEFAULT_PRINT_FILTER:
  315. yellow_print('--- Print filter: {} ---'.format(args.print_filter))
  316. monitor.main_loop()
  317. except KeyboardInterrupt:
  318. pass
  319. finally:
  320. if ws:
  321. ws.close()
  322. if __name__ == '__main__':
  323. main()