idf_monitor.py 29 KB

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