idf_monitor.py 15 KB

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