idf_monitor.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  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. # - If core dump output is detected, it is converted to a human-readable report
  10. # by espcoredump.py.
  11. #
  12. # Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
  13. #
  14. # Licensed under the Apache License, Version 2.0 (the "License");
  15. # you may not use this file except in compliance with the License.
  16. # You may obtain a copy of the License at
  17. #
  18. # http://www.apache.org/licenses/LICENSE-2.0
  19. #
  20. # Unless required by applicable law or agreed to in writing, software
  21. # distributed under the License is distributed on an "AS IS" BASIS,
  22. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. # See the License for the specific language governing permissions and
  24. # limitations under the License.
  25. #
  26. # Contains elements taken from miniterm "Very simple serial terminal" which
  27. # is part of pySerial. https://github.com/pyserial/pyserial
  28. # (C)2002-2015 Chris Liechti <cliechti@gmx.net>
  29. #
  30. # Originally released under BSD-3-Clause license.
  31. #
  32. from __future__ import print_function, division
  33. from __future__ import unicode_literals
  34. from builtins import chr
  35. from builtins import object
  36. from builtins import bytes
  37. import subprocess
  38. import argparse
  39. import codecs
  40. import datetime
  41. import re
  42. import os
  43. try:
  44. import queue
  45. except ImportError:
  46. import Queue as queue
  47. import shlex
  48. import time
  49. import sys
  50. import serial
  51. import serial.tools.list_ports
  52. import serial.tools.miniterm as miniterm
  53. import threading
  54. import ctypes
  55. import types
  56. from distutils.version import StrictVersion
  57. from io import open
  58. import textwrap
  59. import tempfile
  60. import json
  61. try:
  62. import websocket
  63. except ImportError:
  64. # This is needed for IDE integration only.
  65. pass
  66. key_description = miniterm.key_description
  67. # Control-key characters
  68. CTRL_A = '\x01'
  69. CTRL_B = '\x02'
  70. CTRL_F = '\x06'
  71. CTRL_H = '\x08'
  72. CTRL_R = '\x12'
  73. CTRL_T = '\x14'
  74. CTRL_Y = '\x19'
  75. CTRL_P = '\x10'
  76. CTRL_X = '\x18'
  77. CTRL_L = '\x0c'
  78. CTRL_RBRACKET = '\x1d' # Ctrl+]
  79. # Command parsed from console inputs
  80. CMD_STOP = 1
  81. CMD_RESET = 2
  82. CMD_MAKE = 3
  83. CMD_APP_FLASH = 4
  84. CMD_OUTPUT_TOGGLE = 5
  85. CMD_TOGGLE_LOGGING = 6
  86. CMD_ENTER_BOOT = 7
  87. # ANSI terminal codes (if changed, regular expressions in LineMatcher need to be udpated)
  88. ANSI_RED = '\033[1;31m'
  89. ANSI_YELLOW = '\033[0;33m'
  90. ANSI_NORMAL = '\033[0m'
  91. def color_print(message, color, newline='\n'):
  92. """ Print a message to stderr with colored highlighting """
  93. sys.stderr.write("%s%s%s%s" % (color, message, ANSI_NORMAL, newline))
  94. def yellow_print(message, newline='\n'):
  95. color_print(message, ANSI_YELLOW, newline)
  96. def red_print(message, newline='\n'):
  97. color_print(message, ANSI_RED, newline)
  98. __version__ = "1.1"
  99. # Tags for tuples in queues
  100. TAG_KEY = 0
  101. TAG_SERIAL = 1
  102. TAG_SERIAL_FLUSH = 2
  103. TAG_CMD = 3
  104. # regex matches an potential PC value (0x4xxxxxxx)
  105. MATCH_PCADDR = re.compile(r'0x4[0-9a-f]{7}', re.IGNORECASE)
  106. DEFAULT_TOOLCHAIN_PREFIX = "xtensa-esp32-elf-"
  107. DEFAULT_PRINT_FILTER = ""
  108. # coredump related messages
  109. COREDUMP_UART_START = b"================= CORE DUMP START ================="
  110. COREDUMP_UART_END = b"================= CORE DUMP END ================="
  111. COREDUMP_UART_PROMPT = b"Press Enter to print core dump to UART..."
  112. # coredump states
  113. COREDUMP_IDLE = 0
  114. COREDUMP_READING = 1
  115. COREDUMP_DONE = 2
  116. # coredump decoding options
  117. COREDUMP_DECODE_DISABLE = "disable"
  118. COREDUMP_DECODE_INFO = "info"
  119. class StoppableThread(object):
  120. """
  121. Provide a Thread-like class which can be 'cancelled' via a subclass-provided
  122. cancellation method.
  123. Can be started and stopped multiple times.
  124. Isn't an instance of type Thread because Python Thread objects can only be run once
  125. """
  126. def __init__(self):
  127. self._thread = None
  128. @property
  129. def alive(self):
  130. """
  131. Is 'alive' whenever the internal thread object exists
  132. """
  133. return self._thread is not None
  134. def start(self):
  135. if self._thread is None:
  136. self._thread = threading.Thread(target=self._run_outer)
  137. self._thread.start()
  138. def _cancel(self):
  139. pass # override to provide cancellation functionality
  140. def run(self):
  141. pass # override for the main thread behaviour
  142. def _run_outer(self):
  143. try:
  144. self.run()
  145. finally:
  146. self._thread = None
  147. def stop(self):
  148. if self._thread is not None:
  149. old_thread = self._thread
  150. self._thread = None
  151. self._cancel()
  152. old_thread.join()
  153. class ConsoleReader(StoppableThread):
  154. """ Read input keys from the console and push them to the queue,
  155. until stopped.
  156. """
  157. def __init__(self, console, event_queue, cmd_queue, parser, test_mode):
  158. super(ConsoleReader, self).__init__()
  159. self.console = console
  160. self.event_queue = event_queue
  161. self.cmd_queue = cmd_queue
  162. self.parser = parser
  163. self.test_mode = test_mode
  164. def run(self):
  165. self.console.setup()
  166. try:
  167. while self.alive:
  168. try:
  169. if os.name == 'nt':
  170. # Windows kludge: because the console.cancel() method doesn't
  171. # seem to work to unblock getkey() on the Windows implementation.
  172. #
  173. # So we only call getkey() if we know there's a key waiting for us.
  174. import msvcrt
  175. while not msvcrt.kbhit() and self.alive:
  176. time.sleep(0.1)
  177. if not self.alive:
  178. break
  179. elif self.test_mode:
  180. # In testing mode the stdin is connected to PTY but is not used for input anything. For PTY
  181. # the canceling by fcntl.ioctl isn't working and would hang in self.console.getkey().
  182. # Therefore, we avoid calling it.
  183. while self.alive:
  184. time.sleep(0.1)
  185. break
  186. c = self.console.getkey()
  187. except KeyboardInterrupt:
  188. c = '\x03'
  189. if c is not None:
  190. ret = self.parser.parse(c)
  191. if ret is not None:
  192. (tag, cmd) = ret
  193. # stop command should be executed last
  194. if tag == TAG_CMD and cmd != CMD_STOP:
  195. self.cmd_queue.put(ret)
  196. else:
  197. self.event_queue.put(ret)
  198. finally:
  199. self.console.cleanup()
  200. def _cancel(self):
  201. if os.name == 'posix' and not self.test_mode:
  202. # this is the way cancel() is implemented in pyserial 3.3 or newer,
  203. # older pyserial (3.1+) has cancellation implemented via 'select',
  204. # which does not work when console sends an escape sequence response
  205. #
  206. # even older pyserial (<3.1) does not have this method
  207. #
  208. # on Windows there is a different (also hacky) fix, applied above.
  209. #
  210. # note that TIOCSTI is not implemented in WSL / bash-on-Windows.
  211. # TODO: introduce some workaround to make it work there.
  212. #
  213. # Note: This would throw exception in testing mode when the stdin is connected to PTY.
  214. import fcntl
  215. import termios
  216. fcntl.ioctl(self.console.fd, termios.TIOCSTI, b'\0')
  217. class ConsoleParser(object):
  218. def __init__(self, eol="CRLF"):
  219. self.translate_eol = {
  220. "CRLF": lambda c: c.replace("\n", "\r\n"),
  221. "CR": lambda c: c.replace("\n", "\r"),
  222. "LF": lambda c: c.replace("\r", "\n"),
  223. }[eol]
  224. self.menu_key = CTRL_T
  225. self.exit_key = CTRL_RBRACKET
  226. self._pressed_menu_key = False
  227. def parse(self, key):
  228. ret = None
  229. if self._pressed_menu_key:
  230. ret = self._handle_menu_key(key)
  231. elif key == self.menu_key:
  232. self._pressed_menu_key = True
  233. elif key == self.exit_key:
  234. ret = (TAG_CMD, CMD_STOP)
  235. else:
  236. key = self.translate_eol(key)
  237. ret = (TAG_KEY, key)
  238. return ret
  239. def _handle_menu_key(self, c):
  240. ret = None
  241. if c == self.exit_key or c == self.menu_key: # send verbatim
  242. ret = (TAG_KEY, c)
  243. elif c in [CTRL_H, 'h', 'H', '?']:
  244. red_print(self.get_help_text())
  245. elif c == CTRL_R: # Reset device via RTS
  246. ret = (TAG_CMD, CMD_RESET)
  247. elif c == CTRL_F: # Recompile & upload
  248. ret = (TAG_CMD, CMD_MAKE)
  249. elif c in [CTRL_A, 'a', 'A']: # Recompile & upload app only
  250. # "CTRL-A" cannot be captured with the default settings of the Windows command line, therefore, "A" can be used
  251. # instead
  252. ret = (TAG_CMD, CMD_APP_FLASH)
  253. elif c == CTRL_Y: # Toggle output display
  254. ret = (TAG_CMD, CMD_OUTPUT_TOGGLE)
  255. elif c == CTRL_L: # Toggle saving output into file
  256. ret = (TAG_CMD, CMD_TOGGLE_LOGGING)
  257. elif c == CTRL_P:
  258. yellow_print("Pause app (enter bootloader mode), press Ctrl-T Ctrl-R to restart")
  259. # to fast trigger pause without press menu key
  260. ret = (TAG_CMD, CMD_ENTER_BOOT)
  261. elif c in [CTRL_X, 'x', 'X']: # Exiting from within the menu
  262. ret = (TAG_CMD, CMD_STOP)
  263. else:
  264. red_print('--- unknown menu character {} --'.format(key_description(c)))
  265. self._pressed_menu_key = False
  266. return ret
  267. def get_help_text(self):
  268. text = """\
  269. --- idf_monitor ({version}) - ESP-IDF monitor tool
  270. --- based on miniterm from pySerial
  271. ---
  272. --- {exit:8} Exit program
  273. --- {menu:8} Menu escape key, followed by:
  274. --- Menu keys:
  275. --- {menu:14} Send the menu character itself to remote
  276. --- {exit:14} Send the exit character itself to remote
  277. --- {reset:14} Reset target board via RTS line
  278. --- {makecmd:14} Build & flash project
  279. --- {appmake:14} Build & flash app only
  280. --- {output:14} Toggle output display
  281. --- {log:14} Toggle saving output into file
  282. --- {pause:14} Reset target into bootloader to pause app via RTS line
  283. --- {menuexit:14} Exit program
  284. """.format(version=__version__,
  285. exit=key_description(self.exit_key),
  286. menu=key_description(self.menu_key),
  287. reset=key_description(CTRL_R),
  288. makecmd=key_description(CTRL_F),
  289. appmake=key_description(CTRL_A) + ' (or A)',
  290. output=key_description(CTRL_Y),
  291. log=key_description(CTRL_L),
  292. pause=key_description(CTRL_P),
  293. menuexit=key_description(CTRL_X) + ' (or X)')
  294. return textwrap.dedent(text)
  295. def get_next_action_text(self):
  296. text = """\
  297. --- Press {} to exit monitor.
  298. --- Press {} to build & flash project.
  299. --- Press {} to build & flash app.
  300. --- Press any other key to resume monitor (resets target).
  301. """.format(key_description(self.exit_key),
  302. key_description(CTRL_F),
  303. key_description(CTRL_A))
  304. return textwrap.dedent(text)
  305. def parse_next_action_key(self, c):
  306. ret = None
  307. if c == self.exit_key:
  308. ret = (TAG_CMD, CMD_STOP)
  309. elif c == CTRL_F: # Recompile & upload
  310. ret = (TAG_CMD, CMD_MAKE)
  311. elif c in [CTRL_A, 'a', 'A']: # Recompile & upload app only
  312. # "CTRL-A" cannot be captured with the default settings of the Windows command line, therefore, "A" can be used
  313. # instead
  314. ret = (TAG_CMD, CMD_APP_FLASH)
  315. return ret
  316. class SerialReader(StoppableThread):
  317. """ Read serial data from the serial port and push to the
  318. event queue, until stopped.
  319. """
  320. def __init__(self, serial, event_queue):
  321. super(SerialReader, self).__init__()
  322. self.baud = serial.baudrate
  323. self.serial = serial
  324. self.event_queue = event_queue
  325. if not hasattr(self.serial, 'cancel_read'):
  326. # enable timeout for checking alive flag,
  327. # if cancel_read not available
  328. self.serial.timeout = 0.25
  329. def run(self):
  330. if not self.serial.is_open:
  331. self.serial.baudrate = self.baud
  332. self.serial.rts = True # Force an RTS reset on open
  333. self.serial.open()
  334. self.serial.rts = False
  335. self.serial.dtr = self.serial.dtr # usbser.sys workaround
  336. try:
  337. while self.alive:
  338. data = self.serial.read(self.serial.in_waiting or 1)
  339. if len(data):
  340. self.event_queue.put((TAG_SERIAL, data), False)
  341. finally:
  342. self.serial.close()
  343. def _cancel(self):
  344. if hasattr(self.serial, 'cancel_read'):
  345. try:
  346. self.serial.cancel_read()
  347. except Exception:
  348. pass
  349. class LineMatcher(object):
  350. """
  351. Assembles a dictionary of filtering rules based on the --print_filter
  352. argument of idf_monitor. Then later it is used to match lines and
  353. determine whether they should be shown on screen or not.
  354. """
  355. LEVEL_N = 0
  356. LEVEL_E = 1
  357. LEVEL_W = 2
  358. LEVEL_I = 3
  359. LEVEL_D = 4
  360. LEVEL_V = 5
  361. level = {'N': LEVEL_N, 'E': LEVEL_E, 'W': LEVEL_W, 'I': LEVEL_I, 'D': LEVEL_D,
  362. 'V': LEVEL_V, '*': LEVEL_V, '': LEVEL_V}
  363. def __init__(self, print_filter):
  364. self._dict = dict()
  365. self._re = re.compile(r'^(?:\033\[[01];?[0-9]+m?)?([EWIDV]) \([0-9]+\) ([^:]+): ')
  366. items = print_filter.split()
  367. if len(items) == 0:
  368. self._dict["*"] = self.LEVEL_V # default is to print everything
  369. for f in items:
  370. s = f.split(r':')
  371. if len(s) == 1:
  372. # specifying no warning level defaults to verbose level
  373. lev = self.LEVEL_V
  374. elif len(s) == 2:
  375. if len(s[0]) == 0:
  376. raise ValueError('No tag specified in filter ' + f)
  377. try:
  378. lev = self.level[s[1].upper()]
  379. except KeyError:
  380. raise ValueError('Unknown warning level in filter ' + f)
  381. else:
  382. raise ValueError('Missing ":" in filter ' + f)
  383. self._dict[s[0]] = lev
  384. def match(self, line):
  385. try:
  386. m = self._re.search(line)
  387. if m:
  388. lev = self.level[m.group(1)]
  389. if m.group(2) in self._dict:
  390. return self._dict[m.group(2)] >= lev
  391. return self._dict.get("*", self.LEVEL_N) >= lev
  392. except (KeyError, IndexError):
  393. # Regular line written with something else than ESP_LOG*
  394. # or an empty line.
  395. pass
  396. # We need something more than "*.N" for printing.
  397. return self._dict.get("*", self.LEVEL_N) > self.LEVEL_N
  398. class SerialStopException(Exception):
  399. """
  400. This exception is used for stopping the IDF monitor in testing mode.
  401. """
  402. pass
  403. class Monitor(object):
  404. """
  405. Monitor application main class.
  406. This was originally derived from miniterm.Miniterm, but it turned out to be easier to write from scratch for this
  407. purpose.
  408. Main difference is that all event processing happens in the main thread, not the worker threads.
  409. """
  410. def __init__(self, serial_instance, elf_file, print_filter, make="make", encrypted=False,
  411. toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, eol="CRLF",
  412. decode_coredumps=COREDUMP_DECODE_INFO,
  413. websocket_client=None):
  414. super(Monitor, self).__init__()
  415. self.event_queue = queue.Queue()
  416. self.cmd_queue = queue.Queue()
  417. self.console = miniterm.Console()
  418. if os.name == 'nt':
  419. sys.stderr = ANSIColorConverter(sys.stderr, decode_output=True)
  420. self.console.output = ANSIColorConverter(self.console.output)
  421. self.console.byte_output = ANSIColorConverter(self.console.byte_output)
  422. if StrictVersion(serial.VERSION) < StrictVersion('3.3.0'):
  423. # Use Console.getkey implementation from 3.3.0 (to be in sync with the ConsoleReader._cancel patch above)
  424. def getkey_patched(self):
  425. c = self.enc_stdin.read(1)
  426. if c == chr(0x7f):
  427. c = chr(8) # map the BS key (which yields DEL) to backspace
  428. return c
  429. self.console.getkey = types.MethodType(getkey_patched, self.console)
  430. socket_mode = serial_instance.port.startswith("socket://") # testing hook - data from serial can make exit the monitor
  431. self.serial = serial_instance
  432. self.console_parser = ConsoleParser(eol)
  433. self.console_reader = ConsoleReader(self.console, self.event_queue, self.cmd_queue, self.console_parser, socket_mode)
  434. self.serial_reader = SerialReader(self.serial, self.event_queue)
  435. self.elf_file = elf_file
  436. if not os.path.exists(make):
  437. self.make = shlex.split(make) # allow for possibility the "make" arg is a list of arguments (for idf.py)
  438. else:
  439. self.make = make
  440. self.encrypted = encrypted
  441. self.toolchain_prefix = toolchain_prefix
  442. self.websocket_client = websocket_client
  443. # internal state
  444. self._last_line_part = b""
  445. self._gdb_buffer = b""
  446. self._pc_address_buffer = b""
  447. self._line_matcher = LineMatcher(print_filter)
  448. self._invoke_processing_last_line_timer = None
  449. self._force_line_print = False
  450. self._output_enabled = True
  451. self._serial_check_exit = socket_mode
  452. self._log_file = None
  453. self._decode_coredumps = decode_coredumps
  454. self._reading_coredump = COREDUMP_IDLE
  455. self._coredump_buffer = b""
  456. def invoke_processing_last_line(self):
  457. self.event_queue.put((TAG_SERIAL_FLUSH, b''), False)
  458. def main_loop(self):
  459. self.console_reader.start()
  460. self.serial_reader.start()
  461. try:
  462. while self.console_reader.alive and self.serial_reader.alive:
  463. try:
  464. item = self.cmd_queue.get_nowait()
  465. except queue.Empty:
  466. try:
  467. item = self.event_queue.get(True, 0.03)
  468. except queue.Empty:
  469. continue
  470. (event_tag, data) = item
  471. if event_tag == TAG_CMD:
  472. self.handle_commands(data)
  473. elif event_tag == TAG_KEY:
  474. try:
  475. self.serial.write(codecs.encode(data))
  476. except serial.SerialException:
  477. pass # this shouldn't happen, but sometimes port has closed in serial thread
  478. except UnicodeEncodeError:
  479. pass # this can happen if a non-ascii character was passed, ignoring
  480. elif event_tag == TAG_SERIAL:
  481. self.handle_serial_input(data)
  482. if self._invoke_processing_last_line_timer is not None:
  483. self._invoke_processing_last_line_timer.cancel()
  484. self._invoke_processing_last_line_timer = threading.Timer(0.1, self.invoke_processing_last_line)
  485. self._invoke_processing_last_line_timer.start()
  486. # If no futher data is received in the next short period
  487. # of time then the _invoke_processing_last_line_timer
  488. # generates an event which will result in the finishing of
  489. # the last line. This is fix for handling lines sent
  490. # without EOL.
  491. elif event_tag == TAG_SERIAL_FLUSH:
  492. self.handle_serial_input(data, finalize_line=True)
  493. else:
  494. raise RuntimeError("Bad event data %r" % ((event_tag,data),))
  495. except SerialStopException:
  496. sys.stderr.write(ANSI_NORMAL + "Stopping condition has been received\n")
  497. finally:
  498. try:
  499. self.console_reader.stop()
  500. self.serial_reader.stop()
  501. self.stop_logging()
  502. # Cancelling _invoke_processing_last_line_timer is not
  503. # important here because receiving empty data doesn't matter.
  504. self._invoke_processing_last_line_timer = None
  505. except Exception:
  506. pass
  507. sys.stderr.write(ANSI_NORMAL + "\n")
  508. def handle_serial_input(self, data, finalize_line=False):
  509. sp = data.split(b'\n')
  510. if self._last_line_part != b"":
  511. # add unprocessed part from previous "data" to the first line
  512. sp[0] = self._last_line_part + sp[0]
  513. self._last_line_part = b""
  514. if sp[-1] != b"":
  515. # last part is not a full line
  516. self._last_line_part = sp.pop()
  517. for line in sp:
  518. if line != b"":
  519. if self._serial_check_exit and line == self.console_parser.exit_key.encode('latin-1'):
  520. raise SerialStopException()
  521. self.check_coredump_trigger_before_print(line)
  522. if self._force_line_print or self._line_matcher.match(line.decode(errors="ignore")):
  523. self._print(line + b'\n')
  524. self.handle_possible_pc_address_in_line(line)
  525. self.check_coredump_trigger_after_print(line)
  526. self.check_gdbstub_trigger(line)
  527. self._force_line_print = False
  528. # Now we have the last part (incomplete line) in _last_line_part. By
  529. # default we don't touch it and just wait for the arrival of the rest
  530. # of the line. But after some time when we didn't received it we need
  531. # to make a decision.
  532. if self._last_line_part != b"":
  533. if self._force_line_print or (finalize_line and self._line_matcher.match(self._last_line_part.decode(errors="ignore"))):
  534. self._force_line_print = True
  535. self._print(self._last_line_part)
  536. self.handle_possible_pc_address_in_line(self._last_line_part)
  537. self.check_gdbstub_trigger(self._last_line_part)
  538. # It is possible that the incomplete line cuts in half the PC
  539. # address. A small buffer is kept and will be used the next time
  540. # handle_possible_pc_address_in_line is invoked to avoid this problem.
  541. # MATCH_PCADDR matches 10 character long addresses. Therefore, we
  542. # keep the last 9 characters.
  543. self._pc_address_buffer = self._last_line_part[-9:]
  544. # GDB sequence can be cut in half also. GDB sequence is 7
  545. # characters long, therefore, we save the last 6 characters.
  546. self._gdb_buffer = self._last_line_part[-6:]
  547. self._last_line_part = b""
  548. # else: keeping _last_line_part and it will be processed the next time
  549. # handle_serial_input is invoked
  550. def handle_possible_pc_address_in_line(self, line):
  551. line = self._pc_address_buffer + line
  552. self._pc_address_buffer = b""
  553. for m in re.finditer(MATCH_PCADDR, line.decode(errors="ignore")):
  554. self.lookup_pc_address(m.group())
  555. def __enter__(self):
  556. """ Use 'with self' to temporarily disable monitoring behaviour """
  557. self.serial_reader.stop()
  558. self.console_reader.stop()
  559. def __exit__(self, *args, **kwargs):
  560. """ Use 'with self' to temporarily disable monitoring behaviour """
  561. self.console_reader.start()
  562. self.serial_reader.start()
  563. def prompt_next_action(self, reason):
  564. self.console.setup() # set up console to trap input characters
  565. try:
  566. red_print("--- {}".format(reason))
  567. red_print(self.console_parser.get_next_action_text())
  568. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  569. while k == CTRL_T:
  570. k = self.console.getkey()
  571. finally:
  572. self.console.cleanup()
  573. ret = self.console_parser.parse_next_action_key(k)
  574. if ret is not None:
  575. cmd = ret[1]
  576. if cmd == CMD_STOP:
  577. # the stop command should be handled last
  578. self.event_queue.put(ret)
  579. else:
  580. self.cmd_queue.put(ret)
  581. def run_make(self, target):
  582. with self:
  583. if isinstance(self.make, list):
  584. popen_args = self.make + [target]
  585. else:
  586. popen_args = [self.make, target]
  587. yellow_print("Running %s..." % " ".join(popen_args))
  588. p = subprocess.Popen(popen_args, env=os.environ)
  589. try:
  590. p.wait()
  591. except KeyboardInterrupt:
  592. p.wait()
  593. if p.returncode != 0:
  594. self.prompt_next_action("Build failed")
  595. else:
  596. self.output_enable(True)
  597. def lookup_pc_address(self, pc_addr):
  598. cmd = ["%saddr2line" % self.toolchain_prefix,
  599. "-pfiaC", "-e", self.elf_file, pc_addr]
  600. try:
  601. translation = subprocess.check_output(cmd, cwd=".")
  602. if b"?? ??:0" not in translation:
  603. self._print(translation.decode(), console_printer=yellow_print)
  604. except OSError as e:
  605. red_print("%s: %s" % (" ".join(cmd), e))
  606. def check_gdbstub_trigger(self, line):
  607. line = self._gdb_buffer + line
  608. self._gdb_buffer = b""
  609. m = re.search(b"\\$(T..)#(..)", line) # look for a gdb "reason" for a break
  610. if m is not None:
  611. try:
  612. chsum = sum(ord(bytes([p])) for p in m.group(1)) & 0xFF
  613. calc_chsum = int(m.group(2), 16)
  614. except ValueError:
  615. return # payload wasn't valid hex digits
  616. if chsum == calc_chsum:
  617. if self.websocket_client:
  618. yellow_print('Communicating through WebSocket')
  619. self.websocket_client.send({'event': 'gdb_stub',
  620. 'port': self.serial.port,
  621. 'prog': self.elf_file})
  622. yellow_print('Waiting for debug finished event')
  623. self.websocket_client.wait([('event', 'debug_finished')])
  624. yellow_print('Communications through WebSocket is finished')
  625. else:
  626. self.run_gdb()
  627. else:
  628. red_print("Malformed gdb message... calculated checksum %02x received %02x" % (chsum, calc_chsum))
  629. def check_coredump_trigger_before_print(self, line):
  630. if self._decode_coredumps == COREDUMP_DECODE_DISABLE:
  631. return
  632. if COREDUMP_UART_PROMPT in line:
  633. yellow_print("Initiating core dump!")
  634. self.event_queue.put((TAG_KEY, '\n'))
  635. return
  636. if COREDUMP_UART_START in line:
  637. yellow_print("Core dump started (further output muted)")
  638. self._reading_coredump = COREDUMP_READING
  639. self._coredump_buffer = b""
  640. self._output_enabled = False
  641. return
  642. if COREDUMP_UART_END in line:
  643. self._reading_coredump = COREDUMP_DONE
  644. yellow_print("\nCore dump finished!")
  645. self.process_coredump()
  646. return
  647. if self._reading_coredump == COREDUMP_READING:
  648. kb = 1024
  649. buffer_len_kb = len(self._coredump_buffer) // kb
  650. self._coredump_buffer += line.replace(b'\r', b'') + b'\n'
  651. new_buffer_len_kb = len(self._coredump_buffer) // kb
  652. if new_buffer_len_kb > buffer_len_kb:
  653. yellow_print("Received %3d kB..." % (new_buffer_len_kb), newline='\r')
  654. def check_coredump_trigger_after_print(self, line):
  655. if self._decode_coredumps == COREDUMP_DECODE_DISABLE:
  656. return
  657. # Re-enable output after the last line of core dump has been consumed
  658. if not self._output_enabled and self._reading_coredump == COREDUMP_DONE:
  659. self._reading_coredump = COREDUMP_IDLE
  660. self._output_enabled = True
  661. self._coredump_buffer = b""
  662. def process_coredump(self):
  663. if self._decode_coredumps != COREDUMP_DECODE_INFO:
  664. raise NotImplementedError("process_coredump: %s not implemented" % self._decode_coredumps)
  665. coredump_script = os.path.join(os.path.dirname(__file__), "..", "components", "espcoredump", "espcoredump.py")
  666. coredump_file = None
  667. try:
  668. # On Windows, the temporary file can't be read unless it is closed.
  669. # Set delete=False and delete the file manually later.
  670. with tempfile.NamedTemporaryFile(mode="wb", delete=False) as coredump_file:
  671. coredump_file.write(self._coredump_buffer)
  672. coredump_file.flush()
  673. if self.websocket_client:
  674. self._output_enabled = True
  675. yellow_print('Communicating through WebSocket')
  676. self.websocket_client.send({'event': 'coredump',
  677. 'file': coredump_file.name,
  678. 'prog': self.elf_file})
  679. yellow_print('Waiting for debug finished event')
  680. self.websocket_client.wait([('event', 'debug_finished')])
  681. yellow_print('Communications through WebSocket is finished')
  682. else:
  683. cmd = [sys.executable,
  684. coredump_script,
  685. "info_corefile",
  686. "--core", coredump_file.name,
  687. "--core-format", "b64",
  688. self.elf_file
  689. ]
  690. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  691. self._output_enabled = True
  692. self._print(output)
  693. self._output_enabled = False # Will be reenabled in check_coredump_trigger_after_print
  694. except subprocess.CalledProcessError as e:
  695. yellow_print("Failed to run espcoredump script: {}\n{}\n\n".format(e, e.output))
  696. self._output_enabled = True
  697. self._print(COREDUMP_UART_START + b'\n')
  698. self._print(self._coredump_buffer)
  699. # end line will be printed in handle_serial_input
  700. finally:
  701. if coredump_file is not None:
  702. try:
  703. os.unlink(coredump_file.name)
  704. except OSError as e:
  705. yellow_print("Couldn't remote temporary core dump file ({})".format(e))
  706. def run_gdb(self):
  707. with self: # disable console control
  708. sys.stderr.write(ANSI_NORMAL)
  709. try:
  710. cmd = ["%sgdb" % self.toolchain_prefix,
  711. "-ex", "set serial baud %d" % self.serial.baudrate,
  712. "-ex", "target remote %s" % self.serial.port,
  713. "-ex", "interrupt", # monitor has already parsed the first 'reason' command, need a second
  714. self.elf_file]
  715. process = subprocess.Popen(cmd, cwd=".")
  716. process.wait()
  717. except OSError as e:
  718. red_print("%s: %s" % (" ".join(cmd), e))
  719. except KeyboardInterrupt:
  720. pass # happens on Windows, maybe other OSes
  721. finally:
  722. try:
  723. # on Linux, maybe other OSes, gdb sometimes seems to be alive even after wait() returns...
  724. process.terminate()
  725. except Exception:
  726. pass
  727. try:
  728. # also on Linux, maybe other OSes, gdb sometimes exits uncleanly and breaks the tty mode
  729. subprocess.call(["stty", "sane"])
  730. except Exception:
  731. pass # don't care if there's no stty, we tried...
  732. self.prompt_next_action("gdb exited")
  733. def output_enable(self, enable):
  734. self._output_enabled = enable
  735. def output_toggle(self):
  736. self._output_enabled = not self._output_enabled
  737. yellow_print("\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.".format(self._output_enabled))
  738. def toggle_logging(self):
  739. if self._log_file:
  740. self.stop_logging()
  741. else:
  742. self.start_logging()
  743. def start_logging(self):
  744. if not self._log_file:
  745. try:
  746. name = "log.{}.{}.txt".format(os.path.splitext(os.path.basename(self.elf_file))[0],
  747. datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
  748. self._log_file = open(name, "wb+")
  749. yellow_print("\nLogging is enabled into file {}".format(name))
  750. except Exception as e:
  751. red_print("\nLog file {} cannot be created: {}".format(name, e))
  752. def stop_logging(self):
  753. if self._log_file:
  754. try:
  755. name = self._log_file.name
  756. self._log_file.close()
  757. yellow_print("\nLogging is disabled and file {} has been closed".format(name))
  758. except Exception as e:
  759. red_print("\nLog file cannot be closed: {}".format(e))
  760. finally:
  761. self._log_file = None
  762. def _print(self, string, console_printer=None):
  763. if console_printer is None:
  764. console_printer = self.console.write_bytes
  765. if self._output_enabled:
  766. console_printer(string)
  767. if self._log_file:
  768. try:
  769. if isinstance(string, type(u'')):
  770. string = string.encode()
  771. self._log_file.write(string)
  772. except Exception as e:
  773. red_print("\nCannot write to file: {}".format(e))
  774. # don't fill-up the screen with the previous errors (probably consequent prints would fail also)
  775. self.stop_logging()
  776. def handle_commands(self, cmd):
  777. if cmd == CMD_STOP:
  778. self.console_reader.stop()
  779. self.serial_reader.stop()
  780. elif cmd == CMD_RESET:
  781. self.serial.setRTS(True)
  782. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  783. time.sleep(0.2)
  784. self.serial.setRTS(False)
  785. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  786. self.output_enable(True)
  787. elif cmd == CMD_MAKE:
  788. self.run_make("encrypted-flash" if self.encrypted else "flash")
  789. elif cmd == CMD_APP_FLASH:
  790. self.run_make("encrypted-app-flash" if self.encrypted else "app-flash")
  791. elif cmd == CMD_OUTPUT_TOGGLE:
  792. self.output_toggle()
  793. elif cmd == CMD_TOGGLE_LOGGING:
  794. self.toggle_logging()
  795. elif cmd == CMD_ENTER_BOOT:
  796. self.serial.setDTR(False) # IO0=HIGH
  797. self.serial.setRTS(True) # EN=LOW, chip in reset
  798. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  799. time.sleep(1.3) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  800. self.serial.setDTR(True) # IO0=LOW
  801. self.serial.setRTS(False) # EN=HIGH, chip out of reset
  802. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  803. time.sleep(0.45) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  804. self.serial.setDTR(False) # IO0=HIGH, done
  805. else:
  806. raise RuntimeError("Bad command data %d" % (cmd))
  807. def main():
  808. def _get_default_serial_port():
  809. """
  810. Same logic for detecting serial port as esptool.py and idf.py: reverse sort by name and choose the first port.
  811. """
  812. try:
  813. ports = list(reversed(sorted(p.device for p in serial.tools.list_ports.comports())))
  814. return ports[0]
  815. except Exception:
  816. return '/dev/ttyUSB0'
  817. parser = argparse.ArgumentParser("idf_monitor - a serial output monitor for esp-idf")
  818. parser.add_argument(
  819. '--port', '-p',
  820. help='Serial port device',
  821. default=os.environ.get('ESPTOOL_PORT', _get_default_serial_port())
  822. )
  823. parser.add_argument(
  824. '--baud', '-b',
  825. help='Serial port baud rate',
  826. type=int,
  827. default=os.getenv('IDF_MONITOR_BAUD', os.getenv('MONITORBAUD', 115200)))
  828. parser.add_argument(
  829. '--make', '-m',
  830. help='Command to run make',
  831. type=str, default='make')
  832. parser.add_argument(
  833. '--encrypted',
  834. help='Use encrypted targets while running make',
  835. action='store_true')
  836. parser.add_argument(
  837. '--toolchain-prefix',
  838. help="Triplet prefix to add before cross-toolchain names",
  839. default=DEFAULT_TOOLCHAIN_PREFIX)
  840. parser.add_argument(
  841. "--eol",
  842. choices=['CR', 'LF', 'CRLF'],
  843. type=lambda c: c.upper(),
  844. help="End of line to use when sending to the serial port",
  845. default='CR')
  846. parser.add_argument(
  847. 'elf_file', help='ELF file of application',
  848. type=argparse.FileType('rb'))
  849. parser.add_argument(
  850. '--print_filter',
  851. help="Filtering string",
  852. default=DEFAULT_PRINT_FILTER)
  853. parser.add_argument(
  854. '--decode-coredumps',
  855. choices=[COREDUMP_DECODE_INFO, COREDUMP_DECODE_DISABLE],
  856. default=COREDUMP_DECODE_INFO,
  857. help="Handling of core dumps found in serial output"
  858. )
  859. parser.add_argument(
  860. '--ws',
  861. default=os.environ.get('ESP_IDF_MONITOR_WS', None),
  862. help="WebSocket URL for communicating with IDE tools for debugging purposes"
  863. )
  864. args = parser.parse_args()
  865. # GDB uses CreateFile to open COM port, which requires the COM name to be r'\\.\COMx' if the COM
  866. # number is larger than 10
  867. if os.name == 'nt' and args.port.startswith("COM"):
  868. args.port = args.port.replace('COM', r'\\.\COM')
  869. yellow_print("--- WARNING: GDB cannot open serial ports accessed as COMx")
  870. yellow_print("--- Using %s instead..." % args.port)
  871. elif args.port.startswith("/dev/tty."):
  872. args.port = args.port.replace("/dev/tty.", "/dev/cu.")
  873. yellow_print("--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.")
  874. yellow_print("--- Using %s instead..." % args.port)
  875. serial_instance = serial.serial_for_url(args.port, args.baud,
  876. do_not_open=True)
  877. serial_instance.dtr = False
  878. serial_instance.rts = False
  879. args.elf_file.close() # don't need this as a file
  880. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  881. # parent make is only running 1 job (monitor), so we can re-spawn
  882. # all of the child makes we need (the -j argument remains part of
  883. # MAKEFLAGS)
  884. try:
  885. makeflags = os.environ["MAKEFLAGS"]
  886. makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
  887. os.environ["MAKEFLAGS"] = makeflags
  888. except KeyError:
  889. pass # not running a make jobserver
  890. # Pass the actual used port to callee of idf_monitor (e.g. make) through `ESPPORT` environment
  891. # variable
  892. # To make sure the key as well as the value are str type, by the requirements of subprocess
  893. espport_key = str("ESPPORT")
  894. espport_val = str(args.port)
  895. os.environ.update({espport_key: espport_val})
  896. ws = WebSocketClient(args.ws) if args.ws else None
  897. try:
  898. monitor = Monitor(serial_instance, args.elf_file.name, args.print_filter, args.make, args.encrypted,
  899. args.toolchain_prefix, args.eol,
  900. args.decode_coredumps,
  901. ws)
  902. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  903. p=serial_instance))
  904. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  905. key_description(monitor.console_parser.exit_key),
  906. key_description(monitor.console_parser.menu_key),
  907. key_description(monitor.console_parser.menu_key),
  908. key_description(CTRL_H)))
  909. if args.print_filter != DEFAULT_PRINT_FILTER:
  910. yellow_print('--- Print filter: {} ---'.format(args.print_filter))
  911. monitor.main_loop()
  912. finally:
  913. if ws:
  914. ws.close()
  915. class WebSocketClient(object):
  916. """
  917. WebSocket client used to advertise debug events to WebSocket server by sending and receiving JSON-serialized
  918. dictionaries.
  919. Advertisement of debug event:
  920. {'event': 'gdb_stub', 'port': '/dev/ttyUSB1', 'prog': 'build/elf_file'} for GDB Stub, or
  921. {'event': 'coredump', 'file': '/tmp/xy', 'prog': 'build/elf_file'} for coredump,
  922. where 'port' is the port for the connected device, 'prog' is the full path to the ELF file and 'file' is the
  923. generated coredump file.
  924. Expected end of external debugging:
  925. {'event': 'debug_finished'}
  926. """
  927. RETRIES = 3
  928. CONNECTION_RETRY_DELAY = 1
  929. def __init__(self, url):
  930. self.url = url
  931. self._connect()
  932. def _connect(self):
  933. """
  934. Connect to WebSocket server at url
  935. """
  936. self.close()
  937. for _ in range(self.RETRIES):
  938. try:
  939. self.ws = websocket.create_connection(self.url)
  940. break # success
  941. except NameError:
  942. raise RuntimeError('Please install the websocket_client package for IDE integration!')
  943. except Exception as e:
  944. red_print('WebSocket connection error: {}'.format(e))
  945. time.sleep(self.CONNECTION_RETRY_DELAY)
  946. else:
  947. raise RuntimeError('Cannot connect to WebSocket server')
  948. def close(self):
  949. try:
  950. self.ws.close()
  951. except AttributeError:
  952. # Not yet connected
  953. pass
  954. except Exception as e:
  955. red_print('WebSocket close error: {}'.format(e))
  956. def send(self, payload_dict):
  957. """
  958. Serialize payload_dict in JSON format and send it to the server
  959. """
  960. for _ in range(self.RETRIES):
  961. try:
  962. self.ws.send(json.dumps(payload_dict))
  963. yellow_print('WebSocket sent: {}'.format(payload_dict))
  964. break
  965. except Exception as e:
  966. red_print('WebSocket send error: {}'.format(e))
  967. self._connect()
  968. else:
  969. raise RuntimeError('Cannot send to WebSocket server')
  970. def wait(self, expect_iterable):
  971. """
  972. Wait until a dictionary in JSON format is received from the server with all (key, value) tuples from
  973. expect_iterable.
  974. """
  975. for _ in range(self.RETRIES):
  976. try:
  977. r = self.ws.recv()
  978. except Exception as e:
  979. red_print('WebSocket receive error: {}'.format(e))
  980. self._connect()
  981. continue
  982. obj = json.loads(r)
  983. if all([k in obj and obj[k] == v for k, v in expect_iterable]):
  984. yellow_print('WebSocket received: {}'.format(obj))
  985. break
  986. red_print('WebSocket expected: {}, received: {}'.format(dict(expect_iterable), obj))
  987. else:
  988. raise RuntimeError('Cannot receive from WebSocket server')
  989. if os.name == 'nt':
  990. # Windows console stuff
  991. STD_OUTPUT_HANDLE = -11
  992. STD_ERROR_HANDLE = -12
  993. # wincon.h values
  994. FOREGROUND_INTENSITY = 8
  995. FOREGROUND_GREY = 7
  996. # matches the ANSI color change sequences that IDF sends
  997. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  998. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  999. ANSI_TO_WINDOWS_COLOR = [0, 4, 2, 6, 1, 5, 3, 7]
  1000. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  1001. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  1002. class ANSIColorConverter(object):
  1003. """Class to wrap a file-like output stream, intercept ANSI color codes,
  1004. and convert them into calls to Windows SetConsoleTextAttribute.
  1005. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  1006. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  1007. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  1008. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  1009. """
  1010. def __init__(self, output=None, decode_output=False):
  1011. self.output = output
  1012. self.decode_output = decode_output
  1013. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  1014. self.matched = b''
  1015. def _output_write(self, data):
  1016. try:
  1017. if self.decode_output:
  1018. self.output.write(data.decode())
  1019. else:
  1020. self.output.write(data)
  1021. except (IOError, OSError):
  1022. # Windows 10 bug since the Fall Creators Update, sometimes writing to console randomly throws
  1023. # an exception (however, the character is still written to the screen)
  1024. # Ref https://github.com/espressif/esp-idf/issues/1163
  1025. #
  1026. # Also possible for Windows to throw an OSError error if the data is invalid for the console
  1027. # (garbage bytes, etc)
  1028. pass
  1029. def write(self, data):
  1030. if isinstance(data, bytes):
  1031. data = bytearray(data)
  1032. else:
  1033. data = bytearray(data, 'utf-8')
  1034. for b in data:
  1035. b = bytes([b])
  1036. length = len(self.matched)
  1037. if b == b'\033': # ESC
  1038. self.matched = b
  1039. elif (length == 1 and b == b'[') or (1 < length < 7):
  1040. self.matched += b
  1041. if self.matched == ANSI_NORMAL.encode('latin-1'): # reset console
  1042. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  1043. self.flush()
  1044. SetConsoleTextAttribute(self.handle, FOREGROUND_GREY)
  1045. self.matched = b''
  1046. elif len(self.matched) == 7: # could be an ANSI sequence
  1047. m = re.match(RE_ANSI_COLOR, self.matched)
  1048. if m is not None:
  1049. color = ANSI_TO_WINDOWS_COLOR[int(m.group(2))]
  1050. if m.group(1) == b'1':
  1051. color |= FOREGROUND_INTENSITY
  1052. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  1053. self.flush()
  1054. SetConsoleTextAttribute(self.handle, color)
  1055. else:
  1056. self._output_write(self.matched) # not an ANSI color code, display verbatim
  1057. self.matched = b''
  1058. else:
  1059. self._output_write(b)
  1060. self.matched = b''
  1061. def flush(self):
  1062. try:
  1063. self.output.flush()
  1064. except OSError:
  1065. # Account for Windows Console refusing to accept garbage bytes (serial noise, etc)
  1066. pass
  1067. if __name__ == "__main__":
  1068. main()