idf_monitor.py 33 KB

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