idf_monitor.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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_RBRACKET = '\x1d' # Ctrl+]
  64. # ANSI terminal codes (if changed, regular expressions in LineMatcher need to be udpated)
  65. ANSI_RED = '\033[1;31m'
  66. ANSI_YELLOW = '\033[0;33m'
  67. ANSI_NORMAL = '\033[0m'
  68. def color_print(message, color):
  69. """ Print a message to stderr with colored highlighting """
  70. sys.stderr.write("%s%s%s\n" % (color, message, ANSI_NORMAL))
  71. def yellow_print(message):
  72. color_print(message, ANSI_YELLOW)
  73. def red_print(message):
  74. color_print(message, ANSI_RED)
  75. __version__ = "1.1"
  76. # Tags for tuples in queues
  77. TAG_KEY = 0
  78. TAG_SERIAL = 1
  79. TAG_SERIAL_FLUSH = 2
  80. # regex matches an potential PC value (0x4xxxxxxx)
  81. MATCH_PCADDR = re.compile(r'0x4[0-9a-f]{7}', re.IGNORECASE)
  82. DEFAULT_TOOLCHAIN_PREFIX = "xtensa-esp32-elf-"
  83. DEFAULT_PRINT_FILTER = ""
  84. class StoppableThread(object):
  85. """
  86. Provide a Thread-like class which can be 'cancelled' via a subclass-provided
  87. cancellation method.
  88. Can be started and stopped multiple times.
  89. Isn't an instance of type Thread because Python Thread objects can only be run once
  90. """
  91. def __init__(self):
  92. self._thread = None
  93. @property
  94. def alive(self):
  95. """
  96. Is 'alive' whenever the internal thread object exists
  97. """
  98. return self._thread is not None
  99. def start(self):
  100. if self._thread is None:
  101. self._thread = threading.Thread(target=self._run_outer)
  102. self._thread.start()
  103. def _cancel(self):
  104. pass # override to provide cancellation functionality
  105. def run(self):
  106. pass # override for the main thread behaviour
  107. def _run_outer(self):
  108. try:
  109. self.run()
  110. finally:
  111. self._thread = None
  112. def stop(self):
  113. if self._thread is not None:
  114. old_thread = self._thread
  115. self._thread = None
  116. self._cancel()
  117. old_thread.join()
  118. class ConsoleReader(StoppableThread):
  119. """ Read input keys from the console and push them to the queue,
  120. until stopped.
  121. """
  122. def __init__(self, console, event_queue, test_mode):
  123. super(ConsoleReader, self).__init__()
  124. self.console = console
  125. self.event_queue = event_queue
  126. self.test_mode = test_mode
  127. def run(self):
  128. self.console.setup()
  129. try:
  130. while self.alive:
  131. try:
  132. if os.name == 'nt':
  133. # Windows kludge: because the console.cancel() method doesn't
  134. # seem to work to unblock getkey() on the Windows implementation.
  135. #
  136. # So we only call getkey() if we know there's a key waiting for us.
  137. import msvcrt
  138. while not msvcrt.kbhit() and self.alive:
  139. time.sleep(0.1)
  140. if not self.alive:
  141. break
  142. elif self.test_mode:
  143. # In testing mode the stdin is connected to PTY but is not used for input anything. For PTY
  144. # the canceling by fcntl.ioctl isn't working and would hang in self.console.getkey().
  145. # Therefore, we avoid calling it.
  146. while self.alive:
  147. time.sleep(0.1)
  148. break
  149. c = self.console.getkey()
  150. except KeyboardInterrupt:
  151. c = '\x03'
  152. if c is not None:
  153. self.event_queue.put((TAG_KEY, c), False)
  154. finally:
  155. self.console.cleanup()
  156. def _cancel(self):
  157. if os.name == 'posix' and not self.test_mode:
  158. # this is the way cancel() is implemented in pyserial 3.3 or newer,
  159. # older pyserial (3.1+) has cancellation implemented via 'select',
  160. # which does not work when console sends an escape sequence response
  161. #
  162. # even older pyserial (<3.1) does not have this method
  163. #
  164. # on Windows there is a different (also hacky) fix, applied above.
  165. #
  166. # note that TIOCSTI is not implemented in WSL / bash-on-Windows.
  167. # TODO: introduce some workaround to make it work there.
  168. #
  169. # Note: This would throw exception in testing mode when the stdin is connected to PTY.
  170. import fcntl
  171. import 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 Exception:
  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. if not os.path.exists(make):
  288. self.make = shlex.split(make) # allow for possibility the "make" arg is a list of arguments (for idf.py)
  289. else:
  290. self.make = make
  291. self.toolchain_prefix = toolchain_prefix
  292. self.menu_key = CTRL_T
  293. self.exit_key = CTRL_RBRACKET
  294. self.translate_eol = {
  295. "CRLF": lambda c: c.replace("\n", "\r\n"),
  296. "CR": lambda c: c.replace("\n", "\r"),
  297. "LF": lambda c: c.replace("\r", "\n"),
  298. }[eol]
  299. # internal state
  300. self._pressed_menu_key = False
  301. self._last_line_part = b""
  302. self._gdb_buffer = b""
  303. self._pc_address_buffer = b""
  304. self._line_matcher = LineMatcher(print_filter)
  305. self._invoke_processing_last_line_timer = None
  306. self._force_line_print = False
  307. self._output_enabled = True
  308. self._serial_check_exit = socket_mode
  309. def invoke_processing_last_line(self):
  310. self.event_queue.put((TAG_SERIAL_FLUSH, b''), False)
  311. def main_loop(self):
  312. self.console_reader.start()
  313. self.serial_reader.start()
  314. try:
  315. while self.console_reader.alive and self.serial_reader.alive:
  316. (event_tag, data) = self.event_queue.get()
  317. if event_tag == TAG_KEY:
  318. self.handle_key(data)
  319. elif event_tag == TAG_SERIAL:
  320. self.handle_serial_input(data)
  321. if self._invoke_processing_last_line_timer is not None:
  322. self._invoke_processing_last_line_timer.cancel()
  323. self._invoke_processing_last_line_timer = threading.Timer(0.1, self.invoke_processing_last_line)
  324. self._invoke_processing_last_line_timer.start()
  325. # If no futher data is received in the next short period
  326. # of time then the _invoke_processing_last_line_timer
  327. # generates an event which will result in the finishing of
  328. # the last line. This is fix for handling lines sent
  329. # without EOL.
  330. elif event_tag == TAG_SERIAL_FLUSH:
  331. self.handle_serial_input(data, finalize_line=True)
  332. else:
  333. raise RuntimeError("Bad event data %r" % ((event_tag,data),))
  334. except SerialStopException:
  335. sys.stderr.write(ANSI_NORMAL + "Stopping condition has been received\n")
  336. finally:
  337. try:
  338. self.console_reader.stop()
  339. self.serial_reader.stop()
  340. # Cancelling _invoke_processing_last_line_timer is not
  341. # important here because receiving empty data doesn't matter.
  342. self._invoke_processing_last_line_timer = None
  343. except Exception:
  344. pass
  345. sys.stderr.write(ANSI_NORMAL + "\n")
  346. def handle_key(self, key):
  347. if self._pressed_menu_key:
  348. self.handle_menu_key(key)
  349. self._pressed_menu_key = False
  350. elif key == self.menu_key:
  351. self._pressed_menu_key = True
  352. elif key == self.exit_key:
  353. self.console_reader.stop()
  354. self.serial_reader.stop()
  355. else:
  356. try:
  357. key = self.translate_eol(key)
  358. self.serial.write(codecs.encode(key))
  359. except serial.SerialException:
  360. pass # this shouldn't happen, but sometimes port has closed in serial thread
  361. except UnicodeEncodeError:
  362. pass # this can happen if a non-ascii character was passed, ignoring
  363. def handle_serial_input(self, data, finalize_line=False):
  364. sp = data.split(b'\n')
  365. if self._last_line_part != b"":
  366. # add unprocessed part from previous "data" to the first line
  367. sp[0] = self._last_line_part + sp[0]
  368. self._last_line_part = b""
  369. if sp[-1] != b"":
  370. # last part is not a full line
  371. self._last_line_part = sp.pop()
  372. for line in sp:
  373. if line != b"":
  374. if self._serial_check_exit and line == self.exit_key.encode('latin-1'):
  375. raise SerialStopException()
  376. if self._output_enabled and (self._force_line_print or self._line_matcher.match(line.decode(errors="ignore"))):
  377. self.console.write_bytes(line + b'\n')
  378. self.handle_possible_pc_address_in_line(line)
  379. self.check_gdbstub_trigger(line)
  380. self._force_line_print = False
  381. # Now we have the last part (incomplete line) in _last_line_part. By
  382. # default we don't touch it and just wait for the arrival of the rest
  383. # of the line. But after some time when we didn't received it we need
  384. # to make a decision.
  385. if self._last_line_part != b"":
  386. if self._force_line_print or (finalize_line and self._line_matcher.match(self._last_line_part.decode(errors="ignore"))):
  387. self._force_line_print = True
  388. if self._output_enabled:
  389. self.console.write_bytes(self._last_line_part)
  390. self.handle_possible_pc_address_in_line(self._last_line_part)
  391. self.check_gdbstub_trigger(self._last_line_part)
  392. # It is possible that the incomplete line cuts in half the PC
  393. # address. A small buffer is kept and will be used the next time
  394. # handle_possible_pc_address_in_line is invoked to avoid this problem.
  395. # MATCH_PCADDR matches 10 character long addresses. Therefore, we
  396. # keep the last 9 characters.
  397. self._pc_address_buffer = self._last_line_part[-9:]
  398. # GDB sequence can be cut in half also. GDB sequence is 7
  399. # characters long, therefore, we save the last 6 characters.
  400. self._gdb_buffer = self._last_line_part[-6:]
  401. self._last_line_part = b""
  402. # else: keeping _last_line_part and it will be processed the next time
  403. # handle_serial_input is invoked
  404. def handle_possible_pc_address_in_line(self, line):
  405. line = self._pc_address_buffer + line
  406. self._pc_address_buffer = b""
  407. for m in re.finditer(MATCH_PCADDR, line.decode(errors="ignore")):
  408. self.lookup_pc_address(m.group())
  409. def handle_menu_key(self, c):
  410. if c == self.exit_key or c == self.menu_key: # send verbatim
  411. self.serial.write(codecs.encode(c))
  412. elif c in [CTRL_H, 'h', 'H', '?']:
  413. red_print(self.get_help_text())
  414. elif c == CTRL_R: # Reset device via RTS
  415. self.serial.setRTS(True)
  416. time.sleep(0.2)
  417. self.serial.setRTS(False)
  418. self.output_enable(True)
  419. elif c == CTRL_F: # Recompile & upload
  420. self.run_make("flash")
  421. elif c == CTRL_A: # Recompile & upload app only
  422. self.run_make("app-flash")
  423. elif c == CTRL_Y: # Toggle output display
  424. self.output_toggle()
  425. elif c == CTRL_P:
  426. yellow_print("Pause app (enter bootloader mode), press Ctrl-T Ctrl-R to restart")
  427. # to fast trigger pause without press menu key
  428. self.serial.setDTR(False) # IO0=HIGH
  429. self.serial.setRTS(True) # EN=LOW, chip in reset
  430. time.sleep(1.3) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  431. self.serial.setDTR(True) # IO0=LOW
  432. self.serial.setRTS(False) # EN=HIGH, chip out of reset
  433. time.sleep(0.45) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  434. self.serial.setDTR(False) # IO0=HIGH, done
  435. else:
  436. red_print('--- unknown menu character {} --'.format(key_description(c)))
  437. def get_help_text(self):
  438. return """
  439. --- idf_monitor ({version}) - ESP-IDF monitor tool
  440. --- based on miniterm from pySerial
  441. ---
  442. --- {exit:8} Exit program
  443. --- {menu:8} Menu escape key, followed by:
  444. --- Menu keys:
  445. --- {menu:7} Send the menu character itself to remote
  446. --- {exit:7} Send the exit character itself to remote
  447. --- {reset:7} Reset target board via RTS line
  448. --- {makecmd:7} Build & flash project
  449. --- {appmake:7} Build & flash app only
  450. --- {output:7} Toggle output display
  451. --- {pause:7} Reset target into bootloader to pause app via RTS line
  452. """.format(version=__version__,
  453. exit=key_description(self.exit_key),
  454. menu=key_description(self.menu_key),
  455. reset=key_description(CTRL_R),
  456. makecmd=key_description(CTRL_F),
  457. appmake=key_description(CTRL_A),
  458. output=key_description(CTRL_Y),
  459. pause=key_description(CTRL_P))
  460. def __enter__(self):
  461. """ Use 'with self' to temporarily disable monitoring behaviour """
  462. self.serial_reader.stop()
  463. self.console_reader.stop()
  464. def __exit__(self, *args, **kwargs):
  465. """ Use 'with self' to temporarily disable monitoring behaviour """
  466. self.console_reader.start()
  467. self.serial_reader.start()
  468. def prompt_next_action(self, reason):
  469. self.console.setup() # set up console to trap input characters
  470. try:
  471. red_print("""
  472. --- {}
  473. --- Press {} to exit monitor.
  474. --- Press {} to build & flash project.
  475. --- Press {} to build & flash app.
  476. --- Press any other key to resume monitor (resets target).""".format(reason,
  477. key_description(self.exit_key),
  478. key_description(CTRL_F),
  479. key_description(CTRL_A)))
  480. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  481. while k == CTRL_T:
  482. k = self.console.getkey()
  483. finally:
  484. self.console.cleanup()
  485. if k == self.exit_key:
  486. self.event_queue.put((TAG_KEY, k))
  487. elif k in [CTRL_F, CTRL_A]:
  488. self.event_queue.put((TAG_KEY, self.menu_key))
  489. self.event_queue.put((TAG_KEY, k))
  490. def run_make(self, target):
  491. with self:
  492. if isinstance(self.make, list):
  493. popen_args = self.make + [target]
  494. else:
  495. popen_args = [self.make, target]
  496. yellow_print("Running %s..." % " ".join(popen_args))
  497. p = subprocess.Popen(popen_args)
  498. try:
  499. p.wait()
  500. except KeyboardInterrupt:
  501. p.wait()
  502. if p.returncode != 0:
  503. self.prompt_next_action("Build failed")
  504. else:
  505. self.output_enable(True)
  506. def lookup_pc_address(self, pc_addr):
  507. cmd = ["%saddr2line" % self.toolchain_prefix,
  508. "-pfiaC", "-e", self.elf_file, pc_addr]
  509. try:
  510. translation = subprocess.check_output(cmd, cwd=".")
  511. if b"?? ??:0" not in translation:
  512. yellow_print(translation.decode())
  513. except OSError as e:
  514. red_print("%s: %s" % (" ".join(cmd), e))
  515. def check_gdbstub_trigger(self, line):
  516. line = self._gdb_buffer + line
  517. self._gdb_buffer = b""
  518. m = re.search(b"\\$(T..)#(..)", line) # look for a gdb "reason" for a break
  519. if m is not None:
  520. try:
  521. chsum = sum(ord(bytes([p])) for p in m.group(1)) & 0xFF
  522. calc_chsum = int(m.group(2), 16)
  523. except ValueError:
  524. return # payload wasn't valid hex digits
  525. if chsum == calc_chsum:
  526. self.run_gdb()
  527. else:
  528. red_print("Malformed gdb message... calculated checksum %02x received %02x" % (chsum, calc_chsum))
  529. def run_gdb(self):
  530. with self: # disable console control
  531. sys.stderr.write(ANSI_NORMAL)
  532. try:
  533. cmd = ["%sgdb" % self.toolchain_prefix,
  534. "-ex", "set serial baud %d" % self.serial.baudrate,
  535. "-ex", "target remote %s" % self.serial.port,
  536. "-ex", "interrupt", # monitor has already parsed the first 'reason' command, need a second
  537. self.elf_file]
  538. process = subprocess.Popen(cmd, cwd=".")
  539. process.wait()
  540. except OSError as e:
  541. red_print("%s: %s" % (" ".join(cmd), e))
  542. except KeyboardInterrupt:
  543. pass # happens on Windows, maybe other OSes
  544. finally:
  545. try:
  546. # on Linux, maybe other OSes, gdb sometimes seems to be alive even after wait() returns...
  547. process.terminate()
  548. except Exception:
  549. pass
  550. try:
  551. # also on Linux, maybe other OSes, gdb sometimes exits uncleanly and breaks the tty mode
  552. subprocess.call(["stty", "sane"])
  553. except Exception:
  554. pass # don't care if there's no stty, we tried...
  555. self.prompt_next_action("gdb exited")
  556. def output_enable(self, enable):
  557. self._output_enabled = enable
  558. def output_toggle(self):
  559. self._output_enabled = not self._output_enabled
  560. yellow_print("\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.".format(self._output_enabled))
  561. def main():
  562. parser = argparse.ArgumentParser("idf_monitor - a serial output monitor for esp-idf")
  563. parser.add_argument(
  564. '--port', '-p',
  565. help='Serial port device',
  566. default=os.environ.get('ESPTOOL_PORT', '/dev/ttyUSB0')
  567. )
  568. parser.add_argument(
  569. '--baud', '-b',
  570. help='Serial port baud rate',
  571. type=int,
  572. default=os.environ.get('MONITOR_BAUD', 115200))
  573. parser.add_argument(
  574. '--make', '-m',
  575. help='Command to run make',
  576. type=str, default='make')
  577. parser.add_argument(
  578. '--toolchain-prefix',
  579. help="Triplet prefix to add before cross-toolchain names",
  580. default=DEFAULT_TOOLCHAIN_PREFIX)
  581. parser.add_argument(
  582. "--eol",
  583. choices=['CR', 'LF', 'CRLF'],
  584. type=lambda c: c.upper(),
  585. help="End of line to use when sending to the serial port",
  586. default='CR')
  587. parser.add_argument(
  588. 'elf_file', help='ELF file of application',
  589. type=argparse.FileType('rb'))
  590. parser.add_argument(
  591. '--print_filter',
  592. help="Filtering string",
  593. default=DEFAULT_PRINT_FILTER)
  594. args = parser.parse_args()
  595. if args.port.startswith("/dev/tty."):
  596. args.port = args.port.replace("/dev/tty.", "/dev/cu.")
  597. yellow_print("--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.")
  598. yellow_print("--- Using %s instead..." % args.port)
  599. serial_instance = serial.serial_for_url(args.port, args.baud,
  600. do_not_open=True)
  601. serial_instance.dtr = False
  602. serial_instance.rts = False
  603. args.elf_file.close() # don't need this as a file
  604. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  605. # parent make is only running 1 job (monitor), so we can re-spawn
  606. # all of the child makes we need (the -j argument remains part of
  607. # MAKEFLAGS)
  608. try:
  609. makeflags = os.environ["MAKEFLAGS"]
  610. makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
  611. os.environ["MAKEFLAGS"] = makeflags
  612. except KeyError:
  613. pass # not running a make jobserver
  614. monitor = Monitor(serial_instance, args.elf_file.name, args.print_filter, args.make, args.toolchain_prefix, args.eol)
  615. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  616. p=serial_instance))
  617. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  618. key_description(monitor.exit_key),
  619. key_description(monitor.menu_key),
  620. key_description(monitor.menu_key),
  621. key_description(CTRL_H)))
  622. if args.print_filter != DEFAULT_PRINT_FILTER:
  623. yellow_print('--- Print filter: {} ---'.format(args.print_filter))
  624. monitor.main_loop()
  625. if os.name == 'nt':
  626. # Windows console stuff
  627. STD_OUTPUT_HANDLE = -11
  628. STD_ERROR_HANDLE = -12
  629. # wincon.h values
  630. FOREGROUND_INTENSITY = 8
  631. FOREGROUND_GREY = 7
  632. # matches the ANSI color change sequences that IDF sends
  633. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  634. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  635. ANSI_TO_WINDOWS_COLOR = [0, 4, 2, 6, 1, 5, 3, 7]
  636. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  637. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  638. class ANSIColorConverter(object):
  639. """Class to wrap a file-like output stream, intercept ANSI color codes,
  640. and convert them into calls to Windows SetConsoleTextAttribute.
  641. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  642. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  643. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  644. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  645. """
  646. def __init__(self, output=None, decode_output=False):
  647. self.output = output
  648. self.decode_output = decode_output
  649. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  650. self.matched = b''
  651. def _output_write(self, data):
  652. try:
  653. if self.decode_output:
  654. self.output.write(data.decode())
  655. else:
  656. self.output.write(data)
  657. except IOError:
  658. # Windows 10 bug since the Fall Creators Update, sometimes writing to console randomly throws
  659. # an exception (however, the character is still written to the screen)
  660. # Ref https://github.com/espressif/esp-idf/issues/1136
  661. pass
  662. def write(self, data):
  663. if isinstance(data, bytes):
  664. data = bytearray(data)
  665. else:
  666. data = bytearray(data, 'utf-8')
  667. for b in data:
  668. b = bytes([b])
  669. length = len(self.matched)
  670. if b == b'\033': # ESC
  671. self.matched = b
  672. elif (length == 1 and b == b'[') or (1 < length < 7):
  673. self.matched += b
  674. if self.matched == ANSI_NORMAL.encode('latin-1'): # reset console
  675. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  676. self.flush()
  677. SetConsoleTextAttribute(self.handle, FOREGROUND_GREY)
  678. self.matched = b''
  679. elif len(self.matched) == 7: # could be an ANSI sequence
  680. m = re.match(RE_ANSI_COLOR, self.matched)
  681. if m is not None:
  682. color = ANSI_TO_WINDOWS_COLOR[int(m.group(2))]
  683. if m.group(1) == b'1':
  684. color |= FOREGROUND_INTENSITY
  685. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  686. self.flush()
  687. SetConsoleTextAttribute(self.handle, color)
  688. else:
  689. self._output_write(self.matched) # not an ANSI color code, display verbatim
  690. self.matched = b''
  691. else:
  692. self._output_write(b)
  693. self.matched = b''
  694. def flush(self):
  695. self.output.flush()
  696. if __name__ == "__main__":
  697. main()