idf_monitor.py 32 KB

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