idf_monitor.py 36 KB

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