USBPrinterOutputDevice.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Logger import Logger
  4. from UM.i18n import i18nCatalog
  5. from UM.Qt.Duration import DurationFormat
  6. from UM.PluginRegistry import PluginRegistry
  7. from cura.CuraApplication import CuraApplication
  8. from cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
  9. from cura.PrinterOutput.PrinterOutputModel import PrinterOutputModel
  10. from cura.PrinterOutput.PrintJobOutputModel import PrintJobOutputModel
  11. from cura.PrinterOutput.GenericOutputController import GenericOutputController
  12. from .AutoDetectBaudJob import AutoDetectBaudJob
  13. from .avr_isp import stk500v2, intelHex
  14. from PyQt5.QtCore import pyqtSlot, pyqtSignal, pyqtProperty, QUrl
  15. from serial import Serial, SerialException, SerialTimeoutException
  16. from threading import Thread, Event
  17. from time import time, sleep
  18. from queue import Queue
  19. from enum import IntEnum
  20. from typing import Union, Optional, List, cast
  21. import re
  22. import functools # Used for reduce
  23. import os
  24. catalog = i18nCatalog("cura")
  25. class USBPrinterOutputDevice(PrinterOutputDevice):
  26. firmwareProgressChanged = pyqtSignal()
  27. firmwareUpdateStateChanged = pyqtSignal()
  28. def __init__(self, serial_port: str, baud_rate: Optional[int] = None) -> None:
  29. super().__init__(serial_port)
  30. self.setName(catalog.i18nc("@item:inmenu", "USB printing"))
  31. self.setShortDescription(catalog.i18nc("@action:button Preceded by 'Ready to'.", "Print via USB"))
  32. self.setDescription(catalog.i18nc("@info:tooltip", "Print via USB"))
  33. self.setIconName("print")
  34. self._serial = None # type: Optional[Serial]
  35. self._serial_port = serial_port
  36. self._address = serial_port
  37. self._timeout = 3
  38. # List of gcode lines to be printed
  39. self._gcode = [] # type: List[str]
  40. self._gcode_position = 0
  41. self._use_auto_detect = True
  42. self._baud_rate = baud_rate
  43. self._all_baud_rates = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
  44. # Instead of using a timer, we really need the update to be as a thread, as reading from serial can block.
  45. self._update_thread = Thread(target=self._update, daemon = True)
  46. self._update_firmware_thread = Thread(target=self._updateFirmware, daemon = True)
  47. self._last_temperature_request = None # type: Optional[int]
  48. self._is_printing = False # A print is being sent.
  49. ## Set when print is started in order to check running time.
  50. self._print_start_time = None # type: Optional[float]
  51. self._print_estimated_time = None # type: Optional[int]
  52. self._accepts_commands = True
  53. self._paused = False
  54. self._firmware_view = None
  55. self._firmware_location = None
  56. self._firmware_progress = 0
  57. self._firmware_update_state = FirmwareUpdateState.idle
  58. self.setConnectionText(catalog.i18nc("@info:status", "Connected via USB"))
  59. # Queue for commands that need to be sent.
  60. self._command_queue = Queue() # type: Queue
  61. # Event to indicate that an "ok" was received from the printer after sending a command.
  62. self._command_received = Event()
  63. self._command_received.set()
  64. CuraApplication.getInstance().getOnExitCallbackManager().addCallback(self._checkActivePrintingUponAppExit)
  65. # This is a callback function that checks if there is any printing in progress via USB when the application tries
  66. # to exit. If so, it will show a confirmation before
  67. def _checkActivePrintingUponAppExit(self) -> None:
  68. application = CuraApplication.getInstance()
  69. if not self._is_printing:
  70. # This USB printer is not printing, so we have nothing to do. Call the next callback if exists.
  71. application.triggerNextExitCheck()
  72. return
  73. application.setConfirmExitDialogCallback(self._onConfirmExitDialogResult)
  74. application.showConfirmExitDialog.emit(catalog.i18nc("@label", "A USB print is in progress, closing Cura will stop this print. Are you sure?"))
  75. def _onConfirmExitDialogResult(self, result: bool) -> None:
  76. if result:
  77. application = CuraApplication.getInstance()
  78. application.triggerNextExitCheck()
  79. ## Reset USB device settings
  80. #
  81. def resetDeviceSettings(self):
  82. self._firmware_name = None
  83. ## Request the current scene to be sent to a USB-connected printer.
  84. #
  85. # \param nodes A collection of scene nodes to send. This is ignored.
  86. # \param file_name \type{string} A suggestion for a file name to write.
  87. # \param filter_by_machine Whether to filter MIME types by machine. This
  88. # is ignored.
  89. # \param kwargs Keyword arguments.
  90. def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None, **kwargs):
  91. if self._is_printing:
  92. return # Aleady printing
  93. # cancel any ongoing preheat timer before starting a print
  94. self._printers[0].getController().stopPreheatTimers()
  95. CuraApplication.getInstance().getController().setActiveStage("MonitorStage")
  96. # find the G-code for the active build plate to print
  97. active_build_plate_id = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  98. gcode_dict = getattr(CuraApplication.getInstance().getController().getScene(), "gcode_dict")
  99. gcode_list = gcode_dict[active_build_plate_id]
  100. self._printGCode(gcode_list)
  101. ## Show firmware interface.
  102. # This will create the view if its not already created.
  103. def showFirmwareInterface(self):
  104. if self._firmware_view is None:
  105. path = os.path.join(PluginRegistry.getInstance().getPluginPath("USBPrinting"), "FirmwareUpdateWindow.qml")
  106. self._firmware_view = CuraApplication.getInstance().createQmlComponent(path, {"manager": self})
  107. self._firmware_view.show()
  108. @pyqtSlot(str)
  109. def updateFirmware(self, file):
  110. # the file path could be url-encoded.
  111. if file.startswith("file://"):
  112. self._firmware_location = QUrl(file).toLocalFile()
  113. else:
  114. self._firmware_location = file
  115. self.showFirmwareInterface()
  116. self.setFirmwareUpdateState(FirmwareUpdateState.updating)
  117. self._update_firmware_thread.start()
  118. def _updateFirmware(self):
  119. # Ensure that other connections are closed.
  120. if self._connection_state != ConnectionState.closed:
  121. self.close()
  122. try:
  123. hex_file = intelHex.readHex(self._firmware_location)
  124. assert len(hex_file) > 0
  125. except (FileNotFoundError, AssertionError):
  126. Logger.log("e", "Unable to read provided hex file. Could not update firmware.")
  127. self.setFirmwareUpdateState(FirmwareUpdateState.firmware_not_found_error)
  128. return
  129. programmer = stk500v2.Stk500v2()
  130. programmer.progress_callback = self._onFirmwareProgress
  131. try:
  132. programmer.connect(self._serial_port)
  133. except:
  134. programmer.close()
  135. Logger.logException("e", "Failed to update firmware")
  136. self.setFirmwareUpdateState(FirmwareUpdateState.communication_error)
  137. return
  138. # Give programmer some time to connect. Might need more in some cases, but this worked in all tested cases.
  139. sleep(1)
  140. if not programmer.isConnected():
  141. Logger.log("e", "Unable to connect with serial. Could not update firmware")
  142. self.setFirmwareUpdateState(FirmwareUpdateState.communication_error)
  143. try:
  144. programmer.programChip(hex_file)
  145. except SerialException:
  146. self.setFirmwareUpdateState(FirmwareUpdateState.io_error)
  147. return
  148. except:
  149. self.setFirmwareUpdateState(FirmwareUpdateState.unknown_error)
  150. return
  151. programmer.close()
  152. # Clean up for next attempt.
  153. self._update_firmware_thread = Thread(target=self._updateFirmware, daemon=True)
  154. self._firmware_location = ""
  155. self._onFirmwareProgress(100)
  156. self.setFirmwareUpdateState(FirmwareUpdateState.completed)
  157. # Try to re-connect with the machine again, which must be done on the Qt thread, so we use call later.
  158. CuraApplication.getInstance().callLater(self.connect)
  159. @pyqtProperty(float, notify = firmwareProgressChanged)
  160. def firmwareProgress(self):
  161. return self._firmware_progress
  162. @pyqtProperty(int, notify=firmwareUpdateStateChanged)
  163. def firmwareUpdateState(self):
  164. return self._firmware_update_state
  165. def setFirmwareUpdateState(self, state):
  166. if self._firmware_update_state != state:
  167. self._firmware_update_state = state
  168. self.firmwareUpdateStateChanged.emit()
  169. # Callback function for firmware update progress.
  170. def _onFirmwareProgress(self, progress, max_progress = 100):
  171. self._firmware_progress = (progress / max_progress) * 100 # Convert to scale of 0-100
  172. self.firmwareProgressChanged.emit()
  173. ## Start a print based on a g-code.
  174. # \param gcode_list List with gcode (strings).
  175. def _printGCode(self, gcode_list: List[str]):
  176. self._gcode.clear()
  177. self._paused = False
  178. for layer in gcode_list:
  179. self._gcode.extend(layer.split("\n"))
  180. # Reset line number. If this is not done, first line is sometimes ignored
  181. self._gcode.insert(0, "M110")
  182. self._gcode_position = 0
  183. self._print_start_time = time()
  184. self._print_estimated_time = int(CuraApplication.getInstance().getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.Seconds))
  185. for i in range(0, 4): # Push first 4 entries before accepting other inputs
  186. self._sendNextGcodeLine()
  187. self._is_printing = True
  188. self.writeFinished.emit(self)
  189. def _autoDetectFinished(self, job: AutoDetectBaudJob):
  190. result = job.getResult()
  191. if result is not None:
  192. self.setBaudRate(result)
  193. self.connect() # Try to connect (actually create serial, etc)
  194. def setBaudRate(self, baud_rate: int):
  195. if baud_rate not in self._all_baud_rates:
  196. Logger.log("w", "Not updating baudrate to {baud_rate} as it's an unknown baudrate".format(baud_rate=baud_rate))
  197. return
  198. self._baud_rate = baud_rate
  199. def connect(self):
  200. self._firmware_name = None # after each connection ensure that the firmware name is removed
  201. if self._baud_rate is None:
  202. if self._use_auto_detect:
  203. auto_detect_job = AutoDetectBaudJob(self._serial_port)
  204. auto_detect_job.start()
  205. auto_detect_job.finished.connect(self._autoDetectFinished)
  206. return
  207. if self._serial is None:
  208. try:
  209. self._serial = Serial(str(self._serial_port), self._baud_rate, timeout=self._timeout, writeTimeout=self._timeout)
  210. except SerialException:
  211. Logger.log("w", "An exception occured while trying to create serial connection")
  212. return
  213. container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  214. num_extruders = container_stack.getProperty("machine_extruder_count", "value")
  215. # Ensure that a printer is created.
  216. self._printers = [PrinterOutputModel(output_controller=GenericOutputController(self), number_of_extruders=num_extruders)]
  217. self._printers[0].updateName(container_stack.getName())
  218. self.setConnectionState(ConnectionState.connected)
  219. self._update_thread.start()
  220. def close(self):
  221. super().close()
  222. if self._serial is not None:
  223. self._serial.close()
  224. # Re-create the thread so it can be started again later.
  225. self._update_thread = Thread(target=self._update, daemon=True)
  226. self._serial = None
  227. ## Send a command to printer.
  228. def sendCommand(self, command: Union[str, bytes]):
  229. if not self._command_received.is_set():
  230. self._command_queue.put(command)
  231. else:
  232. self._sendCommand(command)
  233. def _sendCommand(self, command: Union[str, bytes]):
  234. if self._serial is None or self._connection_state != ConnectionState.connected:
  235. return
  236. new_command = cast(bytes, command) if type(command) is bytes else cast(str, command).encode() # type: bytes
  237. if not new_command.endswith(b"\n"):
  238. new_command += b"\n"
  239. try:
  240. self._command_received.clear()
  241. self._serial.write(new_command)
  242. except SerialTimeoutException:
  243. Logger.log("w", "Timeout when sending command to printer via USB.")
  244. self._command_received.set()
  245. def _update(self):
  246. while self._connection_state == ConnectionState.connected and self._serial is not None:
  247. try:
  248. line = self._serial.readline()
  249. except:
  250. continue
  251. if self._last_temperature_request is None or time() > self._last_temperature_request + self._timeout:
  252. # Timeout, or no request has been sent at all.
  253. self._command_received.set() # We haven't really received the ok, but we need to send a new command
  254. self.sendCommand("M105")
  255. self._last_temperature_request = time()
  256. if self._firmware_name is None:
  257. self.sendCommand("M115")
  258. if (b"ok " in line and b"T:" in line) or line.startswith(b"T:") or b"ok B:" in line or line.startswith(b"B:"): # Temperature message. 'T:' for extruder and 'B:' for bed
  259. extruder_temperature_matches = re.findall(b"T(\d*): ?([\d\.]+) ?\/?([\d\.]+)?", line)
  260. # Update all temperature values
  261. matched_extruder_nrs = []
  262. for match in extruder_temperature_matches:
  263. extruder_nr = 0
  264. if match[0] != b"":
  265. extruder_nr = int(match[0])
  266. if extruder_nr in matched_extruder_nrs:
  267. continue
  268. matched_extruder_nrs.append(extruder_nr)
  269. if extruder_nr >= len(self._printers[0].extruders):
  270. Logger.log("w", "Printer reports more temperatures than the number of configured extruders")
  271. continue
  272. extruder = self._printers[0].extruders[extruder_nr]
  273. if match[1]:
  274. extruder.updateHotendTemperature(float(match[1]))
  275. if match[2]:
  276. extruder.updateTargetHotendTemperature(float(match[2]))
  277. bed_temperature_matches = re.findall(b"B: ?([\d\.]+) ?\/?([\d\.]+)?", line)
  278. if bed_temperature_matches:
  279. match = bed_temperature_matches[0]
  280. if match[0]:
  281. self._printers[0].updateBedTemperature(float(match[0]))
  282. if match[1]:
  283. self._printers[0].updateTargetBedTemperature(float(match[1]))
  284. if b"FIRMWARE_NAME:" in line:
  285. self._setFirmwareName(line)
  286. if b"ok" in line:
  287. self._command_received.set()
  288. if not self._command_queue.empty():
  289. self._sendCommand(self._command_queue.get())
  290. if self._is_printing:
  291. if self._paused:
  292. pass # Nothing to do!
  293. else:
  294. self._sendNextGcodeLine()
  295. if self._is_printing:
  296. if line.startswith(b'!!'):
  297. Logger.log('e', "Printer signals fatal error. Cancelling print. {}".format(line))
  298. self.cancelPrint()
  299. elif b"resend" in line.lower() or b"rs" in line:
  300. # A resend can be requested either by Resend, resend or rs.
  301. try:
  302. self._gcode_position = int(line.replace(b"N:", b" ").replace(b"N", b" ").replace(b":", b" ").split()[-1])
  303. except:
  304. if b"rs" in line:
  305. # In some cases of the RS command it needs to be handled differently.
  306. self._gcode_position = int(line.split()[1])
  307. def _setFirmwareName(self, name):
  308. new_name = re.findall(r"FIRMWARE_NAME:(.*);", str(name))
  309. if new_name:
  310. self._firmware_name = new_name[0]
  311. Logger.log("i", "USB output device Firmware name: %s", self._firmware_name)
  312. else:
  313. self._firmware_name = "Unknown"
  314. Logger.log("i", "Unknown USB output device Firmware name: %s", str(name))
  315. def getFirmwareName(self):
  316. return self._firmware_name
  317. def pausePrint(self):
  318. self._paused = True
  319. def resumePrint(self):
  320. self._paused = False
  321. self._sendNextGcodeLine() #Send one line of g-code next so that we'll trigger an "ok" response loop even if we're not polling temperatures.
  322. def cancelPrint(self):
  323. self._gcode_position = 0
  324. self._gcode.clear()
  325. self._printers[0].updateActivePrintJob(None)
  326. self._is_printing = False
  327. self._paused = False
  328. # Turn off temperatures, fan and steppers
  329. self._sendCommand("M140 S0")
  330. self._sendCommand("M104 S0")
  331. self._sendCommand("M107")
  332. # Home XY to prevent nozzle resting on aborted print
  333. # Don't home bed because it may crash the printhead into the print on printers that home on the bottom
  334. self.printers[0].homeHead()
  335. self._sendCommand("M84")
  336. def _sendNextGcodeLine(self):
  337. if self._gcode_position >= len(self._gcode):
  338. self._printers[0].updateActivePrintJob(None)
  339. self._is_printing = False
  340. return
  341. line = self._gcode[self._gcode_position]
  342. if ";" in line:
  343. line = line[:line.find(";")]
  344. line = line.strip()
  345. # Don't send empty lines. But we do have to send something, so send M105 instead.
  346. # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
  347. if line == "" or line == "M0" or line == "M1":
  348. line = "M105"
  349. checksum = functools.reduce(lambda x, y: x ^ y, map(ord, "N%d%s" % (self._gcode_position, line)))
  350. self._sendCommand("N%d%s*%d" % (self._gcode_position, line, checksum))
  351. progress = (self._gcode_position / len(self._gcode))
  352. elapsed_time = int(time() - self._print_start_time)
  353. print_job = self._printers[0].activePrintJob
  354. if print_job is None:
  355. print_job = PrintJobOutputModel(output_controller = GenericOutputController(self), name= CuraApplication.getInstance().getPrintInformation().jobName)
  356. print_job.updateState("printing")
  357. self._printers[0].updateActivePrintJob(print_job)
  358. print_job.updateTimeElapsed(elapsed_time)
  359. estimated_time = self._print_estimated_time
  360. if progress > .1:
  361. estimated_time = self._print_estimated_time * (1 - progress) + elapsed_time
  362. print_job.updateTimeTotal(estimated_time)
  363. self._gcode_position += 1
  364. class FirmwareUpdateState(IntEnum):
  365. idle = 0
  366. updating = 1
  367. completed = 2
  368. unknown_error = 3
  369. communication_error = 4
  370. io_error = 5
  371. firmware_not_found_error = 6