USBPrinterOutputDevice.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. # Copyright (c) 2016 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from .avr_isp import stk500v2, ispBase, intelHex
  4. import serial # type: ignore
  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 Preceded by 'Ready to'.", "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. ## A name for the device.
  91. @pyqtProperty(str, constant = True)
  92. def name(self):
  93. return self.getName()
  94. ## The address of the device.
  95. @pyqtProperty(str, constant = True)
  96. def address(self):
  97. return self._serial_port
  98. def startPrint(self):
  99. self.writeStarted.emit(self)
  100. gcode_list = getattr( Application.getInstance().getController().getScene(), "gcode_list")
  101. self._updateJobState("printing")
  102. self.printGCode(gcode_list)
  103. def _moveHead(self, x, y, z, speed):
  104. self._sendCommand("G91")
  105. self._sendCommand("G0 X%s Y%s Z%s F%s" % (x, y, z, speed))
  106. self._sendCommand("G90")
  107. ## Start a print based on a g-code.
  108. # \param gcode_list List with gcode (strings).
  109. def printGCode(self, gcode_list):
  110. Logger.log("d", "Started printing g-code")
  111. if self._progress or self._connection_state != ConnectionState.connected:
  112. self._error_message = Message(catalog.i18nc("@info:status", "Unable to start a new job because the printer is busy or not connected."), title = catalog.i18nc("@info:title", "Printer Unavailable"))
  113. self._error_message.show()
  114. Logger.log("d", "Printer is busy or not connected, aborting print")
  115. self.writeError.emit(self)
  116. return
  117. self._gcode.clear()
  118. for layer in gcode_list:
  119. self._gcode.extend(layer.split("\n"))
  120. # Reset line number. If this is not done, first line is sometimes ignored
  121. self._gcode.insert(0, "M110")
  122. self._gcode_position = 0
  123. self._print_start_time_100 = None
  124. self._is_printing = True
  125. self._print_start_time = time.time()
  126. for i in range(0, 4): # Push first 4 entries before accepting other inputs
  127. self._sendNextGcodeLine()
  128. self.writeFinished.emit(self)
  129. ## Get the serial port string of this connection.
  130. # \return serial port
  131. def getSerialPort(self):
  132. return self._serial_port
  133. ## Try to connect the serial. This simply starts the thread, which runs _connect.
  134. def connect(self):
  135. if not self._updating_firmware and not self._connect_thread.isAlive():
  136. self._connect_thread.start()
  137. ## Private function (threaded) that actually uploads the firmware.
  138. def _updateFirmware(self):
  139. Logger.log("d", "Attempting to update firmware")
  140. self._error_code = 0
  141. self.setProgress(0, 100)
  142. self._firmware_update_finished = False
  143. if self._connection_state != ConnectionState.closed:
  144. self.close()
  145. hex_file = intelHex.readHex(self._firmware_file_name)
  146. if len(hex_file) == 0:
  147. Logger.log("e", "Unable to read provided hex file. Could not update firmware")
  148. self._updateFirmwareFailedMissingFirmware()
  149. return
  150. programmer = stk500v2.Stk500v2()
  151. programmer.progress_callback = self.setProgress
  152. try:
  153. programmer.connect(self._serial_port)
  154. except Exception:
  155. programmer.close()
  156. pass
  157. # Give programmer some time to connect. Might need more in some cases, but this worked in all tested cases.
  158. time.sleep(1)
  159. if not programmer.isConnected():
  160. Logger.log("e", "Unable to connect with serial. Could not update firmware")
  161. self._updateFirmwareFailedCommunicationError()
  162. return
  163. self._updating_firmware = True
  164. try:
  165. programmer.programChip(hex_file)
  166. self._updating_firmware = False
  167. except serial.SerialException as e:
  168. Logger.log("e", "SerialException while trying to update firmware: <%s>" %(repr(e)))
  169. self._updateFirmwareFailedIOError()
  170. return
  171. except Exception as e:
  172. Logger.log("e", "Exception while trying to update firmware: <%s>" %(repr(e)))
  173. self._updateFirmwareFailedUnknown()
  174. return
  175. programmer.close()
  176. self._updateFirmwareCompletedSucessfully()
  177. return
  178. ## Private function which makes sure that firmware update process has failed by missing firmware
  179. def _updateFirmwareFailedMissingFirmware(self):
  180. return self._updateFirmwareFailedCommon(4)
  181. ## Private function which makes sure that firmware update process has failed by an IO error
  182. def _updateFirmwareFailedIOError(self):
  183. return self._updateFirmwareFailedCommon(3)
  184. ## Private function which makes sure that firmware update process has failed by a communication problem
  185. def _updateFirmwareFailedCommunicationError(self):
  186. return self._updateFirmwareFailedCommon(2)
  187. ## Private function which makes sure that firmware update process has failed by an unknown error
  188. def _updateFirmwareFailedUnknown(self):
  189. return self._updateFirmwareFailedCommon(1)
  190. ## Private common function which makes sure that firmware update process has completed/ended with a set progress state
  191. def _updateFirmwareFailedCommon(self, code):
  192. if not code:
  193. raise Exception("Error code not set!")
  194. self._error_code = code
  195. self._firmware_update_finished = True
  196. self.resetFirmwareUpdate(update_has_finished = True)
  197. self.progressChanged.emit()
  198. self.firmwareUpdateComplete.emit()
  199. return
  200. ## Private function which makes sure that firmware update process has successfully completed
  201. def _updateFirmwareCompletedSucessfully(self):
  202. self.setProgress(100, 100)
  203. self._firmware_update_finished = True
  204. self.resetFirmwareUpdate(update_has_finished = True)
  205. self.firmwareUpdateComplete.emit()
  206. return
  207. ## Upload new firmware to machine
  208. # \param filename full path of firmware file to be uploaded
  209. def updateFirmware(self, file_name):
  210. Logger.log("i", "Updating firmware of %s using %s", self._serial_port, file_name)
  211. self._firmware_file_name = file_name
  212. self._update_firmware_thread.start()
  213. @property
  214. def firmwareUpdateFinished(self):
  215. return self._firmware_update_finished
  216. def resetFirmwareUpdate(self, update_has_finished = False):
  217. self._firmware_update_finished = update_has_finished
  218. self.firmwareUpdateChange.emit()
  219. @pyqtSlot()
  220. def startPollEndstop(self):
  221. if not self._poll_endstop:
  222. self._poll_endstop = True
  223. if self._end_stop_thread is None:
  224. self._end_stop_thread = threading.Thread(target=self._pollEndStop)
  225. self._end_stop_thread.daemon = True
  226. self._end_stop_thread.start()
  227. @pyqtSlot()
  228. def stopPollEndstop(self):
  229. self._poll_endstop = False
  230. self._end_stop_thread = None
  231. def _pollEndStop(self):
  232. while self._connection_state == ConnectionState.connected and self._poll_endstop:
  233. self.sendCommand("M119")
  234. time.sleep(0.5)
  235. ## Private connect function run by thread. Can be started by calling connect.
  236. def _connect(self):
  237. Logger.log("d", "Attempting to connect to %s", self._serial_port)
  238. self.setConnectionState(ConnectionState.connecting)
  239. programmer = stk500v2.Stk500v2()
  240. try:
  241. programmer.connect(self._serial_port) # Connect with the serial, if this succeeds, it's an arduino based usb device.
  242. self._serial = programmer.leaveISP()
  243. except ispBase.IspError as e:
  244. programmer.close()
  245. Logger.log("i", "Could not establish connection on %s: %s. Device is not arduino based." %(self._serial_port,str(e)))
  246. except Exception as e:
  247. programmer.close()
  248. Logger.log("i", "Could not establish connection on %s, unknown reasons. Device is not arduino based." % self._serial_port)
  249. # If the programmer connected, we know its an atmega based version.
  250. # Not all that useful, but it does give some debugging information.
  251. for baud_rate in self._getBaudrateList(): # Cycle all baud rates (auto detect)
  252. Logger.log("d", "Attempting to connect to printer with serial %s on baud rate %s", self._serial_port, baud_rate)
  253. if self._serial is None:
  254. try:
  255. self._serial = serial.Serial(str(self._serial_port), baud_rate, timeout = 3, writeTimeout = 10000)
  256. time.sleep(10)
  257. except serial.SerialException:
  258. Logger.log("d", "Could not open port %s" % self._serial_port)
  259. continue
  260. else:
  261. if not self.setBaudRate(baud_rate):
  262. continue # Could not set the baud rate, go to the next
  263. time.sleep(1.5) # Ensure that we are not talking to the bootloader. 1.5 seconds seems to be the magic number
  264. sucesfull_responses = 0
  265. timeout_time = time.time() + 5
  266. self._serial.write(b"\n")
  267. self._sendCommand("M105") # Request temperature, as this should (if baudrate is correct) result in a command with "T:" in it
  268. while timeout_time > time.time():
  269. line = self._readline()
  270. if line is None:
  271. Logger.log("d", "No response from serial connection received.")
  272. # Something went wrong with reading, could be that close was called.
  273. self.setConnectionState(ConnectionState.closed)
  274. return
  275. if b"T:" in line:
  276. Logger.log("d", "Correct response for auto-baudrate detection received.")
  277. self._serial.timeout = 0.5
  278. sucesfull_responses += 1
  279. if sucesfull_responses >= self._required_responses_auto_baud:
  280. self._serial.timeout = 2 # Reset serial timeout
  281. self.setConnectionState(ConnectionState.connected)
  282. self._listen_thread.start() # Start listening
  283. Logger.log("i", "Established printer connection on port %s" % self._serial_port)
  284. return
  285. self._sendCommand("M105") # Send M105 as long as we are listening, otherwise we end up in an undefined state
  286. Logger.log("e", "Baud rate detection for %s failed", self._serial_port)
  287. self.close() # Unable to connect, wrap up.
  288. self.setConnectionState(ConnectionState.closed)
  289. ## Set the baud rate of the serial. This can cause exceptions, but we simply want to ignore those.
  290. def setBaudRate(self, baud_rate):
  291. try:
  292. self._serial.baudrate = baud_rate
  293. return True
  294. except Exception as e:
  295. return False
  296. ## Close the printer connection
  297. def close(self):
  298. Logger.log("d", "Closing the USB printer connection.")
  299. if self._connect_thread.isAlive():
  300. try:
  301. self._connect_thread.join()
  302. except Exception as e:
  303. Logger.log("d", "PrinterConnection.close: %s (expected)", e)
  304. pass # This should work, but it does fail sometimes for some reason
  305. self._connect_thread = threading.Thread(target = self._connect)
  306. self._connect_thread.daemon = True
  307. self.setConnectionState(ConnectionState.closed)
  308. if self._serial is not None:
  309. try:
  310. self._listen_thread.join()
  311. except:
  312. pass
  313. self._serial.close()
  314. self._listen_thread = threading.Thread(target = self._listen)
  315. self._listen_thread.daemon = True
  316. self._serial = None
  317. ## Directly send the command, withouth checking connection state (eg; printing).
  318. # \param cmd string with g-code
  319. def _sendCommand(self, cmd):
  320. if self._serial is None:
  321. return
  322. if "M109" in cmd or "M190" in cmd:
  323. self._heatup_wait_start_time = time.time()
  324. try:
  325. command = (cmd + "\n").encode()
  326. self._serial.write(b"\n")
  327. self._serial.write(command)
  328. except serial.SerialTimeoutException:
  329. Logger.log("w","Serial timeout while writing to serial port, trying again.")
  330. try:
  331. time.sleep(0.5)
  332. self._serial.write((cmd + "\n").encode())
  333. except Exception as e:
  334. Logger.log("e","Unexpected error while writing serial port %s " % e)
  335. self._setErrorState("Unexpected error while writing serial port %s " % e)
  336. self.close()
  337. except Exception as e:
  338. Logger.log("e","Unexpected error while writing serial port %s" % e)
  339. self._setErrorState("Unexpected error while writing serial port %s " % e)
  340. self.close()
  341. ## Send a command to printer.
  342. # \param cmd string with g-code
  343. def sendCommand(self, cmd):
  344. if self._progress:
  345. self._command_queue.put(cmd)
  346. elif self._connection_state == ConnectionState.connected:
  347. self._sendCommand(cmd)
  348. ## Set the error state with a message.
  349. # \param error String with the error message.
  350. def _setErrorState(self, error):
  351. self._updateJobState("error")
  352. self._error_state = error
  353. self.onError.emit()
  354. ## Request the current scene to be sent to a USB-connected printer.
  355. #
  356. # \param nodes A collection of scene nodes to send. This is ignored.
  357. # \param file_name \type{string} A suggestion for a file name to write.
  358. # This is ignored.
  359. # \param filter_by_machine Whether to filter MIME types by machine. This
  360. # is ignored.
  361. # \param kwargs Keyword arguments.
  362. def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None, **kwargs):
  363. container_stack = Application.getInstance().getGlobalContainerStack()
  364. if container_stack.getProperty("machine_gcode_flavor", "value") == "UltiGCode":
  365. self._error_message = Message(catalog.i18nc("@info:status", "This printer does not support USB printing because it uses UltiGCode flavor."), title = catalog.i18nc("@info:title", "USB Printing"))
  366. self._error_message.show()
  367. return
  368. elif not container_stack.getMetaDataEntry("supports_usb_connection"):
  369. self._error_message = Message(catalog.i18nc("@info:status", "Unable to start a new job because the printer does not support usb printing."), title = catalog.i18nc("@info:title", "Warning"))
  370. self._error_message.show()
  371. return
  372. Application.getInstance().showPrintMonitor.emit(True)
  373. self.startPrint()
  374. def _setEndstopState(self, endstop_key, value):
  375. if endstop_key == b"x_min":
  376. if self._x_min_endstop_pressed != value:
  377. self.endstopStateChanged.emit("x_min", value)
  378. self._x_min_endstop_pressed = value
  379. elif endstop_key == b"y_min":
  380. if self._y_min_endstop_pressed != value:
  381. self.endstopStateChanged.emit("y_min", value)
  382. self._y_min_endstop_pressed = value
  383. elif endstop_key == b"z_min":
  384. if self._z_min_endstop_pressed != value:
  385. self.endstopStateChanged.emit("z_min", value)
  386. self._z_min_endstop_pressed = value
  387. ## Listen thread function.
  388. def _listen(self):
  389. Logger.log("i", "Printer connection listen thread started for %s" % self._serial_port)
  390. temperature_request_timeout = time.time()
  391. ok_timeout = time.time()
  392. while self._connection_state == ConnectionState.connected:
  393. line = self._readline()
  394. if line is None:
  395. break # None is only returned when something went wrong. Stop listening
  396. if time.time() > temperature_request_timeout:
  397. if self._num_extruders > 1:
  398. self._temperature_requested_extruder_index = (self._temperature_requested_extruder_index + 1) % self._num_extruders
  399. self.sendCommand("M105 T%d" % (self._temperature_requested_extruder_index))
  400. else:
  401. self.sendCommand("M105")
  402. temperature_request_timeout = time.time() + 5
  403. if line.startswith(b"Error:"):
  404. # Oh YEAH, consistency.
  405. # Marlin reports a MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
  406. # But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
  407. # So we can have an extra newline in the most common case. Awesome work people.
  408. if re.match(b"Error:[0-9]\n", line):
  409. line = line.rstrip() + self._readline()
  410. # Skip the communication errors, as those get corrected.
  411. 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:
  412. if not self.hasError():
  413. self._setErrorState(line[6:])
  414. elif b" T:" in line or line.startswith(b"T:"): # Temperature message
  415. try:
  416. self._setHotendTemperature(self._temperature_requested_extruder_index, float(re.search(b"T: *([0-9\.]*)", line).group(1)))
  417. except:
  418. pass
  419. if b"B:" in line: # Check if it's a bed temperature
  420. try:
  421. self._setBedTemperature(float(re.search(b"B: *([0-9\.]*)", line).group(1)))
  422. except Exception as e:
  423. pass
  424. #TODO: temperature changed callback
  425. elif b"_min" in line or b"_max" in line:
  426. tag, value = line.split(b":", 1)
  427. self._setEndstopState(tag,(b"H" in value or b"TRIGGERED" in value))
  428. if self._is_printing:
  429. if line == b"" and time.time() > ok_timeout:
  430. line = b"ok" # Force a timeout (basically, send next command)
  431. if b"ok" in line:
  432. ok_timeout = time.time() + 5
  433. if not self._command_queue.empty():
  434. self._sendCommand(self._command_queue.get())
  435. elif self._is_paused:
  436. line = b"" # Force getting temperature as keep alive
  437. else:
  438. self._sendNextGcodeLine()
  439. elif b"resend" in line.lower() or b"rs" in line: # Because a resend can be asked with "resend" and "rs"
  440. try:
  441. Logger.log("d", "Got a resend response")
  442. self._gcode_position = int(line.replace(b"N:",b" ").replace(b"N",b" ").replace(b":",b" ").split()[-1])
  443. except:
  444. if b"rs" in line:
  445. self._gcode_position = int(line.split()[1])
  446. # Request the temperature on comm timeout (every 2 seconds) when we are not printing.)
  447. if line == b"":
  448. if self._num_extruders > 1:
  449. self._temperature_requested_extruder_index = (self._temperature_requested_extruder_index + 1) % self._num_extruders
  450. self.sendCommand("M105 T%d" % self._temperature_requested_extruder_index)
  451. else:
  452. self.sendCommand("M105")
  453. Logger.log("i", "Printer connection listen thread stopped for %s" % self._serial_port)
  454. ## Send next Gcode in the gcode list
  455. def _sendNextGcodeLine(self):
  456. if self._gcode_position >= len(self._gcode):
  457. return
  458. if self._gcode_position == 100:
  459. self._print_start_time_100 = time.time()
  460. line = self._gcode[self._gcode_position]
  461. if ";" in line:
  462. line = line[:line.find(";")]
  463. line = line.strip()
  464. # Don't send empty lines. But we do have to send something, so send
  465. # m105 instead.
  466. # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as
  467. # an LCD menu pause.
  468. if line == "" or line == "M0" or line == "M1":
  469. line = "M105"
  470. try:
  471. if ("G0" in line or "G1" in line) and "Z" in line:
  472. z = float(re.search("Z([0-9\.]*)", line).group(1))
  473. if self._current_z != z:
  474. self._current_z = z
  475. except Exception as e:
  476. Logger.log("e", "Unexpected error with printer connection, could not parse current Z: %s: %s" % (e, line))
  477. self._setErrorState("Unexpected error: %s" %e)
  478. checksum = functools.reduce(lambda x,y: x^y, map(ord, "N%d%s" % (self._gcode_position, line)))
  479. self._sendCommand("N%d%s*%d" % (self._gcode_position, line, checksum))
  480. self._gcode_position += 1
  481. self.setProgress((self._gcode_position / len(self._gcode)) * 100)
  482. self.progressChanged.emit()
  483. ## Set the state of the print.
  484. # Sent from the print monitor
  485. def _setJobState(self, job_state):
  486. if job_state == "pause":
  487. self._is_paused = True
  488. self._updateJobState("paused")
  489. elif job_state == "print":
  490. self._is_paused = False
  491. self._updateJobState("printing")
  492. elif job_state == "abort":
  493. self.cancelPrint()
  494. ## Set the progress of the print.
  495. # It will be normalized (based on max_progress) to range 0 - 100
  496. def setProgress(self, progress, max_progress = 100):
  497. self._progress = (progress / max_progress) * 100 # Convert to scale of 0-100
  498. if self._progress == 100:
  499. # Printing is done, reset progress
  500. self._gcode_position = 0
  501. self.setProgress(0)
  502. self._is_printing = False
  503. self._is_paused = False
  504. self._updateJobState("ready")
  505. self.progressChanged.emit()
  506. ## Cancel the current print. Printer connection wil continue to listen.
  507. def cancelPrint(self):
  508. self._gcode_position = 0
  509. self.setProgress(0)
  510. self._gcode = []
  511. # Turn off temperatures, fan and steppers
  512. self._sendCommand("M140 S0")
  513. self._sendCommand("M104 S0")
  514. self._sendCommand("M107")
  515. # Home XY to prevent nozzle resting on aborted print
  516. # Don't home bed because it may crash the printhead into the print on printers that home on the bottom
  517. self.homeHead()
  518. self._sendCommand("M84")
  519. self._is_printing = False
  520. self._is_paused = False
  521. self._updateJobState("ready")
  522. Application.getInstance().showPrintMonitor.emit(False)
  523. ## Check if the process did not encounter an error yet.
  524. def hasError(self):
  525. return self._error_state is not None
  526. ## private read line used by printer connection to listen for data on serial port.
  527. def _readline(self):
  528. if self._serial is None:
  529. return None
  530. try:
  531. ret = self._serial.readline()
  532. except Exception as e:
  533. Logger.log("e", "Unexpected error while reading serial port. %s" % e)
  534. self._setErrorState("Printer has been disconnected")
  535. self.close()
  536. return None
  537. return ret
  538. ## Create a list of baud rates at which we can communicate.
  539. # \return list of int
  540. def _getBaudrateList(self):
  541. ret = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
  542. return ret
  543. def _onFirmwareUpdateComplete(self):
  544. self._update_firmware_thread.join()
  545. self._update_firmware_thread = threading.Thread(target = self._updateFirmware)
  546. self._update_firmware_thread.daemon = True
  547. self.connect()
  548. ## Pre-heats the heated bed of the printer, if it has one.
  549. #
  550. # \param temperature The temperature to heat the bed to, in degrees
  551. # Celsius.
  552. # \param duration How long the bed should stay warm, in seconds. This is
  553. # ignored because there is no g-code to set this.
  554. @pyqtSlot(float, float)
  555. def preheatBed(self, temperature, duration):
  556. Logger.log("i", "Pre-heating the bed to %i degrees.", temperature)
  557. self._setTargetBedTemperature(temperature)
  558. self.preheatBedRemainingTimeChanged.emit()
  559. ## Cancels pre-heating the heated bed of the printer.
  560. #
  561. # If the bed is not pre-heated, nothing happens.
  562. @pyqtSlot()
  563. def cancelPreheatBed(self):
  564. Logger.log("i", "Cancelling pre-heating of the bed.")
  565. self._setTargetBedTemperature(0)
  566. self.preheatBedRemainingTimeChanged.emit()