idf_monitor.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  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 division, print_function, unicode_literals
  33. import argparse
  34. import codecs
  35. import datetime
  36. import os
  37. import re
  38. import subprocess
  39. from builtins import bytes, chr, object
  40. try:
  41. import queue
  42. except ImportError:
  43. import Queue as queue
  44. import ctypes
  45. import json
  46. import shlex
  47. import sys
  48. import tempfile
  49. import textwrap
  50. import threading
  51. import time
  52. import types
  53. from distutils.version import StrictVersion
  54. from io import open
  55. import serial
  56. import serial.tools.list_ports
  57. import serial.tools.miniterm as miniterm
  58. try:
  59. import websocket
  60. except ImportError:
  61. # This is needed for IDE integration only.
  62. pass
  63. key_description = miniterm.key_description
  64. # Control-key characters
  65. CTRL_A = '\x01'
  66. CTRL_B = '\x02'
  67. CTRL_F = '\x06'
  68. CTRL_H = '\x08'
  69. CTRL_R = '\x12'
  70. CTRL_T = '\x14'
  71. CTRL_Y = '\x19'
  72. CTRL_P = '\x10'
  73. CTRL_X = '\x18'
  74. CTRL_L = '\x0c'
  75. CTRL_RBRACKET = '\x1d' # Ctrl+]
  76. # Command parsed from console inputs
  77. CMD_STOP = 1
  78. CMD_RESET = 2
  79. CMD_MAKE = 3
  80. CMD_APP_FLASH = 4
  81. CMD_OUTPUT_TOGGLE = 5
  82. CMD_TOGGLE_LOGGING = 6
  83. CMD_ENTER_BOOT = 7
  84. # ANSI terminal codes (if changed, regular expressions in LineMatcher need to be udpated)
  85. ANSI_RED = '\033[1;31m'
  86. ANSI_YELLOW = '\033[0;33m'
  87. ANSI_NORMAL = '\033[0m'
  88. def color_print(message, color, newline='\n'):
  89. """ Print a message to stderr with colored highlighting """
  90. sys.stderr.write('%s%s%s%s' % (color, message, ANSI_NORMAL, newline))
  91. def yellow_print(message, newline='\n'):
  92. color_print(message, ANSI_YELLOW, newline)
  93. def red_print(message, newline='\n'):
  94. color_print(message, ANSI_RED, newline)
  95. __version__ = '1.1'
  96. # Tags for tuples in queues
  97. TAG_KEY = 0
  98. TAG_SERIAL = 1
  99. TAG_SERIAL_FLUSH = 2
  100. TAG_CMD = 3
  101. # regex matches an potential PC value (0x4xxxxxxx)
  102. MATCH_PCADDR = re.compile(r'0x4[0-9a-f]{7}', re.IGNORECASE)
  103. DEFAULT_TOOLCHAIN_PREFIX = 'xtensa-esp32-elf-'
  104. DEFAULT_PRINT_FILTER = ''
  105. # coredump related messages
  106. COREDUMP_UART_START = b'================= CORE DUMP START ================='
  107. COREDUMP_UART_END = b'================= CORE DUMP END ================='
  108. COREDUMP_UART_PROMPT = b'Press Enter to print core dump to UART...'
  109. # coredump states
  110. COREDUMP_IDLE = 0
  111. COREDUMP_READING = 1
  112. COREDUMP_DONE = 2
  113. # coredump decoding options
  114. COREDUMP_DECODE_DISABLE = 'disable'
  115. COREDUMP_DECODE_INFO = 'info'
  116. # panic handler related messages
  117. PANIC_START = r'Core \s*\d+ register dump:'
  118. PANIC_END = b'ELF file SHA256:'
  119. PANIC_STACK_DUMP = b'Stack memory:'
  120. # panic handler decoding states
  121. PANIC_IDLE = 0
  122. PANIC_READING = 1
  123. # panic handler decoding options
  124. PANIC_DECODE_DISABLE = 'disable'
  125. PANIC_DECODE_BACKTRACE = 'backtrace'
  126. class StoppableThread(object):
  127. """
  128. Provide a Thread-like class which can be 'cancelled' via a subclass-provided
  129. cancellation method.
  130. Can be started and stopped multiple times.
  131. Isn't an instance of type Thread because Python Thread objects can only be run once
  132. """
  133. def __init__(self):
  134. self._thread = None
  135. @property
  136. def alive(self):
  137. """
  138. Is 'alive' whenever the internal thread object exists
  139. """
  140. return self._thread is not None
  141. def start(self):
  142. if self._thread is None:
  143. self._thread = threading.Thread(target=self._run_outer)
  144. self._thread.start()
  145. def _cancel(self):
  146. pass # override to provide cancellation functionality
  147. def run(self):
  148. pass # override for the main thread behaviour
  149. def _run_outer(self):
  150. try:
  151. self.run()
  152. finally:
  153. self._thread = None
  154. def stop(self):
  155. if self._thread is not None:
  156. old_thread = self._thread
  157. self._thread = None
  158. self._cancel()
  159. old_thread.join()
  160. class ConsoleReader(StoppableThread):
  161. """ Read input keys from the console and push them to the queue,
  162. until stopped.
  163. """
  164. def __init__(self, console, event_queue, cmd_queue, parser, test_mode):
  165. super(ConsoleReader, self).__init__()
  166. self.console = console
  167. self.event_queue = event_queue
  168. self.cmd_queue = cmd_queue
  169. self.parser = parser
  170. self.test_mode = test_mode
  171. def run(self):
  172. self.console.setup()
  173. try:
  174. while self.alive:
  175. try:
  176. if os.name == 'nt':
  177. # Windows kludge: because the console.cancel() method doesn't
  178. # seem to work to unblock getkey() on the Windows implementation.
  179. #
  180. # So we only call getkey() if we know there's a key waiting for us.
  181. import msvcrt
  182. while not msvcrt.kbhit() and self.alive:
  183. time.sleep(0.1)
  184. if not self.alive:
  185. break
  186. elif self.test_mode:
  187. # In testing mode the stdin is connected to PTY but is not used for input anything. For PTY
  188. # the canceling by fcntl.ioctl isn't working and would hang in self.console.getkey().
  189. # Therefore, we avoid calling it.
  190. while self.alive:
  191. time.sleep(0.1)
  192. break
  193. c = self.console.getkey()
  194. except KeyboardInterrupt:
  195. c = '\x03'
  196. if c is not None:
  197. ret = self.parser.parse(c)
  198. if ret is not None:
  199. (tag, cmd) = ret
  200. # stop command should be executed last
  201. if tag == TAG_CMD and cmd != CMD_STOP:
  202. self.cmd_queue.put(ret)
  203. else:
  204. self.event_queue.put(ret)
  205. finally:
  206. self.console.cleanup()
  207. def _cancel(self):
  208. if os.name == 'posix' and not self.test_mode:
  209. # this is the way cancel() is implemented in pyserial 3.3 or newer,
  210. # older pyserial (3.1+) has cancellation implemented via 'select',
  211. # which does not work when console sends an escape sequence response
  212. #
  213. # even older pyserial (<3.1) does not have this method
  214. #
  215. # on Windows there is a different (also hacky) fix, applied above.
  216. #
  217. # note that TIOCSTI is not implemented in WSL / bash-on-Windows.
  218. # TODO: introduce some workaround to make it work there.
  219. #
  220. # Note: This would throw exception in testing mode when the stdin is connected to PTY.
  221. import fcntl
  222. import termios
  223. fcntl.ioctl(self.console.fd, termios.TIOCSTI, b'\0')
  224. class ConsoleParser(object):
  225. def __init__(self, eol='CRLF'):
  226. self.translate_eol = {
  227. 'CRLF': lambda c: c.replace('\n', '\r\n'),
  228. 'CR': lambda c: c.replace('\n', '\r'),
  229. 'LF': lambda c: c.replace('\r', '\n'),
  230. }[eol]
  231. self.menu_key = CTRL_T
  232. self.exit_key = CTRL_RBRACKET
  233. self._pressed_menu_key = False
  234. def parse(self, key):
  235. ret = None
  236. if self._pressed_menu_key:
  237. ret = self._handle_menu_key(key)
  238. elif key == self.menu_key:
  239. self._pressed_menu_key = True
  240. elif key == self.exit_key:
  241. ret = (TAG_CMD, CMD_STOP)
  242. else:
  243. key = self.translate_eol(key)
  244. ret = (TAG_KEY, key)
  245. return ret
  246. def _handle_menu_key(self, c):
  247. ret = None
  248. if c == self.exit_key or c == self.menu_key: # send verbatim
  249. ret = (TAG_KEY, c)
  250. elif c in [CTRL_H, 'h', 'H', '?']:
  251. red_print(self.get_help_text())
  252. elif c == CTRL_R: # Reset device via RTS
  253. ret = (TAG_CMD, CMD_RESET)
  254. elif c == CTRL_F: # Recompile & upload
  255. ret = (TAG_CMD, CMD_MAKE)
  256. elif c in [CTRL_A, 'a', 'A']: # Recompile & upload app only
  257. # "CTRL-A" cannot be captured with the default settings of the Windows command line, therefore, "A" can be used
  258. # instead
  259. ret = (TAG_CMD, CMD_APP_FLASH)
  260. elif c == CTRL_Y: # Toggle output display
  261. ret = (TAG_CMD, CMD_OUTPUT_TOGGLE)
  262. elif c == CTRL_L: # Toggle saving output into file
  263. ret = (TAG_CMD, CMD_TOGGLE_LOGGING)
  264. elif c == CTRL_P:
  265. yellow_print('Pause app (enter bootloader mode), press Ctrl-T Ctrl-R to restart')
  266. # to fast trigger pause without press menu key
  267. ret = (TAG_CMD, CMD_ENTER_BOOT)
  268. elif c in [CTRL_X, 'x', 'X']: # Exiting from within the menu
  269. ret = (TAG_CMD, CMD_STOP)
  270. else:
  271. red_print('--- unknown menu character {} --'.format(key_description(c)))
  272. self._pressed_menu_key = False
  273. return ret
  274. def get_help_text(self):
  275. text = """\
  276. --- idf_monitor ({version}) - ESP-IDF monitor tool
  277. --- based on miniterm from pySerial
  278. ---
  279. --- {exit:8} Exit program
  280. --- {menu:8} Menu escape key, followed by:
  281. --- Menu keys:
  282. --- {menu:14} Send the menu character itself to remote
  283. --- {exit:14} Send the exit character itself to remote
  284. --- {reset:14} Reset target board via RTS line
  285. --- {makecmd:14} Build & flash project
  286. --- {appmake:14} Build & flash app only
  287. --- {output:14} Toggle output display
  288. --- {log:14} Toggle saving output into file
  289. --- {pause:14} Reset target into bootloader to pause app via RTS line
  290. --- {menuexit:14} Exit program
  291. """.format(version=__version__,
  292. exit=key_description(self.exit_key),
  293. menu=key_description(self.menu_key),
  294. reset=key_description(CTRL_R),
  295. makecmd=key_description(CTRL_F),
  296. appmake=key_description(CTRL_A) + ' (or A)',
  297. output=key_description(CTRL_Y),
  298. log=key_description(CTRL_L),
  299. pause=key_description(CTRL_P),
  300. menuexit=key_description(CTRL_X) + ' (or X)')
  301. return textwrap.dedent(text)
  302. def get_next_action_text(self):
  303. text = """\
  304. --- Press {} to exit monitor.
  305. --- Press {} to build & flash project.
  306. --- Press {} to build & flash app.
  307. --- Press any other key to resume monitor (resets target).
  308. """.format(key_description(self.exit_key),
  309. key_description(CTRL_F),
  310. key_description(CTRL_A))
  311. return textwrap.dedent(text)
  312. def parse_next_action_key(self, c):
  313. ret = None
  314. if c == self.exit_key:
  315. ret = (TAG_CMD, CMD_STOP)
  316. elif c == CTRL_F: # Recompile & upload
  317. ret = (TAG_CMD, CMD_MAKE)
  318. elif c in [CTRL_A, 'a', 'A']: # Recompile & upload app only
  319. # "CTRL-A" cannot be captured with the default settings of the Windows command line, therefore, "A" can be used
  320. # instead
  321. ret = (TAG_CMD, CMD_APP_FLASH)
  322. return ret
  323. class SerialReader(StoppableThread):
  324. """ Read serial data from the serial port and push to the
  325. event queue, until stopped.
  326. """
  327. def __init__(self, serial, event_queue):
  328. super(SerialReader, self).__init__()
  329. self.baud = serial.baudrate
  330. self.serial = serial
  331. self.event_queue = event_queue
  332. if not hasattr(self.serial, 'cancel_read'):
  333. # enable timeout for checking alive flag,
  334. # if cancel_read not available
  335. self.serial.timeout = 0.25
  336. def run(self):
  337. if not self.serial.is_open:
  338. self.serial.baudrate = self.baud
  339. self.serial.rts = True # Force an RTS reset on open
  340. self.serial.open()
  341. time.sleep(0.005) # Add a delay to meet the requirements of minimal EN low time (2ms for ESP32-C3)
  342. self.serial.rts = False
  343. self.serial.dtr = self.serial.dtr # usbser.sys workaround
  344. try:
  345. while self.alive:
  346. try:
  347. data = self.serial.read(self.serial.in_waiting or 1)
  348. except (serial.serialutil.SerialException, IOError) as e:
  349. data = b''
  350. # self.serial.open() was successful before, therefore, this is an issue related to
  351. # the disappearance of the device
  352. red_print(e)
  353. yellow_print('Waiting for the device to reconnect', newline='')
  354. self.serial.close()
  355. while self.alive: # so that exiting monitor works while waiting
  356. try:
  357. time.sleep(0.5)
  358. self.serial.open()
  359. break # device connected
  360. except serial.serialutil.SerialException:
  361. yellow_print('.', newline='')
  362. sys.stderr.flush()
  363. yellow_print('') # go to new line
  364. if len(data):
  365. self.event_queue.put((TAG_SERIAL, data), False)
  366. finally:
  367. self.serial.close()
  368. def _cancel(self):
  369. if hasattr(self.serial, 'cancel_read'):
  370. try:
  371. self.serial.cancel_read()
  372. except Exception:
  373. pass
  374. class LineMatcher(object):
  375. """
  376. Assembles a dictionary of filtering rules based on the --print_filter
  377. argument of idf_monitor. Then later it is used to match lines and
  378. determine whether they should be shown on screen or not.
  379. """
  380. LEVEL_N = 0
  381. LEVEL_E = 1
  382. LEVEL_W = 2
  383. LEVEL_I = 3
  384. LEVEL_D = 4
  385. LEVEL_V = 5
  386. level = {'N': LEVEL_N, 'E': LEVEL_E, 'W': LEVEL_W, 'I': LEVEL_I, 'D': LEVEL_D,
  387. 'V': LEVEL_V, '*': LEVEL_V, '': LEVEL_V}
  388. def __init__(self, print_filter):
  389. self._dict = dict()
  390. self._re = re.compile(r'^(?:\033\[[01];?[0-9]+m?)?([EWIDV]) \([0-9]+\) ([^:]+): ')
  391. items = print_filter.split()
  392. if len(items) == 0:
  393. self._dict['*'] = self.LEVEL_V # default is to print everything
  394. for f in items:
  395. s = f.split(r':')
  396. if len(s) == 1:
  397. # specifying no warning level defaults to verbose level
  398. lev = self.LEVEL_V
  399. elif len(s) == 2:
  400. if len(s[0]) == 0:
  401. raise ValueError('No tag specified in filter ' + f)
  402. try:
  403. lev = self.level[s[1].upper()]
  404. except KeyError:
  405. raise ValueError('Unknown warning level in filter ' + f)
  406. else:
  407. raise ValueError('Missing ":" in filter ' + f)
  408. self._dict[s[0]] = lev
  409. def match(self, line):
  410. try:
  411. m = self._re.search(line)
  412. if m:
  413. lev = self.level[m.group(1)]
  414. if m.group(2) in self._dict:
  415. return self._dict[m.group(2)] >= lev
  416. return self._dict.get('*', self.LEVEL_N) >= lev
  417. except (KeyError, IndexError):
  418. # Regular line written with something else than ESP_LOG*
  419. # or an empty line.
  420. pass
  421. # We need something more than "*.N" for printing.
  422. return self._dict.get('*', self.LEVEL_N) > self.LEVEL_N
  423. class SerialStopException(Exception):
  424. """
  425. This exception is used for stopping the IDF monitor in testing mode.
  426. """
  427. pass
  428. class Monitor(object):
  429. """
  430. Monitor application main class.
  431. This was originally derived from miniterm.Miniterm, but it turned out to be easier to write from scratch for this
  432. purpose.
  433. Main difference is that all event processing happens in the main thread, not the worker threads.
  434. """
  435. def __init__(self, serial_instance, elf_file, print_filter, make='make', encrypted=False,
  436. toolchain_prefix=DEFAULT_TOOLCHAIN_PREFIX, eol='CRLF',
  437. decode_coredumps=COREDUMP_DECODE_INFO,
  438. decode_panic=PANIC_DECODE_DISABLE,
  439. target=None,
  440. websocket_client=None,
  441. enable_address_decoding=True):
  442. super(Monitor, self).__init__()
  443. self.event_queue = queue.Queue()
  444. self.cmd_queue = queue.Queue()
  445. self.console = miniterm.Console()
  446. self.enable_address_decoding = enable_address_decoding
  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 further 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. if self.enable_address_decoding:
  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. parser = argparse.ArgumentParser('idf_monitor - a serial output monitor for esp-idf')
  889. parser.add_argument(
  890. '--port', '-p',
  891. help='Serial port device',
  892. default=os.environ.get('ESPTOOL_PORT', '/dev/ttyUSB0')
  893. )
  894. parser.add_argument(
  895. '--disable-address-decoding', '-d',
  896. help="Don't print lines about decoded addresses from the application ELF file.",
  897. action='store_true',
  898. default=True if os.environ.get('ESP_MONITOR_DECODE') == 0 else False
  899. )
  900. parser.add_argument(
  901. '--baud', '-b',
  902. help='Serial port baud rate',
  903. type=int,
  904. default=os.getenv('IDF_MONITOR_BAUD', os.getenv('MONITORBAUD', 115200)))
  905. parser.add_argument(
  906. '--make', '-m',
  907. help='Command to run make',
  908. type=str, default='make')
  909. parser.add_argument(
  910. '--encrypted',
  911. help='Use encrypted targets while running make',
  912. action='store_true')
  913. parser.add_argument(
  914. '--toolchain-prefix',
  915. help='Triplet prefix to add before cross-toolchain names',
  916. default=DEFAULT_TOOLCHAIN_PREFIX)
  917. parser.add_argument(
  918. '--eol',
  919. choices=['CR', 'LF', 'CRLF'],
  920. type=lambda c: c.upper(),
  921. help='End of line to use when sending to the serial port',
  922. default='CR')
  923. parser.add_argument(
  924. 'elf_file', help='ELF file of application',
  925. type=argparse.FileType('rb'))
  926. parser.add_argument(
  927. '--print_filter',
  928. help='Filtering string',
  929. default=DEFAULT_PRINT_FILTER)
  930. parser.add_argument(
  931. '--decode-coredumps',
  932. choices=[COREDUMP_DECODE_INFO, COREDUMP_DECODE_DISABLE],
  933. default=COREDUMP_DECODE_INFO,
  934. help='Handling of core dumps found in serial output'
  935. )
  936. parser.add_argument(
  937. '--decode-panic',
  938. choices=[PANIC_DECODE_BACKTRACE, PANIC_DECODE_DISABLE],
  939. default=PANIC_DECODE_DISABLE,
  940. help='Handling of panic handler info found in serial output'
  941. )
  942. parser.add_argument(
  943. '--target',
  944. required=False,
  945. help='Target name (used when stack dump decoding is enabled)'
  946. )
  947. parser.add_argument(
  948. '--ws',
  949. default=os.environ.get('ESP_IDF_MONITOR_WS', None),
  950. help='WebSocket URL for communicating with IDE tools for debugging purposes'
  951. )
  952. args = parser.parse_args()
  953. # GDB uses CreateFile to open COM port, which requires the COM name to be r'\\.\COMx' if the COM
  954. # number is larger than 10
  955. if os.name == 'nt' and args.port.startswith('COM'):
  956. args.port = args.port.replace('COM', r'\\.\COM')
  957. yellow_print('--- WARNING: GDB cannot open serial ports accessed as COMx')
  958. yellow_print('--- Using %s instead...' % args.port)
  959. elif args.port.startswith('/dev/tty.') and sys.platform == 'darwin':
  960. args.port = args.port.replace('/dev/tty.', '/dev/cu.')
  961. yellow_print('--- WARNING: Serial ports accessed as /dev/tty.* will hang gdb if launched.')
  962. yellow_print('--- Using %s instead...' % args.port)
  963. serial_instance = serial.serial_for_url(args.port, args.baud,
  964. do_not_open=True)
  965. serial_instance.dtr = False
  966. serial_instance.rts = False
  967. args.elf_file.close() # don't need this as a file
  968. # remove the parallel jobserver arguments from MAKEFLAGS, as any
  969. # parent make is only running 1 job (monitor), so we can re-spawn
  970. # all of the child makes we need (the -j argument remains part of
  971. # MAKEFLAGS)
  972. try:
  973. makeflags = os.environ['MAKEFLAGS']
  974. makeflags = re.sub(r'--jobserver[^ =]*=[0-9,]+ ?', '', makeflags)
  975. os.environ['MAKEFLAGS'] = makeflags
  976. except KeyError:
  977. pass # not running a make jobserver
  978. # Pass the actual used port to callee of idf_monitor (e.g. make) through `ESPPORT` environment
  979. # variable
  980. # To make sure the key as well as the value are str type, by the requirements of subprocess
  981. espport_key = str('ESPPORT')
  982. espport_val = str(args.port)
  983. os.environ.update({espport_key: espport_val})
  984. ws = WebSocketClient(args.ws) if args.ws else None
  985. try:
  986. monitor = Monitor(serial_instance, args.elf_file.name, args.print_filter, args.make, args.encrypted,
  987. args.toolchain_prefix, args.eol,
  988. args.decode_coredumps, args.decode_panic, args.target,
  989. ws, enable_address_decoding=not args.disable_address_decoding)
  990. yellow_print('--- idf_monitor on {p.name} {p.baudrate} ---'.format(
  991. p=serial_instance))
  992. yellow_print('--- Quit: {} | Menu: {} | Help: {} followed by {} ---'.format(
  993. key_description(monitor.console_parser.exit_key),
  994. key_description(monitor.console_parser.menu_key),
  995. key_description(monitor.console_parser.menu_key),
  996. key_description(CTRL_H)))
  997. if args.print_filter != DEFAULT_PRINT_FILTER:
  998. yellow_print('--- Print filter: {} ---'.format(args.print_filter))
  999. monitor.main_loop()
  1000. finally:
  1001. if ws:
  1002. ws.close()
  1003. class WebSocketClient(object):
  1004. """
  1005. WebSocket client used to advertise debug events to WebSocket server by sending and receiving JSON-serialized
  1006. dictionaries.
  1007. Advertisement of debug event:
  1008. {'event': 'gdb_stub', 'port': '/dev/ttyUSB1', 'prog': 'build/elf_file'} for GDB Stub, or
  1009. {'event': 'coredump', 'file': '/tmp/xy', 'prog': 'build/elf_file'} for coredump,
  1010. where 'port' is the port for the connected device, 'prog' is the full path to the ELF file and 'file' is the
  1011. generated coredump file.
  1012. Expected end of external debugging:
  1013. {'event': 'debug_finished'}
  1014. """
  1015. RETRIES = 3
  1016. CONNECTION_RETRY_DELAY = 1
  1017. def __init__(self, url):
  1018. self.url = url
  1019. self._connect()
  1020. def _connect(self):
  1021. """
  1022. Connect to WebSocket server at url
  1023. """
  1024. self.close()
  1025. for _ in range(self.RETRIES):
  1026. try:
  1027. self.ws = websocket.create_connection(self.url)
  1028. break # success
  1029. except NameError:
  1030. raise RuntimeError('Please install the websocket_client package for IDE integration!')
  1031. except Exception as e:
  1032. red_print('WebSocket connection error: {}'.format(e))
  1033. time.sleep(self.CONNECTION_RETRY_DELAY)
  1034. else:
  1035. raise RuntimeError('Cannot connect to WebSocket server')
  1036. def close(self):
  1037. try:
  1038. self.ws.close()
  1039. except AttributeError:
  1040. # Not yet connected
  1041. pass
  1042. except Exception as e:
  1043. red_print('WebSocket close error: {}'.format(e))
  1044. def send(self, payload_dict):
  1045. """
  1046. Serialize payload_dict in JSON format and send it to the server
  1047. """
  1048. for _ in range(self.RETRIES):
  1049. try:
  1050. self.ws.send(json.dumps(payload_dict))
  1051. yellow_print('WebSocket sent: {}'.format(payload_dict))
  1052. break
  1053. except Exception as e:
  1054. red_print('WebSocket send error: {}'.format(e))
  1055. self._connect()
  1056. else:
  1057. raise RuntimeError('Cannot send to WebSocket server')
  1058. def wait(self, expect_iterable):
  1059. """
  1060. Wait until a dictionary in JSON format is received from the server with all (key, value) tuples from
  1061. expect_iterable.
  1062. """
  1063. for _ in range(self.RETRIES):
  1064. try:
  1065. r = self.ws.recv()
  1066. except Exception as e:
  1067. red_print('WebSocket receive error: {}'.format(e))
  1068. self._connect()
  1069. continue
  1070. obj = json.loads(r)
  1071. if all([k in obj and obj[k] == v for k, v in expect_iterable]):
  1072. yellow_print('WebSocket received: {}'.format(obj))
  1073. break
  1074. red_print('WebSocket expected: {}, received: {}'.format(dict(expect_iterable), obj))
  1075. else:
  1076. raise RuntimeError('Cannot receive from WebSocket server')
  1077. if os.name == 'nt':
  1078. # Windows console stuff
  1079. STD_OUTPUT_HANDLE = -11
  1080. STD_ERROR_HANDLE = -12
  1081. # wincon.h values
  1082. FOREGROUND_INTENSITY = 8
  1083. FOREGROUND_GREY = 7
  1084. # matches the ANSI color change sequences that IDF sends
  1085. RE_ANSI_COLOR = re.compile(b'\033\\[([01]);3([0-7])m')
  1086. # list mapping the 8 ANSI colors (the indexes) to Windows Console colors
  1087. ANSI_TO_WINDOWS_COLOR = [0, 4, 2, 6, 1, 5, 3, 7]
  1088. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  1089. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  1090. class ANSIColorConverter(object):
  1091. """Class to wrap a file-like output stream, intercept ANSI color codes,
  1092. and convert them into calls to Windows SetConsoleTextAttribute.
  1093. Doesn't support all ANSI terminal code escape sequences, only the sequences IDF uses.
  1094. Ironically, in Windows this console output is normally wrapped by winpty which will then detect the console text
  1095. color changes and convert these back to ANSI color codes for MSYS' terminal to display. However this is the
  1096. least-bad working solution, as winpty doesn't support any "passthrough" mode for raw output.
  1097. """
  1098. def __init__(self, output=None, decode_output=False):
  1099. self.output = output
  1100. self.decode_output = decode_output
  1101. self.handle = GetStdHandle(STD_ERROR_HANDLE if self.output == sys.stderr else STD_OUTPUT_HANDLE)
  1102. self.matched = b''
  1103. def _output_write(self, data):
  1104. try:
  1105. if self.decode_output:
  1106. self.output.write(data.decode())
  1107. else:
  1108. self.output.write(data)
  1109. except (IOError, OSError):
  1110. # Windows 10 bug since the Fall Creators Update, sometimes writing to console randomly throws
  1111. # an exception (however, the character is still written to the screen)
  1112. # Ref https://github.com/espressif/esp-idf/issues/1163
  1113. #
  1114. # Also possible for Windows to throw an OSError error if the data is invalid for the console
  1115. # (garbage bytes, etc)
  1116. pass
  1117. except UnicodeDecodeError:
  1118. # In case of double byte Unicode characters display '?'
  1119. self.output.write('?')
  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()