AutoDetectBaudJob.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Copyright (c) 2017 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.stk500v2 import Stk500v2
  6. from time import time, sleep
  7. from serial import Serial, SerialException
  8. # An async job that attempts to find the correct baud rate for a USB printer.
  9. # It tries a pre-set list of baud rates. All these baud rates are validated by requesting the temperature a few times
  10. # and checking if the results make sense. If getResult() is not None, it was able to find a correct baud rate.
  11. class AutoDetectBaudJob(Job):
  12. def __init__(self, serial_port):
  13. super().__init__()
  14. self._serial_port = serial_port
  15. self._all_baud_rates = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
  16. def run(self):
  17. Logger.log("d", "Auto detect baud rate started.")
  18. timeout = 3
  19. programmer = Stk500v2()
  20. serial = None
  21. try:
  22. programmer.connect(self._serial_port)
  23. serial = programmer.leaveISP()
  24. except:
  25. programmer.close()
  26. for baud_rate in self._all_baud_rates:
  27. Logger.log("d", "Checking {serial} if baud rate {baud_rate} works".format(serial= self._serial_port, baud_rate = baud_rate))
  28. if serial is None:
  29. try:
  30. serial = Serial(str(self._serial_port), baud_rate, timeout = timeout, writeTimeout = timeout)
  31. except SerialException as e:
  32. Logger.logException("w", "Unable to create serial")
  33. continue
  34. else:
  35. # We already have a serial connection, just change the baud rate.
  36. try:
  37. serial.baudrate = baud_rate
  38. except:
  39. continue
  40. sleep(1.5) # Ensure that we are not talking to the boot loader. 1.5 seconds seems to be the magic number
  41. successful_responses = 0
  42. serial.write(b"\n") # Ensure we clear out previous responses
  43. serial.write(b"M105\n")
  44. timeout_time = time() + timeout
  45. while timeout_time > time():
  46. line = serial.readline()
  47. if b"ok T:" in line:
  48. successful_responses += 1
  49. if successful_responses >= 3:
  50. self.setResult(baud_rate)
  51. return
  52. serial.write(b"M105\n")
  53. self.setResult(None) # Unable to detect the correct baudrate.