idf_monitor.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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. try:
  339. data = self.serial.read(self.serial.in_waiting or 1)
  340. except (serial.serialutil.SerialException, IOError) as e:
  341. data = b''
  342. # self.serial.open() was successful before, therefore, this is an issue related to
  343. # the disapperence of the device
  344. red_print(e)
  345. yellow_print('Waiting for the device to reconnect', newline='')
  346. self.serial.close()
  347. while self.alive: # so that exiting monitor works while waiting
  348. try:
  349. time.sleep(0.5)
  350. self.serial.open()
  351. break # device connected
  352. except serial.serialutil.SerialException:
  353. yellow_print('.', newline='')
  354. sys.stderr.flush()
  355. yellow_print('') # go to new line
  356. if len(data):
  357. self.event_queue.put((TAG_SERIAL, data), False)
  358. finally:
  359. self.serial.close()
  360. def _cancel(self):
  361. if hasattr(self.serial, 'cancel_read'):
  362. try:
  363. self.serial.cancel_read()
  364. except Exception:
  365. pass
  366. class LineMatcher(object):
  367. """
  368. Assembles a dictionary of filtering rules based on the --print_filter
  369. argument of idf_monitor. Then later it is used to match lines and
  370. determine whether they should be shown on screen or not.
  371. """
  372. LEVEL_N = 0
  373. LEVEL_E = 1
  374. LEVEL_W = 2
  375. LEVEL_I = 3
  376. LEVEL_D = 4
  377. LEVEL_V = 5
  378. level = {'N': LEVEL_N, 'E': LEVEL_E, 'W': LEVEL_W, 'I': LEVEL_I, 'D': LEVEL_D,
  379. 'V': LEVEL_V, '*': LEVEL_V, '': LEVEL_V}
  380. def __init__(self, print_filter):
  381. self._dict = dict()
  382. self._re = re.compile(r'^(?:\033\[[01];?[0-9]+m?)?([EWIDV]) \([0-9]+\) ([^:]+): ')
  383. items = print_filter.split()
  384. if len(items) == 0:
  385. self._dict["*"] = self.LEVEL_V # default is to print everything
  386. for f in items:
  387. s = f.split(r':')
  388. if len(s) == 1:
  389. # specifying no warning level defaults to verbose level
  390. lev = self.LEVEL_V
  391. elif len(s) == 2:
  392. if len(s[0]) == 0:
  393. raise ValueError('No tag specified in filter ' + f)
  394. try:
  395. lev = self.level[s[1].upper()]
  396. except KeyError:
  397. raise ValueError('Unknown warning level in filter ' + f)
  398. else:
  399. raise ValueError('Missing ":" in filter ' + f)
  400. self._dict[s[0]] = lev
  401. def match(self, line):
  402. try:
  403. m = self._re.search(line)
  404. if m:
  405. lev = self.level[m.group(1)]
  406. if m.group(2) in self._dict:
  407. return self._dict[m.group(2)] >= lev
  408. return self._dict.get("*", self.LEVEL_N) >= lev
  409. except (KeyError, IndexError):
  410. # Regular line written with something else than ESP_LOG*
  411. # or an empty line.
  412. pass
  413. # We need something more than "*.N" for printing.
  414. return self._dict.get("*", self.LEVEL_N) > self.LEVEL_N
  415. class SerialStopException(Exception):
  416. """
  417. This exception is used for stopping the IDF monitor in testing mode.
  418. """
  419. pass
  420. class Monitor(object):
  421. """
  422. Monitor application main class.
  423. This was originally derived from miniterm.Miniterm, but it turned out to be easier to write from scratch for this
  424. purpose.
  425. Main difference is that all event processing happens in the main thread, not the worker threads.
  426. """
  427. def __init__(self, serial_instance, elf_file, print_filter, make="make", encrypted=False,
  428. toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, eol="CRLF",
  429. decode_coredumps=COREDUMP_DECODE_INFO,
  430. websocket_client=None):
  431. super(Monitor, self).__init__()
  432. self.event_queue = queue.Queue()
  433. self.cmd_queue = queue.Queue()
  434. self.console = miniterm.Console()
  435. if os.name == 'nt':
  436. sys.stderr = ANSIColorConverter(sys.stderr, decode_output=True)
  437. self.console.output = ANSIColorConverter(self.console.output)
  438. self.console.byte_output = ANSIColorConverter(self.console.byte_output)
  439. if StrictVersion(serial.VERSION) < StrictVersion('3.3.0'):
  440. # Use Console.getkey implementation from 3.3.0 (to be in sync with the ConsoleReader._cancel patch above)
  441. def getkey_patched(self):
  442. c = self.enc_stdin.read(1)
  443. if c == chr(0x7f):
  444. c = chr(8) # map the BS key (which yields DEL) to backspace
  445. return c
  446. self.console.getkey = types.MethodType(getkey_patched, self.console)
  447. socket_mode = serial_instance.port.startswith("socket://") # testing hook - data from serial can make exit the monitor
  448. self.serial = serial_instance
  449. self.console_parser = ConsoleParser(eol)
  450. self.console_reader = ConsoleReader(self.console, self.event_queue, self.cmd_queue, self.console_parser, socket_mode)
  451. self.serial_reader = SerialReader(self.serial, self.event_queue)
  452. self.elf_file = elf_file
  453. if not os.path.exists(make):
  454. self.make = shlex.split(make) # allow for possibility the "make" arg is a list of arguments (for idf.py)
  455. else:
  456. self.make = make
  457. self.encrypted = encrypted
  458. self.toolchain_prefix = toolchain_prefix
  459. self.websocket_client = websocket_client
  460. # internal state
  461. self._last_line_part = b""
  462. self._gdb_buffer = b""
  463. self._pc_address_buffer = b""
  464. self._line_matcher = LineMatcher(print_filter)
  465. self._invoke_processing_last_line_timer = None
  466. self._force_line_print = False
  467. self._output_enabled = True
  468. self._serial_check_exit = socket_mode
  469. self._log_file = None
  470. self._decode_coredumps = decode_coredumps
  471. self._reading_coredump = COREDUMP_IDLE
  472. self._coredump_buffer = b""
  473. def invoke_processing_last_line(self):
  474. self.event_queue.put((TAG_SERIAL_FLUSH, b''), False)
  475. def main_loop(self):
  476. self.console_reader.start()
  477. self.serial_reader.start()
  478. try:
  479. while self.console_reader.alive and self.serial_reader.alive:
  480. try:
  481. item = self.cmd_queue.get_nowait()
  482. except queue.Empty:
  483. try:
  484. item = self.event_queue.get(True, 0.03)
  485. except queue.Empty:
  486. continue
  487. (event_tag, data) = item
  488. if event_tag == TAG_CMD:
  489. self.handle_commands(data)
  490. elif event_tag == TAG_KEY:
  491. try:
  492. self.serial.write(codecs.encode(data))
  493. except serial.SerialException:
  494. pass # this shouldn't happen, but sometimes port has closed in serial thread
  495. except UnicodeEncodeError:
  496. pass # this can happen if a non-ascii character was passed, ignoring
  497. elif event_tag == TAG_SERIAL:
  498. self.handle_serial_input(data)
  499. if self._invoke_processing_last_line_timer is not None:
  500. self._invoke_processing_last_line_timer.cancel()
  501. self._invoke_processing_last_line_timer = threading.Timer(0.1, self.invoke_processing_last_line)
  502. self._invoke_processing_last_line_timer.start()
  503. # If no futher data is received in the next short period
  504. # of time then the _invoke_processing_last_line_timer
  505. # generates an event which will result in the finishing of
  506. # the last line. This is fix for handling lines sent
  507. # without EOL.
  508. elif event_tag == TAG_SERIAL_FLUSH:
  509. self.handle_serial_input(data, finalize_line=True)
  510. else:
  511. raise RuntimeError("Bad event data %r" % ((event_tag,data),))
  512. except SerialStopException:
  513. sys.stderr.write(ANSI_NORMAL + "Stopping condition has been received\n")
  514. finally:
  515. try:
  516. self.console_reader.stop()
  517. self.serial_reader.stop()
  518. self.stop_logging()
  519. # Cancelling _invoke_processing_last_line_timer is not
  520. # important here because receiving empty data doesn't matter.
  521. self._invoke_processing_last_line_timer = None
  522. except Exception:
  523. pass
  524. sys.stderr.write(ANSI_NORMAL + "\n")
  525. def handle_serial_input(self, data, finalize_line=False):
  526. sp = data.split(b'\n')
  527. if self._last_line_part != b"":
  528. # add unprocessed part from previous "data" to the first line
  529. sp[0] = self._last_line_part + sp[0]
  530. self._last_line_part = b""
  531. if sp[-1] != b"":
  532. # last part is not a full line
  533. self._last_line_part = sp.pop()
  534. for line in sp:
  535. if line != b"":
  536. if self._serial_check_exit and line == self.console_parser.exit_key.encode('latin-1'):
  537. raise SerialStopException()
  538. self.check_coredump_trigger_before_print(line)
  539. if self._force_line_print or self._line_matcher.match(line.decode(errors="ignore")):
  540. self._print(line + b'\n')
  541. self.handle_possible_pc_address_in_line(line)
  542. self.check_coredump_trigger_after_print(line)
  543. self.check_gdbstub_trigger(line)
  544. self._force_line_print = False
  545. # Now we have the last part (incomplete line) in _last_line_part. By
  546. # default we don't touch it and just wait for the arrival of the rest
  547. # of the line. But after some time when we didn't received it we need
  548. # to make a decision.
  549. if self._last_line_part != b"":
  550. if self._force_line_print or (finalize_line and self._line_matcher.match(self._last_line_part.decode(errors="ignore"))):
  551. self._force_line_print = True
  552. self._print(self._last_line_part)
  553. self.handle_possible_pc_address_in_line(self._last_line_part)
  554. self.check_gdbstub_trigger(self._last_line_part)
  555. # It is possible that the incomplete line cuts in half the PC
  556. # address. A small buffer is kept and will be used the next time
  557. # handle_possible_pc_address_in_line is invoked to avoid this problem.
  558. # MATCH_PCADDR matches 10 character long addresses. Therefore, we
  559. # keep the last 9 characters.
  560. self._pc_address_buffer = self._last_line_part[-9:]
  561. # GDB sequence can be cut in half also. GDB sequence is 7
  562. # characters long, therefore, we save the last 6 characters.
  563. self._gdb_buffer = self._last_line_part[-6:]
  564. self._last_line_part = b""
  565. # else: keeping _last_line_part and it will be processed the next time
  566. # handle_serial_input is invoked
  567. def handle_possible_pc_address_in_line(self, line):
  568. line = self._pc_address_buffer + line
  569. self._pc_address_buffer = b""
  570. for m in re.finditer(MATCH_PCADDR, line.decode(errors="ignore")):
  571. self.lookup_pc_address(m.group())
  572. def __enter__(self):
  573. """ Use 'with self' to temporarily disable monitoring behaviour """
  574. self.serial_reader.stop()
  575. self.console_reader.stop()
  576. def __exit__(self, *args, **kwargs):
  577. """ Use 'with self' to temporarily disable monitoring behaviour """
  578. self.console_reader.start()
  579. self.serial_reader.start()
  580. def prompt_next_action(self, reason):
  581. self.console.setup() # set up console to trap input characters
  582. try:
  583. red_print("--- {}".format(reason))
  584. red_print(self.console_parser.get_next_action_text())
  585. k = CTRL_T # ignore CTRL-T here, so people can muscle-memory Ctrl-T Ctrl-F, etc.
  586. while k == CTRL_T:
  587. k = self.console.getkey()
  588. finally:
  589. self.console.cleanup()
  590. ret = self.console_parser.parse_next_action_key(k)
  591. if ret is not None:
  592. cmd = ret[1]
  593. if cmd == CMD_STOP:
  594. # the stop command should be handled last
  595. self.event_queue.put(ret)
  596. else:
  597. self.cmd_queue.put(ret)
  598. def run_make(self, target):
  599. with self:
  600. if isinstance(self.make, list):
  601. popen_args = self.make + [target]
  602. else:
  603. popen_args = [self.make, target]
  604. yellow_print("Running %s..." % " ".join(popen_args))
  605. p = subprocess.Popen(popen_args, env=os.environ)
  606. try:
  607. p.wait()
  608. except KeyboardInterrupt:
  609. p.wait()
  610. if p.returncode != 0:
  611. self.prompt_next_action("Build failed")
  612. else:
  613. self.output_enable(True)
  614. def lookup_pc_address(self, pc_addr):
  615. cmd = ["%saddr2line" % self.toolchain_prefix,
  616. "-pfiaC", "-e", self.elf_file, pc_addr]
  617. try:
  618. translation = subprocess.check_output(cmd, cwd=".")
  619. if b"?? ??:0" not in translation:
  620. self._print(translation.decode(), console_printer=yellow_print)
  621. except OSError as e:
  622. red_print("%s: %s" % (" ".join(cmd), e))
  623. def check_gdbstub_trigger(self, line):
  624. line = self._gdb_buffer + line
  625. self._gdb_buffer = b""
  626. m = re.search(b"\\$(T..)#(..)", line) # look for a gdb "reason" for a break
  627. if m is not None:
  628. try:
  629. chsum = sum(ord(bytes([p])) for p in m.group(1)) & 0xFF
  630. calc_chsum = int(m.group(2), 16)
  631. except ValueError:
  632. return # payload wasn't valid hex digits
  633. if chsum == calc_chsum:
  634. if self.websocket_client:
  635. yellow_print('Communicating through WebSocket')
  636. self.websocket_client.send({'event': 'gdb_stub',
  637. 'port': self.serial.port,
  638. 'prog': self.elf_file})
  639. yellow_print('Waiting for debug finished event')
  640. self.websocket_client.wait([('event', 'debug_finished')])
  641. yellow_print('Communications through WebSocket is finished')
  642. else:
  643. self.run_gdb()
  644. else:
  645. red_print("Malformed gdb message... calculated checksum %02x received %02x" % (chsum, calc_chsum))
  646. def check_coredump_trigger_before_print(self, line):
  647. if self._decode_coredumps == COREDUMP_DECODE_DISABLE:
  648. return
  649. if COREDUMP_UART_PROMPT in line:
  650. yellow_print("Initiating core dump!")
  651. self.event_queue.put((TAG_KEY, '\n'))
  652. return
  653. if COREDUMP_UART_START in line:
  654. yellow_print("Core dump started (further output muted)")
  655. self._reading_coredump = COREDUMP_READING
  656. self._coredump_buffer = b""
  657. self._output_enabled = False
  658. return
  659. if COREDUMP_UART_END in line:
  660. self._reading_coredump = COREDUMP_DONE
  661. yellow_print("\nCore dump finished!")
  662. self.process_coredump()
  663. return
  664. if self._reading_coredump == COREDUMP_READING:
  665. kb = 1024
  666. buffer_len_kb = len(self._coredump_buffer) // kb
  667. self._coredump_buffer += line.replace(b'\r', b'') + b'\n'
  668. new_buffer_len_kb = len(self._coredump_buffer) // kb
  669. if new_buffer_len_kb > buffer_len_kb:
  670. yellow_print("Received %3d kB..." % (new_buffer_len_kb), newline='\r')
  671. def check_coredump_trigger_after_print(self, line):
  672. if self._decode_coredumps == COREDUMP_DECODE_DISABLE:
  673. return
  674. # Re-enable output after the last line of core dump has been consumed
  675. if not self._output_enabled and self._reading_coredump == COREDUMP_DONE:
  676. self._reading_coredump = COREDUMP_IDLE
  677. self._output_enabled = True
  678. self._coredump_buffer = b""
  679. def process_coredump(self):
  680. if self._decode_coredumps != COREDUMP_DECODE_INFO:
  681. raise NotImplementedError("process_coredump: %s not implemented" % self._decode_coredumps)
  682. coredump_script = os.path.join(os.path.dirname(__file__), "..", "components", "espcoredump", "espcoredump.py")
  683. coredump_file = None
  684. try:
  685. # On Windows, the temporary file can't be read unless it is closed.
  686. # Set delete=False and delete the file manually later.
  687. with tempfile.NamedTemporaryFile(mode="wb", delete=False) as coredump_file:
  688. coredump_file.write(self._coredump_buffer)
  689. coredump_file.flush()
  690. if self.websocket_client:
  691. self._output_enabled = True
  692. yellow_print('Communicating through WebSocket')
  693. self.websocket_client.send({'event': 'coredump',
  694. 'file': coredump_file.name,
  695. 'prog': self.elf_file})
  696. yellow_print('Waiting for debug finished event')
  697. self.websocket_client.wait([('event', 'debug_finished')])
  698. yellow_print('Communications through WebSocket is finished')
  699. else:
  700. cmd = [sys.executable,
  701. coredump_script,
  702. "info_corefile",
  703. "--core", coredump_file.name,
  704. "--core-format", "b64",
  705. self.elf_file
  706. ]
  707. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  708. self._output_enabled = True
  709. self._print(output)
  710. self._output_enabled = False # Will be reenabled in check_coredump_trigger_after_print
  711. except subprocess.CalledProcessError as e:
  712. yellow_print("Failed to run espcoredump script: {}\n{}\n\n".format(e, e.output))
  713. self._output_enabled = True
  714. self._print(COREDUMP_UART_START + b'\n')
  715. self._print(self._coredump_buffer)
  716. # end line will be printed in handle_serial_input
  717. finally:
  718. if coredump_file is not None:
  719. try:
  720. os.unlink(coredump_file.name)
  721. except OSError as e:
  722. yellow_print("Couldn't remote temporary core dump file ({})".format(e))
  723. def run_gdb(self):
  724. with self: # disable console control
  725. sys.stderr.write(ANSI_NORMAL)
  726. try:
  727. cmd = ["%sgdb" % self.toolchain_prefix,
  728. "-ex", "set serial baud %d" % self.serial.baudrate,
  729. "-ex", "target remote %s" % self.serial.port,
  730. "-ex", "interrupt", # monitor has already parsed the first 'reason' command, need a second
  731. self.elf_file]
  732. process = subprocess.Popen(cmd, cwd=".")
  733. process.wait()
  734. except OSError as e:
  735. red_print("%s: %s" % (" ".join(cmd), e))
  736. except KeyboardInterrupt:
  737. pass # happens on Windows, maybe other OSes
  738. finally:
  739. try:
  740. # on Linux, maybe other OSes, gdb sometimes seems to be alive even after wait() returns...
  741. process.terminate()
  742. except Exception:
  743. pass
  744. try:
  745. # also on Linux, maybe other OSes, gdb sometimes exits uncleanly and breaks the tty mode
  746. subprocess.call(["stty", "sane"])
  747. except Exception:
  748. pass # don't care if there's no stty, we tried...
  749. self.prompt_next_action("gdb exited")
  750. def output_enable(self, enable):
  751. self._output_enabled = enable
  752. def output_toggle(self):
  753. self._output_enabled = not self._output_enabled
  754. yellow_print("\nToggle output display: {}, Type Ctrl-T Ctrl-Y to show/disable output again.".format(self._output_enabled))
  755. def toggle_logging(self):
  756. if self._log_file:
  757. self.stop_logging()
  758. else:
  759. self.start_logging()
  760. def start_logging(self):
  761. if not self._log_file:
  762. try:
  763. name = "log.{}.{}.txt".format(os.path.splitext(os.path.basename(self.elf_file))[0],
  764. datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
  765. self._log_file = open(name, "wb+")
  766. yellow_print("\nLogging is enabled into file {}".format(name))
  767. except Exception as e:
  768. red_print("\nLog file {} cannot be created: {}".format(name, e))
  769. def stop_logging(self):
  770. if self._log_file:
  771. try:
  772. name = self._log_file.name
  773. self._log_file.close()
  774. yellow_print("\nLogging is disabled and file {} has been closed".format(name))
  775. except Exception as e:
  776. red_print("\nLog file cannot be closed: {}".format(e))
  777. finally:
  778. self._log_file = None
  779. def _print(self, string, console_printer=None):
  780. if console_printer is None:
  781. console_printer = self.console.write_bytes
  782. if self._output_enabled:
  783. console_printer(string)
  784. if self._log_file:
  785. try:
  786. if isinstance(string, type(u'')):
  787. string = string.encode()
  788. self._log_file.write(string)
  789. except Exception as e:
  790. red_print("\nCannot write to file: {}".format(e))
  791. # don't fill-up the screen with the previous errors (probably consequent prints would fail also)
  792. self.stop_logging()
  793. def handle_commands(self, cmd):
  794. if cmd == CMD_STOP:
  795. self.console_reader.stop()
  796. self.serial_reader.stop()
  797. elif cmd == CMD_RESET:
  798. self.serial.setRTS(True)
  799. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  800. time.sleep(0.2)
  801. self.serial.setRTS(False)
  802. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  803. self.output_enable(True)
  804. elif cmd == CMD_MAKE:
  805. self.run_make("encrypted-flash" if self.encrypted else "flash")
  806. elif cmd == CMD_APP_FLASH:
  807. self.run_make("encrypted-app-flash" if self.encrypted else "app-flash")
  808. elif cmd == CMD_OUTPUT_TOGGLE:
  809. self.output_toggle()
  810. elif cmd == CMD_TOGGLE_LOGGING:
  811. self.toggle_logging()
  812. elif cmd == CMD_ENTER_BOOT:
  813. self.serial.setDTR(False) # IO0=HIGH
  814. self.serial.setRTS(True) # EN=LOW, chip in reset
  815. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  816. time.sleep(1.3) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  817. self.serial.setDTR(True) # IO0=LOW
  818. self.serial.setRTS(False) # EN=HIGH, chip out of reset
  819. self.serial.setDTR(self.serial.dtr) # usbser.sys workaround
  820. time.sleep(0.45) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  821. self.serial.setDTR(False) # IO0=HIGH, done
  822. else:
  823. raise RuntimeError("Bad command data %d" % (cmd))
  824. def main():
  825. def _get_default_serial_port():
  826. """
  827. Same logic for detecting serial port as esptool.py and idf.py: reverse sort by name and choose the first port.
  828. """
  829. try:
  830. ports = list(reversed(sorted(p.device for p in serial.tools.list_ports.comports())))
  831. return ports[0]
  832. except Exception:
  833. return '/dev/ttyUSB0'
  834. parser = argparse.ArgumentParser("idf_monitor - a serial output monitor for esp-idf")
  835. parser.add_argument(
  836. '--port', '-p',
  837. help='Serial port device',
  838. default=os.environ.get('ESPTOOL_PORT', _get_default_serial_port())
  839. )
  840. parser.add_argument(
  841. '--baud', '-b',
  842. help='Serial port baud rate',
  843. type=int,
  844. default=os.getenv('IDF_MONITOR_BAUD', os.getenv('MONITORBAUD', 115200)))
  845. parser.add_argument(
  846. '--make', '-m',
  847. help='Command to run make',
  848. type=str, default='make')
  849. parser.add_argument(
  850. '--encrypted',
  851. help='Use encrypted targets while running make',
  852. action='store_true')
  853. parser.add_argument(
  854. '--toolchain-prefix',
  855. help="Triplet prefix to add before cross-toolchain names",
  856. default=DEFAULT_TOOLCHAIN_PREFIX)
  857. parser.add_argument(
  858. "--eol",
  859. choices=['CR', 'LF', 'CRLF'],
  860. type=lambda c: c.upper(),
  861. help="End of line to use when sending to the serial port",
  862. default='CR')
  863. parser.add_argument(
  864. 'elf_file', help='ELF file of application',
  865. type=argparse.FileType('rb'))
  866. parser.add_argument(
  867. '--print_filter',
  868. help="Filtering string",
  869. default=DEFAULT_PRINT_FILTER)
  870. parser.add_argument(
  871. '--decode-coredumps',
  872. choices=[COREDUMP_DECODE_INFO, COREDUMP_DECODE_DISABLE],
  873. default=COREDUMP_DECODE_INFO,
  874. help="Handling of core dumps found in serial output"
  875. )
  876. parser.add_argument(
  877. '--ws',
  878. default=os.environ.get('ESP_IDF_MONITOR_WS', None),
  879. help="WebSocket URL for communicating with IDE tools for debugging purposes"
  880. )
  881. args = parser.parse_args()
  882. # GDB uses CreateFile to open COM port, which requires the COM name to be r'\\.\COMx' if the COM
  883. # number is larger than 10
  884. if os.name == 'nt' and args.port.startswith("COM"):
  885. args.port = args.port.replace('COM', r'\\.\COM')
  886. yellow_print("--- WARNING: GDB cannot open serial ports accessed as COMx")
  887. yellow_print("--- Using %s instead..." % args.port)
  888. elif args.port.startswith("/dev/tty.") and sys.platform == 'darwin':
  889. args.port = args.port.replace("/dev/tty.", "/dev/cu.")
  890. yellow_print("--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.")
  891. yellow_print("--- Using %s instead..." % args.port)
  892. serial_instance = serial.serial_for_url(args.port, args.baud,
  893. do_not_open=True)
  894. serial_instance.dtr = False
  895. serial_instance.rts = False
  896. args.elf_file.close() # don't need this as a file
  897. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  898. # parent make is only running 1 job (monitor), so we can re-spawn
  899. # all of the child makes we need (the -j argument remains part of
  900. # MAKEFLAGS)
  901. try:
  902. makeflags = os.environ["MAKEFLAGS"]
  903. makeflags = re.sub(r"--jobserver[^ =]*=[0-9,]+ ?", "", makeflags)
  904. os.environ["MAKEFLAGS"] = makeflags
  905. except KeyError:
  906. pass # not running a make jobserver
  907. # Pass the actual used port to callee of idf_monitor (e.g. make) through `ESPPORT` environment
  908. # variable
  909. # To make sure the key as well as the value are str type, by the requirements of subprocess
  910. espport_key = str("ESPPORT")
  911. espport_val = str(args.port)
  912. os.environ.update({espport_key: espport_val})
  913. ws = WebSocketClient(args.ws) if args.ws else None
  914. try:
  915. monitor = Monitor(serial_instance, args.elf_file.name, args.print_filter, args.make, args.encrypted,
  916. args.toolchain_prefix, args.eol,
  917. args.decode_coredumps,
  918. ws)
  919. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  920. p=serial_instance))
  921. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  922. key_description(monitor.console_parser.exit_key),
  923. key_description(monitor.console_parser.menu_key),
  924. key_description(monitor.console_parser.menu_key),
  925. key_description(CTRL_H)))
  926. if args.print_filter != DEFAULT_PRINT_FILTER:
  927. yellow_print('--- Print filter: {} ---'.format(args.print_filter))
  928. monitor.main_loop()
  929. finally:
  930. if ws:
  931. ws.close()
  932. class WebSocketClient(object):
  933. """
  934. WebSocket client used to advertise debug events to WebSocket server by sending and receiving JSON-serialized
  935. dictionaries.
  936. Advertisement of debug event:
  937. {'event': 'gdb_stub', 'port': '/dev/ttyUSB1', 'prog': 'build/elf_file'} for GDB Stub, or
  938. {'event': 'coredump', 'file': '/tmp/xy', 'prog': 'build/elf_file'} for coredump,
  939. where 'port' is the port for the connected device, 'prog' is the full path to the ELF file and 'file' is the
  940. generated coredump file.
  941. Expected end of external debugging:
  942. {'event': 'debug_finished'}
  943. """
  944. RETRIES = 3
  945. CONNECTION_RETRY_DELAY = 1
  946. def __init__(self, url):
  947. self.url = url
  948. self._connect()
  949. def _connect(self):
  950. """
  951. Connect to WebSocket server at url
  952. """
  953. self.close()
  954. for _ in range(self.RETRIES):
  955. try:
  956. self.ws = websocket.create_connection(self.url)
  957. break # success
  958. except NameError:
  959. raise RuntimeError('Please install the websocket_client package for IDE integration!')
  960. except Exception as e:
  961. red_print('WebSocket connection error: {}'.format(e))
  962. time.sleep(self.CONNECTION_RETRY_DELAY)
  963. else:
  964. raise RuntimeError('Cannot connect to WebSocket server')
  965. def close(self):
  966. try:
  967. self.ws.close()
  968. except AttributeError:
  969. # Not yet connected
  970. pass
  971. except Exception as e:
  972. red_print('WebSocket close error: {}'.format(e))
  973. def send(self, payload_dict):
  974. """
  975. Serialize payload_dict in JSON format and send it to the server
  976. """
  977. for _ in range(self.RETRIES):
  978. try:
  979. self.ws.send(json.dumps(payload_dict))
  980. yellow_print('WebSocket sent: {}'.format(payload_dict))
  981. break
  982. except Exception as e:
  983. red_print('WebSocket send error: {}'.format(e))
  984. self._connect()
  985. else:
  986. raise RuntimeError('Cannot send to WebSocket server')
  987. def wait(self, expect_iterable):
  988. """
  989. Wait until a dictionary in JSON format is received from the server with all (key, value) tuples from
  990. expect_iterable.
  991. """
  992. for _ in range(self.RETRIES):
  993. try:
  994. r = self.ws.recv()
  995. except Exception as e:
  996. red_print('WebSocket receive error: {}'.format(e))
  997. self._connect()
  998. continue
  999. obj = json.loads(r)
  1000. if all([k in obj and obj[k] == v for k, v in expect_iterable]):
  1001. yellow_print('WebSocket received: {}'.format(obj))
  1002. break
  1003. red_print('WebSocket expected: {}, received: {}'.format(dict(expect_iterable), obj))
  1004. else:
  1005. raise RuntimeError('Cannot receive from WebSocket server')
  1006. if os.name == 'nt':
  1007. # Windows console stuff
  1008. STD_OUTPUT_HANDLE = -11
  1009. STD_ERROR_HANDLE = -12
  1010. # wincon.h values
  1011. FOREGROUND_INTENSITY = 8
  1012. FOREGROUND_GREY = 7
  1013. # matches the ANSI color change sequences that IDF sends
  1014. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  1015. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  1016. ANSI_TO_WINDOWS_COLOR = [0, 4, 2, 6, 1, 5, 3, 7]
  1017. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  1018. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  1019. class ANSIColorConverter(object):
  1020. """Class to wrap a file-like output stream, intercept ANSI color codes,
  1021. and convert them into calls to Windows SetConsoleTextAttribute.
  1022. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  1023. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  1024. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  1025. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  1026. """
  1027. def __init__(self, output=None, decode_output=False):
  1028. self.output = output
  1029. self.decode_output = decode_output
  1030. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  1031. self.matched = b''
  1032. def _output_write(self, data):
  1033. try:
  1034. if self.decode_output:
  1035. self.output.write(data.decode())
  1036. else:
  1037. self.output.write(data)
  1038. except (IOError, OSError):
  1039. # Windows 10 bug since the Fall Creators Update, sometimes writing to console randomly throws
  1040. # an exception (however, the character is still written to the screen)
  1041. # Ref https://github.com/espressif/esp-idf/issues/1163
  1042. #
  1043. # Also possible for Windows to throw an OSError error if the data is invalid for the console
  1044. # (garbage bytes, etc)
  1045. pass
  1046. def write(self, data):
  1047. if isinstance(data, bytes):
  1048. data = bytearray(data)
  1049. else:
  1050. data = bytearray(data, 'utf-8')
  1051. for b in data:
  1052. b = bytes([b])
  1053. length = len(self.matched)
  1054. if b == b'\033': # ESC
  1055. self.matched = b
  1056. elif (length == 1 and b == b'[') or (1 < length < 7):
  1057. self.matched += b
  1058. if self.matched == ANSI_NORMAL.encode('latin-1'): # reset console
  1059. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  1060. self.flush()
  1061. SetConsoleTextAttribute(self.handle, FOREGROUND_GREY)
  1062. self.matched = b''
  1063. elif len(self.matched) == 7: # could be an ANSI sequence
  1064. m = re.match(RE_ANSI_COLOR, self.matched)
  1065. if m is not None:
  1066. color = ANSI_TO_WINDOWS_COLOR[int(m.group(2))]
  1067. if m.group(1) == b'1':
  1068. color |= FOREGROUND_INTENSITY
  1069. # Flush is required only with Python3 - switching color before it is printed would mess up the console
  1070. self.flush()
  1071. SetConsoleTextAttribute(self.handle, color)
  1072. else:
  1073. self._output_write(self.matched) # not an ANSI color code, display verbatim
  1074. self.matched = b''
  1075. else:
  1076. self._output_write(b)
  1077. self.matched = b''
  1078. def flush(self):
  1079. try:
  1080. self.output.flush()
  1081. except OSError:
  1082. # Account for Windows Console refusing to accept garbage bytes (serial noise, etc)
  1083. pass
  1084. if __name__ == "__main__":
  1085. main()