idf_monitor.py 31 KB

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