USBPrinterOutputDevice.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from .avr_isp import stk500v2, ispBase, intelHex
  4. import serial
  5. import threading
  6. import time
  7. import queue
  8. import re
  9. import functools
  10. from UM.Application import Application
  11. from UM.Logger import Logger
  12. from cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
  13. from UM.Message import Message
  14. from PyQt5.QtCore import QUrl, pyqtSlot, pyqtSignal, pyqtProperty
  15. from UM.i18n import i18nCatalog
  16. catalog = i18nCatalog("cura")
  17. class USBPrinterOutputDevice(PrinterOutputDevice):
  18. def __init__(self, serial_port):
  19. super().__init__(serial_port)
  20. self.setName(catalog.i18nc("@item:inmenu", "USB printing"))
  21. self.setShortDescription(catalog.i18nc("@action:button", "Print via USB"))
  22. self.setDescription(catalog.i18nc("@info:tooltip", "Print via USB"))
  23. self.setIconName("print")
  24. self.setConnectionText(catalog.i18nc("@info:status", "Connected via USB"))
  25. self._serial = None
  26. self._serial_port = serial_port
  27. self._error_state = None
  28. self._connect_thread = threading.Thread(target = self._connect)
  29. self._connect_thread.daemon = True
  30. self._end_stop_thread = None
  31. self._poll_endstop = False
  32. # The baud checking is done by sending a number of m105 commands to the printer and waiting for a readable
  33. # response. If the baudrate is correct, this should make sense, else we get giberish.
  34. self._required_responses_auto_baud = 3
  35. self._listen_thread = threading.Thread(target=self._listen)
  36. self._listen_thread.daemon = True
  37. self._update_firmware_thread = threading.Thread(target= self._updateFirmware)
  38. self._update_firmware_thread.daemon = True
  39. self.firmwareUpdateComplete.connect(self._onFirmwareUpdateComplete)
  40. self._heatup_wait_start_time = time.time()
  41. ## Queue for commands that need to be send. Used when command is sent when a print is active.
  42. self._command_queue = queue.Queue()
  43. self._is_printing = False
  44. self._is_paused = False
  45. ## Set when print is started in order to check running time.
  46. self._print_start_time = None
  47. self._print_start_time_100 = None
  48. ## Keep track where in the provided g-code the print is
  49. self._gcode_position = 0
  50. # List of gcode lines to be printed
  51. self._gcode = []
  52. # Check if endstops are ever pressed (used for first run)
  53. self._x_min_endstop_pressed = False
  54. self._y_min_endstop_pressed = False
  55. self._z_min_endstop_pressed = False
  56. self._x_max_endstop_pressed = False
  57. self._y_max_endstop_pressed = False
  58. self._z_max_endstop_pressed = False
  59. # In order to keep the connection alive we request the temperature every so often from a different extruder.
  60. # This index is the extruder we requested data from the last time.
  61. self._temperature_requested_extruder_index = 0
  62. self._current_z = 0
  63. self._updating_firmware = False
  64. self._firmware_file_name = None
  65. self._firmware_update_finished = False
  66. self._error_message = None
  67. self._error_code = 0
  68. onError = pyqtSignal()
  69. firmwareUpdateComplete = pyqtSignal()
  70. firmwareUpdateChange = pyqtSignal()
  71. endstopStateChanged = pyqtSignal(str ,bool, arguments = ["key","state"])
  72. def _setTargetBedTemperature(self, temperature):
  73. Logger.log("d", "Setting bed temperature to %s", temperature)
  74. self._sendCommand("M140 S%s" % temperature)
  75. def _setTargetHotendTemperature(self, index, temperature):
  76. Logger.log("d", "Setting hotend %s temperature to %s", index, temperature)
  77. self._sendCommand("M104 T%s S%s" % (index, temperature))
  78. def _setHeadPosition(self, x, y , z, speed):
  79. self._sendCommand("G0 X%s Y%s Z%s F%s" % (x, y, z, speed))
  80. def _setHeadX(self, x, speed):
  81. self._sendCommand("G0 X%s F%s" % (x, speed))
  82. def _setHeadY(self, y, speed):
  83. self._sendCommand("G0 Y%s F%s" % (y, speed))
  84. def _setHeadZ(self, z, speed):
  85. self._sendCommand("G0 Y%s F%s" % (z, speed))
  86. def _homeHead(self):
  87. self._sendCommand("G28")
  88. def _homeBed(self):
  89. self._sendCommand("G28 Z")
  90. def startPrint(self):
  91. self.writeStarted.emit(self)
  92. gcode_list = getattr( Application.getInstance().getController().getScene(), "gcode_list")
  93. self._updateJobState("printing")
  94. self.printGCode(gcode_list)
  95. def _moveHead(self, x, y, z, speed):
  96. self._sendCommand("G91")
  97. self._sendCommand("G0 X%s Y%s Z%s F%s" % (x, y, z, speed))
  98. self._sendCommand("G90")
  99. ## Start a print based on a g-code.
  100. # \param gcode_list List with gcode (strings).
  101. def printGCode(self, gcode_list):
  102. if self._progress or self._connection_state != ConnectionState.connected:
  103. self._error_message = Message(catalog.i18nc("@info:status", "Printer is busy or not connected. Unable to start a new job."))
  104. self._error_message.show()
  105. Logger.log("d", "Printer is busy or not connected, aborting print")
  106. self.writeError.emit(self)
  107. return
  108. self._gcode.clear()
  109. for layer in gcode_list:
  110. self._gcode.extend(layer.split("\n"))
  111. # Reset line number. If this is not done, first line is sometimes ignored
  112. self._gcode.insert(0, "M110")
  113. self._gcode_position = 0
  114. self._print_start_time_100 = None
  115. self._is_printing = True
  116. self._print_start_time = time.time()
  117. for i in range(0, 4): # Push first 4 entries before accepting other inputs
  118. self._sendNextGcodeLine()
  119. self.writeFinished.emit(self)
  120. ## Get the serial port string of this connection.
  121. # \return serial port
  122. def getSerialPort(self):
  123. return self._serial_port
  124. ## Try to connect the serial. This simply starts the thread, which runs _connect.
  125. def connect(self):
  126. if not self._updating_firmware and not self._connect_thread.isAlive():
  127. self._connect_thread.start()
  128. ## Private function (threaded) that actually uploads the firmware.
  129. def _updateFirmware(self):
  130. self._error_code = 0
  131. self.setProgress(0, 100)
  132. self._firmware_update_finished = False
  133. if self._connection_state != ConnectionState.closed:
  134. self.close()
  135. hex_file = intelHex.readHex(self._firmware_file_name)
  136. if len(hex_file) == 0:
  137. Logger.log("e", "Unable to read provided hex file. Could not update firmware")
  138. self._updateFirmwareFailedMissingFirmware()
  139. return
  140. programmer = stk500v2.Stk500v2()
  141. programmer.progress_callback = self.setProgress
  142. try:
  143. programmer.connect(self._serial_port)
  144. except Exception:
  145. pass
  146. # Give programmer some time to connect. Might need more in some cases, but this worked in all tested cases.
  147. time.sleep(1)
  148. if not programmer.isConnected():
  149. Logger.log("e", "Unable to connect with serial. Could not update firmware")
  150. self._updateFirmwareFailedCommunicationError()
  151. return
  152. self._updating_firmware = True
  153. try:
  154. programmer.programChip(hex_file)
  155. self._updating_firmware = False
  156. except serial.SerialException as e:
  157. Logger.log("e", "SerialException while trying to update firmware: <%s>" %(repr(e)))
  158. self._updateFirmwareFailedIOError()
  159. return
  160. except Exception as e:
  161. Logger.log("e", "Exception while trying to update firmware: <%s>" %(repr(e)))
  162. self._updateFirmwareFailedUnknown()
  163. return
  164. programmer.close()
  165. self._updateFirmwareCompletedSucessfully()
  166. return
  167. ## Private function which makes sure that firmware update process has failed by missing firmware
  168. def _updateFirmwareFailedMissingFirmware(self):
  169. return self._updateFirmwareFailedCommon(4)
  170. ## Private function which makes sure that firmware update process has failed by an IO error
  171. def _updateFirmwareFailedIOError(self):
  172. return self._updateFirmwareFailedCommon(3)
  173. ## Private function which makes sure that firmware update process has failed by a communication problem
  174. def _updateFirmwareFailedCommunicationError(self):
  175. return self._updateFirmwareFailedCommon(2)
  176. ## Private function which makes sure that firmware update process has failed by an unknown error
  177. def _updateFirmwareFailedUnknown(self):
  178. return self._updateFirmwareFailedCommon(1)
  179. ## Private common function which makes sure that firmware update process has completed/ended with a set progress state
  180. def _updateFirmwareFailedCommon(self, code):
  181. if not code:
  182. raise Exception("Error code not set!")
  183. self._error_code = code
  184. self._firmware_update_finished = True
  185. self.resetFirmwareUpdate(update_has_finished = True)
  186. self.progressChanged.emit()
  187. self.firmwareUpdateComplete.emit()
  188. return
  189. ## Private function which makes sure that firmware update process has successfully completed
  190. def _updateFirmwareCompletedSucessfully(self):
  191. self.setProgress(100, 100)
  192. self._firmware_update_finished = True
  193. self.resetFirmwareUpdate(update_has_finished = True)
  194. self.firmwareUpdateComplete.emit()
  195. return
  196. ## Upload new firmware to machine
  197. # \param filename full path of firmware file to be uploaded
  198. def updateFirmware(self, file_name):
  199. Logger.log("i", "Updating firmware of %s using %s", self._serial_port, file_name)
  200. self._firmware_file_name = file_name
  201. self._update_firmware_thread.start()
  202. @property
  203. def firmwareUpdateFinished(self):
  204. return self._firmware_update_finished
  205. def resetFirmwareUpdate(self, update_has_finished = False):
  206. self._firmware_update_finished = update_has_finished
  207. self.firmwareUpdateChange.emit()
  208. @pyqtSlot()
  209. def startPollEndstop(self):
  210. if not self._poll_endstop:
  211. self._poll_endstop = True
  212. if self._end_stop_thread is None:
  213. self._end_stop_thread = threading.Thread(target=self._pollEndStop)
  214. self._end_stop_thread.daemon = True
  215. self._end_stop_thread.start()
  216. @pyqtSlot()
  217. def stopPollEndstop(self):
  218. self._poll_endstop = False
  219. self._end_stop_thread = None
  220. def _pollEndStop(self):
  221. while self._connection_state == ConnectionState.connected and self._poll_endstop:
  222. self.sendCommand("M119")
  223. time.sleep(0.5)
  224. ## Private connect function run by thread. Can be started by calling connect.
  225. def _connect(self):
  226. Logger.log("d", "Attempting to connect to %s", self._serial_port)
  227. self.setConnectionState(ConnectionState.connecting)
  228. programmer = stk500v2.Stk500v2()
  229. try:
  230. programmer.connect(self._serial_port) # Connect with the serial, if this succeeds, it's an arduino based usb device.
  231. self._serial = programmer.leaveISP()
  232. except ispBase.IspError as e:
  233. Logger.log("i", "Could not establish connection on %s: %s. Device is not arduino based." %(self._serial_port,str(e)))
  234. except Exception as e:
  235. Logger.log("i", "Could not establish connection on %s, unknown reasons. Device is not arduino based." % self._serial_port)
  236. # If the programmer connected, we know its an atmega based version.
  237. # Not all that useful, but it does give some debugging information.
  238. for baud_rate in self._getBaudrateList(): # Cycle all baud rates (auto detect)
  239. Logger.log("d", "Attempting to connect to printer with serial %s on baud rate %s", self._serial_port, baud_rate)
  240. if self._serial is None:
  241. try:
  242. self._serial = serial.Serial(str(self._serial_port), baud_rate, timeout = 3, writeTimeout = 10000)
  243. except serial.SerialException:
  244. Logger.log("d", "Could not open port %s" % self._serial_port)
  245. continue
  246. else:
  247. if not self.setBaudRate(baud_rate):
  248. continue # Could not set the baud rate, go to the next
  249. time.sleep(1.5) # Ensure that we are not talking to the bootloader. 1.5 seconds seems to be the magic number
  250. sucesfull_responses = 0
  251. timeout_time = time.time() + 5
  252. self._serial.write(b"\n")
  253. self._sendCommand("M105") # Request temperature, as this should (if baudrate is correct) result in a command with "T:" in it
  254. while timeout_time > time.time():
  255. line = self._readline()
  256. if line is None:
  257. Logger.log("d", "No response from serial connection received.")
  258. # Something went wrong with reading, could be that close was called.
  259. self.setConnectionState(ConnectionState.closed)
  260. return
  261. if b"T:" in line:
  262. Logger.log("d", "Correct response for auto-baudrate detection received.")
  263. self._serial.timeout = 0.5
  264. sucesfull_responses += 1
  265. if sucesfull_responses >= self._required_responses_auto_baud:
  266. self._serial.timeout = 2 # Reset serial timeout
  267. self.setConnectionState(ConnectionState.connected)
  268. self._listen_thread.start() # Start listening
  269. Logger.log("i", "Established printer connection on port %s" % self._serial_port)
  270. return
  271. self._sendCommand("M105") # Send M105 as long as we are listening, otherwise we end up in an undefined state
  272. Logger.log("e", "Baud rate detection for %s failed", self._serial_port)
  273. self.close() # Unable to connect, wrap up.
  274. self.setConnectionState(ConnectionState.closed)
  275. ## Set the baud rate of the serial. This can cause exceptions, but we simply want to ignore those.
  276. def setBaudRate(self, baud_rate):
  277. try:
  278. self._serial.baudrate = baud_rate
  279. return True
  280. except Exception as e:
  281. return False
  282. ## Close the printer connection
  283. def close(self):
  284. Logger.log("d", "Closing the USB printer connection.")
  285. if self._connect_thread.isAlive():
  286. try:
  287. self._connect_thread.join()
  288. except Exception as e:
  289. Logger.log("d", "PrinterConnection.close: %s (expected)", e)
  290. pass # This should work, but it does fail sometimes for some reason
  291. self._connect_thread = threading.Thread(target = self._connect)
  292. self._connect_thread.daemon = True
  293. self.setConnectionState(ConnectionState.closed)
  294. if self._serial is not None:
  295. try:
  296. self._listen_thread.join()
  297. except:
  298. pass
  299. self._serial.close()
  300. self._listen_thread = threading.Thread(target = self._listen)
  301. self._listen_thread.daemon = True
  302. self._serial = None
  303. ## Directly send the command, withouth checking connection state (eg; printing).
  304. # \param cmd string with g-code
  305. def _sendCommand(self, cmd):
  306. if self._serial is None:
  307. return
  308. if "M109" in cmd or "M190" in cmd:
  309. self._heatup_wait_start_time = time.time()
  310. try:
  311. command = (cmd + "\n").encode()
  312. self._serial.write(b"\n")
  313. self._serial.write(command)
  314. except serial.SerialTimeoutException:
  315. Logger.log("w","Serial timeout while writing to serial port, trying again.")
  316. try:
  317. time.sleep(0.5)
  318. self._serial.write((cmd + "\n").encode())
  319. except Exception as e:
  320. Logger.log("e","Unexpected error while writing serial port %s " % e)
  321. self._setErrorState("Unexpected error while writing serial port %s " % e)
  322. self.close()
  323. except Exception as e:
  324. Logger.log("e","Unexpected error while writing serial port %s" % e)
  325. self._setErrorState("Unexpected error while writing serial port %s " % e)
  326. self.close()
  327. ## Send a command to printer.
  328. # \param cmd string with g-code
  329. def sendCommand(self, cmd):
  330. if self._progress:
  331. self._command_queue.put(cmd)
  332. elif self._connection_state == ConnectionState.connected:
  333. self._sendCommand(cmd)
  334. ## Set the error state with a message.
  335. # \param error String with the error message.
  336. def _setErrorState(self, error):
  337. self._updateJobState("error")
  338. self._error_state = error
  339. self.onError.emit()
  340. def requestWrite(self, node, file_name = None, filter_by_machine = False):
  341. Application.getInstance().showPrintMonitor.emit(True)
  342. self.startPrint()
  343. def _setEndstopState(self, endstop_key, value):
  344. if endstop_key == b"x_min":
  345. if self._x_min_endstop_pressed != value:
  346. self.endstopStateChanged.emit("x_min", value)
  347. self._x_min_endstop_pressed = value
  348. elif endstop_key == b"y_min":
  349. if self._y_min_endstop_pressed != value:
  350. self.endstopStateChanged.emit("y_min", value)
  351. self._y_min_endstop_pressed = value
  352. elif endstop_key == b"z_min":
  353. if self._z_min_endstop_pressed != value:
  354. self.endstopStateChanged.emit("z_min", value)
  355. self._z_min_endstop_pressed = value
  356. ## Listen thread function.
  357. def _listen(self):
  358. Logger.log("i", "Printer connection listen thread started for %s" % self._serial_port)
  359. temperature_request_timeout = time.time()
  360. ok_timeout = time.time()
  361. while self._connection_state == ConnectionState.connected:
  362. line = self._readline()
  363. if line is None:
  364. break # None is only returned when something went wrong. Stop listening
  365. if time.time() > temperature_request_timeout:
  366. if self._num_extruders > 0:
  367. self._temperature_requested_extruder_index = (self._temperature_requested_extruder_index + 1) % self._num_extruders
  368. self.sendCommand("M105 T%d" % (self._temperature_requested_extruder_index))
  369. else:
  370. self.sendCommand("M105")
  371. temperature_request_timeout = time.time() + 5
  372. if line.startswith(b"Error:"):
  373. # Oh YEAH, consistency.
  374. # Marlin reports a MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
  375. # But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
  376. # So we can have an extra newline in the most common case. Awesome work people.
  377. if re.match(b"Error:[0-9]\n", line):
  378. line = line.rstrip() + self._readline()
  379. # Skip the communication errors, as those get corrected.
  380. if b"Extruder switched off" in line or b"Temperature heated bed switched off" in line or b"Something is wrong, please turn off the printer." in line:
  381. if not self.hasError():
  382. self._setErrorState(line[6:])
  383. elif b" T:" in line or line.startswith(b"T:"): # Temperature message
  384. try:
  385. self._setHotendTemperature(self._temperature_requested_extruder_index, float(re.search(b"T: *([0-9\.]*)", line).group(1)))
  386. except:
  387. pass
  388. if b"B:" in line: # Check if it's a bed temperature
  389. try:
  390. self._setBedTemperature(float(re.search(b"B: *([0-9\.]*)", line).group(1)))
  391. except Exception as e:
  392. pass
  393. #TODO: temperature changed callback
  394. elif b"_min" in line or b"_max" in line:
  395. tag, value = line.split(b":", 1)
  396. self._setEndstopState(tag,(b"H" in value or b"TRIGGERED" in value))
  397. if self._is_printing:
  398. if line == b"" and time.time() > ok_timeout:
  399. line = b"ok" # Force a timeout (basically, send next command)
  400. if b"ok" in line:
  401. ok_timeout = time.time() + 5
  402. if not self._command_queue.empty():
  403. self._sendCommand(self._command_queue.get())
  404. elif self._is_paused:
  405. line = b"" # Force getting temperature as keep alive
  406. else:
  407. self._sendNextGcodeLine()
  408. elif b"resend" in line.lower() or b"rs" in line: # Because a resend can be asked with "resend" and "rs"
  409. try:
  410. self._gcode_position = int(line.replace(b"N:",b" ").replace(b"N",b" ").replace(b":",b" ").split()[-1])
  411. except:
  412. if b"rs" in line:
  413. self._gcode_position = int(line.split()[1])
  414. # Request the temperature on comm timeout (every 2 seconds) when we are not printing.)
  415. if line == b"":
  416. if self._num_extruders > 0:
  417. self._temperature_requested_extruder_index = (self._temperature_requested_extruder_index + 1) % self._num_extruders
  418. self.sendCommand("M105 T%d" % self._temperature_requested_extruder_index)
  419. else:
  420. self.sendCommand("M105")
  421. Logger.log("i", "Printer connection listen thread stopped for %s" % self._serial_port)
  422. ## Send next Gcode in the gcode list
  423. def _sendNextGcodeLine(self):
  424. if self._gcode_position >= len(self._gcode):
  425. return
  426. if self._gcode_position == 100:
  427. self._print_start_time_100 = time.time()
  428. line = self._gcode[self._gcode_position]
  429. if ";" in line:
  430. line = line[:line.find(";")]
  431. line = line.strip()
  432. try:
  433. if line == "M0" or line == "M1":
  434. line = "M105" # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
  435. if ("G0" in line or "G1" in line) and "Z" in line:
  436. z = float(re.search("Z([0-9\.]*)", line).group(1))
  437. if self._current_z != z:
  438. self._current_z = z
  439. except Exception as e:
  440. Logger.log("e", "Unexpected error with printer connection: %s" % e)
  441. self._setErrorState("Unexpected error: %s" %e)
  442. checksum = functools.reduce(lambda x,y: x^y, map(ord, "N%d%s" % (self._gcode_position, line)))
  443. self._sendCommand("N%d%s*%d" % (self._gcode_position, line, checksum))
  444. self._gcode_position += 1
  445. self.setProgress((self._gcode_position / len(self._gcode)) * 100)
  446. self.progressChanged.emit()
  447. ## Set the state of the print.
  448. # Sent from the print monitor
  449. def _setJobState(self, job_state):
  450. if job_state == "pause":
  451. self._is_paused = True
  452. self._updateJobState("paused")
  453. elif job_state == "print":
  454. self._is_paused = False
  455. self._updateJobState("printing")
  456. elif job_state == "abort":
  457. self.cancelPrint()
  458. ## Set the progress of the print.
  459. # It will be normalized (based on max_progress) to range 0 - 100
  460. def setProgress(self, progress, max_progress = 100):
  461. self._progress = (progress / max_progress) * 100 # Convert to scale of 0-100
  462. if self._progress == 100:
  463. # Printing is done, reset progress
  464. self._gcode_position = 0
  465. self.setProgress(0)
  466. self._is_printing = False
  467. self._is_paused = False
  468. self._updateJobState("ready")
  469. self.progressChanged.emit()
  470. ## Cancel the current print. Printer connection wil continue to listen.
  471. def cancelPrint(self):
  472. self._gcode_position = 0
  473. self.setProgress(0)
  474. self._gcode = []
  475. # Turn off temperatures, fan and steppers
  476. self._sendCommand("M140 S0")
  477. self._sendCommand("M104 S0")
  478. self._sendCommand("M107")
  479. self._sendCommand("M84")
  480. self._is_printing = False
  481. self._is_paused = False
  482. self._updateJobState("ready")
  483. Application.getInstance().showPrintMonitor.emit(False)
  484. ## Check if the process did not encounter an error yet.
  485. def hasError(self):
  486. return self._error_state is not None
  487. ## private read line used by printer connection to listen for data on serial port.
  488. def _readline(self):
  489. if self._serial is None:
  490. return None
  491. try:
  492. ret = self._serial.readline()
  493. except Exception as e:
  494. Logger.log("e", "Unexpected error while reading serial port. %s" % e)
  495. self._setErrorState("Printer has been disconnected")
  496. self.close()
  497. return None
  498. return ret
  499. ## Create a list of baud rates at which we can communicate.
  500. # \return list of int
  501. def _getBaudrateList(self):
  502. ret = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
  503. return ret
  504. def _onFirmwareUpdateComplete(self):
  505. self._update_firmware_thread.join()
  506. self._update_firmware_thread = threading.Thread(target = self._updateFirmware)
  507. self._update_firmware_thread.daemon = True
  508. self.connect()