idf_monitor.py 15 KB

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