idf_monitor.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. #!/usr/bin/env python
  2. #
  3. # esp-idf serial output monitor tool. Does some helpful things:
  4. # - Looks up hex addresses in ELF file with addr2line
  5. # - Reset ESP32 via serial RTS line (Ctrl-T Ctrl-R)
  6. # - Run "make flash" (Ctrl-T Ctrl-F)
  7. # - Run "make app-flash" (Ctrl-T Ctrl-A)
  8. # - If gdbstub output is detected, gdb is automatically loaded
  9. #
  10. # Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23. #
  24. # Contains elements taken from miniterm "Very simple serial terminal" which
  25. # is part of pySerial. https://github.com/pyserial/pyserial
  26. # (C)2002-2015 Chris Liechti <cliechti@gmx.net>
  27. #
  28. # Originally released under BSD-3-Clause license.
  29. #
  30. from __future__ import print_function, division
  31. import subprocess
  32. import argparse
  33. import codecs
  34. import re
  35. import os
  36. try:
  37. import queue
  38. except ImportError:
  39. import Queue as queue
  40. import time
  41. import sys
  42. import serial
  43. import serial.tools.miniterm as miniterm
  44. import threading
  45. import ctypes
  46. import types
  47. from distutils.version import StrictVersion
  48. key_description = miniterm.key_description
  49. # Control-key characters
  50. CTRL_A = '\x01'
  51. CTRL_B = '\x02'
  52. CTRL_F = '\x06'
  53. CTRL_H = '\x08'
  54. CTRL_R = '\x12'
  55. CTRL_T = '\x14'
  56. CTRL_RBRACKET = '\x1d' # Ctrl+]
  57. # ANSI terminal codes
  58. ANSI_RED = '\033[1;31m'
  59. ANSI_YELLOW = '\033[0;33m'
  60. ANSI_NORMAL = '\033[0m'
  61. def color_print(message, color):
  62. """ Print a message to stderr with colored highlighting """
  63. sys.stderr.write("%s%s%s\n" % (color, message, ANSI_NORMAL))
  64. def yellow_print(message):
  65. color_print(message, ANSI_YELLOW)
  66. def red_print(message):
  67. color_print(message, ANSI_RED)
  68. __version__ = "1.0"
  69. # Tags for tuples in queues
  70. TAG_KEY = 0
  71. TAG_SERIAL = 1
  72. # regex matches an potential PC value (0x4xxxxxxx)
  73. MATCH_PCADDR = re.compile(r'0x4[0-9a-f]{7}', re.IGNORECASE)
  74. DEFAULT_TOOLCHAIN_PREFIX = "xtensa-esp32-elf-"
  75. class StoppableThread(object):
  76. """
  77. Provide a Thread-like class which can be 'cancelled' via a subclass-provided
  78. cancellation method.
  79. Can be started and stopped multiple times.
  80. Isn't an instance of type Thread because Python Thread objects can only be run once
  81. """
  82. def __init__(self):
  83. self._thread = None
  84. @property
  85. def alive(self):
  86. """
  87. Is 'alive' whenever the internal thread object exists
  88. """
  89. return self._thread is not None
  90. def start(self):
  91. if self._thread is None:
  92. self._thread = threading.Thread(target=self._run_outer)
  93. self._thread.start()
  94. def _cancel(self):
  95. pass # override to provide cancellation functionality
  96. def run(self):
  97. pass # override for the main thread behaviour
  98. def _run_outer(self):
  99. try:
  100. self.run()
  101. finally:
  102. self._thread = None
  103. def stop(self):
  104. if self._thread is not None:
  105. old_thread = self._thread
  106. self._thread = None
  107. self._cancel()
  108. old_thread.join()
  109. class ConsoleReader(StoppableThread):
  110. """ Read input keys from the console and push them to the queue,
  111. until stopped.
  112. """
  113. def __init__(self, console, event_queue):
  114. super(ConsoleReader, self).__init__()
  115. self.console = console
  116. self.event_queue = event_queue
  117. def run(self):
  118. self.console.setup()
  119. try:
  120. while self.alive:
  121. try:
  122. if os.name == 'nt':
  123. # Windows kludge: because the console.cancel() method doesn't
  124. # seem to work to unblock getkey() on the Windows implementation.
  125. #
  126. # So we only call getkey() if we know there's a key waiting for us.
  127. import msvcrt
  128. while not msvcrt.kbhit() and self.alive:
  129. time.sleep(0.1)
  130. if not self.alive:
  131. break
  132. c = self.console.getkey()
  133. except KeyboardInterrupt:
  134. c = '\x03'
  135. if c is not None:
  136. self.event_queue.put((TAG_KEY, c), False)
  137. finally:
  138. self.console.cleanup()
  139. def _cancel(self):
  140. if os.name == 'posix':
  141. # this is the way cancel() is implemented in pyserial 3.3 or newer,
  142. # older pyserial (3.1+) has cancellation implemented via 'select',
  143. # which does not work when console sends an escape sequence response
  144. #
  145. # even older pyserial (<3.1) does not have this method
  146. #
  147. # on Windows there is a different (also hacky) fix, applied above.
  148. #
  149. # note that TIOCSTI is not implemented in WSL / bash-on-Windows.
  150. # TODO: introduce some workaround to make it work there.
  151. import fcntl, termios
  152. fcntl.ioctl(self.console.fd, termios.TIOCSTI, b'\0')
  153. class SerialReader(StoppableThread):
  154. """ Read serial data from the serial port and push to the
  155. event queue, until stopped.
  156. """
  157. def __init__(self, serial, event_queue):
  158. super(SerialReader, self).__init__()
  159. self.baud = serial.baudrate
  160. self.serial = serial
  161. self.event_queue = event_queue
  162. if not hasattr(self.serial, 'cancel_read'):
  163. # enable timeout for checking alive flag,
  164. # if cancel_read not available
  165. self.serial.timeout = 0.25
  166. def run(self):
  167. if not self.serial.is_open:
  168. self.serial.baudrate = self.baud
  169. self.serial.rts = True # Force an RTS reset on open
  170. self.serial.open()
  171. self.serial.rts = False
  172. try:
  173. while self.alive:
  174. data = self.serial.read(self.serial.in_waiting or 1)
  175. if len(data):
  176. self.event_queue.put((TAG_SERIAL, data), False)
  177. finally:
  178. self.serial.close()
  179. def _cancel(self):
  180. if hasattr(self.serial, 'cancel_read'):
  181. try:
  182. self.serial.cancel_read()
  183. except:
  184. pass
  185. class Monitor(object):
  186. """
  187. Monitor application main class.
  188. This was originally derived from miniterm.Miniterm, but it turned out to be easier to write from scratch for this
  189. purpose.
  190. Main difference is that all event processing happens in the main thread, not the worker threads.
  191. """
  192. def __init__(self, serial_instance, elf_file, make="make", toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, eol="CRLF"):
  193. super(Monitor, self).__init__()
  194. self.event_queue = queue.Queue()
  195. self.console = miniterm.Console()
  196. if os.name == 'nt':
  197. sys.stderr = ANSIColorConverter(sys.stderr)
  198. self.console.output = ANSIColorConverter(self.console.output)
  199. self.console.byte_output = ANSIColorConverter(self.console.byte_output)
  200. if StrictVersion(serial.VERSION) < StrictVersion('3.3.0'):
  201. # Use Console.getkey implementation from 3.3.0 (to be in sync with the ConsoleReader._cancel patch above)
  202. def getkey_patched(self):
  203. c = self.enc_stdin.read(1)
  204. if c == unichr(0x7f):
  205. c = unichr(8) # map the BS key (which yields DEL) to backspace
  206. return c
  207. self.console.getkey = types.MethodType(getkey_patched, self.console)
  208. self.serial = serial_instance
  209. self.console_reader = ConsoleReader(self.console, self.event_queue)
  210. self.serial_reader = SerialReader(self.serial, self.event_queue)
  211. self.elf_file = elf_file
  212. self.make = make
  213. self.toolchain_prefix = toolchain_prefix
  214. self.menu_key = CTRL_T
  215. self.exit_key = CTRL_RBRACKET
  216. self.translate_eol = {
  217. "CRLF": lambda c: c.replace(b"\n", b"\r\n"),
  218. "CR": lambda c: c.replace(b"\n", b"\r"),
  219. "LF": lambda c: c.replace(b"\r", b"\n"),
  220. }[eol]
  221. # internal state
  222. self._pressed_menu_key = False
  223. self._read_line = b""
  224. self._gdb_buffer = b""
  225. def main_loop(self):
  226. self.console_reader.start()
  227. self.serial_reader.start()
  228. try:
  229. while self.console_reader.alive and self.serial_reader.alive:
  230. (event_tag, data) = self.event_queue.get()
  231. if event_tag == TAG_KEY:
  232. self.handle_key(data)
  233. elif event_tag == TAG_SERIAL:
  234. self.handle_serial_input(data)
  235. else:
  236. raise RuntimeError("Bad event data %r" % ((event_tag,data),))
  237. finally:
  238. try:
  239. self.console_reader.stop()
  240. self.serial_reader.stop()
  241. except:
  242. pass
  243. sys.stderr.write(ANSI_NORMAL + "\n")
  244. def handle_key(self, key):
  245. if self._pressed_menu_key:
  246. self.handle_menu_key(key)
  247. self._pressed_menu_key = False
  248. elif key == self.menu_key:
  249. self._pressed_menu_key = True
  250. elif key == self.exit_key:
  251. self.console_reader.stop()
  252. self.serial_reader.stop()
  253. else:
  254. try:
  255. key = self.translate_eol(key)
  256. self.serial.write(codecs.encode(key))
  257. except serial.SerialException:
  258. pass # this shouldn't happen, but sometimes port has closed in serial thread
  259. except UnicodeEncodeError:
  260. pass # this can happen if a non-ascii character was passed, ignoring
  261. def handle_serial_input(self, data):
  262. # this may need to be made more efficient, as it pushes out a byte
  263. # at a time to the console
  264. for b in data:
  265. self.console.write_bytes(b)
  266. if b == b'\n': # end of line
  267. self.handle_serial_input_line(self._read_line.strip())
  268. self._read_line = b""
  269. else:
  270. self._read_line += b
  271. self.check_gdbstub_trigger(b)
  272. def handle_serial_input_line(self, line):
  273. for m in re.finditer(MATCH_PCADDR, line):
  274. self.lookup_pc_address(m.group())
  275. def handle_menu_key(self, c):
  276. if c == self.exit_key or c == self.menu_key: # send verbatim
  277. self.serial.write(codecs.encode(c))
  278. elif c in [ CTRL_H, 'h', 'H', '?' ]:
  279. red_print(self.get_help_text())
  280. elif c == CTRL_R: # Reset device via RTS
  281. self.serial.setRTS(True)
  282. time.sleep(0.2)
  283. self.serial.setRTS(False)
  284. elif c == CTRL_F: # Recompile & upload
  285. self.run_make("flash")
  286. elif c == CTRL_A: # Recompile & upload app only
  287. self.run_make("app-flash")
  288. else:
  289. red_print('--- unknown menu character {} --'.format(key_description(c)))
  290. def get_help_text(self):
  291. return """
  292. --- idf_monitor ({version}) - ESP-IDF monitor tool
  293. --- based on miniterm from pySerial
  294. ---
  295. --- {exit:8} Exit program
  296. --- {menu:8} Menu escape key, followed by:
  297. --- Menu keys:
  298. --- {menu:7} Send the menu character itself to remote
  299. --- {exit:7} Send the exit character itself to remote
  300. --- {reset:7} Reset target board via RTS line
  301. --- {make:7} Run 'make flash' to build & flash
  302. --- {appmake:7} Run 'make app-flash to build & flash app
  303. """.format(version=__version__,
  304. exit=key_description(self.exit_key),
  305. menu=key_description(self.menu_key),
  306. reset=key_description(CTRL_R),
  307. make=key_description(CTRL_F),
  308. appmake=key_description(CTRL_A),
  309. )
  310. def __enter__(self):
  311. """ Use 'with self' to temporarily disable monitoring behaviour """
  312. self.serial_reader.stop()
  313. self.console_reader.stop()
  314. def __exit__(self, *args, **kwargs):
  315. """ Use 'with self' to temporarily disable monitoring behaviour """
  316. self.console_reader.start()
  317. self.serial_reader.start()
  318. def prompt_next_action(self, reason):
  319. self.console.setup() # set up console to trap input characters
  320. try:
  321. red_print("""
  322. --- {}
  323. --- Press {} to exit monitor.
  324. --- Press {} to run 'make flash'.
  325. --- Press {} to run 'make app-flash'.
  326. --- Press any other key to resume monitor (resets target).""".format(reason,
  327. key_description(self.exit_key),
  328. key_description(CTRL_F),
  329. key_description(CTRL_A)))
  330. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  331. while k == CTRL_T:
  332. k = self.console.getkey()
  333. finally:
  334. self.console.cleanup()
  335. if k == self.exit_key:
  336. self.event_queue.put((TAG_KEY, k))
  337. elif k in [ CTRL_F, CTRL_A ]:
  338. self.event_queue.put((TAG_KEY, self.menu_key))
  339. self.event_queue.put((TAG_KEY, k))
  340. def run_make(self, target):
  341. with self:
  342. yellow_print("Running make %s..." % target)
  343. p = subprocess.Popen([self.make,
  344. target ])
  345. try:
  346. p.wait()
  347. except KeyboardInterrupt:
  348. p.wait()
  349. if p.returncode != 0:
  350. self.prompt_next_action("Build failed")
  351. def lookup_pc_address(self, pc_addr):
  352. translation = subprocess.check_output(
  353. ["%saddr2line" % self.toolchain_prefix,
  354. "-pfiaC", "-e", self.elf_file, pc_addr],
  355. cwd=".")
  356. if not "?? ??:0" in translation:
  357. yellow_print(translation)
  358. def check_gdbstub_trigger(self, c):
  359. self._gdb_buffer = self._gdb_buffer[-6:] + c # keep the last 7 characters seen
  360. m = re.match(b"\\$(T..)#(..)", self._gdb_buffer) # look for a gdb "reason" for a break
  361. if m is not None:
  362. try:
  363. chsum = sum(ord(p) for p in m.group(1)) & 0xFF
  364. calc_chsum = int(m.group(2), 16)
  365. except ValueError:
  366. return # payload wasn't valid hex digits
  367. if chsum == calc_chsum:
  368. self.run_gdb()
  369. else:
  370. red_print("Malformed gdb message... calculated checksum %02x received %02x" % (chsum, calc_chsum))
  371. def run_gdb(self):
  372. with self: # disable console control
  373. sys.stderr.write(ANSI_NORMAL)
  374. try:
  375. subprocess.call(["%sgdb" % self.toolchain_prefix,
  376. "-ex", "set serial baud %d" % self.serial.baudrate,
  377. "-ex", "target remote %s" % self.serial.port,
  378. "-ex", "interrupt", # monitor has already parsed the first 'reason' command, need a second
  379. self.elf_file], cwd=".")
  380. except KeyboardInterrupt:
  381. pass # happens on Windows, maybe other OSes
  382. self.prompt_next_action("gdb exited")
  383. def main():
  384. parser = argparse.ArgumentParser("idf_monitor - a serial output monitor for esp-idf")
  385. parser.add_argument(
  386. '--port', '-p',
  387. help='Serial port device',
  388. default=os.environ.get('ESPTOOL_PORT', '/dev/ttyUSB0')
  389. )
  390. parser.add_argument(
  391. '--baud', '-b',
  392. help='Serial port baud rate',
  393. type=int,
  394. default=os.environ.get('MONITOR_BAUD', 115200))
  395. parser.add_argument(
  396. '--make', '-m',
  397. help='Command to run make',
  398. type=str, default='make')
  399. parser.add_argument(
  400. '--toolchain-prefix',
  401. help="Triplet prefix to add before cross-toolchain names",
  402. default=DEFAULT_TOOLCHAIN_PREFIX)
  403. parser.add_argument(
  404. "--eol",
  405. choices=['CR', 'LF', 'CRLF'],
  406. type=lambda c: c.upper(),
  407. help="End of line to use when sending to the serial port",
  408. default='CR')
  409. parser.add_argument(
  410. 'elf_file', help='ELF file of application',
  411. type=argparse.FileType('rb'))
  412. args = parser.parse_args()
  413. if args.port.startswith("/dev/tty."):
  414. args.port = args.port.replace("/dev/tty.", "/dev/cu.")
  415. yellow_print("--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.")
  416. yellow_print("--- Using %s instead..." % args.port)
  417. serial_instance = serial.serial_for_url(args.port, args.baud,
  418. do_not_open=True)
  419. serial_instance.dtr = False
  420. serial_instance.rts = False
  421. args.elf_file.close() # don't need this as a file
  422. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  423. # parent make is only running 1 job (monitor), so we can re-spawn
  424. # all of the child makes we need (the -j argument remains part of
  425. # MAKEFLAGS)
  426. try:
  427. makeflags = os.environ["MAKEFLAGS"]
  428. makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
  429. os.environ["MAKEFLAGS"] = makeflags
  430. except KeyError:
  431. pass # not running a make jobserver
  432. monitor = Monitor(serial_instance, args.elf_file.name, args.make, args.toolchain_prefix, args.eol)
  433. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  434. p=serial_instance))
  435. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  436. key_description(monitor.exit_key),
  437. key_description(monitor.menu_key),
  438. key_description(monitor.menu_key),
  439. key_description(CTRL_H)))
  440. monitor.main_loop()
  441. if os.name == 'nt':
  442. # Windows console stuff
  443. STD_OUTPUT_HANDLE = -11
  444. STD_ERROR_HANDLE = -12
  445. # wincon.h values
  446. FOREGROUND_INTENSITY = 8
  447. FOREGROUND_GREY = 7
  448. # matches the ANSI color change sequences that IDF sends
  449. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  450. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  451. ANSI_TO_WINDOWS_COLOR = [ 0, 4, 2, 6, 1, 5, 3, 7 ]
  452. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  453. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  454. class ANSIColorConverter(object):
  455. """Class to wrap a file-like output stream, intercept ANSI color codes,
  456. and convert them into calls to Windows SetConsoleTextAttribute.
  457. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  458. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  459. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  460. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  461. """
  462. def __init__(self, output):
  463. self.output = output
  464. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  465. self.matched = b''
  466. def write(self, data):
  467. for b in data:
  468. l = len(self.matched)
  469. if b == '\033': # ESC
  470. self.matched = b
  471. elif (l == 1 and b == '[') or (1 < l < 7):
  472. self.matched += b
  473. if self.matched == ANSI_NORMAL: # reset console
  474. SetConsoleTextAttribute(self.handle, FOREGROUND_GREY)
  475. self.matched = b''
  476. elif len(self.matched) == 7: # could be an ANSI sequence
  477. m = re.match(RE_ANSI_COLOR, self.matched)
  478. if m is not None:
  479. color = ANSI_TO_WINDOWS_COLOR[int(m.group(2))]
  480. if m.group(1) == b'1':
  481. color |= FOREGROUND_INTENSITY
  482. SetConsoleTextAttribute(self.handle, color)
  483. else:
  484. self.output.write(self.matched) # not an ANSI color code, display verbatim
  485. self.matched = b''
  486. else:
  487. try:
  488. self.output.write(b)
  489. except IOError:
  490. # Windows 10 bug since the Fall Creators Update, sometimes writing to console randomly fails
  491. # (but always succeeds the second time, it seems.) Ref https://github.com/espressif/esp-idf/issues/1136
  492. self.output.write(b)
  493. self.matched = b''
  494. def flush(self):
  495. self.output.flush()
  496. if __name__ == "__main__":
  497. main()