idf_monitor.py 52 KB

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