serial_handler.py 9.1 KB

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