USBPrinterOutputDevice.py 32 KB

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