idf_monitor.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. def handle_serial_input(self, data):
  260. # this may need to be made more efficient, as it pushes out a byte
  261. # at a time to the console
  262. for b in data:
  263. self.console.write_bytes(b)
  264. if b == b'\n': # end of line
  265. self.handle_serial_input_line(self._read_line.strip())
  266. self._read_line = b""
  267. else:
  268. self._read_line += b
  269. self.check_gdbstub_trigger(b)
  270. def handle_serial_input_line(self, line):
  271. for m in re.finditer(MATCH_PCADDR, line):
  272. self.lookup_pc_address(m.group())
  273. def handle_menu_key(self, c):
  274. if c == self.exit_key or c == self.menu_key: # send verbatim
  275. self.serial.write(codecs.encode(c))
  276. elif c in [ CTRL_H, 'h', 'H', '?' ]:
  277. red_print(self.get_help_text())
  278. elif c == CTRL_R: # Reset device via RTS
  279. self.serial.setRTS(True)
  280. time.sleep(0.2)
  281. self.serial.setRTS(False)
  282. elif c == CTRL_F: # Recompile & upload
  283. self.run_make("flash")
  284. elif c == CTRL_A: # Recompile & upload app only
  285. self.run_make("app-flash")
  286. else:
  287. red_print('--- unknown menu character {} --'.format(key_description(c)))
  288. def get_help_text(self):
  289. return """
  290. --- idf_monitor ({version}) - ESP-IDF monitor tool
  291. --- based on miniterm from pySerial
  292. ---
  293. --- {exit:8} Exit program
  294. --- {menu:8} Menu escape key, followed by:
  295. --- Menu keys:
  296. --- {menu:7} Send the menu character itself to remote
  297. --- {exit:7} Send the exit character itself to remote
  298. --- {reset:7} Reset target board via RTS line
  299. --- {make:7} Run 'make flash' to build & flash
  300. --- {appmake:7} Run 'make app-flash to build & flash app
  301. """.format(version=__version__,
  302. exit=key_description(self.exit_key),
  303. menu=key_description(self.menu_key),
  304. reset=key_description(CTRL_R),
  305. make=key_description(CTRL_F),
  306. appmake=key_description(CTRL_A),
  307. )
  308. def __enter__(self):
  309. """ Use 'with self' to temporarily disable monitoring behaviour """
  310. self.serial_reader.stop()
  311. self.console_reader.stop()
  312. def __exit__(self, *args, **kwargs):
  313. """ Use 'with self' to temporarily disable monitoring behaviour """
  314. self.console_reader.start()
  315. self.serial_reader.start()
  316. def prompt_next_action(self, reason):
  317. self.console.setup() # set up console to trap input characters
  318. try:
  319. red_print("""
  320. --- {}
  321. --- Press {} to exit monitor.
  322. --- Press {} to run 'make flash'.
  323. --- Press {} to run 'make app-flash'.
  324. --- Press any other key to resume monitor (resets target).""".format(reason,
  325. key_description(self.exit_key),
  326. key_description(CTRL_F),
  327. key_description(CTRL_A)))
  328. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  329. while k == CTRL_T:
  330. k = self.console.getkey()
  331. finally:
  332. self.console.cleanup()
  333. if k == self.exit_key:
  334. self.event_queue.put((TAG_KEY, k))
  335. elif k in [ CTRL_F, CTRL_A ]:
  336. self.event_queue.put((TAG_KEY, self.menu_key))
  337. self.event_queue.put((TAG_KEY, k))
  338. def run_make(self, target):
  339. with self:
  340. yellow_print("Running make %s..." % target)
  341. p = subprocess.Popen([self.make,
  342. target ])
  343. try:
  344. p.wait()
  345. except KeyboardInterrupt:
  346. p.wait()
  347. if p.returncode != 0:
  348. self.prompt_next_action("Build failed")
  349. def lookup_pc_address(self, pc_addr):
  350. translation = subprocess.check_output(
  351. ["%saddr2line" % self.toolchain_prefix,
  352. "-pfiaC", "-e", self.elf_file, pc_addr],
  353. cwd=".")
  354. if not "?? ??:0" in translation:
  355. yellow_print(translation)
  356. def check_gdbstub_trigger(self, c):
  357. self._gdb_buffer = self._gdb_buffer[-6:] + c # keep the last 7 characters seen
  358. m = re.match(b"\\$(T..)#(..)", self._gdb_buffer) # look for a gdb "reason" for a break
  359. if m is not None:
  360. try:
  361. chsum = sum(ord(p) for p in m.group(1)) & 0xFF
  362. calc_chsum = int(m.group(2), 16)
  363. except ValueError:
  364. return # payload wasn't valid hex digits
  365. if chsum == calc_chsum:
  366. self.run_gdb()
  367. else:
  368. red_print("Malformed gdb message... calculated checksum %02x received %02x" % (chsum, calc_chsum))
  369. def run_gdb(self):
  370. with self: # disable console control
  371. sys.stderr.write(ANSI_NORMAL)
  372. try:
  373. subprocess.call(["%sgdb" % self.toolchain_prefix,
  374. "-ex", "set serial baud %d" % self.serial.baudrate,
  375. "-ex", "target remote %s" % self.serial.port,
  376. "-ex", "interrupt", # monitor has already parsed the first 'reason' command, need a second
  377. self.elf_file], cwd=".")
  378. except KeyboardInterrupt:
  379. pass # happens on Windows, maybe other OSes
  380. self.prompt_next_action("gdb exited")
  381. def main():
  382. parser = argparse.ArgumentParser("idf_monitor - a serial output monitor for esp-idf")
  383. parser.add_argument(
  384. '--port', '-p',
  385. help='Serial port device',
  386. default=os.environ.get('ESPTOOL_PORT', '/dev/ttyUSB0')
  387. )
  388. parser.add_argument(
  389. '--baud', '-b',
  390. help='Serial port baud rate',
  391. type=int,
  392. default=os.environ.get('MONITOR_BAUD', 115200))
  393. parser.add_argument(
  394. '--make', '-m',
  395. help='Command to run make',
  396. type=str, default='make')
  397. parser.add_argument(
  398. '--toolchain-prefix',
  399. help="Triplet prefix to add before cross-toolchain names",
  400. default=DEFAULT_TOOLCHAIN_PREFIX)
  401. parser.add_argument(
  402. "--eol",
  403. choices=['CR', 'LF', 'CRLF'],
  404. type=lambda c: c.upper(),
  405. help="End of line to use when sending to the serial port",
  406. default='CR')
  407. parser.add_argument(
  408. 'elf_file', help='ELF file of application',
  409. type=argparse.FileType('rb'))
  410. args = parser.parse_args()
  411. if args.port.startswith("/dev/tty."):
  412. args.port = args.port.replace("/dev/tty.", "/dev/cu.")
  413. yellow_print("--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.")
  414. yellow_print("--- Using %s instead..." % args.port)
  415. serial_instance = serial.serial_for_url(args.port, args.baud,
  416. do_not_open=True)
  417. serial_instance.dtr = False
  418. serial_instance.rts = False
  419. args.elf_file.close() # don't need this as a file
  420. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  421. # parent make is only running 1 job (monitor), so we can re-spawn
  422. # all of the child makes we need (the -j argument remains part of
  423. # MAKEFLAGS)
  424. try:
  425. makeflags = os.environ["MAKEFLAGS"]
  426. makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
  427. os.environ["MAKEFLAGS"] = makeflags
  428. except KeyError:
  429. pass # not running a make jobserver
  430. monitor = Monitor(serial_instance, args.elf_file.name, args.make, args.toolchain_prefix, args.eol)
  431. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  432. p=serial_instance))
  433. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  434. key_description(monitor.exit_key),
  435. key_description(monitor.menu_key),
  436. key_description(monitor.menu_key),
  437. key_description(CTRL_H)))
  438. monitor.main_loop()
  439. if os.name == 'nt':
  440. # Windows console stuff
  441. STD_OUTPUT_HANDLE = -11
  442. STD_ERROR_HANDLE = -12
  443. # wincon.h values
  444. FOREGROUND_INTENSITY = 8
  445. FOREGROUND_GREY = 7
  446. # matches the ANSI color change sequences that IDF sends
  447. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  448. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  449. ANSI_TO_WINDOWS_COLOR = [ 0, 4, 2, 6, 1, 5, 3, 7 ]
  450. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  451. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  452. class ANSIColorConverter(object):
  453. """Class to wrap a file-like output stream, intercept ANSI color codes,
  454. and convert them into calls to Windows SetConsoleTextAttribute.
  455. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  456. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  457. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  458. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  459. """
  460. def __init__(self, output):
  461. self.output = output
  462. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  463. self.matched = b''
  464. def write(self, data):
  465. for b in data:
  466. l = len(self.matched)
  467. if b == '\033': # ESC
  468. self.matched = b
  469. elif (l == 1 and b == '[') or (1 < l < 7):
  470. self.matched += b
  471. if self.matched == ANSI_NORMAL: # reset console
  472. SetConsoleTextAttribute(self.handle, FOREGROUND_GREY)
  473. self.matched = b''
  474. elif len(self.matched) == 7: # could be an ANSI sequence
  475. m = re.match(RE_ANSI_COLOR, self.matched)
  476. if m is not None:
  477. color = ANSI_TO_WINDOWS_COLOR[int(m.group(2))]
  478. if m.group(1) == b'1':
  479. color |= FOREGROUND_INTENSITY
  480. SetConsoleTextAttribute(self.handle, color)
  481. else:
  482. self.output.write(self.matched) # not an ANSI color code, display verbatim
  483. self.matched = b''
  484. else:
  485. self.output.write(b)
  486. self.matched = b''
  487. def flush(self):
  488. self.output.flush()
  489. if __name__ == "__main__":
  490. main()