idf_monitor.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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", encrypted=False,
  405. toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, eol="CRLF",
  406. decode_coredumps=COREDUMP_DECODE_INFO):
  407. super(Monitor, self).__init__()
  408. self.event_queue = queue.Queue()
  409. self.cmd_queue = queue.Queue()
  410. self.console = miniterm.Console()
  411. if os.name == 'nt':
  412. sys.stderr = ANSIColorConverter(sys.stderr, decode_output=True)
  413. self.console.output = ANSIColorConverter(self.console.output)
  414. self.console.byte_output = ANSIColorConverter(self.console.byte_output)
  415. if StrictVersion(serial.VERSION) < StrictVersion('3.3.0'):
  416. # Use Console.getkey implementation from 3.3.0 (to be in sync with the ConsoleReader._cancel patch above)
  417. def getkey_patched(self):
  418. c = self.enc_stdin.read(1)
  419. if c == chr(0x7f):
  420. c = chr(8) # map the BS key (which yields DEL) to backspace
  421. return c
  422. self.console.getkey = types.MethodType(getkey_patched, self.console)
  423. socket_mode = serial_instance.port.startswith("socket://") # testing hook - data from serial can make exit the monitor
  424. self.serial = serial_instance
  425. self.console_parser = ConsoleParser(eol)
  426. self.console_reader = ConsoleReader(self.console, self.event_queue, self.cmd_queue, self.console_parser, socket_mode)
  427. self.serial_reader = SerialReader(self.serial, self.event_queue)
  428. self.elf_file = elf_file
  429. if not os.path.exists(make):
  430. self.make = shlex.split(make) # allow for possibility the "make" arg is a list of arguments (for idf.py)
  431. else:
  432. self.make = make
  433. self.encrypted = encrypted
  434. self.toolchain_prefix = toolchain_prefix
  435. # internal state
  436. self._last_line_part = b""
  437. self._gdb_buffer = b""
  438. self._pc_address_buffer = b""
  439. self._line_matcher = LineMatcher(print_filter)
  440. self._invoke_processing_last_line_timer = None
  441. self._force_line_print = False
  442. self._output_enabled = True
  443. self._serial_check_exit = socket_mode
  444. self._log_file = None
  445. self._decode_coredumps = decode_coredumps
  446. self._reading_coredump = COREDUMP_IDLE
  447. self._coredump_buffer = b""
  448. def invoke_processing_last_line(self):
  449. self.event_queue.put((TAG_SERIAL_FLUSH, b''), False)
  450. def main_loop(self):
  451. self.console_reader.start()
  452. self.serial_reader.start()
  453. try:
  454. while self.console_reader.alive and self.serial_reader.alive:
  455. try:
  456. item = self.cmd_queue.get_nowait()
  457. except queue.Empty:
  458. try:
  459. item = self.event_queue.get(True, 0.03)
  460. except queue.Empty:
  461. continue
  462. (event_tag, data) = item
  463. if event_tag == TAG_CMD:
  464. self.handle_commands(data)
  465. elif event_tag == TAG_KEY:
  466. try:
  467. self.serial.write(codecs.encode(data))
  468. except serial.SerialException:
  469. pass # this shouldn't happen, but sometimes port has closed in serial thread
  470. except UnicodeEncodeError:
  471. pass # this can happen if a non-ascii character was passed, ignoring
  472. elif event_tag == TAG_SERIAL:
  473. self.handle_serial_input(data)
  474. if self._invoke_processing_last_line_timer is not None:
  475. self._invoke_processing_last_line_timer.cancel()
  476. self._invoke_processing_last_line_timer = threading.Timer(0.1, self.invoke_processing_last_line)
  477. self._invoke_processing_last_line_timer.start()
  478. # If no futher data is received in the next short period
  479. # of time then the _invoke_processing_last_line_timer
  480. # generates an event which will result in the finishing of
  481. # the last line. This is fix for handling lines sent
  482. # without EOL.
  483. elif event_tag == TAG_SERIAL_FLUSH:
  484. self.handle_serial_input(data, finalize_line=True)
  485. else:
  486. raise RuntimeError("Bad event data %r" % ((event_tag,data),))
  487. except SerialStopException:
  488. sys.stderr.write(ANSI_NORMAL + "Stopping condition has been received\n")
  489. finally:
  490. try:
  491. self.console_reader.stop()
  492. self.serial_reader.stop()
  493. self.stop_logging()
  494. # Cancelling _invoke_processing_last_line_timer is not
  495. # important here because receiving empty data doesn't matter.
  496. self._invoke_processing_last_line_timer = None
  497. except Exception:
  498. pass
  499. sys.stderr.write(ANSI_NORMAL + "\n")
  500. def handle_serial_input(self, data, finalize_line=False):
  501. sp = data.split(b'\n')
  502. if self._last_line_part != b"":
  503. # add unprocessed part from previous "data" to the first line
  504. sp[0] = self._last_line_part + sp[0]
  505. self._last_line_part = b""
  506. if sp[-1] != b"":
  507. # last part is not a full line
  508. self._last_line_part = sp.pop()
  509. for line in sp:
  510. if line != b"":
  511. if self._serial_check_exit and line == self.console_parser.exit_key.encode('latin-1'):
  512. raise SerialStopException()
  513. self.check_coredump_trigger_before_print(line)
  514. if self._force_line_print or self._line_matcher.match(line.decode(errors="ignore")):
  515. self._print(line + b'\n')
  516. self.handle_possible_pc_address_in_line(line)
  517. self.check_coredump_trigger_after_print(line)
  518. self.check_gdbstub_trigger(line)
  519. self._force_line_print = False
  520. # Now we have the last part (incomplete line) in _last_line_part. By
  521. # default we don't touch it and just wait for the arrival of the rest
  522. # of the line. But after some time when we didn't received it we need
  523. # to make a decision.
  524. if self._last_line_part != b"":
  525. if self._force_line_print or (finalize_line and self._line_matcher.match(self._last_line_part.decode(errors="ignore"))):
  526. self._force_line_print = True
  527. self._print(self._last_line_part)
  528. self.handle_possible_pc_address_in_line(self._last_line_part)
  529. self.check_gdbstub_trigger(self._last_line_part)
  530. # It is possible that the incomplete line cuts in half the PC
  531. # address. A small buffer is kept and will be used the next time
  532. # handle_possible_pc_address_in_line is invoked to avoid this problem.
  533. # MATCH_PCADDR matches 10 character long addresses. Therefore, we
  534. # keep the last 9 characters.
  535. self._pc_address_buffer = self._last_line_part[-9:]
  536. # GDB sequence can be cut in half also. GDB sequence is 7
  537. # characters long, therefore, we save the last 6 characters.
  538. self._gdb_buffer = self._last_line_part[-6:]
  539. self._last_line_part = b""
  540. # else: keeping _last_line_part and it will be processed the next time
  541. # handle_serial_input is invoked
  542. def handle_possible_pc_address_in_line(self, line):
  543. line = self._pc_address_buffer + line
  544. self._pc_address_buffer = b""
  545. for m in re.finditer(MATCH_PCADDR, line.decode(errors="ignore")):
  546. self.lookup_pc_address(m.group())
  547. def __enter__(self):
  548. """ Use 'with self' to temporarily disable monitoring behaviour """
  549. self.serial_reader.stop()
  550. self.console_reader.stop()
  551. def __exit__(self, *args, **kwargs):
  552. """ Use 'with self' to temporarily disable monitoring behaviour """
  553. self.console_reader.start()
  554. self.serial_reader.start()
  555. def prompt_next_action(self, reason):
  556. self.console.setup() # set up console to trap input characters
  557. try:
  558. red_print("--- {}".format(reason))
  559. red_print(self.console_parser.get_next_action_text())
  560. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  561. while k == CTRL_T:
  562. k = self.console.getkey()
  563. finally:
  564. self.console.cleanup()
  565. ret = self.console_parser.parse_next_action_key(k)
  566. if ret is not None:
  567. cmd = ret[1]
  568. if cmd == CMD_STOP:
  569. # the stop command should be handled last
  570. self.event_queue.put(ret)
  571. else:
  572. self.cmd_queue.put(ret)
  573. def run_make(self, target):
  574. with self:
  575. if isinstance(self.make, list):
  576. popen_args = self.make + [target]
  577. else:
  578. popen_args = [self.make, target]
  579. yellow_print("Running %s..." % " ".join(popen_args))
  580. p = subprocess.Popen(popen_args, env=os.environ)
  581. try:
  582. p.wait()
  583. except KeyboardInterrupt:
  584. p.wait()
  585. if p.returncode != 0:
  586. self.prompt_next_action("Build failed")
  587. else:
  588. self.output_enable(True)
  589. def lookup_pc_address(self, pc_addr):
  590. cmd = ["%saddr2line" % self.toolchain_prefix,
  591. "-pfiaC", "-e", self.elf_file, pc_addr]
  592. try:
  593. translation = subprocess.check_output(cmd, cwd=".")
  594. if b"?? ??:0" not in translation:
  595. self._print(translation.decode(), console_printer=yellow_print)
  596. except OSError as e:
  597. red_print("%s: %s" % (" ".join(cmd), e))
  598. def check_gdbstub_trigger(self, line):
  599. line = self._gdb_buffer + line
  600. self._gdb_buffer = b""
  601. m = re.search(b"\\$(T..)#(..)", line) # look for a gdb "reason" for a break
  602. if m is not None:
  603. try:
  604. chsum = sum(ord(bytes([p])) for p in m.group(1)) & 0xFF
  605. calc_chsum = int(m.group(2), 16)
  606. except ValueError:
  607. return # payload wasn't valid hex digits
  608. if chsum == calc_chsum:
  609. self.run_gdb()
  610. else:
  611. red_print("Malformed gdb message... calculated checksum %02x received %02x" % (chsum, calc_chsum))
  612. def check_coredump_trigger_before_print(self, line):
  613. if self._decode_coredumps == COREDUMP_DECODE_DISABLE:
  614. return
  615. if COREDUMP_UART_PROMPT in line:
  616. yellow_print("Initiating core dump!")
  617. self.event_queue.put((TAG_KEY, '\n'))
  618. return
  619. if COREDUMP_UART_START in line:
  620. yellow_print("Core dump started (further output muted)")
  621. self._reading_coredump = COREDUMP_READING
  622. self._coredump_buffer = b""
  623. self._output_enabled = False
  624. return
  625. if COREDUMP_UART_END in line:
  626. self._reading_coredump = COREDUMP_DONE
  627. yellow_print("\nCore dump finished!")
  628. self.process_coredump()
  629. return
  630. if self._reading_coredump == COREDUMP_READING:
  631. kb = 1024
  632. buffer_len_kb = len(self._coredump_buffer) // kb
  633. self._coredump_buffer += line.replace(b'\r', b'') + b'\n'
  634. new_buffer_len_kb = len(self._coredump_buffer) // kb
  635. if new_buffer_len_kb > buffer_len_kb:
  636. yellow_print("Received %3d kB..." % (new_buffer_len_kb), newline='\r')
  637. def check_coredump_trigger_after_print(self, line):
  638. if self._decode_coredumps == COREDUMP_DECODE_DISABLE:
  639. return
  640. # Re-enable output after the last line of core dump has been consumed
  641. if not self._output_enabled and self._reading_coredump == COREDUMP_DONE:
  642. self._reading_coredump = COREDUMP_IDLE
  643. self._output_enabled = True
  644. self._coredump_buffer = b""
  645. def process_coredump(self):
  646. if self._decode_coredumps != COREDUMP_DECODE_INFO:
  647. raise NotImplementedError("process_coredump: %s not implemented" % self._decode_coredumps)
  648. coredump_script = os.path.join(os.path.dirname(__file__), "..", "components", "espcoredump", "espcoredump.py")
  649. coredump_file = None
  650. try:
  651. # On Windows, the temporary file can't be read unless it is closed.
  652. # Set delete=False and delete the file manually later.
  653. with tempfile.NamedTemporaryFile(mode="wb", delete=False) as coredump_file:
  654. coredump_file.write(self._coredump_buffer)
  655. coredump_file.flush()
  656. cmd = [sys.executable,
  657. coredump_script,
  658. "info_corefile",
  659. "--core", coredump_file.name,
  660. "--core-format", "b64",
  661. self.elf_file
  662. ]
  663. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  664. self._output_enabled = True
  665. self._print(output)
  666. self._output_enabled = False # Will be reenabled in check_coredump_trigger_after_print
  667. except subprocess.CalledProcessError as e:
  668. yellow_print("Failed to run espcoredump script: {}\n\n".format(e))
  669. self._output_enabled = True
  670. self._print(COREDUMP_UART_START + b'\n')
  671. self._print(self._coredump_buffer)
  672. # end line will be printed in handle_serial_input
  673. finally:
  674. if coredump_file is not None:
  675. try:
  676. os.unlink(coredump_file.name)
  677. except OSError as e:
  678. yellow_print("Couldn't remote temporary core dump file ({})".format(e))
  679. def run_gdb(self):
  680. with self: # disable console control
  681. sys.stderr.write(ANSI_NORMAL)
  682. try:
  683. cmd = ["%sgdb" % self.toolchain_prefix,
  684. "-ex", "set serial baud %d" % self.serial.baudrate,
  685. "-ex", "target remote %s" % self.serial.port,
  686. "-ex", "interrupt", # monitor has already parsed the first 'reason' command, need a second
  687. self.elf_file]
  688. process = subprocess.Popen(cmd, cwd=".")
  689. process.wait()
  690. except OSError as e:
  691. red_print("%s: %s" % (" ".join(cmd), e))
  692. except KeyboardInterrupt:
  693. pass # happens on Windows, maybe other OSes
  694. finally:
  695. try:
  696. # on Linux, maybe other OSes, gdb sometimes seems to be alive even after wait() returns...
  697. process.terminate()
  698. except Exception:
  699. pass
  700. try:
  701. # also on Linux, maybe other OSes, gdb sometimes exits uncleanly and breaks the tty mode
  702. subprocess.call(["stty", "sane"])
  703. except Exception:
  704. pass # don't care if there's no stty, we tried...
  705. self.prompt_next_action("gdb exited")
  706. def output_enable(self, enable):
  707. self._output_enabled = enable
  708. def output_toggle(self):
  709. self._output_enabled = not self._output_enabled
  710. yellow_print("\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.".format(self._output_enabled))
  711. def toggle_logging(self):
  712. if self._log_file:
  713. self.stop_logging()
  714. else:
  715. self.start_logging()
  716. def start_logging(self):
  717. if not self._log_file:
  718. try:
  719. name = "log.{}.{}.txt".format(os.path.splitext(os.path.basename(self.elf_file))[0],
  720. datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
  721. self._log_file = open(name, "wb+")
  722. yellow_print("\nLogging is enabled into file {}".format(name))
  723. except Exception as e:
  724. red_print("\nLog file {} cannot be created: {}".format(name, e))
  725. def stop_logging(self):
  726. if self._log_file:
  727. try:
  728. name = self._log_file.name
  729. self._log_file.close()
  730. yellow_print("\nLogging is disabled and file {} has been closed".format(name))
  731. except Exception as e:
  732. red_print("\nLog file cannot be closed: {}".format(e))
  733. finally:
  734. self._log_file = None
  735. def _print(self, string, console_printer=None):
  736. if console_printer is None:
  737. console_printer = self.console.write_bytes
  738. if self._output_enabled:
  739. console_printer(string)
  740. if self._log_file:
  741. try:
  742. if isinstance(string, type(u'')):
  743. string = string.encode()
  744. self._log_file.write(string)
  745. except Exception as e:
  746. red_print("\nCannot write to file: {}".format(e))
  747. # don't fill-up the screen with the previous errors (probably consequent prints would fail also)
  748. self.stop_logging()
  749. def handle_commands(self, cmd):
  750. if cmd == CMD_STOP:
  751. self.console_reader.stop()
  752. self.serial_reader.stop()
  753. elif cmd == CMD_RESET:
  754. self.serial.setRTS(True)
  755. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  756. time.sleep(0.2)
  757. self.serial.setRTS(False)
  758. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  759. self.output_enable(True)
  760. elif cmd == CMD_MAKE:
  761. self.run_make("encrypted-flash" if self.encrypted else "flash")
  762. elif cmd == CMD_APP_FLASH:
  763. self.run_make("encrypted-app-flash" if self.encrypted else "app-flash")
  764. elif cmd == CMD_OUTPUT_TOGGLE:
  765. self.output_toggle()
  766. elif cmd == CMD_TOGGLE_LOGGING:
  767. self.toggle_logging()
  768. elif cmd == CMD_ENTER_BOOT:
  769. self.serial.setDTR(False) # IO0=HIGH
  770. self.serial.setRTS(True) # EN=LOW, chip in reset
  771. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  772. time.sleep(1.3) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  773. self.serial.setDTR(True) # IO0=LOW
  774. self.serial.setRTS(False) # EN=HIGH, chip out of reset
  775. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  776. time.sleep(0.45) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  777. self.serial.setDTR(False) # IO0=HIGH, done
  778. else:
  779. raise RuntimeError("Bad command data %d" % (cmd))
  780. def main():
  781. def _get_default_serial_port():
  782. """
  783. Same logic for detecting serial port as esptool.py and idf.py: reverse sort by name and choose the first port.
  784. """
  785. try:
  786. ports = list(reversed(sorted(p.device for p in serial.tools.list_ports.comports())))
  787. return ports[0]
  788. except Exception:
  789. return '/dev/ttyUSB0'
  790. parser = argparse.ArgumentParser("idf_monitor - a serial output monitor for esp-idf")
  791. parser.add_argument(
  792. '--port', '-p',
  793. help='Serial port device',
  794. default=os.environ.get('ESPTOOL_PORT', _get_default_serial_port())
  795. )
  796. parser.add_argument(
  797. '--baud', '-b',
  798. help='Serial port baud rate',
  799. type=int,
  800. default=os.getenv('IDF_MONITOR_BAUD', os.getenv('MONITORBAUD', 115200)))
  801. parser.add_argument(
  802. '--make', '-m',
  803. help='Command to run make',
  804. type=str, default='make')
  805. parser.add_argument(
  806. '--encrypted',
  807. help='Use encrypted targets while running make',
  808. action='store_true')
  809. parser.add_argument(
  810. '--toolchain-prefix',
  811. help="Triplet prefix to add before cross-toolchain names",
  812. default=DEFAULT_TOOLCHAIN_PREFIX)
  813. parser.add_argument(
  814. "--eol",
  815. choices=['CR', 'LF', 'CRLF'],
  816. type=lambda c: c.upper(),
  817. help="End of line to use when sending to the serial port",
  818. default='CR')
  819. parser.add_argument(
  820. 'elf_file', help='ELF file of application',
  821. type=argparse.FileType('rb'))
  822. parser.add_argument(
  823. '--print_filter',
  824. help="Filtering string",
  825. default=DEFAULT_PRINT_FILTER)
  826. parser.add_argument(
  827. '--decode-coredumps',
  828. choices=[COREDUMP_DECODE_INFO, COREDUMP_DECODE_DISABLE],
  829. default=COREDUMP_DECODE_INFO,
  830. help="Handling of core dumps found in serial output"
  831. )
  832. args = parser.parse_args()
  833. # GDB uses CreateFile to open COM port, which requires the COM name to be r'\\.\COMx' if the COM
  834. # number is larger than 10
  835. if os.name == 'nt' and args.port.startswith("COM"):
  836. args.port = args.port.replace('COM', r'\\.\COM')
  837. yellow_print("--- WARNING: GDB cannot open serial ports accessed as COMx")
  838. yellow_print("--- Using %s instead..." % args.port)
  839. elif args.port.startswith("/dev/tty."):
  840. args.port = args.port.replace("/dev/tty.", "/dev/cu.")
  841. yellow_print("--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.")
  842. yellow_print("--- Using %s instead..." % args.port)
  843. serial_instance = serial.serial_for_url(args.port, args.baud,
  844. do_not_open=True)
  845. serial_instance.dtr = False
  846. serial_instance.rts = False
  847. args.elf_file.close() # don't need this as a file
  848. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  849. # parent make is only running 1 job (monitor), so we can re-spawn
  850. # all of the child makes we need (the -j argument remains part of
  851. # MAKEFLAGS)
  852. try:
  853. makeflags = os.environ["MAKEFLAGS"]
  854. makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
  855. os.environ["MAKEFLAGS"] = makeflags
  856. except KeyError:
  857. pass # not running a make jobserver
  858. # Pass the actual used port to callee of idf_monitor (e.g. make) through `ESPPORT` environment
  859. # variable
  860. # To make sure the key as well as the value are str type, by the requirements of subprocess
  861. espport_key = str("ESPPORT")
  862. espport_val = str(args.port)
  863. os.environ.update({espport_key: espport_val})
  864. monitor = Monitor(serial_instance, args.elf_file.name, args.print_filter, args.make, args.encrypted,
  865. args.toolchain_prefix, args.eol,
  866. args.decode_coredumps)
  867. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  868. p=serial_instance))
  869. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  870. key_description(monitor.console_parser.exit_key),
  871. key_description(monitor.console_parser.menu_key),
  872. key_description(monitor.console_parser.menu_key),
  873. key_description(CTRL_H)))
  874. if args.print_filter != DEFAULT_PRINT_FILTER:
  875. yellow_print('--- Print filter: {} ---'.format(args.print_filter))
  876. monitor.main_loop()
  877. if os.name == 'nt':
  878. # Windows console stuff
  879. STD_OUTPUT_HANDLE = -11
  880. STD_ERROR_HANDLE = -12
  881. # wincon.h values
  882. FOREGROUND_INTENSITY = 8
  883. FOREGROUND_GREY = 7
  884. # matches the ANSI color change sequences that IDF sends
  885. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  886. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  887. ANSI_TO_WINDOWS_COLOR = [0, 4, 2, 6, 1, 5, 3, 7]
  888. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  889. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  890. class ANSIColorConverter(object):
  891. """Class to wrap a file-like output stream, intercept ANSI color codes,
  892. and convert them into calls to Windows SetConsoleTextAttribute.
  893. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  894. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  895. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  896. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  897. """
  898. def __init__(self, output=None, decode_output=False):
  899. self.output = output
  900. self.decode_output = decode_output
  901. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  902. self.matched = b''
  903. def _output_write(self, data):
  904. try:
  905. if self.decode_output:
  906. self.output.write(data.decode())
  907. else:
  908. self.output.write(data)
  909. except (IOError, OSError):
  910. # Windows 10 bug since the Fall Creators Update, sometimes writing to console randomly throws
  911. # an exception (however, the character is still written to the screen)
  912. # Ref https://github.com/espressif/esp-idf/issues/1163
  913. #
  914. # Also possible for Windows to throw an OSError error if the data is invalid for the console
  915. # (garbage bytes, etc)
  916. pass
  917. except UnicodeDecodeError:
  918. # In case of double byte Unicode characters display '?'
  919. self.output.write('?')
  920. def write(self, data):
  921. if isinstance(data, bytes):
  922. data = bytearray(data)
  923. else:
  924. data = bytearray(data, 'utf-8')
  925. for b in data:
  926. b = bytes([b])
  927. length = len(self.matched)
  928. if b == b'\033': # ESC
  929. self.matched = b
  930. elif (length == 1 and b == b'[') or (1 < length < 7):
  931. self.matched += b
  932. if self.matched == ANSI_NORMAL.encode('latin-1'): # reset console
  933. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  934. self.flush()
  935. SetConsoleTextAttribute(self.handle, FOREGROUND_GREY)
  936. self.matched = b''
  937. elif len(self.matched) == 7: # could be an ANSI sequence
  938. m = re.match(RE_ANSI_COLOR, self.matched)
  939. if m is not None:
  940. color = ANSI_TO_WINDOWS_COLOR[int(m.group(2))]
  941. if m.group(1) == b'1':
  942. color |= FOREGROUND_INTENSITY
  943. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  944. self.flush()
  945. SetConsoleTextAttribute(self.handle, color)
  946. else:
  947. self._output_write(self.matched) # not an ANSI color code, display verbatim
  948. self.matched = b''
  949. else:
  950. self._output_write(b)
  951. self.matched = b''
  952. def flush(self):
  953. try:
  954. self.output.flush()
  955. except OSError:
  956. # Account for Windows Console refusing to accept garbage bytes (serial noise, etc)
  957. pass
  958. if __name__ == "__main__":
  959. main()