idf_monitor.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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 argparse
  34. import codecs
  35. import datetime
  36. import os
  37. import re
  38. import subprocess
  39. import threading
  40. import time
  41. from builtins import bytes, object
  42. from typing import BinaryIO, Callable, List, Optional, Union
  43. import serial.tools.miniterm as miniterm
  44. from idf_monitor_base import (COREDUMP_DECODE_DISABLE, COREDUMP_DECODE_INFO, COREDUMP_DONE, COREDUMP_IDLE,
  45. COREDUMP_READING, COREDUMP_UART_END, COREDUMP_UART_PROMPT, COREDUMP_UART_START,
  46. DEFAULT_PRINT_FILTER, DEFAULT_TOOLCHAIN_PREFIX, MATCH_PCADDR, PANIC_DECODE_BACKTRACE,
  47. PANIC_DECODE_DISABLE, PANIC_END, PANIC_IDLE, PANIC_READING, PANIC_STACK_DUMP,
  48. PANIC_START)
  49. from idf_monitor_base.chip_specific_config import get_chip_config
  50. from idf_monitor_base.console_parser import ConsoleParser
  51. from idf_monitor_base.console_reader import ConsoleReader
  52. from idf_monitor_base.constants import (CMD_APP_FLASH, CMD_ENTER_BOOT, CMD_MAKE, CMD_OUTPUT_TOGGLE, CMD_RESET,
  53. CMD_STOP, CMD_TOGGLE_LOGGING, CTRL_H, CTRL_T, TAG_CMD, TAG_KEY, TAG_SERIAL,
  54. TAG_SERIAL_FLUSH)
  55. from idf_monitor_base.exceptions import SerialStopException
  56. from idf_monitor_base.line_matcher import LineMatcher
  57. from idf_monitor_base.output_helpers import normal_print, red_print, yellow_print
  58. from idf_monitor_base.serial_reader import SerialReader
  59. from idf_monitor_base.web_socket_client import WebSocketClient
  60. try:
  61. import queue # noqa
  62. except ImportError:
  63. import Queue as queue # type: ignore # noqa
  64. import shlex
  65. import sys
  66. import tempfile
  67. import serial
  68. import serial.tools.list_ports
  69. # Windows console stuff
  70. from idf_monitor_base.ansi_color_converter import get_converter
  71. key_description = miniterm.key_description
  72. class Monitor(object):
  73. """
  74. Monitor application main class.
  75. This was originally derived from miniterm.Miniterm, but it turned out to be easier to write from scratch for this
  76. purpose.
  77. Main difference is that all event processing happens in the main thread, not the worker threads.
  78. """
  79. def __init__(self, serial_instance, elf_file, print_filter, make='make', encrypted=False,
  80. toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, eol='CRLF',
  81. decode_coredumps=COREDUMP_DECODE_INFO,
  82. decode_panic=PANIC_DECODE_DISABLE,
  83. target='esp32',
  84. websocket_client=None, enable_address_decoding=True):
  85. # type: (serial.Serial, str, str, str, bool, str, str, str, str, str, WebSocketClient, bool) -> None
  86. super(Monitor, self).__init__()
  87. self.event_queue = queue.Queue() # type: queue.Queue
  88. self.cmd_queue = queue.Queue() # type: queue.Queue
  89. self.console = miniterm.Console()
  90. self.enable_address_decoding = enable_address_decoding
  91. sys.stderr = get_converter(sys.stderr, decode_output=True)
  92. self.console.output = get_converter(self.console.output)
  93. self.console.byte_output = get_converter(self.console.byte_output)
  94. socket_mode = serial_instance.port.startswith(
  95. 'socket://') # testing hook - data from serial can make exit the monitor
  96. self.serial = serial_instance
  97. self.console_parser = ConsoleParser(eol)
  98. self.console_reader = ConsoleReader(self.console, self.event_queue, self.cmd_queue, self.console_parser,
  99. socket_mode)
  100. self.serial_reader = SerialReader(self.serial, self.event_queue)
  101. self.elf_file = elf_file
  102. if not os.path.exists(make):
  103. # allow for possibility the "make" arg is a list of arguments (for idf.py)
  104. self.make = shlex.split(make) # type: Union[str, List[str]]
  105. else:
  106. self.make = make
  107. self.encrypted = encrypted
  108. self.toolchain_prefix = toolchain_prefix
  109. self.websocket_client = websocket_client
  110. self.target = target
  111. # internal state
  112. self._last_line_part = b''
  113. self._gdb_buffer = b''
  114. self._pc_address_buffer = b''
  115. self._line_matcher = LineMatcher(print_filter)
  116. self._invoke_processing_last_line_timer = None # type: Optional[threading.Timer]
  117. self._force_line_print = False
  118. self._output_enabled = True
  119. self._serial_check_exit = socket_mode
  120. self._log_file = None # type: Optional[BinaryIO]
  121. self._decode_coredumps = decode_coredumps
  122. self._reading_coredump = COREDUMP_IDLE
  123. self._coredump_buffer = b''
  124. self._decode_panic = decode_panic
  125. self._reading_panic = PANIC_IDLE
  126. self._panic_buffer = b''
  127. self.gdb_exit = False
  128. self.start_cmd_sent = False
  129. def invoke_processing_last_line(self):
  130. # type: () -> None
  131. self.event_queue.put((TAG_SERIAL_FLUSH, b''), False)
  132. def main_loop(self):
  133. # type: () -> None
  134. self.console_reader.start()
  135. self.serial_reader.start()
  136. self.gdb_exit = False
  137. self.start_cmd_sent = False
  138. try:
  139. while self.console_reader.alive and self.serial_reader.alive:
  140. try:
  141. if self.gdb_exit is True:
  142. self.gdb_exit = False
  143. time.sleep(0.3)
  144. try:
  145. # Continue the program after exit from the GDB
  146. self.serial.write(codecs.encode('+$c#63'))
  147. self.start_cmd_sent = True
  148. except serial.SerialException:
  149. pass # this shouldn't happen, but sometimes port has closed in serial thread
  150. except UnicodeEncodeError:
  151. pass # this can happen if a non-ascii character was passed, ignoring
  152. try:
  153. item = self.cmd_queue.get_nowait()
  154. except queue.Empty:
  155. try:
  156. item = self.event_queue.get(True, 0.03)
  157. except queue.Empty:
  158. continue
  159. (event_tag, data) = item
  160. if event_tag == TAG_CMD:
  161. self.handle_commands(data, self.target)
  162. elif event_tag == TAG_KEY:
  163. try:
  164. self.serial.write(codecs.encode(data))
  165. except serial.SerialException:
  166. pass # this shouldn't happen, but sometimes port has closed in serial thread
  167. except UnicodeEncodeError:
  168. pass # this can happen if a non-ascii character was passed, ignoring
  169. elif event_tag == TAG_SERIAL:
  170. self.handle_serial_input(data)
  171. if self._invoke_processing_last_line_timer is not None:
  172. self._invoke_processing_last_line_timer.cancel()
  173. self._invoke_processing_last_line_timer = threading.Timer(0.1, self.invoke_processing_last_line)
  174. self._invoke_processing_last_line_timer.start()
  175. # If no futher data is received in the next short period
  176. # of time then the _invoke_processing_last_line_timer
  177. # generates an event which will result in the finishing of
  178. # the last line. This is fix for handling lines sent
  179. # without EOL.
  180. elif event_tag == TAG_SERIAL_FLUSH:
  181. self.handle_serial_input(data, finalize_line=True)
  182. else:
  183. raise RuntimeError('Bad event data %r' % ((event_tag,data),))
  184. except KeyboardInterrupt:
  185. try:
  186. yellow_print('To exit from IDF monitor please use \"Ctrl+]\"')
  187. self.serial.write(codecs.encode('\x03'))
  188. except serial.SerialException:
  189. pass # this shouldn't happen, but sometimes port has closed in serial thread
  190. except UnicodeEncodeError:
  191. pass # this can happen if a non-ascii character was passed, ignoring
  192. except SerialStopException:
  193. normal_print('Stopping condition has been received\n')
  194. except KeyboardInterrupt:
  195. pass
  196. finally:
  197. try:
  198. self.console_reader.stop()
  199. self.serial_reader.stop()
  200. self.stop_logging()
  201. # Cancelling _invoke_processing_last_line_timer is not
  202. # important here because receiving empty data doesn't matter.
  203. self._invoke_processing_last_line_timer = None
  204. except Exception:
  205. pass
  206. normal_print('\n')
  207. def handle_serial_input(self, data, finalize_line=False):
  208. # type: (bytes, bool) -> None
  209. # Remove "+" after Continue command
  210. if self.start_cmd_sent is True:
  211. self.start_cmd_sent = False
  212. pos = data.find(b'+')
  213. if pos != -1:
  214. data = data[(pos + 1):]
  215. sp = data.split(b'\n')
  216. if self._last_line_part != b'':
  217. # add unprocessed part from previous "data" to the first line
  218. sp[0] = self._last_line_part + sp[0]
  219. self._last_line_part = b''
  220. if sp[-1] != b'':
  221. # last part is not a full line
  222. self._last_line_part = sp.pop()
  223. for line in sp:
  224. if line != b'':
  225. if self._serial_check_exit and line == self.console_parser.exit_key.encode('latin-1'):
  226. raise SerialStopException()
  227. self.check_panic_decode_trigger(line)
  228. self.check_coredump_trigger_before_print(line)
  229. if self._force_line_print or self._line_matcher.match(line.decode(errors='ignore')):
  230. self._print(line + b'\n')
  231. self.handle_possible_pc_address_in_line(line)
  232. self.check_coredump_trigger_after_print()
  233. self.check_gdbstub_trigger(line)
  234. self._force_line_print = False
  235. # Now we have the last part (incomplete line) in _last_line_part. By
  236. # default we don't touch it and just wait for the arrival of the rest
  237. # of the line. But after some time when we didn't received it we need
  238. # to make a decision.
  239. if self._last_line_part != b'':
  240. if self._force_line_print or (finalize_line and self._line_matcher.match(self._last_line_part.decode(errors='ignore'))):
  241. self._force_line_print = True
  242. self._print(self._last_line_part)
  243. self.handle_possible_pc_address_in_line(self._last_line_part)
  244. self.check_gdbstub_trigger(self._last_line_part)
  245. # It is possible that the incomplete line cuts in half the PC
  246. # address. A small buffer is kept and will be used the next time
  247. # handle_possible_pc_address_in_line is invoked to avoid this problem.
  248. # MATCH_PCADDR matches 10 character long addresses. Therefore, we
  249. # keep the last 9 characters.
  250. self._pc_address_buffer = self._last_line_part[-9:]
  251. # GDB sequence can be cut in half also. GDB sequence is 7
  252. # characters long, therefore, we save the last 6 characters.
  253. self._gdb_buffer = self._last_line_part[-6:]
  254. self._last_line_part = b''
  255. # else: keeping _last_line_part and it will be processed the next time
  256. # handle_serial_input is invoked
  257. def handle_possible_pc_address_in_line(self, line):
  258. # type: (bytes) -> None
  259. line = self._pc_address_buffer + line
  260. self._pc_address_buffer = b''
  261. if self.enable_address_decoding:
  262. for m in re.finditer(MATCH_PCADDR, line.decode(errors='ignore')):
  263. self.lookup_pc_address(m.group())
  264. def __enter__(self):
  265. # type: () -> None
  266. """ Use 'with self' to temporarily disable monitoring behaviour """
  267. self.serial_reader.stop()
  268. self.console_reader.stop()
  269. def __exit__(self, *args, **kwargs): # type: ignore
  270. """ Use 'with self' to temporarily disable monitoring behaviour """
  271. self.console_reader.start()
  272. self.serial_reader.gdb_exit = self.gdb_exit # write gdb_exit flag
  273. self.serial_reader.start()
  274. def prompt_next_action(self, reason): # type: (str) -> None
  275. self.console.setup() # set up console to trap input characters
  276. try:
  277. red_print('--- {}'.format(reason))
  278. red_print(self.console_parser.get_next_action_text())
  279. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  280. while k == CTRL_T:
  281. k = self.console.getkey()
  282. finally:
  283. self.console.cleanup()
  284. ret = self.console_parser.parse_next_action_key(k)
  285. if ret is not None:
  286. cmd = ret[1]
  287. if cmd == CMD_STOP:
  288. # the stop command should be handled last
  289. self.event_queue.put(ret)
  290. else:
  291. self.cmd_queue.put(ret)
  292. def run_make(self, target): # type: (str) -> None
  293. with self:
  294. if isinstance(self.make, list):
  295. popen_args = self.make + [target]
  296. else:
  297. popen_args = [self.make, target]
  298. yellow_print('Running %s...' % ' '.join(popen_args))
  299. p = subprocess.Popen(popen_args, env=os.environ)
  300. try:
  301. p.wait()
  302. except KeyboardInterrupt:
  303. p.wait()
  304. if p.returncode != 0:
  305. self.prompt_next_action('Build failed')
  306. else:
  307. self.output_enable(True)
  308. def lookup_pc_address(self, pc_addr): # type: (str) -> None
  309. cmd = ['%saddr2line' % self.toolchain_prefix,
  310. '-pfiaC', '-e', self.elf_file, pc_addr]
  311. try:
  312. translation = subprocess.check_output(cmd, cwd='.')
  313. if b'?? ??:0' not in translation:
  314. self._print(translation.decode(), console_printer=yellow_print)
  315. except OSError as e:
  316. red_print('%s: %s' % (' '.join(cmd), e))
  317. def check_gdbstub_trigger(self, line): # type: (bytes) -> None
  318. line = self._gdb_buffer + line
  319. self._gdb_buffer = b''
  320. m = re.search(b'\\$(T..)#(..)', line) # look for a gdb "reason" for a break
  321. if m is not None:
  322. try:
  323. chsum = sum(ord(bytes([p])) for p in m.group(1)) & 0xFF
  324. calc_chsum = int(m.group(2), 16)
  325. except ValueError:
  326. return # payload wasn't valid hex digits
  327. if chsum == calc_chsum:
  328. if self.websocket_client:
  329. yellow_print('Communicating through WebSocket')
  330. self.websocket_client.send({'event': 'gdb_stub',
  331. 'port': self.serial.port,
  332. 'prog': self.elf_file})
  333. yellow_print('Waiting for debug finished event')
  334. self.websocket_client.wait([('event', 'debug_finished')])
  335. yellow_print('Communications through WebSocket is finished')
  336. else:
  337. self.run_gdb()
  338. else:
  339. red_print('Malformed gdb message... calculated checksum %02x received %02x' % (chsum, calc_chsum))
  340. def check_coredump_trigger_before_print(self, line): # type: (bytes) -> None
  341. if self._decode_coredumps == COREDUMP_DECODE_DISABLE:
  342. return
  343. if COREDUMP_UART_PROMPT in line:
  344. yellow_print('Initiating core dump!')
  345. self.event_queue.put((TAG_KEY, '\n'))
  346. return
  347. if COREDUMP_UART_START in line:
  348. yellow_print('Core dump started (further output muted)')
  349. self._reading_coredump = COREDUMP_READING
  350. self._coredump_buffer = b''
  351. self._output_enabled = False
  352. return
  353. if COREDUMP_UART_END in line:
  354. self._reading_coredump = COREDUMP_DONE
  355. yellow_print('\nCore dump finished!')
  356. self.process_coredump()
  357. return
  358. if self._reading_coredump == COREDUMP_READING:
  359. kb = 1024
  360. buffer_len_kb = len(self._coredump_buffer) // kb
  361. self._coredump_buffer += line.replace(b'\r', b'') + b'\n'
  362. new_buffer_len_kb = len(self._coredump_buffer) // kb
  363. if new_buffer_len_kb > buffer_len_kb:
  364. yellow_print('Received %3d kB...' % (new_buffer_len_kb), newline='\r')
  365. def check_coredump_trigger_after_print(self): # type: () -> None
  366. if self._decode_coredumps == COREDUMP_DECODE_DISABLE:
  367. return
  368. # Re-enable output after the last line of core dump has been consumed
  369. if not self._output_enabled and self._reading_coredump == COREDUMP_DONE:
  370. self._reading_coredump = COREDUMP_IDLE
  371. self._output_enabled = True
  372. self._coredump_buffer = b''
  373. def process_coredump(self): # type: () -> None
  374. if self._decode_coredumps != COREDUMP_DECODE_INFO:
  375. raise NotImplementedError('process_coredump: %s not implemented' % self._decode_coredumps)
  376. coredump_script = os.path.join(os.path.dirname(__file__), '..', 'components', 'espcoredump', 'espcoredump.py')
  377. coredump_file = None
  378. try:
  379. # On Windows, the temporary file can't be read unless it is closed.
  380. # Set delete=False and delete the file manually later.
  381. with tempfile.NamedTemporaryFile(mode='wb', delete=False) as coredump_file:
  382. coredump_file.write(self._coredump_buffer)
  383. coredump_file.flush()
  384. if self.websocket_client:
  385. self._output_enabled = True
  386. yellow_print('Communicating through WebSocket')
  387. self.websocket_client.send({'event': 'coredump',
  388. 'file': coredump_file.name,
  389. 'prog': self.elf_file})
  390. yellow_print('Waiting for debug finished event')
  391. self.websocket_client.wait([('event', 'debug_finished')])
  392. yellow_print('Communications through WebSocket is finished')
  393. else:
  394. cmd = [sys.executable,
  395. coredump_script,
  396. 'info_corefile',
  397. '--core', coredump_file.name,
  398. '--core-format', 'b64',
  399. self.elf_file
  400. ]
  401. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  402. self._output_enabled = True
  403. self._print(output)
  404. self._output_enabled = False # Will be reenabled in check_coredump_trigger_after_print
  405. except subprocess.CalledProcessError as e:
  406. yellow_print('Failed to run espcoredump script: {}\n{}\n\n'.format(e, e.output))
  407. self._output_enabled = True
  408. self._print(COREDUMP_UART_START + b'\n')
  409. self._print(self._coredump_buffer)
  410. # end line will be printed in handle_serial_input
  411. finally:
  412. if coredump_file is not None:
  413. try:
  414. os.unlink(coredump_file.name)
  415. except OSError as e:
  416. yellow_print('Couldn\'t remote temporary core dump file ({})'.format(e))
  417. def check_panic_decode_trigger(self, line): # type: (bytes) -> None
  418. if self._decode_panic == PANIC_DECODE_DISABLE:
  419. return
  420. if self._reading_panic == PANIC_IDLE and re.search(PANIC_START, line.decode('ascii', errors='ignore')):
  421. self._reading_panic = PANIC_READING
  422. yellow_print('Stack dump detected')
  423. if self._reading_panic == PANIC_READING and PANIC_STACK_DUMP in line:
  424. self._output_enabled = False
  425. if self._reading_panic == PANIC_READING:
  426. self._panic_buffer += line.replace(b'\r', b'') + b'\n'
  427. if self._reading_panic == PANIC_READING and PANIC_END in line:
  428. self._reading_panic = PANIC_IDLE
  429. self._output_enabled = True
  430. self.process_panic_output(self._panic_buffer)
  431. self._panic_buffer = b''
  432. def process_panic_output(self, panic_output): # type: (bytes) -> None
  433. panic_output_decode_script = os.path.join(os.path.dirname(__file__), '..', 'tools', 'gdb_panic_server.py')
  434. panic_output_file = None
  435. try:
  436. # On Windows, the temporary file can't be read unless it is closed.
  437. # Set delete=False and delete the file manually later.
  438. with tempfile.NamedTemporaryFile(mode='wb', delete=False) as panic_output_file:
  439. panic_output_file.write(panic_output)
  440. panic_output_file.flush()
  441. cmd = [self.toolchain_prefix + 'gdb',
  442. '--batch', '-n',
  443. self.elf_file,
  444. '-ex', "target remote | \"{python}\" \"{script}\" --target {target} \"{output_file}\""
  445. .format(python=sys.executable,
  446. script=panic_output_decode_script,
  447. target=self.target,
  448. output_file=panic_output_file.name),
  449. '-ex', 'bt']
  450. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  451. yellow_print('\nBacktrace:\n\n')
  452. self._print(output)
  453. except subprocess.CalledProcessError as e:
  454. yellow_print('Failed to run gdb_panic_server.py script: {}\n{}\n\n'.format(e, e.output))
  455. self._print(panic_output)
  456. finally:
  457. if panic_output_file is not None:
  458. try:
  459. os.unlink(panic_output_file.name)
  460. except OSError as e:
  461. yellow_print('Couldn\'t remove temporary panic output file ({})'.format(e))
  462. def run_gdb(self): # type: () -> None
  463. with self: # disable console control
  464. normal_print('')
  465. try:
  466. cmd = ['%sgdb' % self.toolchain_prefix,
  467. '-ex', 'set serial baud %d' % self.serial.baudrate,
  468. '-ex', 'target remote %s' % self.serial.port,
  469. self.elf_file]
  470. # Here we handling GDB as a process
  471. # Open GDB process
  472. try:
  473. process = subprocess.Popen(cmd, cwd='.')
  474. except KeyboardInterrupt:
  475. pass
  476. # We ignore Ctrl+C interrupt form external process abd wait responce util GDB will be finished.
  477. while True:
  478. try:
  479. process.wait()
  480. break
  481. except KeyboardInterrupt:
  482. pass # We ignore the Ctrl+C
  483. self.gdb_exit = True
  484. except OSError as e:
  485. red_print('%s: %s' % (' '.join(cmd), e))
  486. except KeyboardInterrupt:
  487. pass # happens on Windows, maybe other OSes
  488. finally:
  489. try:
  490. # on Linux, maybe other OSes, gdb sometimes seems to be alive even after wait() returns...
  491. process.terminate()
  492. except Exception:
  493. pass
  494. try:
  495. # also on Linux, maybe other OSes, gdb sometimes exits uncleanly and breaks the tty mode
  496. subprocess.call(['stty', 'sane'])
  497. except Exception:
  498. pass # don't care if there's no stty, we tried...
  499. def output_enable(self, enable): # type: (bool) -> None
  500. self._output_enabled = enable
  501. def output_toggle(self): # type: () -> None
  502. self._output_enabled = not self._output_enabled
  503. yellow_print('\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.'.format(
  504. self._output_enabled))
  505. def toggle_logging(self): # type: () -> None
  506. if self._log_file:
  507. self.stop_logging()
  508. else:
  509. self.start_logging()
  510. def start_logging(self): # type: () -> None
  511. if not self._log_file:
  512. name = 'log.{}.{}.txt'.format(os.path.splitext(os.path.basename(self.elf_file))[0],
  513. datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
  514. try:
  515. self._log_file = open(name, 'wb+')
  516. yellow_print('\nLogging is enabled into file {}'.format(name))
  517. except Exception as e:
  518. red_print('\nLog file {} cannot be created: {}'.format(name, e))
  519. def stop_logging(self): # type: () -> None
  520. if self._log_file:
  521. try:
  522. name = self._log_file.name
  523. self._log_file.close()
  524. yellow_print('\nLogging is disabled and file {} has been closed'.format(name))
  525. except Exception as e:
  526. red_print('\nLog file cannot be closed: {}'.format(e))
  527. finally:
  528. self._log_file = None
  529. def _print(self, string, console_printer=None): # type: (Union[str, bytes], Optional[Callable]) -> None
  530. if console_printer is None:
  531. console_printer = self.console.write_bytes
  532. if self._output_enabled:
  533. console_printer(string)
  534. if self._log_file:
  535. try:
  536. if isinstance(string, type(u'')):
  537. string = string.encode()
  538. self._log_file.write(string) # type: ignore
  539. except Exception as e:
  540. red_print('\nCannot write to file: {}'.format(e))
  541. # don't fill-up the screen with the previous errors (probably consequent prints would fail also)
  542. self.stop_logging()
  543. def handle_commands(self, cmd, chip): # type: (int, str) -> None
  544. config = get_chip_config(chip)
  545. reset_delay = config['reset']
  546. enter_boot_set = config['enter_boot_set']
  547. enter_boot_unset = config['enter_boot_unset']
  548. high = False
  549. low = True
  550. if cmd == CMD_STOP:
  551. self.console_reader.stop()
  552. self.serial_reader.stop()
  553. elif cmd == CMD_RESET:
  554. self.serial.setRTS(low)
  555. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  556. time.sleep(reset_delay)
  557. self.serial.setRTS(high)
  558. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  559. self.output_enable(low)
  560. elif cmd == CMD_MAKE:
  561. self.run_make('encrypted-flash' if self.encrypted else 'flash')
  562. elif cmd == CMD_APP_FLASH:
  563. self.run_make('encrypted-app-flash' if self.encrypted else 'app-flash')
  564. elif cmd == CMD_OUTPUT_TOGGLE:
  565. self.output_toggle()
  566. elif cmd == CMD_TOGGLE_LOGGING:
  567. self.toggle_logging()
  568. elif cmd == CMD_ENTER_BOOT:
  569. self.serial.setDTR(high) # IO0=HIGH
  570. self.serial.setRTS(low) # EN=LOW, chip in reset
  571. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  572. time.sleep(enter_boot_set) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  573. self.serial.setDTR(low) # IO0=LOW
  574. self.serial.setRTS(high) # EN=HIGH, chip out of reset
  575. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  576. time.sleep(enter_boot_unset) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  577. self.serial.setDTR(high) # IO0=HIGH, done
  578. else:
  579. raise RuntimeError('Bad command data %d' % cmd) # type: ignore
  580. def main(): # type: () -> None
  581. parser = argparse.ArgumentParser('idf_monitor - a serial output monitor for esp-idf')
  582. parser.add_argument(
  583. '--port', '-p',
  584. help='Serial port device',
  585. default=os.environ.get('ESPTOOL_PORT', '/dev/ttyUSB0')
  586. )
  587. parser.add_argument(
  588. '--disable-address-decoding', '-d',
  589. help="Don't print lines about decoded addresses from the application ELF file",
  590. action='store_true',
  591. default=True if os.environ.get('ESP_MONITOR_DECODE') == 0 else False
  592. )
  593. parser.add_argument(
  594. '--baud', '-b',
  595. help='Serial port baud rate',
  596. type=int,
  597. default=os.getenv('IDF_MONITOR_BAUD', os.getenv('MONITORBAUD', 115200)))
  598. parser.add_argument(
  599. '--make', '-m',
  600. help='Command to run make',
  601. type=str, default='make')
  602. parser.add_argument(
  603. '--encrypted',
  604. help='Use encrypted targets while running make',
  605. action='store_true')
  606. parser.add_argument(
  607. '--toolchain-prefix',
  608. help='Triplet prefix to add before cross-toolchain names',
  609. default=DEFAULT_TOOLCHAIN_PREFIX)
  610. parser.add_argument(
  611. '--eol',
  612. choices=['CR', 'LF', 'CRLF'],
  613. type=lambda c: c.upper(),
  614. help='End of line to use when sending to the serial port',
  615. default='CR')
  616. parser.add_argument(
  617. 'elf_file', help='ELF file of application',
  618. type=argparse.FileType('rb'))
  619. parser.add_argument(
  620. '--print_filter',
  621. help='Filtering string',
  622. default=DEFAULT_PRINT_FILTER)
  623. parser.add_argument(
  624. '--decode-coredumps',
  625. choices=[COREDUMP_DECODE_INFO, COREDUMP_DECODE_DISABLE],
  626. default=COREDUMP_DECODE_INFO,
  627. help='Handling of core dumps found in serial output'
  628. )
  629. parser.add_argument(
  630. '--decode-panic',
  631. choices=[PANIC_DECODE_BACKTRACE, PANIC_DECODE_DISABLE],
  632. default=PANIC_DECODE_DISABLE,
  633. help='Handling of panic handler info found in serial output'
  634. )
  635. parser.add_argument(
  636. '--target',
  637. help='Target name (used when stack dump decoding is enabled)',
  638. default=os.environ.get('IDF_TARGET', 'esp32')
  639. )
  640. parser.add_argument(
  641. '--revision',
  642. help='Revision of the target',
  643. type=int,
  644. default=0
  645. )
  646. parser.add_argument(
  647. '--ws',
  648. default=os.environ.get('ESP_IDF_MONITOR_WS', None),
  649. help='WebSocket URL for communicating with IDE tools for debugging purposes'
  650. )
  651. args = parser.parse_args()
  652. # GDB uses CreateFile to open COM port, which requires the COM name to be r'\\.\COMx' if the COM
  653. # number is larger than 10
  654. if os.name == 'nt' and args.port.startswith('COM'):
  655. args.port = args.port.replace('COM', r'\\.\COM')
  656. yellow_print('--- WARNING: GDB cannot open serial ports accessed as COMx')
  657. yellow_print('--- Using %s instead...' % args.port)
  658. elif args.port.startswith('/dev/tty.') and sys.platform == 'darwin':
  659. args.port = args.port.replace('/dev/tty.', '/dev/cu.')
  660. yellow_print('--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.')
  661. yellow_print('--- Using %s instead...' % args.port)
  662. serial_instance = serial.serial_for_url(args.port, args.baud,
  663. do_not_open=True)
  664. serial_instance.dtr = False
  665. serial_instance.rts = False
  666. args.elf_file.close() # don't need this as a file
  667. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  668. # parent make is only running 1 job (monitor), so we can re-spawn
  669. # all of the child makes we need (the -j argument remains part of
  670. # MAKEFLAGS)
  671. try:
  672. makeflags = os.environ['MAKEFLAGS']
  673. makeflags = re.sub(r'--jobserver[^ =]*=[0-9,]+ ?', '', makeflags)
  674. os.environ['MAKEFLAGS'] = makeflags
  675. except KeyError:
  676. pass # not running a make jobserver
  677. # Pass the actual used port to callee of idf_monitor (e.g. make) through `ESPPORT` environment
  678. # variable
  679. # To make sure the key as well as the value are str type, by the requirements of subprocess
  680. espport_key = str('ESPPORT')
  681. espport_val = str(args.port)
  682. os.environ.update({espport_key: espport_val})
  683. ws = WebSocketClient(args.ws) if args.ws else None
  684. try:
  685. monitor = Monitor(serial_instance, args.elf_file.name, args.print_filter, args.make, args.encrypted,
  686. args.toolchain_prefix, args.eol,
  687. args.decode_coredumps, args.decode_panic, args.target,
  688. ws, enable_address_decoding=not args.disable_address_decoding)
  689. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(p=serial_instance))
  690. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  691. key_description(monitor.console_parser.exit_key),
  692. key_description(monitor.console_parser.menu_key),
  693. key_description(monitor.console_parser.menu_key),
  694. key_description(CTRL_H)))
  695. if args.print_filter != DEFAULT_PRINT_FILTER:
  696. yellow_print('--- Print filter: {} ---'.format(args.print_filter))
  697. monitor.main_loop()
  698. except KeyboardInterrupt:
  699. pass
  700. finally:
  701. if ws:
  702. ws.close()
  703. if __name__ == '__main__':
  704. main()