idf_monitor.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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. self.serial.dtr = self.serial.dtr # usbser.sys workaround
  316. try:
  317. while self.alive:
  318. data = self.serial.read(self.serial.in_waiting or 1)
  319. if len(data):
  320. self.event_queue.put((TAG_SERIAL, data), False)
  321. finally:
  322. self.serial.close()
  323. def _cancel(self):
  324. if hasattr(self.serial, 'cancel_read'):
  325. try:
  326. self.serial.cancel_read()
  327. except Exception:
  328. pass
  329. class LineMatcher(object):
  330. """
  331. Assembles a dictionary of filtering rules based on the --print_filter
  332. argument of idf_monitor. Then later it is used to match lines and
  333. determine whether they should be shown on screen or not.
  334. """
  335. LEVEL_N = 0
  336. LEVEL_E = 1
  337. LEVEL_W = 2
  338. LEVEL_I = 3
  339. LEVEL_D = 4
  340. LEVEL_V = 5
  341. level = {'N': LEVEL_N, 'E': LEVEL_E, 'W': LEVEL_W, 'I': LEVEL_I, 'D': LEVEL_D,
  342. 'V': LEVEL_V, '*': LEVEL_V, '': LEVEL_V}
  343. def __init__(self, print_filter):
  344. self._dict = dict()
  345. self._re = re.compile(r'^(?:\033\[[01];?[0-9]+m?)?([EWIDV]) \([0-9]+\) ([^:]+): ')
  346. items = print_filter.split()
  347. if len(items) == 0:
  348. self._dict["*"] = self.LEVEL_V # default is to print everything
  349. for f in items:
  350. s = f.split(r':')
  351. if len(s) == 1:
  352. # specifying no warning level defaults to verbose level
  353. lev = self.LEVEL_V
  354. elif len(s) == 2:
  355. if len(s[0]) == 0:
  356. raise ValueError('No tag specified in filter ' + f)
  357. try:
  358. lev = self.level[s[1].upper()]
  359. except KeyError:
  360. raise ValueError('Unknown warning level in filter ' + f)
  361. else:
  362. raise ValueError('Missing ":" in filter ' + f)
  363. self._dict[s[0]] = lev
  364. def match(self, line):
  365. try:
  366. m = self._re.search(line)
  367. if m:
  368. lev = self.level[m.group(1)]
  369. if m.group(2) in self._dict:
  370. return self._dict[m.group(2)] >= lev
  371. return self._dict.get("*", self.LEVEL_N) >= lev
  372. except (KeyError, IndexError):
  373. # Regular line written with something else than ESP_LOG*
  374. # or an empty line.
  375. pass
  376. # We need something more than "*.N" for printing.
  377. return self._dict.get("*", self.LEVEL_N) > self.LEVEL_N
  378. class SerialStopException(Exception):
  379. """
  380. This exception is used for stopping the IDF monitor in testing mode.
  381. """
  382. pass
  383. class Monitor(object):
  384. """
  385. Monitor application main class.
  386. This was originally derived from miniterm.Miniterm, but it turned out to be easier to write from scratch for this
  387. purpose.
  388. Main difference is that all event processing happens in the main thread, not the worker threads.
  389. """
  390. def __init__(self, serial_instance, elf_file, print_filter, make="make", encrypted=False,
  391. toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, eol="CRLF"):
  392. super(Monitor, self).__init__()
  393. self.event_queue = queue.Queue()
  394. self.cmd_queue = queue.Queue()
  395. self.console = miniterm.Console()
  396. if os.name == 'nt':
  397. sys.stderr = ANSIColorConverter(sys.stderr, decode_output=True)
  398. self.console.output = ANSIColorConverter(self.console.output)
  399. self.console.byte_output = ANSIColorConverter(self.console.byte_output)
  400. if StrictVersion(serial.VERSION) < StrictVersion('3.3.0'):
  401. # Use Console.getkey implementation from 3.3.0 (to be in sync with the ConsoleReader._cancel patch above)
  402. def getkey_patched(self):
  403. c = self.enc_stdin.read(1)
  404. if c == chr(0x7f):
  405. c = chr(8) # map the BS key (which yields DEL) to backspace
  406. return c
  407. self.console.getkey = types.MethodType(getkey_patched, self.console)
  408. socket_mode = serial_instance.port.startswith("socket://") # testing hook - data from serial can make exit the monitor
  409. self.serial = serial_instance
  410. self.console_parser = ConsoleParser(eol)
  411. self.console_reader = ConsoleReader(self.console, self.event_queue, self.cmd_queue, self.console_parser, socket_mode)
  412. self.serial_reader = SerialReader(self.serial, self.event_queue)
  413. self.elf_file = elf_file
  414. if not os.path.exists(make):
  415. self.make = shlex.split(make) # allow for possibility the "make" arg is a list of arguments (for idf.py)
  416. else:
  417. self.make = make
  418. self.encrypted = encrypted
  419. self.toolchain_prefix = toolchain_prefix
  420. # internal state
  421. self._last_line_part = b""
  422. self._gdb_buffer = b""
  423. self._pc_address_buffer = b""
  424. self._line_matcher = LineMatcher(print_filter)
  425. self._invoke_processing_last_line_timer = None
  426. self._force_line_print = False
  427. self._output_enabled = True
  428. self._serial_check_exit = socket_mode
  429. self._log_file = None
  430. def invoke_processing_last_line(self):
  431. self.event_queue.put((TAG_SERIAL_FLUSH, b''), False)
  432. def main_loop(self):
  433. self.console_reader.start()
  434. self.serial_reader.start()
  435. try:
  436. while self.console_reader.alive and self.serial_reader.alive:
  437. try:
  438. item = self.cmd_queue.get_nowait()
  439. except queue.Empty:
  440. try:
  441. item = self.event_queue.get(True, 0.03)
  442. except queue.Empty:
  443. continue
  444. (event_tag, data) = item
  445. if event_tag == TAG_CMD:
  446. self.handle_commands(data)
  447. elif event_tag == TAG_KEY:
  448. try:
  449. self.serial.write(codecs.encode(data))
  450. except serial.SerialException:
  451. pass # this shouldn't happen, but sometimes port has closed in serial thread
  452. except UnicodeEncodeError:
  453. pass # this can happen if a non-ascii character was passed, ignoring
  454. elif event_tag == TAG_SERIAL:
  455. self.handle_serial_input(data)
  456. if self._invoke_processing_last_line_timer is not None:
  457. self._invoke_processing_last_line_timer.cancel()
  458. self._invoke_processing_last_line_timer = threading.Timer(0.1, self.invoke_processing_last_line)
  459. self._invoke_processing_last_line_timer.start()
  460. # If no futher data is received in the next short period
  461. # of time then the _invoke_processing_last_line_timer
  462. # generates an event which will result in the finishing of
  463. # the last line. This is fix for handling lines sent
  464. # without EOL.
  465. elif event_tag == TAG_SERIAL_FLUSH:
  466. self.handle_serial_input(data, finalize_line=True)
  467. else:
  468. raise RuntimeError("Bad event data %r" % ((event_tag,data),))
  469. except SerialStopException:
  470. sys.stderr.write(ANSI_NORMAL + "Stopping condition has been received\n")
  471. finally:
  472. try:
  473. self.console_reader.stop()
  474. self.serial_reader.stop()
  475. self.stop_logging()
  476. # Cancelling _invoke_processing_last_line_timer is not
  477. # important here because receiving empty data doesn't matter.
  478. self._invoke_processing_last_line_timer = None
  479. except Exception:
  480. pass
  481. sys.stderr.write(ANSI_NORMAL + "\n")
  482. def handle_serial_input(self, data, finalize_line=False):
  483. sp = data.split(b'\n')
  484. if self._last_line_part != b"":
  485. # add unprocessed part from previous "data" to the first line
  486. sp[0] = self._last_line_part + sp[0]
  487. self._last_line_part = b""
  488. if sp[-1] != b"":
  489. # last part is not a full line
  490. self._last_line_part = sp.pop()
  491. for line in sp:
  492. if line != b"":
  493. if self._serial_check_exit and line == self.console_parser.exit_key.encode('latin-1'):
  494. raise SerialStopException()
  495. if self._force_line_print or self._line_matcher.match(line.decode(errors="ignore")):
  496. self._print(line + b'\n')
  497. self.handle_possible_pc_address_in_line(line)
  498. self.check_gdbstub_trigger(line)
  499. self._force_line_print = False
  500. # Now we have the last part (incomplete line) in _last_line_part. By
  501. # default we don't touch it and just wait for the arrival of the rest
  502. # of the line. But after some time when we didn't received it we need
  503. # to make a decision.
  504. if self._last_line_part != b"":
  505. if self._force_line_print or (finalize_line and self._line_matcher.match(self._last_line_part.decode(errors="ignore"))):
  506. self._force_line_print = True
  507. self._print(self._last_line_part)
  508. self.handle_possible_pc_address_in_line(self._last_line_part)
  509. self.check_gdbstub_trigger(self._last_line_part)
  510. # It is possible that the incomplete line cuts in half the PC
  511. # address. A small buffer is kept and will be used the next time
  512. # handle_possible_pc_address_in_line is invoked to avoid this problem.
  513. # MATCH_PCADDR matches 10 character long addresses. Therefore, we
  514. # keep the last 9 characters.
  515. self._pc_address_buffer = self._last_line_part[-9:]
  516. # GDB sequence can be cut in half also. GDB sequence is 7
  517. # characters long, therefore, we save the last 6 characters.
  518. self._gdb_buffer = self._last_line_part[-6:]
  519. self._last_line_part = b""
  520. # else: keeping _last_line_part and it will be processed the next time
  521. # handle_serial_input is invoked
  522. def handle_possible_pc_address_in_line(self, line):
  523. line = self._pc_address_buffer + line
  524. self._pc_address_buffer = b""
  525. for m in re.finditer(MATCH_PCADDR, line.decode(errors="ignore")):
  526. self.lookup_pc_address(m.group())
  527. def __enter__(self):
  528. """ Use 'with self' to temporarily disable monitoring behaviour """
  529. self.serial_reader.stop()
  530. self.console_reader.stop()
  531. def __exit__(self, *args, **kwargs):
  532. """ Use 'with self' to temporarily disable monitoring behaviour """
  533. self.console_reader.start()
  534. self.serial_reader.start()
  535. def prompt_next_action(self, reason):
  536. self.console.setup() # set up console to trap input characters
  537. try:
  538. red_print("--- {}".format(reason))
  539. red_print(self.console_parser.get_next_action_text())
  540. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  541. while k == CTRL_T:
  542. k = self.console.getkey()
  543. finally:
  544. self.console.cleanup()
  545. ret = self.console_parser.parse_next_action_key(k)
  546. if ret is not None:
  547. cmd = ret[1]
  548. if cmd == CMD_STOP:
  549. # the stop command should be handled last
  550. self.event_queue.put(ret)
  551. else:
  552. self.cmd_queue.put(ret)
  553. def run_make(self, target):
  554. with self:
  555. if isinstance(self.make, list):
  556. popen_args = self.make + [target]
  557. else:
  558. popen_args = [self.make, target]
  559. yellow_print("Running %s..." % " ".join(popen_args))
  560. p = subprocess.Popen(popen_args)
  561. try:
  562. p.wait()
  563. except KeyboardInterrupt:
  564. p.wait()
  565. if p.returncode != 0:
  566. self.prompt_next_action("Build failed")
  567. else:
  568. self.output_enable(True)
  569. def lookup_pc_address(self, pc_addr):
  570. cmd = ["%saddr2line" % self.toolchain_prefix,
  571. "-pfiaC", "-e", self.elf_file, pc_addr]
  572. try:
  573. translation = subprocess.check_output(cmd, cwd=".")
  574. if b"?? ??:0" not in translation:
  575. self._print(translation.decode(), console_printer=yellow_print)
  576. except OSError as e:
  577. red_print("%s: %s" % (" ".join(cmd), e))
  578. def check_gdbstub_trigger(self, line):
  579. line = self._gdb_buffer + line
  580. self._gdb_buffer = b""
  581. m = re.search(b"\\$(T..)#(..)", line) # look for a gdb "reason" for a break
  582. if m is not None:
  583. try:
  584. chsum = sum(ord(bytes([p])) for p in m.group(1)) & 0xFF
  585. calc_chsum = int(m.group(2), 16)
  586. except ValueError:
  587. return # payload wasn't valid hex digits
  588. if chsum == calc_chsum:
  589. self.run_gdb()
  590. else:
  591. red_print("Malformed gdb message... calculated checksum %02x received %02x" % (chsum, calc_chsum))
  592. def run_gdb(self):
  593. with self: # disable console control
  594. sys.stderr.write(ANSI_NORMAL)
  595. try:
  596. cmd = ["%sgdb" % self.toolchain_prefix,
  597. "-ex", "set serial baud %d" % self.serial.baudrate,
  598. "-ex", "target remote %s" % self.serial.port,
  599. "-ex", "interrupt", # monitor has already parsed the first 'reason' command, need a second
  600. self.elf_file]
  601. process = subprocess.Popen(cmd, cwd=".")
  602. process.wait()
  603. except OSError as e:
  604. red_print("%s: %s" % (" ".join(cmd), e))
  605. except KeyboardInterrupt:
  606. pass # happens on Windows, maybe other OSes
  607. finally:
  608. try:
  609. # on Linux, maybe other OSes, gdb sometimes seems to be alive even after wait() returns...
  610. process.terminate()
  611. except Exception:
  612. pass
  613. try:
  614. # also on Linux, maybe other OSes, gdb sometimes exits uncleanly and breaks the tty mode
  615. subprocess.call(["stty", "sane"])
  616. except Exception:
  617. pass # don't care if there's no stty, we tried...
  618. self.prompt_next_action("gdb exited")
  619. def output_enable(self, enable):
  620. self._output_enabled = enable
  621. def output_toggle(self):
  622. self._output_enabled = not self._output_enabled
  623. yellow_print("\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.".format(self._output_enabled))
  624. def toggle_logging(self):
  625. if self._log_file:
  626. self.stop_logging()
  627. else:
  628. self.start_logging()
  629. def start_logging(self):
  630. if not self._log_file:
  631. try:
  632. name = "log.{}.{}.txt".format(os.path.splitext(os.path.basename(self.elf_file))[0],
  633. datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
  634. self._log_file = open(name, "wb+")
  635. yellow_print("\nLogging is enabled into file {}".format(name))
  636. except Exception as e:
  637. red_print("\nLog file {} cannot be created: {}".format(name, e))
  638. def stop_logging(self):
  639. if self._log_file:
  640. try:
  641. name = self._log_file.name
  642. self._log_file.close()
  643. yellow_print("\nLogging is disabled and file {} has been closed".format(name))
  644. except Exception as e:
  645. red_print("\nLog file cannot be closed: {}".format(e))
  646. finally:
  647. self._log_file = None
  648. def _print(self, string, console_printer=None):
  649. if console_printer is None:
  650. console_printer = self.console.write_bytes
  651. if self._output_enabled:
  652. console_printer(string)
  653. if self._log_file:
  654. try:
  655. if isinstance(string, type(u'')):
  656. string = string.encode()
  657. self._log_file.write(string)
  658. except Exception as e:
  659. red_print("\nCannot write to file: {}".format(e))
  660. # don't fill-up the screen with the previous errors (probably consequent prints would fail also)
  661. self.stop_logging()
  662. def handle_commands(self, cmd):
  663. if cmd == CMD_STOP:
  664. self.console_reader.stop()
  665. self.serial_reader.stop()
  666. elif cmd == CMD_RESET:
  667. self.serial.setRTS(True)
  668. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  669. time.sleep(0.2)
  670. self.serial.setRTS(False)
  671. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  672. self.output_enable(True)
  673. elif cmd == CMD_MAKE:
  674. self.run_make("encrypted-flash" if self.encrypted else "flash")
  675. elif cmd == CMD_APP_FLASH:
  676. self.run_make("encrypted-app-flash" if self.encrypted else "app-flash")
  677. elif cmd == CMD_OUTPUT_TOGGLE:
  678. self.output_toggle()
  679. elif cmd == CMD_TOGGLE_LOGGING:
  680. self.toggle_logging()
  681. elif cmd == CMD_ENTER_BOOT:
  682. self.serial.setDTR(False) # IO0=HIGH
  683. self.serial.setRTS(True) # EN=LOW, chip in reset
  684. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  685. time.sleep(1.3) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  686. self.serial.setDTR(True) # IO0=LOW
  687. self.serial.setRTS(False) # EN=HIGH, chip out of reset
  688. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  689. time.sleep(0.45) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  690. self.serial.setDTR(False) # IO0=HIGH, done
  691. else:
  692. raise RuntimeError("Bad command data %d" % (cmd))
  693. def main():
  694. def _get_default_serial_port():
  695. """
  696. Same logic for detecting serial port as esptool.py and idf.py: reverse sort by name and choose the first port.
  697. """
  698. try:
  699. ports = list(reversed(sorted(p.device for p in serial.tools.list_ports.comports())))
  700. return ports[0]
  701. except Exception:
  702. return '/dev/ttyUSB0'
  703. parser = argparse.ArgumentParser("idf_monitor - a serial output monitor for esp-idf")
  704. parser.add_argument(
  705. '--port', '-p',
  706. help='Serial port device',
  707. default=os.environ.get('ESPTOOL_PORT', _get_default_serial_port())
  708. )
  709. parser.add_argument(
  710. '--baud', '-b',
  711. help='Serial port baud rate',
  712. type=int,
  713. default=os.getenv('IDF_MONITOR_BAUD', os.getenv('MONITORBAUD', 115200)))
  714. parser.add_argument(
  715. '--make', '-m',
  716. help='Command to run make',
  717. type=str, default='make')
  718. parser.add_argument(
  719. '--encrypted',
  720. help='Use encrypted targets while running make',
  721. action='store_true')
  722. parser.add_argument(
  723. '--toolchain-prefix',
  724. help="Triplet prefix to add before cross-toolchain names",
  725. default=DEFAULT_TOOLCHAIN_PREFIX)
  726. parser.add_argument(
  727. "--eol",
  728. choices=['CR', 'LF', 'CRLF'],
  729. type=lambda c: c.upper(),
  730. help="End of line to use when sending to the serial port",
  731. default='CR')
  732. parser.add_argument(
  733. 'elf_file', help='ELF file of application',
  734. type=argparse.FileType('rb'))
  735. parser.add_argument(
  736. '--print_filter',
  737. help="Filtering string",
  738. default=DEFAULT_PRINT_FILTER)
  739. args = parser.parse_args()
  740. if args.port.startswith("/dev/tty."):
  741. args.port = args.port.replace("/dev/tty.", "/dev/cu.")
  742. yellow_print("--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.")
  743. yellow_print("--- Using %s instead..." % args.port)
  744. serial_instance = serial.serial_for_url(args.port, args.baud,
  745. do_not_open=True)
  746. serial_instance.dtr = False
  747. serial_instance.rts = False
  748. args.elf_file.close() # don't need this as a file
  749. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  750. # parent make is only running 1 job (monitor), so we can re-spawn
  751. # all of the child makes we need (the -j argument remains part of
  752. # MAKEFLAGS)
  753. try:
  754. makeflags = os.environ["MAKEFLAGS"]
  755. makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
  756. os.environ["MAKEFLAGS"] = makeflags
  757. except KeyError:
  758. pass # not running a make jobserver
  759. monitor = Monitor(serial_instance, args.elf_file.name, args.print_filter, args.make, args.encrypted,
  760. args.toolchain_prefix, args.eol)
  761. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  762. p=serial_instance))
  763. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  764. key_description(monitor.console_parser.exit_key),
  765. key_description(monitor.console_parser.menu_key),
  766. key_description(monitor.console_parser.menu_key),
  767. key_description(CTRL_H)))
  768. if args.print_filter != DEFAULT_PRINT_FILTER:
  769. yellow_print('--- Print filter: {} ---'.format(args.print_filter))
  770. monitor.main_loop()
  771. if os.name == 'nt':
  772. # Windows console stuff
  773. STD_OUTPUT_HANDLE = -11
  774. STD_ERROR_HANDLE = -12
  775. # wincon.h values
  776. FOREGROUND_INTENSITY = 8
  777. FOREGROUND_GREY = 7
  778. # matches the ANSI color change sequences that IDF sends
  779. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  780. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  781. ANSI_TO_WINDOWS_COLOR = [0, 4, 2, 6, 1, 5, 3, 7]
  782. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  783. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  784. class ANSIColorConverter(object):
  785. """Class to wrap a file-like output stream, intercept ANSI color codes,
  786. and convert them into calls to Windows SetConsoleTextAttribute.
  787. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  788. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  789. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  790. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  791. """
  792. def __init__(self, output=None, decode_output=False):
  793. self.output = output
  794. self.decode_output = decode_output
  795. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  796. self.matched = b''
  797. def _output_write(self, data):
  798. try:
  799. if self.decode_output:
  800. self.output.write(data.decode())
  801. else:
  802. self.output.write(data)
  803. except (IOError, OSError):
  804. # Windows 10 bug since the Fall Creators Update, sometimes writing to console randomly throws
  805. # an exception (however, the character is still written to the screen)
  806. # Ref https://github.com/espressif/esp-idf/issues/1163
  807. #
  808. # Also possible for Windows to throw an OSError error if the data is invalid for the console
  809. # (garbage bytes, etc)
  810. pass
  811. except UnicodeDecodeError:
  812. # In case of double byte Unicode characters display '?'
  813. self.output.write('?')
  814. def write(self, data):
  815. if isinstance(data, bytes):
  816. data = bytearray(data)
  817. else:
  818. data = bytearray(data, 'utf-8')
  819. for b in data:
  820. b = bytes([b])
  821. length = len(self.matched)
  822. if b == b'\033': # ESC
  823. self.matched = b
  824. elif (length == 1 and b == b'[') or (1 < length < 7):
  825. self.matched += b
  826. if self.matched == ANSI_NORMAL.encode('latin-1'): # reset console
  827. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  828. self.flush()
  829. SetConsoleTextAttribute(self.handle, FOREGROUND_GREY)
  830. self.matched = b''
  831. elif len(self.matched) == 7: # could be an ANSI sequence
  832. m = re.match(RE_ANSI_COLOR, self.matched)
  833. if m is not None:
  834. color = ANSI_TO_WINDOWS_COLOR[int(m.group(2))]
  835. if m.group(1) == b'1':
  836. color |= FOREGROUND_INTENSITY
  837. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  838. self.flush()
  839. SetConsoleTextAttribute(self.handle, color)
  840. else:
  841. self._output_write(self.matched) # not an ANSI color code, display verbatim
  842. self.matched = b''
  843. else:
  844. self._output_write(b)
  845. self.matched = b''
  846. def flush(self):
  847. try:
  848. self.output.flush()
  849. except OSError:
  850. # Account for Windows Console refusing to accept garbage bytes (serial noise, etc)
  851. pass
  852. if __name__ == "__main__":
  853. main()