idf_monitor.py 19 KB

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