idf_monitor.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  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-2016 Espressif Systems (Shanghai) PTE 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 print_function, division
  33. from __future__ import unicode_literals
  34. from builtins import chr
  35. from builtins import object
  36. from builtins import bytes
  37. import subprocess
  38. import argparse
  39. import codecs
  40. import datetime
  41. import re
  42. import os
  43. try:
  44. import queue
  45. except ImportError:
  46. import Queue as queue
  47. import shlex
  48. import time
  49. import sys
  50. import serial
  51. import serial.tools.list_ports
  52. import serial.tools.miniterm as miniterm
  53. import threading
  54. import ctypes
  55. import types
  56. from distutils.version import StrictVersion
  57. from io import open
  58. import textwrap
  59. import tempfile
  60. key_description = miniterm.key_description
  61. # Control-key characters
  62. CTRL_A = '\x01'
  63. CTRL_B = '\x02'
  64. CTRL_F = '\x06'
  65. CTRL_H = '\x08'
  66. CTRL_R = '\x12'
  67. CTRL_T = '\x14'
  68. CTRL_Y = '\x19'
  69. CTRL_P = '\x10'
  70. CTRL_X = '\x18'
  71. CTRL_L = '\x0c'
  72. CTRL_RBRACKET = '\x1d' # Ctrl+]
  73. # Command parsed from console inputs
  74. CMD_STOP = 1
  75. CMD_RESET = 2
  76. CMD_MAKE = 3
  77. CMD_APP_FLASH = 4
  78. CMD_OUTPUT_TOGGLE = 5
  79. CMD_TOGGLE_LOGGING = 6
  80. CMD_ENTER_BOOT = 7
  81. # ANSI terminal codes (if changed, regular expressions in LineMatcher need to be udpated)
  82. ANSI_RED = '\033[1;31m'
  83. ANSI_YELLOW = '\033[0;33m'
  84. ANSI_NORMAL = '\033[0m'
  85. def color_print(message, color, newline='\n'):
  86. """ Print a message to stderr with colored highlighting """
  87. sys.stderr.write("%s%s%s%s" % (color, message, ANSI_NORMAL, newline))
  88. def yellow_print(message, newline='\n'):
  89. color_print(message, ANSI_YELLOW, newline)
  90. def red_print(message, newline='\n'):
  91. color_print(message, ANSI_RED, newline)
  92. __version__ = "1.1"
  93. # Tags for tuples in queues
  94. TAG_KEY = 0
  95. TAG_SERIAL = 1
  96. TAG_SERIAL_FLUSH = 2
  97. TAG_CMD = 3
  98. # regex matches an potential PC value (0x4xxxxxxx)
  99. MATCH_PCADDR = re.compile(r'0x4[0-9a-f]{7}', re.IGNORECASE)
  100. DEFAULT_TOOLCHAIN_PREFIX = "xtensa-esp32-elf-"
  101. DEFAULT_PRINT_FILTER = ""
  102. # coredump related messages
  103. COREDUMP_UART_START = b"================= CORE DUMP START ================="
  104. COREDUMP_UART_END = b"================= CORE DUMP END ================="
  105. COREDUMP_UART_PROMPT = b"Press Enter to print core dump to UART..."
  106. # coredump states
  107. COREDUMP_IDLE = 0
  108. COREDUMP_READING = 1
  109. COREDUMP_DONE = 2
  110. # coredump decoding options
  111. COREDUMP_DECODE_DISABLE = "disable"
  112. COREDUMP_DECODE_INFO = "info"
  113. class StoppableThread(object):
  114. """
  115. Provide a Thread-like class which can be 'cancelled' via a subclass-provided
  116. cancellation method.
  117. Can be started and stopped multiple times.
  118. Isn't an instance of type Thread because Python Thread objects can only be run once
  119. """
  120. def __init__(self):
  121. self._thread = None
  122. @property
  123. def alive(self):
  124. """
  125. Is 'alive' whenever the internal thread object exists
  126. """
  127. return self._thread is not None
  128. def start(self):
  129. if self._thread is None:
  130. self._thread = threading.Thread(target=self._run_outer)
  131. self._thread.start()
  132. def _cancel(self):
  133. pass # override to provide cancellation functionality
  134. def run(self):
  135. pass # override for the main thread behaviour
  136. def _run_outer(self):
  137. try:
  138. self.run()
  139. finally:
  140. self._thread = None
  141. def stop(self):
  142. if self._thread is not None:
  143. old_thread = self._thread
  144. self._thread = None
  145. self._cancel()
  146. old_thread.join()
  147. class ConsoleReader(StoppableThread):
  148. """ Read input keys from the console and push them to the queue,
  149. until stopped.
  150. """
  151. def __init__(self, console, event_queue, cmd_queue, parser, test_mode):
  152. super(ConsoleReader, self).__init__()
  153. self.console = console
  154. self.event_queue = event_queue
  155. self.cmd_queue = cmd_queue
  156. self.parser = parser
  157. self.test_mode = test_mode
  158. def run(self):
  159. self.console.setup()
  160. try:
  161. while self.alive:
  162. try:
  163. if os.name == 'nt':
  164. # Windows kludge: because the console.cancel() method doesn't
  165. # seem to work to unblock getkey() on the Windows implementation.
  166. #
  167. # So we only call getkey() if we know there's a key waiting for us.
  168. import msvcrt
  169. while not msvcrt.kbhit() and self.alive:
  170. time.sleep(0.1)
  171. if not self.alive:
  172. break
  173. elif self.test_mode:
  174. # In testing mode the stdin is connected to PTY but is not used for input anything. For PTY
  175. # the canceling by fcntl.ioctl isn't working and would hang in self.console.getkey().
  176. # Therefore, we avoid calling it.
  177. while self.alive:
  178. time.sleep(0.1)
  179. break
  180. c = self.console.getkey()
  181. except KeyboardInterrupt:
  182. c = '\x03'
  183. if c is not None:
  184. ret = self.parser.parse(c)
  185. if ret is not None:
  186. (tag, cmd) = ret
  187. # stop command should be executed last
  188. if tag == TAG_CMD and cmd != CMD_STOP:
  189. self.cmd_queue.put(ret)
  190. else:
  191. self.event_queue.put(ret)
  192. finally:
  193. self.console.cleanup()
  194. def _cancel(self):
  195. if os.name == 'posix' and not self.test_mode:
  196. # this is the way cancel() is implemented in pyserial 3.3 or newer,
  197. # older pyserial (3.1+) has cancellation implemented via 'select',
  198. # which does not work when console sends an escape sequence response
  199. #
  200. # even older pyserial (<3.1) does not have this method
  201. #
  202. # on Windows there is a different (also hacky) fix, applied above.
  203. #
  204. # note that TIOCSTI is not implemented in WSL / bash-on-Windows.
  205. # TODO: introduce some workaround to make it work there.
  206. #
  207. # Note: This would throw exception in testing mode when the stdin is connected to PTY.
  208. import fcntl
  209. import termios
  210. fcntl.ioctl(self.console.fd, termios.TIOCSTI, b'\0')
  211. class ConsoleParser(object):
  212. def __init__(self, eol="CRLF"):
  213. self.translate_eol = {
  214. "CRLF": lambda c: c.replace("\n", "\r\n"),
  215. "CR": lambda c: c.replace("\n", "\r"),
  216. "LF": lambda c: c.replace("\r", "\n"),
  217. }[eol]
  218. self.menu_key = CTRL_T
  219. self.exit_key = CTRL_RBRACKET
  220. self._pressed_menu_key = False
  221. def parse(self, key):
  222. ret = None
  223. if self._pressed_menu_key:
  224. ret = self._handle_menu_key(key)
  225. elif key == self.menu_key:
  226. self._pressed_menu_key = True
  227. elif key == self.exit_key:
  228. ret = (TAG_CMD, CMD_STOP)
  229. else:
  230. key = self.translate_eol(key)
  231. ret = (TAG_KEY, key)
  232. return ret
  233. def _handle_menu_key(self, c):
  234. ret = None
  235. if c == self.exit_key or c == self.menu_key: # send verbatim
  236. ret = (TAG_KEY, c)
  237. elif c in [CTRL_H, 'h', 'H', '?']:
  238. red_print(self.get_help_text())
  239. elif c == CTRL_R: # Reset device via RTS
  240. ret = (TAG_CMD, CMD_RESET)
  241. elif c == CTRL_F: # Recompile & upload
  242. ret = (TAG_CMD, CMD_MAKE)
  243. elif c in [CTRL_A, 'a', 'A']: # Recompile & upload app only
  244. # "CTRL-A" cannot be captured with the default settings of the Windows command line, therefore, "A" can be used
  245. # instead
  246. ret = (TAG_CMD, CMD_APP_FLASH)
  247. elif c == CTRL_Y: # Toggle output display
  248. ret = (TAG_CMD, CMD_OUTPUT_TOGGLE)
  249. elif c == CTRL_L: # Toggle saving output into file
  250. ret = (TAG_CMD, CMD_TOGGLE_LOGGING)
  251. elif c == CTRL_P:
  252. yellow_print("Pause app (enter bootloader mode), press Ctrl-T Ctrl-R to restart")
  253. # to fast trigger pause without press menu key
  254. ret = (TAG_CMD, CMD_ENTER_BOOT)
  255. elif c in [CTRL_X, 'x', 'X']: # Exiting from within the menu
  256. ret = (TAG_CMD, CMD_STOP)
  257. else:
  258. red_print('--- unknown menu character {} --'.format(key_description(c)))
  259. self._pressed_menu_key = False
  260. return ret
  261. def get_help_text(self):
  262. text = """\
  263. --- idf_monitor ({version}) - ESP-IDF monitor tool
  264. --- based on miniterm from pySerial
  265. ---
  266. --- {exit:8} Exit program
  267. --- {menu:8} Menu escape key, followed by:
  268. --- Menu keys:
  269. --- {menu:14} Send the menu character itself to remote
  270. --- {exit:14} Send the exit character itself to remote
  271. --- {reset:14} Reset target board via RTS line
  272. --- {makecmd:14} Build & flash project
  273. --- {appmake:14} Build & flash app only
  274. --- {output:14} Toggle output display
  275. --- {log:14} Toggle saving output into file
  276. --- {pause:14} Reset target into bootloader to pause app via RTS line
  277. --- {menuexit:14} Exit program
  278. """.format(version=__version__,
  279. exit=key_description(self.exit_key),
  280. menu=key_description(self.menu_key),
  281. reset=key_description(CTRL_R),
  282. makecmd=key_description(CTRL_F),
  283. appmake=key_description(CTRL_A) + ' (or A)',
  284. output=key_description(CTRL_Y),
  285. log=key_description(CTRL_L),
  286. pause=key_description(CTRL_P),
  287. menuexit=key_description(CTRL_X) + ' (or X)')
  288. return textwrap.dedent(text)
  289. def get_next_action_text(self):
  290. text = """\
  291. --- Press {} to exit monitor.
  292. --- Press {} to build & flash project.
  293. --- Press {} to build & flash app.
  294. --- Press any other key to resume monitor (resets target).
  295. """.format(key_description(self.exit_key),
  296. key_description(CTRL_F),
  297. key_description(CTRL_A))
  298. return textwrap.dedent(text)
  299. def parse_next_action_key(self, c):
  300. ret = None
  301. if c == self.exit_key:
  302. ret = (TAG_CMD, CMD_STOP)
  303. elif c == CTRL_F: # Recompile & upload
  304. ret = (TAG_CMD, CMD_MAKE)
  305. elif c in [CTRL_A, 'a', 'A']: # Recompile & upload app only
  306. # "CTRL-A" cannot be captured with the default settings of the Windows command line, therefore, "A" can be used
  307. # instead
  308. ret = (TAG_CMD, CMD_APP_FLASH)
  309. return ret
  310. class SerialReader(StoppableThread):
  311. """ Read serial data from the serial port and push to the
  312. event queue, until stopped.
  313. """
  314. def __init__(self, serial, event_queue):
  315. super(SerialReader, self).__init__()
  316. self.baud = serial.baudrate
  317. self.serial = serial
  318. self.event_queue = event_queue
  319. if not hasattr(self.serial, 'cancel_read'):
  320. # enable timeout for checking alive flag,
  321. # if cancel_read not available
  322. self.serial.timeout = 0.25
  323. def run(self):
  324. if not self.serial.is_open:
  325. self.serial.baudrate = self.baud
  326. self.serial.rts = True # Force an RTS reset on open
  327. self.serial.open()
  328. self.serial.rts = False
  329. self.serial.dtr = self.serial.dtr # usbser.sys workaround
  330. try:
  331. while self.alive:
  332. data = self.serial.read(self.serial.in_waiting or 1)
  333. if len(data):
  334. self.event_queue.put((TAG_SERIAL, data), False)
  335. finally:
  336. self.serial.close()
  337. def _cancel(self):
  338. if hasattr(self.serial, 'cancel_read'):
  339. try:
  340. self.serial.cancel_read()
  341. except Exception:
  342. pass
  343. class LineMatcher(object):
  344. """
  345. Assembles a dictionary of filtering rules based on the --print_filter
  346. argument of idf_monitor. Then later it is used to match lines and
  347. determine whether they should be shown on screen or not.
  348. """
  349. LEVEL_N = 0
  350. LEVEL_E = 1
  351. LEVEL_W = 2
  352. LEVEL_I = 3
  353. LEVEL_D = 4
  354. LEVEL_V = 5
  355. level = {'N': LEVEL_N, 'E': LEVEL_E, 'W': LEVEL_W, 'I': LEVEL_I, 'D': LEVEL_D,
  356. 'V': LEVEL_V, '*': LEVEL_V, '': LEVEL_V}
  357. def __init__(self, print_filter):
  358. self._dict = dict()
  359. self._re = re.compile(r'^(?:\033\[[01];?[0-9]+m?)?([EWIDV]) \([0-9]+\) ([^:]+): ')
  360. items = print_filter.split()
  361. if len(items) == 0:
  362. self._dict["*"] = self.LEVEL_V # default is to print everything
  363. for f in items:
  364. s = f.split(r':')
  365. if len(s) == 1:
  366. # specifying no warning level defaults to verbose level
  367. lev = self.LEVEL_V
  368. elif len(s) == 2:
  369. if len(s[0]) == 0:
  370. raise ValueError('No tag specified in filter ' + f)
  371. try:
  372. lev = self.level[s[1].upper()]
  373. except KeyError:
  374. raise ValueError('Unknown warning level in filter ' + f)
  375. else:
  376. raise ValueError('Missing ":" in filter ' + f)
  377. self._dict[s[0]] = lev
  378. def match(self, line):
  379. try:
  380. m = self._re.search(line)
  381. if m:
  382. lev = self.level[m.group(1)]
  383. if m.group(2) in self._dict:
  384. return self._dict[m.group(2)] >= lev
  385. return self._dict.get("*", self.LEVEL_N) >= lev
  386. except (KeyError, IndexError):
  387. # Regular line written with something else than ESP_LOG*
  388. # or an empty line.
  389. pass
  390. # We need something more than "*.N" for printing.
  391. return self._dict.get("*", self.LEVEL_N) > self.LEVEL_N
  392. class SerialStopException(Exception):
  393. """
  394. This exception is used for stopping the IDF monitor in testing mode.
  395. """
  396. pass
  397. class Monitor(object):
  398. """
  399. Monitor application main class.
  400. This was originally derived from miniterm.Miniterm, but it turned out to be easier to write from scratch for this
  401. purpose.
  402. Main difference is that all event processing happens in the main thread, not the worker threads.
  403. """
  404. def __init__(self, serial_instance, elf_file, print_filter, make="make", toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, eol="CRLF",
  405. decode_coredumps=COREDUMP_DECODE_INFO):
  406. super(Monitor, self).__init__()
  407. self.event_queue = queue.Queue()
  408. self.cmd_queue = queue.Queue()
  409. self.console = miniterm.Console()
  410. if os.name == 'nt':
  411. sys.stderr = ANSIColorConverter(sys.stderr, decode_output=True)
  412. self.console.output = ANSIColorConverter(self.console.output)
  413. self.console.byte_output = ANSIColorConverter(self.console.byte_output)
  414. if StrictVersion(serial.VERSION) < StrictVersion('3.3.0'):
  415. # Use Console.getkey implementation from 3.3.0 (to be in sync with the ConsoleReader._cancel patch above)
  416. def getkey_patched(self):
  417. c = self.enc_stdin.read(1)
  418. if c == chr(0x7f):
  419. c = chr(8) # map the BS key (which yields DEL) to backspace
  420. return c
  421. self.console.getkey = types.MethodType(getkey_patched, self.console)
  422. socket_mode = serial_instance.port.startswith("socket://") # testing hook - data from serial can make exit the monitor
  423. self.serial = serial_instance
  424. self.console_parser = ConsoleParser(eol)
  425. self.console_reader = ConsoleReader(self.console, self.event_queue, self.cmd_queue, self.console_parser, socket_mode)
  426. self.serial_reader = SerialReader(self.serial, self.event_queue)
  427. self.elf_file = elf_file
  428. if not os.path.exists(make):
  429. self.make = shlex.split(make) # allow for possibility the "make" arg is a list of arguments (for idf.py)
  430. else:
  431. self.make = make
  432. self.toolchain_prefix = toolchain_prefix
  433. # internal state
  434. self._last_line_part = b""
  435. self._gdb_buffer = b""
  436. self._pc_address_buffer = b""
  437. self._line_matcher = LineMatcher(print_filter)
  438. self._invoke_processing_last_line_timer = None
  439. self._force_line_print = False
  440. self._output_enabled = True
  441. self._serial_check_exit = socket_mode
  442. self._log_file = None
  443. self._decode_coredumps = decode_coredumps
  444. self._reading_coredump = COREDUMP_IDLE
  445. self._coredump_buffer = b""
  446. def invoke_processing_last_line(self):
  447. self.event_queue.put((TAG_SERIAL_FLUSH, b''), False)
  448. def main_loop(self):
  449. self.console_reader.start()
  450. self.serial_reader.start()
  451. try:
  452. while self.console_reader.alive and self.serial_reader.alive:
  453. try:
  454. item = self.cmd_queue.get_nowait()
  455. except queue.Empty:
  456. try:
  457. item = self.event_queue.get(True, 0.03)
  458. except queue.Empty:
  459. continue
  460. (event_tag, data) = item
  461. if event_tag == TAG_CMD:
  462. self.handle_commands(data)
  463. elif event_tag == TAG_KEY:
  464. try:
  465. self.serial.write(codecs.encode(data))
  466. except serial.SerialException:
  467. pass # this shouldn't happen, but sometimes port has closed in serial thread
  468. except UnicodeEncodeError:
  469. pass # this can happen if a non-ascii character was passed, ignoring
  470. elif event_tag == TAG_SERIAL:
  471. self.handle_serial_input(data)
  472. if self._invoke_processing_last_line_timer is not None:
  473. self._invoke_processing_last_line_timer.cancel()
  474. self._invoke_processing_last_line_timer = threading.Timer(0.1, self.invoke_processing_last_line)
  475. self._invoke_processing_last_line_timer.start()
  476. # If no futher data is received in the next short period
  477. # of time then the _invoke_processing_last_line_timer
  478. # generates an event which will result in the finishing of
  479. # the last line. This is fix for handling lines sent
  480. # without EOL.
  481. elif event_tag == TAG_SERIAL_FLUSH:
  482. self.handle_serial_input(data, finalize_line=True)
  483. else:
  484. raise RuntimeError("Bad event data %r" % ((event_tag,data),))
  485. except SerialStopException:
  486. sys.stderr.write(ANSI_NORMAL + "Stopping condition has been received\n")
  487. finally:
  488. try:
  489. self.console_reader.stop()
  490. self.serial_reader.stop()
  491. self.stop_logging()
  492. # Cancelling _invoke_processing_last_line_timer is not
  493. # important here because receiving empty data doesn't matter.
  494. self._invoke_processing_last_line_timer = None
  495. except Exception:
  496. pass
  497. sys.stderr.write(ANSI_NORMAL + "\n")
  498. def handle_serial_input(self, data, finalize_line=False):
  499. sp = data.split(b'\n')
  500. if self._last_line_part != b"":
  501. # add unprocessed part from previous "data" to the first line
  502. sp[0] = self._last_line_part + sp[0]
  503. self._last_line_part = b""
  504. if sp[-1] != b"":
  505. # last part is not a full line
  506. self._last_line_part = sp.pop()
  507. for line in sp:
  508. if line != b"":
  509. if self._serial_check_exit and line == self.console_parser.exit_key.encode('latin-1'):
  510. raise SerialStopException()
  511. self.check_coredump_trigger_before_print(line)
  512. if self._force_line_print or self._line_matcher.match(line.decode(errors="ignore")):
  513. self._print(line + b'\n')
  514. self.handle_possible_pc_address_in_line(line)
  515. self.check_coredump_trigger_after_print(line)
  516. self.check_gdbstub_trigger(line)
  517. self._force_line_print = False
  518. # Now we have the last part (incomplete line) in _last_line_part. By
  519. # default we don't touch it and just wait for the arrival of the rest
  520. # of the line. But after some time when we didn't received it we need
  521. # to make a decision.
  522. if self._last_line_part != b"":
  523. if self._force_line_print or (finalize_line and self._line_matcher.match(self._last_line_part.decode(errors="ignore"))):
  524. self._force_line_print = True
  525. self._print(self._last_line_part)
  526. self.handle_possible_pc_address_in_line(self._last_line_part)
  527. self.check_gdbstub_trigger(self._last_line_part)
  528. # It is possible that the incomplete line cuts in half the PC
  529. # address. A small buffer is kept and will be used the next time
  530. # handle_possible_pc_address_in_line is invoked to avoid this problem.
  531. # MATCH_PCADDR matches 10 character long addresses. Therefore, we
  532. # keep the last 9 characters.
  533. self._pc_address_buffer = self._last_line_part[-9:]
  534. # GDB sequence can be cut in half also. GDB sequence is 7
  535. # characters long, therefore, we save the last 6 characters.
  536. self._gdb_buffer = self._last_line_part[-6:]
  537. self._last_line_part = b""
  538. # else: keeping _last_line_part and it will be processed the next time
  539. # handle_serial_input is invoked
  540. def handle_possible_pc_address_in_line(self, line):
  541. line = self._pc_address_buffer + line
  542. self._pc_address_buffer = b""
  543. for m in re.finditer(MATCH_PCADDR, line.decode(errors="ignore")):
  544. self.lookup_pc_address(m.group())
  545. def __enter__(self):
  546. """ Use 'with self' to temporarily disable monitoring behaviour """
  547. self.serial_reader.stop()
  548. self.console_reader.stop()
  549. def __exit__(self, *args, **kwargs):
  550. """ Use 'with self' to temporarily disable monitoring behaviour """
  551. self.console_reader.start()
  552. self.serial_reader.start()
  553. def prompt_next_action(self, reason):
  554. self.console.setup() # set up console to trap input characters
  555. try:
  556. red_print("--- {}".format(reason))
  557. red_print(self.console_parser.get_next_action_text())
  558. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  559. while k == CTRL_T:
  560. k = self.console.getkey()
  561. finally:
  562. self.console.cleanup()
  563. ret = self.console_parser.parse_next_action_key(k)
  564. if ret is not None:
  565. cmd = ret[1]
  566. if cmd == CMD_STOP:
  567. # the stop command should be handled last
  568. self.event_queue.put(ret)
  569. else:
  570. self.cmd_queue.put(ret)
  571. def run_make(self, target):
  572. with self:
  573. if isinstance(self.make, list):
  574. popen_args = self.make + [target]
  575. else:
  576. popen_args = [self.make, target]
  577. yellow_print("Running %s..." % " ".join(popen_args))
  578. p = subprocess.Popen(popen_args)
  579. try:
  580. p.wait()
  581. except KeyboardInterrupt:
  582. p.wait()
  583. if p.returncode != 0:
  584. self.prompt_next_action("Build failed")
  585. else:
  586. self.output_enable(True)
  587. def lookup_pc_address(self, pc_addr):
  588. cmd = ["%saddr2line" % self.toolchain_prefix,
  589. "-pfiaC", "-e", self.elf_file, pc_addr]
  590. try:
  591. translation = subprocess.check_output(cmd, cwd=".")
  592. if b"?? ??:0" not in translation:
  593. self._print(translation.decode(), console_printer=yellow_print)
  594. except OSError as e:
  595. red_print("%s: %s" % (" ".join(cmd), e))
  596. def check_gdbstub_trigger(self, line):
  597. line = self._gdb_buffer + line
  598. self._gdb_buffer = b""
  599. m = re.search(b"\\$(T..)#(..)", line) # look for a gdb "reason" for a break
  600. if m is not None:
  601. try:
  602. chsum = sum(ord(bytes([p])) for p in m.group(1)) & 0xFF
  603. calc_chsum = int(m.group(2), 16)
  604. except ValueError:
  605. return # payload wasn't valid hex digits
  606. if chsum == calc_chsum:
  607. self.run_gdb()
  608. else:
  609. red_print("Malformed gdb message... calculated checksum %02x received %02x" % (chsum, calc_chsum))
  610. def check_coredump_trigger_before_print(self, line):
  611. if self._decode_coredumps == COREDUMP_DECODE_DISABLE:
  612. return
  613. if COREDUMP_UART_PROMPT in line:
  614. yellow_print("Initiating core dump!")
  615. self.event_queue.put((TAG_KEY, '\n'))
  616. return
  617. if COREDUMP_UART_START in line:
  618. yellow_print("Core dump started (further output muted)")
  619. self._reading_coredump = COREDUMP_READING
  620. self._coredump_buffer = b""
  621. self._output_enabled = False
  622. return
  623. if COREDUMP_UART_END in line:
  624. self._reading_coredump = COREDUMP_DONE
  625. yellow_print("\nCore dump finished!")
  626. self.process_coredump()
  627. return
  628. if self._reading_coredump == COREDUMP_READING:
  629. kb = 1024
  630. buffer_len_kb = len(self._coredump_buffer) // kb
  631. self._coredump_buffer += line.replace(b'\r', b'') + b'\n'
  632. new_buffer_len_kb = len(self._coredump_buffer) // kb
  633. if new_buffer_len_kb > buffer_len_kb:
  634. yellow_print("Received %3d kB..." % (new_buffer_len_kb), newline='\r')
  635. def check_coredump_trigger_after_print(self, line):
  636. if self._decode_coredumps == COREDUMP_DECODE_DISABLE:
  637. return
  638. # Re-enable output after the last line of core dump has been consumed
  639. if not self._output_enabled and self._reading_coredump == COREDUMP_DONE:
  640. self._reading_coredump = COREDUMP_IDLE
  641. self._output_enabled = True
  642. self._coredump_buffer = b""
  643. def process_coredump(self):
  644. if self._decode_coredumps != COREDUMP_DECODE_INFO:
  645. raise NotImplementedError("process_coredump: %s not implemented" % self._decode_coredumps)
  646. coredump_script = os.path.join(os.path.dirname(__file__), "..", "components", "espcoredump", "espcoredump.py")
  647. coredump_file = None
  648. try:
  649. # On Windows, the temporary file can't be read unless it is closed.
  650. # Set delete=False and delete the file manually later.
  651. with tempfile.NamedTemporaryFile(mode="wb", delete=False) as coredump_file:
  652. coredump_file.write(self._coredump_buffer)
  653. coredump_file.flush()
  654. cmd = [sys.executable,
  655. coredump_script,
  656. "info_corefile",
  657. "--core", coredump_file.name,
  658. "--core-format", "b64",
  659. self.elf_file
  660. ]
  661. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  662. self._output_enabled = True
  663. self._print(output)
  664. self._output_enabled = False # Will be reenabled in check_coredump_trigger_after_print
  665. except subprocess.CalledProcessError as e:
  666. yellow_print("Failed to run espcoredump script: {}\n\n".format(e))
  667. self._output_enabled = True
  668. self._print(COREDUMP_UART_START + b'\n')
  669. self._print(self._coredump_buffer)
  670. # end line will be printed in handle_serial_input
  671. finally:
  672. if coredump_file is not None:
  673. try:
  674. os.unlink(coredump_file.name)
  675. except OSError as e:
  676. yellow_print("Couldn't remote temporary core dump file ({})".format(e))
  677. def run_gdb(self):
  678. with self: # disable console control
  679. sys.stderr.write(ANSI_NORMAL)
  680. try:
  681. cmd = ["%sgdb" % self.toolchain_prefix,
  682. "-ex", "set serial baud %d" % self.serial.baudrate,
  683. "-ex", "target remote %s" % self.serial.port,
  684. "-ex", "interrupt", # monitor has already parsed the first 'reason' command, need a second
  685. self.elf_file]
  686. process = subprocess.Popen(cmd, cwd=".")
  687. process.wait()
  688. except OSError as e:
  689. red_print("%s: %s" % (" ".join(cmd), e))
  690. except KeyboardInterrupt:
  691. pass # happens on Windows, maybe other OSes
  692. finally:
  693. try:
  694. # on Linux, maybe other OSes, gdb sometimes seems to be alive even after wait() returns...
  695. process.terminate()
  696. except Exception:
  697. pass
  698. try:
  699. # also on Linux, maybe other OSes, gdb sometimes exits uncleanly and breaks the tty mode
  700. subprocess.call(["stty", "sane"])
  701. except Exception:
  702. pass # don't care if there's no stty, we tried...
  703. self.prompt_next_action("gdb exited")
  704. def output_enable(self, enable):
  705. self._output_enabled = enable
  706. def output_toggle(self):
  707. self._output_enabled = not self._output_enabled
  708. yellow_print("\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.".format(self._output_enabled))
  709. def toggle_logging(self):
  710. if self._log_file:
  711. self.stop_logging()
  712. else:
  713. self.start_logging()
  714. def start_logging(self):
  715. if not self._log_file:
  716. try:
  717. name = "log.{}.{}.txt".format(os.path.splitext(os.path.basename(self.elf_file))[0],
  718. datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
  719. self._log_file = open(name, "wb+")
  720. yellow_print("\nLogging is enabled into file {}".format(name))
  721. except Exception as e:
  722. red_print("\nLog file {} cannot be created: {}".format(name, e))
  723. def stop_logging(self):
  724. if self._log_file:
  725. try:
  726. name = self._log_file.name
  727. self._log_file.close()
  728. yellow_print("\nLogging is disabled and file {} has been closed".format(name))
  729. except Exception as e:
  730. red_print("\nLog file cannot be closed: {}".format(e))
  731. finally:
  732. self._log_file = None
  733. def _print(self, string, console_printer=None):
  734. if console_printer is None:
  735. console_printer = self.console.write_bytes
  736. if self._output_enabled:
  737. console_printer(string)
  738. if self._log_file:
  739. try:
  740. if isinstance(string, type(u'')):
  741. string = string.encode()
  742. self._log_file.write(string)
  743. except Exception as e:
  744. red_print("\nCannot write to file: {}".format(e))
  745. # don't fill-up the screen with the previous errors (probably consequent prints would fail also)
  746. self.stop_logging()
  747. def handle_commands(self, cmd):
  748. if cmd == CMD_STOP:
  749. self.console_reader.stop()
  750. self.serial_reader.stop()
  751. elif cmd == CMD_RESET:
  752. self.serial.setRTS(True)
  753. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  754. time.sleep(0.2)
  755. self.serial.setRTS(False)
  756. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  757. self.output_enable(True)
  758. elif cmd == CMD_MAKE:
  759. self.run_make("flash")
  760. elif cmd == CMD_APP_FLASH:
  761. self.run_make("app-flash")
  762. elif cmd == CMD_OUTPUT_TOGGLE:
  763. self.output_toggle()
  764. elif cmd == CMD_TOGGLE_LOGGING:
  765. self.toggle_logging()
  766. elif cmd == CMD_ENTER_BOOT:
  767. self.serial.setDTR(False) # IO0=HIGH
  768. self.serial.setRTS(True) # EN=LOW, chip in reset
  769. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  770. time.sleep(1.3) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  771. self.serial.setDTR(True) # IO0=LOW
  772. self.serial.setRTS(False) # EN=HIGH, chip out of reset
  773. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  774. time.sleep(0.45) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  775. self.serial.setDTR(False) # IO0=HIGH, done
  776. else:
  777. raise RuntimeError("Bad command data %d" % (cmd))
  778. def main():
  779. def _get_default_serial_port():
  780. """
  781. Same logic for detecting serial port as esptool.py and idf.py: reverse sort by name and choose the first port.
  782. """
  783. try:
  784. ports = list(reversed(sorted(p.device for p in serial.tools.list_ports.comports())))
  785. return ports[0]
  786. except Exception:
  787. return '/dev/ttyUSB0'
  788. parser = argparse.ArgumentParser("idf_monitor - a serial output monitor for esp-idf")
  789. parser.add_argument(
  790. '--port', '-p',
  791. help='Serial port device',
  792. default=os.environ.get('ESPTOOL_PORT', _get_default_serial_port())
  793. )
  794. parser.add_argument(
  795. '--baud', '-b',
  796. help='Serial port baud rate',
  797. type=int,
  798. default=os.getenv('IDF_MONITOR_BAUD', os.getenv('MONITORBAUD', 115200)))
  799. parser.add_argument(
  800. '--make', '-m',
  801. help='Command to run make',
  802. type=str, default='make')
  803. parser.add_argument(
  804. '--toolchain-prefix',
  805. help="Triplet prefix to add before cross-toolchain names",
  806. default=DEFAULT_TOOLCHAIN_PREFIX)
  807. parser.add_argument(
  808. "--eol",
  809. choices=['CR', 'LF', 'CRLF'],
  810. type=lambda c: c.upper(),
  811. help="End of line to use when sending to the serial port",
  812. default='CR')
  813. parser.add_argument(
  814. 'elf_file', help='ELF file of application',
  815. type=argparse.FileType('rb'))
  816. parser.add_argument(
  817. '--print_filter',
  818. help="Filtering string",
  819. default=DEFAULT_PRINT_FILTER)
  820. parser.add_argument(
  821. '--decode-coredumps',
  822. choices=[COREDUMP_DECODE_INFO, COREDUMP_DECODE_DISABLE],
  823. default=COREDUMP_DECODE_INFO,
  824. help="Handling of core dumps found in serial output"
  825. )
  826. args = parser.parse_args()
  827. # GDB uses CreateFile to open COM port, which requires the COM name to be r'\\.\COMx' if the COM
  828. # number is larger than 10
  829. if os.name == 'nt' and args.port.startswith("COM"):
  830. args.port = args.port.replace('COM', r'\\.\COM')
  831. yellow_print("--- WARNING: GDB cannot open serial ports accessed as COMx")
  832. yellow_print("--- Using %s instead..." % args.port)
  833. elif args.port.startswith("/dev/tty."):
  834. args.port = args.port.replace("/dev/tty.", "/dev/cu.")
  835. yellow_print("--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.")
  836. yellow_print("--- Using %s instead..." % args.port)
  837. serial_instance = serial.serial_for_url(args.port, args.baud,
  838. do_not_open=True)
  839. serial_instance.dtr = False
  840. serial_instance.rts = False
  841. args.elf_file.close() # don't need this as a file
  842. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  843. # parent make is only running 1 job (monitor), so we can re-spawn
  844. # all of the child makes we need (the -j argument remains part of
  845. # MAKEFLAGS)
  846. try:
  847. makeflags = os.environ["MAKEFLAGS"]
  848. makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
  849. os.environ["MAKEFLAGS"] = makeflags
  850. except KeyError:
  851. pass # not running a make jobserver
  852. monitor = Monitor(serial_instance, args.elf_file.name, args.print_filter, args.make, args.toolchain_prefix, args.eol,
  853. args.decode_coredumps)
  854. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  855. p=serial_instance))
  856. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  857. key_description(monitor.console_parser.exit_key),
  858. key_description(monitor.console_parser.menu_key),
  859. key_description(monitor.console_parser.menu_key),
  860. key_description(CTRL_H)))
  861. if args.print_filter != DEFAULT_PRINT_FILTER:
  862. yellow_print('--- Print filter: {} ---'.format(args.print_filter))
  863. monitor.main_loop()
  864. if os.name == 'nt':
  865. # Windows console stuff
  866. STD_OUTPUT_HANDLE = -11
  867. STD_ERROR_HANDLE = -12
  868. # wincon.h values
  869. FOREGROUND_INTENSITY = 8
  870. FOREGROUND_GREY = 7
  871. # matches the ANSI color change sequences that IDF sends
  872. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  873. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  874. ANSI_TO_WINDOWS_COLOR = [0, 4, 2, 6, 1, 5, 3, 7]
  875. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  876. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  877. class ANSIColorConverter(object):
  878. """Class to wrap a file-like output stream, intercept ANSI color codes,
  879. and convert them into calls to Windows SetConsoleTextAttribute.
  880. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  881. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  882. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  883. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  884. """
  885. def __init__(self, output=None, decode_output=False):
  886. self.output = output
  887. self.decode_output = decode_output
  888. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  889. self.matched = b''
  890. def _output_write(self, data):
  891. try:
  892. if self.decode_output:
  893. self.output.write(data.decode())
  894. else:
  895. self.output.write(data)
  896. except (IOError, OSError):
  897. # Windows 10 bug since the Fall Creators Update, sometimes writing to console randomly throws
  898. # an exception (however, the character is still written to the screen)
  899. # Ref https://github.com/espressif/esp-idf/issues/1163
  900. #
  901. # Also possible for Windows to throw an OSError error if the data is invalid for the console
  902. # (garbage bytes, etc)
  903. pass
  904. def write(self, data):
  905. if isinstance(data, bytes):
  906. data = bytearray(data)
  907. else:
  908. data = bytearray(data, 'utf-8')
  909. for b in data:
  910. b = bytes([b])
  911. length = len(self.matched)
  912. if b == b'\033': # ESC
  913. self.matched = b
  914. elif (length == 1 and b == b'[') or (1 < length < 7):
  915. self.matched += b
  916. if self.matched == ANSI_NORMAL.encode('latin-1'): # reset console
  917. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  918. self.flush()
  919. SetConsoleTextAttribute(self.handle, FOREGROUND_GREY)
  920. self.matched = b''
  921. elif len(self.matched) == 7: # could be an ANSI sequence
  922. m = re.match(RE_ANSI_COLOR, self.matched)
  923. if m is not None:
  924. color = ANSI_TO_WINDOWS_COLOR[int(m.group(2))]
  925. if m.group(1) == b'1':
  926. color |= FOREGROUND_INTENSITY
  927. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  928. self.flush()
  929. SetConsoleTextAttribute(self.handle, color)
  930. else:
  931. self._output_write(self.matched) # not an ANSI color code, display verbatim
  932. self.matched = b''
  933. else:
  934. self._output_write(b)
  935. self.matched = b''
  936. def flush(self):
  937. try:
  938. self.output.flush()
  939. except OSError:
  940. # Account for Windows Console refusing to accept garbage bytes (serial noise, etc)
  941. pass
  942. if __name__ == "__main__":
  943. main()