idf_monitor.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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 "make flash" (Ctrl-T Ctrl-F)
  7. # - Run "make app-flash" (Ctrl-T Ctrl-A)
  8. # - If gdbstub output is detected, gdb is automatically loaded
  9. #
  10. # Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23. #
  24. # Contains elements taken from miniterm "Very simple serial terminal" which
  25. # is part of pySerial. https://github.com/pyserial/pyserial
  26. # (C)2002-2015 Chris Liechti <cliechti@gmx.net>
  27. #
  28. # Originally released under BSD-3-Clause license.
  29. #
  30. from __future__ import print_function, division
  31. from __future__ import unicode_literals
  32. from future import standard_library
  33. standard_library.install_aliases()
  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 re
  41. import os
  42. try:
  43. import queue
  44. except ImportError:
  45. import Queue as queue
  46. import time
  47. import sys
  48. import serial
  49. import serial.tools.miniterm as miniterm
  50. import threading
  51. import ctypes
  52. import types
  53. from distutils.version import StrictVersion
  54. key_description = miniterm.key_description
  55. # Control-key characters
  56. CTRL_A = '\x01'
  57. CTRL_B = '\x02'
  58. CTRL_F = '\x06'
  59. CTRL_H = '\x08'
  60. CTRL_R = '\x12'
  61. CTRL_T = '\x14'
  62. CTRL_Y = '\x19'
  63. CTRL_P = '\x10'
  64. CTRL_RBRACKET = '\x1d' # Ctrl+]
  65. # ANSI terminal codes (if changed, regular expressions in LineMatcher need to be udpated)
  66. ANSI_RED = '\033[1;31m'
  67. ANSI_YELLOW = '\033[0;33m'
  68. ANSI_NORMAL = '\033[0m'
  69. def color_print(message, color):
  70. """ Print a message to stderr with colored highlighting """
  71. sys.stderr.write("%s%s%s\n" % (color, message, ANSI_NORMAL))
  72. def yellow_print(message):
  73. color_print(message, ANSI_YELLOW)
  74. def red_print(message):
  75. color_print(message, ANSI_RED)
  76. __version__ = "1.1"
  77. # Tags for tuples in queues
  78. TAG_KEY = 0
  79. TAG_SERIAL = 1
  80. TAG_SERIAL_FLUSH = 2
  81. # regex matches an potential PC value (0x4xxxxxxx)
  82. MATCH_PCADDR = re.compile(r'0x4[0-9a-f]{7}', re.IGNORECASE)
  83. DEFAULT_TOOLCHAIN_PREFIX = "xtensa-esp32-elf-"
  84. DEFAULT_PRINT_FILTER = ""
  85. class StoppableThread(object):
  86. """
  87. Provide a Thread-like class which can be 'cancelled' via a subclass-provided
  88. cancellation method.
  89. Can be started and stopped multiple times.
  90. Isn't an instance of type Thread because Python Thread objects can only be run once
  91. """
  92. def __init__(self):
  93. self._thread = None
  94. @property
  95. def alive(self):
  96. """
  97. Is 'alive' whenever the internal thread object exists
  98. """
  99. return self._thread is not None
  100. def start(self):
  101. if self._thread is None:
  102. self._thread = threading.Thread(target=self._run_outer)
  103. self._thread.start()
  104. def _cancel(self):
  105. pass # override to provide cancellation functionality
  106. def run(self):
  107. pass # override for the main thread behaviour
  108. def _run_outer(self):
  109. try:
  110. self.run()
  111. finally:
  112. self._thread = None
  113. def stop(self):
  114. if self._thread is not None:
  115. old_thread = self._thread
  116. self._thread = None
  117. self._cancel()
  118. old_thread.join()
  119. class ConsoleReader(StoppableThread):
  120. """ Read input keys from the console and push them to the queue,
  121. until stopped.
  122. """
  123. def __init__(self, console, event_queue, test_mode):
  124. super(ConsoleReader, self).__init__()
  125. self.console = console
  126. self.event_queue = event_queue
  127. self.test_mode = test_mode
  128. def run(self):
  129. self.console.setup()
  130. try:
  131. while self.alive:
  132. try:
  133. if os.name == 'nt':
  134. # Windows kludge: because the console.cancel() method doesn't
  135. # seem to work to unblock getkey() on the Windows implementation.
  136. #
  137. # So we only call getkey() if we know there's a key waiting for us.
  138. import msvcrt
  139. while not msvcrt.kbhit() and self.alive:
  140. time.sleep(0.1)
  141. if not self.alive:
  142. break
  143. elif self.test_mode:
  144. # In testing mode the stdin is connected to PTY but is not used for input anything. For PTY
  145. # the canceling by fcntl.ioctl isn't working and would hang in self.console.getkey().
  146. # Therefore, we avoid calling it.
  147. while self.alive:
  148. time.sleep(0.1)
  149. break
  150. c = self.console.getkey()
  151. except KeyboardInterrupt:
  152. c = '\x03'
  153. if c is not None:
  154. self.event_queue.put((TAG_KEY, c), False)
  155. finally:
  156. self.console.cleanup()
  157. def _cancel(self):
  158. if os.name == 'posix' and not self.test_mode:
  159. # this is the way cancel() is implemented in pyserial 3.3 or newer,
  160. # older pyserial (3.1+) has cancellation implemented via 'select',
  161. # which does not work when console sends an escape sequence response
  162. #
  163. # even older pyserial (<3.1) does not have this method
  164. #
  165. # on Windows there is a different (also hacky) fix, applied above.
  166. #
  167. # note that TIOCSTI is not implemented in WSL / bash-on-Windows.
  168. # TODO: introduce some workaround to make it work there.
  169. #
  170. # Note: This would throw exception in testing mode when the stdin is connected to PTY.
  171. import fcntl, termios
  172. fcntl.ioctl(self.console.fd, termios.TIOCSTI, b'\0')
  173. class SerialReader(StoppableThread):
  174. """ Read serial data from the serial port and push to the
  175. event queue, until stopped.
  176. """
  177. def __init__(self, serial, event_queue):
  178. super(SerialReader, self).__init__()
  179. self.baud = serial.baudrate
  180. self.serial = serial
  181. self.event_queue = event_queue
  182. if not hasattr(self.serial, 'cancel_read'):
  183. # enable timeout for checking alive flag,
  184. # if cancel_read not available
  185. self.serial.timeout = 0.25
  186. def run(self):
  187. if not self.serial.is_open:
  188. self.serial.baudrate = self.baud
  189. self.serial.rts = True # Force an RTS reset on open
  190. self.serial.open()
  191. self.serial.rts = False
  192. try:
  193. while self.alive:
  194. data = self.serial.read(self.serial.in_waiting or 1)
  195. if len(data):
  196. self.event_queue.put((TAG_SERIAL, data), False)
  197. finally:
  198. self.serial.close()
  199. def _cancel(self):
  200. if hasattr(self.serial, 'cancel_read'):
  201. try:
  202. self.serial.cancel_read()
  203. except:
  204. pass
  205. class LineMatcher(object):
  206. """
  207. Assembles a dictionary of filtering rules based on the --print_filter
  208. argument of idf_monitor. Then later it is used to match lines and
  209. determine whether they should be shown on screen or not.
  210. """
  211. LEVEL_N = 0
  212. LEVEL_E = 1
  213. LEVEL_W = 2
  214. LEVEL_I = 3
  215. LEVEL_D = 4
  216. LEVEL_V = 5
  217. level = {'N': LEVEL_N, 'E': LEVEL_E, 'W': LEVEL_W, 'I': LEVEL_I, 'D': LEVEL_D,
  218. 'V': LEVEL_V, '*': LEVEL_V, '': LEVEL_V}
  219. def __init__(self, print_filter):
  220. self._dict = dict()
  221. self._re = re.compile(r'^(?:\033\[[01];?[0-9]+m?)?([EWIDV]) \([0-9]+\) ([^:]+): ')
  222. items = print_filter.split()
  223. if len(items) == 0:
  224. self._dict["*"] = self.LEVEL_V # default is to print everything
  225. for f in items:
  226. s = f.split(r':')
  227. if len(s) == 1:
  228. # specifying no warning level defaults to verbose level
  229. lev = self.LEVEL_V
  230. elif len(s) == 2:
  231. if len(s[0]) == 0:
  232. raise ValueError('No tag specified in filter ' + f)
  233. try:
  234. lev = self.level[s[1].upper()]
  235. except KeyError:
  236. raise ValueError('Unknown warning level in filter ' + f)
  237. else:
  238. raise ValueError('Missing ":" in filter ' + f)
  239. self._dict[s[0]] = lev
  240. def match(self, line):
  241. try:
  242. m = self._re.search(line)
  243. if m:
  244. lev = self.level[m.group(1)]
  245. if m.group(2) in self._dict:
  246. return self._dict[m.group(2)] >= lev
  247. return self._dict.get("*", self.LEVEL_N) >= lev
  248. except (KeyError, IndexError):
  249. # Regular line written with something else than ESP_LOG*
  250. # or an empty line.
  251. pass
  252. # We need something more than "*.N" for printing.
  253. return self._dict.get("*", self.LEVEL_N) > self.LEVEL_N
  254. class SerialStopException(Exception):
  255. """
  256. This exception is used for stopping the IDF monitor in testing mode.
  257. """
  258. pass
  259. class Monitor(object):
  260. """
  261. Monitor application main class.
  262. This was originally derived from miniterm.Miniterm, but it turned out to be easier to write from scratch for this
  263. purpose.
  264. Main difference is that all event processing happens in the main thread, not the worker threads.
  265. """
  266. def __init__(self, serial_instance, elf_file, print_filter, make="make", toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, eol="CRLF"):
  267. super(Monitor, self).__init__()
  268. self.event_queue = queue.Queue()
  269. self.console = miniterm.Console()
  270. if os.name == 'nt':
  271. sys.stderr = ANSIColorConverter(sys.stderr, decode_output=True)
  272. self.console.output = ANSIColorConverter(self.console.output)
  273. self.console.byte_output = ANSIColorConverter(self.console.byte_output)
  274. if StrictVersion(serial.VERSION) < StrictVersion('3.3.0'):
  275. # Use Console.getkey implementation from 3.3.0 (to be in sync with the ConsoleReader._cancel patch above)
  276. def getkey_patched(self):
  277. c = self.enc_stdin.read(1)
  278. if c == chr(0x7f):
  279. c = chr(8) # map the BS key (which yields DEL) to backspace
  280. return c
  281. self.console.getkey = types.MethodType(getkey_patched, self.console)
  282. socket_mode = serial_instance.port.startswith("socket://") # testing hook - data from serial can make exit the monitor
  283. self.serial = serial_instance
  284. self.console_reader = ConsoleReader(self.console, self.event_queue, socket_mode)
  285. self.serial_reader = SerialReader(self.serial, self.event_queue)
  286. self.elf_file = elf_file
  287. self.make = make
  288. self.toolchain_prefix = toolchain_prefix
  289. self.menu_key = CTRL_T
  290. self.exit_key = CTRL_RBRACKET
  291. self.translate_eol = {
  292. "CRLF": lambda c: c.replace("\n", "\r\n"),
  293. "CR": lambda c: c.replace("\n", "\r"),
  294. "LF": lambda c: c.replace("\r", "\n"),
  295. }[eol]
  296. # internal state
  297. self._pressed_menu_key = False
  298. self._last_line_part = b""
  299. self._gdb_buffer = b""
  300. self._pc_address_buffer = b""
  301. self._line_matcher = LineMatcher(print_filter)
  302. self._invoke_processing_last_line_timer = None
  303. self._force_line_print = False
  304. self._output_enabled = True
  305. self._serial_check_exit = socket_mode
  306. def invoke_processing_last_line(self):
  307. self.event_queue.put((TAG_SERIAL_FLUSH, b''), False)
  308. def main_loop(self):
  309. self.console_reader.start()
  310. self.serial_reader.start()
  311. try:
  312. while self.console_reader.alive and self.serial_reader.alive:
  313. (event_tag, data) = self.event_queue.get()
  314. if event_tag == TAG_KEY:
  315. self.handle_key(data)
  316. elif event_tag == TAG_SERIAL:
  317. self.handle_serial_input(data)
  318. if self._invoke_processing_last_line_timer is not None:
  319. self._invoke_processing_last_line_timer.cancel()
  320. self._invoke_processing_last_line_timer = threading.Timer(0.1, self.invoke_processing_last_line)
  321. self._invoke_processing_last_line_timer.start()
  322. # If no futher data is received in the next short period
  323. # of time then the _invoke_processing_last_line_timer
  324. # generates an event which will result in the finishing of
  325. # the last line. This is fix for handling lines sent
  326. # without EOL.
  327. elif event_tag == TAG_SERIAL_FLUSH:
  328. self.handle_serial_input(data, finalize_line=True)
  329. else:
  330. raise RuntimeError("Bad event data %r" % ((event_tag,data),))
  331. except SerialStopException:
  332. pass
  333. finally:
  334. try:
  335. self.console_reader.stop()
  336. self.serial_reader.stop()
  337. # Cancelling _invoke_processing_last_line_timer is not
  338. # important here because receiving empty data doesn't matter.
  339. self._invoke_processing_last_line_timer = None
  340. except:
  341. pass
  342. sys.stderr.write(ANSI_NORMAL + "\n")
  343. def handle_key(self, key):
  344. if self._pressed_menu_key:
  345. self.handle_menu_key(key)
  346. self._pressed_menu_key = False
  347. elif key == self.menu_key:
  348. self._pressed_menu_key = True
  349. elif key == self.exit_key:
  350. self.console_reader.stop()
  351. self.serial_reader.stop()
  352. else:
  353. try:
  354. key = self.translate_eol(key)
  355. self.serial.write(codecs.encode(key))
  356. except serial.SerialException:
  357. pass # this shouldn't happen, but sometimes port has closed in serial thread
  358. except UnicodeEncodeError:
  359. pass # this can happen if a non-ascii character was passed, ignoring
  360. def handle_serial_input(self, data, finalize_line=False):
  361. sp = data.split(b'\n')
  362. if self._last_line_part != b"":
  363. # add unprocessed part from previous "data" to the first line
  364. sp[0] = self._last_line_part + sp[0]
  365. self._last_line_part = b""
  366. if sp[-1] != b"":
  367. # last part is not a full line
  368. self._last_line_part = sp.pop()
  369. for line in sp:
  370. if line != b"":
  371. if self._serial_check_exit and line == self.exit_key.encode('latin-1'):
  372. raise SerialStopException()
  373. if self._output_enabled and (self._force_line_print or self._line_matcher.match(line.decode(errors="ignore"))):
  374. self.console.write_bytes(line + b'\n')
  375. self.handle_possible_pc_address_in_line(line)
  376. self.check_gdbstub_trigger(line)
  377. self._force_line_print = False
  378. # Now we have the last part (incomplete line) in _last_line_part. By
  379. # default we don't touch it and just wait for the arrival of the rest
  380. # of the line. But after some time when we didn't received it we need
  381. # to make a decision.
  382. if self._last_line_part != b"":
  383. if self._force_line_print or (finalize_line and self._line_matcher.match(self._last_line_part.decode(errors="ignore"))):
  384. self._force_line_print = True;
  385. if self._output_enabled:
  386. self.console.write_bytes(self._last_line_part)
  387. self.handle_possible_pc_address_in_line(self._last_line_part)
  388. self.check_gdbstub_trigger(self._last_line_part)
  389. # It is possible that the incomplete line cuts in half the PC
  390. # address. A small buffer is kept and will be used the next time
  391. # handle_possible_pc_address_in_line is invoked to avoid this problem.
  392. # MATCH_PCADDR matches 10 character long addresses. Therefore, we
  393. # keep the last 9 characters.
  394. self._pc_address_buffer = self._last_line_part[-9:]
  395. # GDB sequence can be cut in half also. GDB sequence is 7
  396. # characters long, therefore, we save the last 6 characters.
  397. self._gdb_buffer = self._last_line_part[-6:]
  398. self._last_line_part = b""
  399. # else: keeping _last_line_part and it will be processed the next time
  400. # handle_serial_input is invoked
  401. def handle_possible_pc_address_in_line(self, line):
  402. line = self._pc_address_buffer + line
  403. self._pc_address_buffer = b""
  404. for m in re.finditer(MATCH_PCADDR, line.decode(errors="ignore")):
  405. self.lookup_pc_address(m.group())
  406. def handle_menu_key(self, c):
  407. if c == self.exit_key or c == self.menu_key: # send verbatim
  408. self.serial.write(codecs.encode(c))
  409. elif c in [ CTRL_H, 'h', 'H', '?' ]:
  410. red_print(self.get_help_text())
  411. elif c == CTRL_R: # Reset device via RTS
  412. self.serial.setRTS(True)
  413. time.sleep(0.2)
  414. self.serial.setRTS(False)
  415. self.output_enable(True)
  416. elif c == CTRL_F: # Recompile & upload
  417. self.run_make("flash")
  418. elif c == CTRL_A: # Recompile & upload app only
  419. self.run_make("app-flash")
  420. elif c == CTRL_Y: # Toggle output display
  421. self.output_toggle()
  422. elif c == CTRL_P:
  423. yellow_print("Pause app (enter bootloader mode), press Ctrl-T Ctrl-R to restart")
  424. # to fast trigger pause without press menu key
  425. self.serial.setDTR(False) # IO0=HIGH
  426. self.serial.setRTS(True) # EN=LOW, chip in reset
  427. time.sleep(1.3) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  428. self.serial.setDTR(True) # IO0=LOW
  429. self.serial.setRTS(False) # EN=HIGH, chip out of reset
  430. time.sleep(0.45) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  431. self.serial.setDTR(False) # IO0=HIGH, done
  432. else:
  433. red_print('--- unknown menu character {} --'.format(key_description(c)))
  434. def get_help_text(self):
  435. return """
  436. --- idf_monitor ({version}) - ESP-IDF monitor tool
  437. --- based on miniterm from pySerial
  438. ---
  439. --- {exit:8} Exit program
  440. --- {menu:8} Menu escape key, followed by:
  441. --- Menu keys:
  442. --- {menu:7} Send the menu character itself to remote
  443. --- {exit:7} Send the exit character itself to remote
  444. --- {reset:7} Reset target board via RTS line
  445. --- {make:7} Run 'make flash' to build & flash
  446. --- {appmake:7} Run 'make app-flash to build & flash app
  447. --- {output:7} Toggle output display
  448. --- {pause:7} Reset target into bootloader to pause app via RTS line
  449. """.format(version=__version__,
  450. exit=key_description(self.exit_key),
  451. menu=key_description(self.menu_key),
  452. reset=key_description(CTRL_R),
  453. make=key_description(CTRL_F),
  454. appmake=key_description(CTRL_A),
  455. output=key_description(CTRL_Y),
  456. pause=key_description(CTRL_P),
  457. )
  458. def __enter__(self):
  459. """ Use 'with self' to temporarily disable monitoring behaviour """
  460. self.serial_reader.stop()
  461. self.console_reader.stop()
  462. def __exit__(self, *args, **kwargs):
  463. """ Use 'with self' to temporarily disable monitoring behaviour """
  464. self.console_reader.start()
  465. self.serial_reader.start()
  466. def prompt_next_action(self, reason):
  467. self.console.setup() # set up console to trap input characters
  468. try:
  469. red_print("""
  470. --- {}
  471. --- Press {} to exit monitor.
  472. --- Press {} to run 'make flash'.
  473. --- Press {} to run 'make app-flash'.
  474. --- Press any other key to resume monitor (resets target).""".format(reason,
  475. key_description(self.exit_key),
  476. key_description(CTRL_F),
  477. key_description(CTRL_A)))
  478. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  479. while k == CTRL_T:
  480. k = self.console.getkey()
  481. finally:
  482. self.console.cleanup()
  483. if k == self.exit_key:
  484. self.event_queue.put((TAG_KEY, k))
  485. elif k in [ CTRL_F, CTRL_A ]:
  486. self.event_queue.put((TAG_KEY, self.menu_key))
  487. self.event_queue.put((TAG_KEY, k))
  488. def run_make(self, target):
  489. with self:
  490. yellow_print("Running make %s..." % target)
  491. p = subprocess.Popen([self.make,
  492. target ])
  493. try:
  494. p.wait()
  495. except KeyboardInterrupt:
  496. p.wait()
  497. if p.returncode != 0:
  498. self.prompt_next_action("Build failed")
  499. else:
  500. self.output_enable(True)
  501. def lookup_pc_address(self, pc_addr):
  502. translation = subprocess.check_output(
  503. ["%saddr2line" % self.toolchain_prefix,
  504. "-pfiaC", "-e", self.elf_file, pc_addr],
  505. cwd=".")
  506. if not b"?? ??:0" in translation:
  507. yellow_print(translation.decode())
  508. def check_gdbstub_trigger(self, line):
  509. line = self._gdb_buffer + line
  510. self._gdb_buffer = b""
  511. m = re.search(b"\\$(T..)#(..)", line) # look for a gdb "reason" for a break
  512. if m is not None:
  513. try:
  514. chsum = sum(ord(bytes([p])) for p in m.group(1)) & 0xFF
  515. calc_chsum = int(m.group(2), 16)
  516. except ValueError:
  517. return # payload wasn't valid hex digits
  518. if chsum == calc_chsum:
  519. self.run_gdb()
  520. else:
  521. red_print("Malformed gdb message... calculated checksum %02x received %02x" % (chsum, calc_chsum))
  522. def run_gdb(self):
  523. with self: # disable console control
  524. sys.stderr.write(ANSI_NORMAL)
  525. try:
  526. process = subprocess.Popen(["%sgdb" % self.toolchain_prefix,
  527. "-ex", "set serial baud %d" % self.serial.baudrate,
  528. "-ex", "target remote %s" % self.serial.port,
  529. "-ex", "interrupt", # monitor has already parsed the first 'reason' command, need a second
  530. self.elf_file], cwd=".")
  531. process.wait()
  532. except KeyboardInterrupt:
  533. pass # happens on Windows, maybe other OSes
  534. finally:
  535. try:
  536. # on Linux, maybe other OSes, gdb sometimes seems to be alive even after wait() returns...
  537. process.terminate()
  538. except:
  539. pass
  540. try:
  541. # also on Linux, maybe other OSes, gdb sometimes exits uncleanly and breaks the tty mode
  542. subprocess.call(["stty", "sane"])
  543. except:
  544. pass # don't care if there's no stty, we tried...
  545. self.prompt_next_action("gdb exited")
  546. def output_enable(self, enable):
  547. self._output_enabled = enable
  548. def output_toggle(self):
  549. self._output_enabled = not self._output_enabled
  550. yellow_print("\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.".format(self._output_enabled))
  551. def main():
  552. parser = argparse.ArgumentParser("idf_monitor - a serial output monitor for esp-idf")
  553. parser.add_argument(
  554. '--port', '-p',
  555. help='Serial port device',
  556. default=os.environ.get('ESPTOOL_PORT', '/dev/ttyUSB0')
  557. )
  558. parser.add_argument(
  559. '--baud', '-b',
  560. help='Serial port baud rate',
  561. type=int,
  562. default=os.environ.get('MONITOR_BAUD', 115200))
  563. parser.add_argument(
  564. '--make', '-m',
  565. help='Command to run make',
  566. type=str, default='make')
  567. parser.add_argument(
  568. '--toolchain-prefix',
  569. help="Triplet prefix to add before cross-toolchain names",
  570. default=DEFAULT_TOOLCHAIN_PREFIX)
  571. parser.add_argument(
  572. "--eol",
  573. choices=['CR', 'LF', 'CRLF'],
  574. type=lambda c: c.upper(),
  575. help="End of line to use when sending to the serial port",
  576. default='CR')
  577. parser.add_argument(
  578. 'elf_file', help='ELF file of application',
  579. type=argparse.FileType('rb'))
  580. parser.add_argument(
  581. '--print_filter',
  582. help="Filtering string",
  583. default=DEFAULT_PRINT_FILTER)
  584. args = parser.parse_args()
  585. if args.port.startswith("/dev/tty."):
  586. args.port = args.port.replace("/dev/tty.", "/dev/cu.")
  587. yellow_print("--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.")
  588. yellow_print("--- Using %s instead..." % args.port)
  589. serial_instance = serial.serial_for_url(args.port, args.baud,
  590. do_not_open=True)
  591. serial_instance.dtr = False
  592. serial_instance.rts = False
  593. args.elf_file.close() # don't need this as a file
  594. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  595. # parent make is only running 1 job (monitor), so we can re-spawn
  596. # all of the child makes we need (the -j argument remains part of
  597. # MAKEFLAGS)
  598. try:
  599. makeflags = os.environ["MAKEFLAGS"]
  600. makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
  601. os.environ["MAKEFLAGS"] = makeflags
  602. except KeyError:
  603. pass # not running a make jobserver
  604. monitor = Monitor(serial_instance, args.elf_file.name, args.print_filter, args.make, args.toolchain_prefix, args.eol)
  605. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  606. p=serial_instance))
  607. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  608. key_description(monitor.exit_key),
  609. key_description(monitor.menu_key),
  610. key_description(monitor.menu_key),
  611. key_description(CTRL_H)))
  612. if args.print_filter != DEFAULT_PRINT_FILTER:
  613. yellow_print('--- Print filter: {} ---'.format(args.print_filter))
  614. monitor.main_loop()
  615. if os.name == 'nt':
  616. # Windows console stuff
  617. STD_OUTPUT_HANDLE = -11
  618. STD_ERROR_HANDLE = -12
  619. # wincon.h values
  620. FOREGROUND_INTENSITY = 8
  621. FOREGROUND_GREY = 7
  622. # matches the ANSI color change sequences that IDF sends
  623. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  624. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  625. ANSI_TO_WINDOWS_COLOR = [ 0, 4, 2, 6, 1, 5, 3, 7 ]
  626. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  627. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  628. class ANSIColorConverter(object):
  629. """Class to wrap a file-like output stream, intercept ANSI color codes,
  630. and convert them into calls to Windows SetConsoleTextAttribute.
  631. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  632. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  633. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  634. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  635. """
  636. def __init__(self, output=None, decode_output=False):
  637. self.output = output
  638. self.decode_output = decode_output
  639. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  640. self.matched = b''
  641. def _output_write(self, data):
  642. try:
  643. if self.decode_output:
  644. self.output.write(data.decode())
  645. else:
  646. self.output.write(data)
  647. except IOError:
  648. # Windows 10 bug since the Fall Creators Update, sometimes writing to console randomly throws
  649. # an exception (however, the character is still written to the screen)
  650. # Ref https://github.com/espressif/esp-idf/issues/1136
  651. pass
  652. def write(self, data):
  653. if type(data) is not bytes:
  654. data = data.encode('latin-1')
  655. for b in data:
  656. b = bytes([b])
  657. l = len(self.matched)
  658. if b == b'\033': # ESC
  659. self.matched = b
  660. elif (l == 1 and b == b'[') or (1 < l < 7):
  661. self.matched += b
  662. if self.matched == ANSI_NORMAL.encode('latin-1'): # reset console
  663. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  664. self.flush()
  665. SetConsoleTextAttribute(self.handle, FOREGROUND_GREY)
  666. self.matched = b''
  667. elif len(self.matched) == 7: # could be an ANSI sequence
  668. m = re.match(RE_ANSI_COLOR, self.matched)
  669. if m is not None:
  670. color = ANSI_TO_WINDOWS_COLOR[int(m.group(2))]
  671. if m.group(1) == b'1':
  672. color |= FOREGROUND_INTENSITY
  673. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  674. self.flush()
  675. SetConsoleTextAttribute(self.handle, color)
  676. else:
  677. self._output_write(self.matched) # not an ANSI color code, display verbatim
  678. self.matched = b''
  679. else:
  680. self._output_write(b)
  681. self.matched = b''
  682. def flush(self):
  683. self.output.flush()
  684. if __name__ == "__main__":
  685. main()