idf_monitor.py 32 KB

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