AutoDetectBaudJob.py 4.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Job import Job
  4. from UM.Logger import Logger
  5. from .avr_isp import ispBase
  6. from .avr_isp.stk500v2 import Stk500v2
  7. from time import time, sleep
  8. from serial import Serial, SerialException
  9. # An async job that attempts to find the correct baud rate for a USB printer.
  10. # It tries a pre-set list of baud rates. All these baud rates are validated by requesting the temperature a few times
  11. # and checking if the results make sense. If getResult() is not None, it was able to find a correct baud rate.
  12. class AutoDetectBaudJob(Job):
  13. def __init__(self, serial_port: int) -> None:
  14. super().__init__()
  15. self._serial_port = serial_port
  16. self._all_baud_rates = [115200, 250000, 500000, 230400, 76800, 57600, 38400, 19200, 9600]
  17. def run(self) -> None:
  18. Logger.debug(f"Auto detect baud rate started for {self._serial_port}")
  19. wait_response_timeouts = [3, 15, 30]
  20. wait_bootloader_times = [1.5, 5, 15]
  21. write_timeout = 3
  22. read_timeout = 3
  23. tries = 2
  24. programmer = Stk500v2()
  25. serial = None
  26. try:
  27. programmer.connect(self._serial_port)
  28. serial = programmer.leaveISP()
  29. except ispBase.IspError:
  30. programmer.close()
  31. for retry in range(tries):
  32. for baud_rate in self._all_baud_rates:
  33. if retry < len(wait_response_timeouts):
  34. wait_response_timeout = wait_response_timeouts[retry]
  35. else:
  36. wait_response_timeout = wait_response_timeouts[-1]
  37. if retry < len(wait_bootloader_times):
  38. wait_bootloader = wait_bootloader_times[retry]
  39. else:
  40. wait_bootloader = wait_bootloader_times[-1]
  41. Logger.debug(f"Checking {self._serial_port} if baud rate {baud_rate} works. Retry nr: {retry}. Wait timeout: {wait_response_timeout}")
  42. if serial is None:
  43. try:
  44. serial = Serial(str(self._serial_port), baud_rate, timeout = read_timeout, writeTimeout = write_timeout)
  45. except SerialException:
  46. Logger.warning(f"Unable to create serial connection to {serial} with baud rate {baud_rate}")
  47. continue
  48. else:
  49. # We already have a serial connection, just change the baud rate.
  50. try:
  51. serial.baudrate = baud_rate
  52. except ValueError:
  53. continue
  54. # Ensure that we are not talking to the boot loader. 1.5 seconds seems to be the magic number
  55. sleep(wait_bootloader)
  56. serial.write(b"\n") # Ensure we clear out previous responses
  57. serial.write(b"M105\n")
  58. start_timeout_time = time()
  59. timeout_time = time() + wait_response_timeout
  60. while timeout_time > time():
  61. # If baudrate is wrong, then readline() might never
  62. # return, even with timeouts set. Using read_until
  63. # with size limit seems to fix this.
  64. line = serial.read_until(size = 100)
  65. if b"ok" in line and b"T:" in line:
  66. self.setResult(baud_rate)
  67. Logger.log("d", "Detected baud rate {baud_rate} on serial {serial} on retry {retry} with after {time_elapsed:0.2f} seconds.".format(
  68. serial = self._serial_port, baud_rate = baud_rate, retry = retry, time_elapsed = time() - start_timeout_time))
  69. serial.close() # close serial port so it can be opened by the USBPrinterOutputDevice
  70. return
  71. serial.write(b"M105\n")
  72. sleep(15) # Give the printer some time to init and try again.
  73. Logger.debug(f"Unable to find a working baudrate for {serial}")
  74. self.setResult(None) # Unable to detect the correct baudrate.