idf_monitor.py 52 KB

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