serial_handler.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. # SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import os
  4. import queue # noqa: F401
  5. import re
  6. import subprocess
  7. import time
  8. from typing import Callable, Optional
  9. import serial # noqa: F401
  10. from serial.tools import miniterm # noqa: F401
  11. from .chip_specific_config import get_chip_config
  12. from .console_parser import ConsoleParser, prompt_next_action # noqa: F401
  13. from .console_reader import ConsoleReader # noqa: F401
  14. from .constants import (CMD_APP_FLASH, CMD_ENTER_BOOT, CMD_MAKE, CMD_OUTPUT_TOGGLE, CMD_RESET, CMD_STOP,
  15. CMD_TOGGLE_LOGGING, CMD_TOGGLE_TIMESTAMPS, PANIC_DECODE_DISABLE, PANIC_END, PANIC_IDLE,
  16. PANIC_READING, PANIC_STACK_DUMP, PANIC_START)
  17. from .coredump import CoreDump
  18. from .exceptions import SerialStopException
  19. from .gdbhelper import GDBHelper
  20. from .line_matcher import LineMatcher
  21. from .logger import Logger
  22. from .output_helpers import yellow_print
  23. from .serial_reader import Reader
  24. def run_make(target, make, console, console_parser, event_queue, cmd_queue, logger):
  25. # type: (str, str, miniterm.Console, ConsoleParser, queue.Queue, queue.Queue, Logger) -> None
  26. if isinstance(make, list):
  27. popen_args = make + [target]
  28. else:
  29. popen_args = [make, target]
  30. yellow_print('Running %s...' % ' '.join(popen_args))
  31. p = subprocess.Popen(popen_args, env=os.environ)
  32. try:
  33. p.wait()
  34. except KeyboardInterrupt:
  35. p.wait()
  36. if p.returncode != 0:
  37. prompt_next_action('Build failed', console, console_parser, event_queue, cmd_queue)
  38. else:
  39. logger.output_enabled = True
  40. class SerialHandler:
  41. """
  42. The class is responsible for buffering serial input and performing corresponding commands.
  43. """
  44. def __init__(self, last_line_part, serial_check_exit, logger, decode_panic, reading_panic, panic_buffer, target,
  45. force_line_print, start_cmd_sent, serial_instance, encrypted):
  46. # type: (bytes, bool, Logger, str, int, bytes,str, bool, bool, serial.Serial, bool) -> None
  47. self._last_line_part = last_line_part
  48. self._serial_check_exit = serial_check_exit
  49. self.logger = logger
  50. self._decode_panic = decode_panic
  51. self._reading_panic = reading_panic
  52. self._panic_buffer = panic_buffer
  53. self.target = target
  54. self._force_line_print = force_line_print
  55. self.start_cmd_sent = start_cmd_sent
  56. self.serial_instance = serial_instance
  57. self.encrypted = encrypted
  58. def handle_serial_input(self, data, console_parser, coredump, gdb_helper, line_matcher,
  59. check_gdb_stub_and_run, finalize_line=False):
  60. # type: (bytes, ConsoleParser, CoreDump, Optional[GDBHelper], LineMatcher, Callable, bool) -> None
  61. # Remove "+" after Continue command
  62. if self.start_cmd_sent:
  63. self.start_cmd_sent = False
  64. pos = data.find(b'+')
  65. if pos != -1:
  66. data = data[(pos + 1):]
  67. sp = data.split(b'\n')
  68. if self._last_line_part != b'':
  69. # add unprocessed part from previous "data" to the first line
  70. sp[0] = self._last_line_part + sp[0]
  71. self._last_line_part = b''
  72. if sp[-1] != b'':
  73. # last part is not a full line
  74. self._last_line_part = sp.pop()
  75. for line in sp:
  76. if line == b'':
  77. continue
  78. if self._serial_check_exit and line == console_parser.exit_key.encode('latin-1'):
  79. raise SerialStopException()
  80. if gdb_helper:
  81. self.check_panic_decode_trigger(line, gdb_helper)
  82. with coredump.check(line):
  83. if self._force_line_print or line_matcher.match(line.decode(errors='ignore')):
  84. self.logger.print(line + b'\n')
  85. self.logger.handle_possible_pc_address_in_line(line)
  86. check_gdb_stub_and_run(line)
  87. self._force_line_print = False
  88. # Now we have the last part (incomplete line) in _last_line_part. By
  89. # default we don't touch it and just wait for the arrival of the rest
  90. # of the line. But after some time when we didn't received it we need
  91. # to make a decision.
  92. force_print_or_matched = any((
  93. self._force_line_print,
  94. (finalize_line and line_matcher.match(self._last_line_part.decode(errors='ignore')))
  95. ))
  96. if self._last_line_part != b'' and force_print_or_matched:
  97. self._force_line_print = True
  98. self.logger.print(self._last_line_part)
  99. self.logger.handle_possible_pc_address_in_line(self._last_line_part)
  100. check_gdb_stub_and_run(self._last_line_part)
  101. # It is possible that the incomplete line cuts in half the PC
  102. # address. A small buffer is kept and will be used the next time
  103. # handle_possible_pc_address_in_line is invoked to avoid this problem.
  104. # MATCH_PCADDR matches 10 character long addresses. Therefore, we
  105. # keep the last 9 characters.
  106. self.logger.pc_address_buffer = self._last_line_part[-9:]
  107. # GDB sequence can be cut in half also. GDB sequence is 7
  108. # characters long, therefore, we save the last 6 characters.
  109. if gdb_helper:
  110. gdb_helper.gdb_buffer = self._last_line_part[-6:]
  111. self._last_line_part = b''
  112. # else: keeping _last_line_part and it will be processed the next time
  113. # handle_serial_input is invoked
  114. def check_panic_decode_trigger(self, line, gdb_helper): # type: (bytes, GDBHelper) -> None
  115. if self._decode_panic == PANIC_DECODE_DISABLE:
  116. return
  117. if self._reading_panic == PANIC_IDLE and re.search(PANIC_START, line.decode('ascii', errors='ignore')):
  118. self._reading_panic = PANIC_READING
  119. yellow_print('Stack dump detected')
  120. if self._reading_panic == PANIC_READING and PANIC_STACK_DUMP in line:
  121. self.logger.output_enabled = False
  122. if self._reading_panic == PANIC_READING:
  123. self._panic_buffer += line.replace(b'\r', b'') + b'\n'
  124. if self._reading_panic == PANIC_READING and PANIC_END in line:
  125. self._reading_panic = PANIC_IDLE
  126. self.logger.output_enabled = True
  127. gdb_helper.process_panic_output(self._panic_buffer, self.logger, self.target)
  128. self._panic_buffer = b''
  129. def handle_commands(self, cmd, chip, run_make_func, console_reader, serial_reader):
  130. # type: (int, str, Callable, ConsoleReader, Reader) -> None
  131. config = get_chip_config(chip)
  132. reset_delay = config['reset']
  133. enter_boot_set = config['enter_boot_set']
  134. enter_boot_unset = config['enter_boot_unset']
  135. high = False
  136. low = True
  137. if chip == 'linux':
  138. if cmd in [CMD_RESET,
  139. CMD_MAKE,
  140. CMD_APP_FLASH,
  141. CMD_ENTER_BOOT]:
  142. yellow_print('linux target does not support this command')
  143. return
  144. if cmd == CMD_STOP:
  145. console_reader.stop()
  146. serial_reader.stop()
  147. elif cmd == CMD_RESET:
  148. self.serial_instance.setRTS(low)
  149. self.serial_instance.setDTR(self.serial_instance.dtr) # usbser.sys workaround
  150. time.sleep(reset_delay)
  151. self.serial_instance.setRTS(high)
  152. self.serial_instance.setDTR(self.serial_instance.dtr) # usbser.sys workaround
  153. self.logger.output_enabled = True
  154. elif cmd == CMD_MAKE:
  155. run_make_func('encrypted-flash' if self.encrypted else 'flash')
  156. elif cmd == CMD_APP_FLASH:
  157. run_make_func('encrypted-app-flash' if self.encrypted else 'app-flash')
  158. elif cmd == CMD_OUTPUT_TOGGLE:
  159. self.logger.output_toggle()
  160. elif cmd == CMD_TOGGLE_LOGGING:
  161. self.logger.toggle_logging()
  162. elif cmd == CMD_TOGGLE_TIMESTAMPS:
  163. self.logger.toggle_timestamps()
  164. elif cmd == CMD_ENTER_BOOT:
  165. yellow_print('Pause app (enter bootloader mode), press Ctrl-T Ctrl-R to restart')
  166. self.serial_instance.setDTR(high) # IO0=HIGH
  167. self.serial_instance.setRTS(low) # EN=LOW, chip in reset
  168. self.serial_instance.setDTR(self.serial_instance.dtr) # usbser.sys workaround
  169. time.sleep(enter_boot_set) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.1
  170. self.serial_instance.setDTR(low) # IO0=LOW
  171. self.serial_instance.setRTS(high) # EN=HIGH, chip out of reset
  172. self.serial_instance.setDTR(self.serial_instance.dtr) # usbser.sys workaround
  173. time.sleep(enter_boot_unset) # timeouts taken from esptool.py, includes esp32r0 workaround. defaults: 0.05
  174. self.serial_instance.setDTR(high) # IO0=HIGH, done
  175. else:
  176. raise RuntimeError('Bad command data %d' % cmd) # type: ignore