idf_monitor.py 36 KB

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