serial_reader.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. # SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import queue
  4. import subprocess
  5. import sys
  6. import time
  7. import serial
  8. from .constants import CHECK_ALIVE_FLAG_TIMEOUT, MINIMAL_EN_LOW_DELAY, RECONNECT_DELAY, TAG_SERIAL
  9. from .output_helpers import red_print, yellow_print
  10. from .stoppable_thread import StoppableThread
  11. class Reader(StoppableThread):
  12. """ Output Reader base class """
  13. class SerialReader(Reader):
  14. """ Read serial data from the serial port and push to the
  15. event queue, until stopped.
  16. """
  17. def __init__(self, serial_instance, event_queue, reset):
  18. # type: (serial.Serial, queue.Queue, bool) -> None
  19. super(SerialReader, self).__init__()
  20. self.baud = serial_instance.baudrate
  21. self.serial = serial_instance
  22. self.event_queue = event_queue
  23. self.gdb_exit = False
  24. self.reset = reset
  25. if not hasattr(self.serial, 'cancel_read'):
  26. # enable timeout for checking alive flag,
  27. # if cancel_read not available
  28. self.serial.timeout = CHECK_ALIVE_FLAG_TIMEOUT
  29. def run(self):
  30. # type: () -> None
  31. if not self.serial.is_open:
  32. self.serial.baudrate = self.baud
  33. # We can come to this thread at startup or from external application line GDB.
  34. # If we come from GDB we would like to continue to run without reset.
  35. high = False
  36. low = True
  37. self.serial.dtr = low # Non reset state
  38. self.serial.rts = high # IO0=HIGH
  39. self.serial.dtr = self.serial.dtr # usbser.sys workaround
  40. # Current state not reset the target!
  41. self.serial.open()
  42. if not self.gdb_exit and self.reset:
  43. self.serial.dtr = high # Set dtr to reset state (affected by rts)
  44. self.serial.rts = low # Set rts/dtr to the reset state
  45. self.serial.dtr = self.serial.dtr # usbser.sys workaround
  46. # Add a delay to meet the requirements of minimal EN low time (2ms for ESP32-C3)
  47. time.sleep(MINIMAL_EN_LOW_DELAY)
  48. elif not self.reset:
  49. self.serial.setDTR(high) # IO0=HIGH, default state
  50. self.gdb_exit = False
  51. self.serial.rts = high # Set rts/dtr to the working state
  52. self.serial.dtr = self.serial.dtr # usbser.sys workaround
  53. try:
  54. while self.alive:
  55. try:
  56. data = self.serial.read(self.serial.in_waiting or 1)
  57. except (serial.serialutil.SerialException, IOError) as e:
  58. data = b''
  59. # self.serial.open() was successful before, therefore, this is an issue related to
  60. # the disappearance of the device
  61. red_print(e)
  62. yellow_print('Waiting for the device to reconnect', newline='')
  63. self.serial.close()
  64. while self.alive: # so that exiting monitor works while waiting
  65. try:
  66. time.sleep(RECONNECT_DELAY)
  67. if not self.reset:
  68. self.serial.dtr = low # Non reset state
  69. self.serial.rts = high # IO0=HIGH
  70. self.serial.dtr = self.serial.dtr # usbser.sys workaround
  71. self.serial.open()
  72. break # device connected
  73. except serial.serialutil.SerialException:
  74. yellow_print('.', newline='')
  75. sys.stderr.flush()
  76. yellow_print('') # go to new line
  77. if data:
  78. self.event_queue.put((TAG_SERIAL, data), False)
  79. finally:
  80. self.serial.close()
  81. def _cancel(self):
  82. # type: () -> None
  83. if hasattr(self.serial, 'cancel_read'):
  84. try:
  85. self.serial.cancel_read()
  86. except Exception: # noqa
  87. pass
  88. class LinuxReader(Reader):
  89. """ Read data from the subprocess that runs runnable and push to the
  90. event queue, until stopped.
  91. """
  92. def __init__(self, process, event_queue):
  93. # type: (subprocess.Popen, queue.Queue) -> None
  94. super().__init__()
  95. self.proc = process
  96. self.event_queue = event_queue
  97. self._stdout = iter(self.proc.stdout.readline, b'') # type: ignore
  98. def run(self): # type: () -> None
  99. try:
  100. while self.alive:
  101. for line in self._stdout:
  102. if line:
  103. self.event_queue.put((TAG_SERIAL, line), False)
  104. finally:
  105. self.proc.terminate()
  106. def _cancel(self): # type: () -> None
  107. self.proc.terminate()