USBPrinterOutputDevice.py 32 KB

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