USBPrinterOutputDevice.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os
  4. from UM.i18n import i18nCatalog
  5. from UM.Logger import Logger
  6. from UM.Mesh.MeshWriter import MeshWriter # To get the g-code output.
  7. from UM.Message import Message # Show an error when already printing.
  8. from UM.PluginRegistry import PluginRegistry # To get the g-code output.
  9. from UM.Qt.Duration import DurationFormat
  10. from cura.CuraApplication import CuraApplication
  11. from cura.PrinterOutput.PrinterOutputDevice import PrinterOutputDevice, ConnectionState, ConnectionType
  12. from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel
  13. from cura.PrinterOutput.Models.PrintJobOutputModel import PrintJobOutputModel
  14. from cura.PrinterOutput.GenericOutputController import GenericOutputController
  15. from .AutoDetectBaudJob import AutoDetectBaudJob
  16. from .AvrFirmwareUpdater import AvrFirmwareUpdater
  17. from io import StringIO # To write the g-code output.
  18. from queue import Queue
  19. from serial import Serial, SerialException, SerialTimeoutException
  20. from threading import Thread, Event
  21. from time import time
  22. from typing import Union, Optional, List, cast, TYPE_CHECKING
  23. import re
  24. import functools # Used for reduce
  25. if TYPE_CHECKING:
  26. from UM.FileHandler.FileHandler import FileHandler
  27. from UM.Scene.SceneNode import SceneNode
  28. catalog = i18nCatalog("cura")
  29. class USBPrinterOutputDevice(PrinterOutputDevice):
  30. def __init__(self, serial_port: str, baud_rate: Optional[int] = None) -> None:
  31. super().__init__(serial_port, connection_type = ConnectionType.UsbConnection)
  32. self.setName(catalog.i18nc("@item:inmenu", "USB printing"))
  33. self.setShortDescription(catalog.i18nc("@action:button Preceded by 'Ready to'.", "Print via USB"))
  34. self.setDescription(catalog.i18nc("@info:tooltip", "Print via USB"))
  35. self.setIconName("print")
  36. self._serial = None # type: Optional[Serial]
  37. self._serial_port = serial_port
  38. self._address = serial_port
  39. self._timeout = 3
  40. # List of gcode lines to be printed
  41. self._gcode = [] # type: List[str]
  42. self._gcode_position = 0
  43. self._use_auto_detect = True
  44. self._baud_rate = baud_rate
  45. self._all_baud_rates = [115200, 250000, 500000, 230400, 76800, 57600, 38400, 19200, 9600]
  46. # Instead of using a timer, we really need the update to be as a thread, as reading from serial can block.
  47. self._update_thread = Thread(target = self._update, daemon = True, name = "USBPrinterUpdate")
  48. self._last_temperature_request = None # type: Optional[int]
  49. self._firmware_idle_count = 0
  50. self._is_printing = False # A print is being sent.
  51. ## Set when print is started in order to check running time.
  52. self._print_start_time = None # type: Optional[float]
  53. self._print_estimated_time = None # type: Optional[int]
  54. self._accepts_commands = True
  55. self._paused = False
  56. self._printer_busy = False # When printer is preheating and waiting (M190/M109), or when waiting for action on the printer
  57. self.setConnectionText(catalog.i18nc("@info:status", "Connected via USB"))
  58. # Queue for commands that need to be sent.
  59. self._command_queue = Queue() # type: Queue
  60. # Event to indicate that an "ok" was received from the printer after sending a command.
  61. self._command_received = Event()
  62. self._command_received.set()
  63. self._firmware_name_requested = False
  64. self._firmware_updater = AvrFirmwareUpdater(self)
  65. plugin_path = PluginRegistry.getInstance().getPluginPath("USBPrinting")
  66. if plugin_path:
  67. self._monitor_view_qml_path = os.path.join(plugin_path, "MonitorItem.qml")
  68. else:
  69. Logger.log("e", "Cannot create Monitor QML view: cannot find plugin path for plugin [USBPrinting]")
  70. self._monitor_view_qml_path = ""
  71. CuraApplication.getInstance().getOnExitCallbackManager().addCallback(self._checkActivePrintingUponAppExit)
  72. CuraApplication.getInstance().getPreferences().addPreference("usb_printing/enabled", False)
  73. # This is a callback function that checks if there is any printing in progress via USB when the application tries
  74. # to exit. If so, it will show a confirmation before
  75. def _checkActivePrintingUponAppExit(self) -> None:
  76. application = CuraApplication.getInstance()
  77. if not self._is_printing:
  78. # This USB printer is not printing, so we have nothing to do. Call the next callback if exists.
  79. application.triggerNextExitCheck()
  80. return
  81. application.setConfirmExitDialogCallback(self._onConfirmExitDialogResult)
  82. application.showConfirmExitDialog.emit(catalog.i18nc("@label", "A USB print is in progress, closing Cura will stop this print. Are you sure?"))
  83. def _onConfirmExitDialogResult(self, result: bool) -> None:
  84. if result:
  85. application = CuraApplication.getInstance()
  86. application.triggerNextExitCheck()
  87. def resetDeviceSettings(self) -> None:
  88. """Reset USB device settings"""
  89. self._firmware_name = None
  90. def requestWrite(self, nodes: List["SceneNode"], file_name: Optional[str] = None, limit_mimetypes: bool = False,
  91. file_handler: Optional["FileHandler"] = None, filter_by_machine: bool = False, **kwargs) -> None:
  92. """Request the current scene to be sent to a USB-connected printer.
  93. :param nodes: A collection of scene nodes to send. This is ignored.
  94. :param file_name: A suggestion for a file name to write.
  95. :param filter_by_machine: Whether to filter MIME types by machine. This
  96. is ignored.
  97. :param kwargs: Keyword arguments.
  98. """
  99. if self._is_printing:
  100. message = Message(text = catalog.i18nc("@message",
  101. "A print is still in progress. Cura cannot start another print via USB until the previous print has completed."),
  102. title = catalog.i18nc("@message", "Print in Progress"),
  103. message_type = Message.MessageType.ERROR)
  104. message.show()
  105. return # Already printing
  106. self.writeStarted.emit(self)
  107. # cancel any ongoing preheat timer before starting a print
  108. controller = cast(GenericOutputController, self._printers[0].getController())
  109. controller.stopPreheatTimers()
  110. CuraApplication.getInstance().getController().setActiveStage("MonitorStage")
  111. CuraApplication.getInstance().getPreferences().setValue("usb_printing/enabled", True)
  112. #Find the g-code to print.
  113. gcode_textio = StringIO()
  114. gcode_writer = cast(MeshWriter, PluginRegistry.getInstance().getPluginObject("GCodeWriter"))
  115. success = gcode_writer.write(gcode_textio, None)
  116. if not success:
  117. return
  118. self._printGCode(gcode_textio.getvalue())
  119. def _printGCode(self, gcode: str):
  120. """Start a print based on a g-code.
  121. :param gcode: The g-code to print.
  122. """
  123. self._gcode.clear()
  124. self._paused = False
  125. self._gcode.extend(gcode.split("\n"))
  126. # Reset line number. If this is not done, first line is sometimes ignored
  127. self._gcode.insert(0, "M110")
  128. self._gcode_position = 0
  129. self._print_start_time = time()
  130. self._print_estimated_time = int(CuraApplication.getInstance().getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.Seconds))
  131. for i in range(0, 4): # Push first 4 entries before accepting other inputs
  132. self._sendNextGcodeLine()
  133. self._is_printing = True
  134. self.writeFinished.emit(self)
  135. def _autoDetectFinished(self, job: AutoDetectBaudJob):
  136. result = job.getResult()
  137. if result is not None:
  138. self.setBaudRate(result)
  139. self.connect() # Try to connect (actually create serial, etc)
  140. def setBaudRate(self, baud_rate: int):
  141. if baud_rate not in self._all_baud_rates:
  142. Logger.log("w", "Not updating baudrate to {baud_rate} as it's an unknown baudrate".format(baud_rate=baud_rate))
  143. return
  144. self._baud_rate = baud_rate
  145. def connect(self):
  146. self._firmware_name = None # after each connection ensure that the firmware name is removed
  147. if self._baud_rate is None:
  148. if self._use_auto_detect:
  149. auto_detect_job = AutoDetectBaudJob(self._serial_port)
  150. auto_detect_job.start()
  151. auto_detect_job.finished.connect(self._autoDetectFinished)
  152. return
  153. if self._serial is None:
  154. try:
  155. self._serial = Serial(str(self._serial_port), self._baud_rate, timeout=self._timeout, writeTimeout=self._timeout)
  156. except SerialException:
  157. Logger.warning("An exception occurred while trying to create serial connection.")
  158. return
  159. except OSError as e:
  160. Logger.warning("The serial device is suddenly unavailable while trying to create a serial connection: {err}".format(err = str(e)))
  161. return
  162. CuraApplication.getInstance().globalContainerStackChanged.connect(self._onGlobalContainerStackChanged)
  163. self._onGlobalContainerStackChanged()
  164. self.setConnectionState(ConnectionState.Connected)
  165. self._update_thread.start()
  166. def _onGlobalContainerStackChanged(self):
  167. container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  168. if container_stack is None:
  169. return
  170. num_extruders = container_stack.getProperty("machine_extruder_count", "value")
  171. # Ensure that a printer is created.
  172. controller = GenericOutputController(self)
  173. controller.setCanUpdateFirmware(True)
  174. self._printers = [PrinterOutputModel(output_controller = controller, number_of_extruders = num_extruders)]
  175. self._printers[0].updateName(container_stack.getName())
  176. def close(self):
  177. super().close()
  178. if self._serial is not None:
  179. self._serial.close()
  180. # Re-create the thread so it can be started again later.
  181. self._update_thread = Thread(target=self._update, daemon=True, name = "USBPrinterUpdate")
  182. self._serial = None
  183. def sendCommand(self, command: Union[str, bytes]):
  184. """Send a command to printer."""
  185. if not self._command_received.is_set():
  186. self._command_queue.put(command)
  187. else:
  188. self._sendCommand(command)
  189. def _sendCommand(self, command: Union[str, bytes]):
  190. if self._serial is None or self._connection_state != ConnectionState.Connected:
  191. return
  192. new_command = cast(bytes, command) if type(command) is bytes else cast(str, command).encode() # type: bytes
  193. if not new_command.endswith(b"\n"):
  194. new_command += b"\n"
  195. try:
  196. self._command_received.clear()
  197. self._serial.write(new_command)
  198. except SerialTimeoutException:
  199. Logger.log("w", "Timeout when sending command to printer via USB.")
  200. self._command_received.set()
  201. except SerialException:
  202. Logger.logException("w", "An unexpected exception occurred while writing to the serial.")
  203. self.setConnectionState(ConnectionState.Error)
  204. def _update(self):
  205. while self._connection_state == ConnectionState.Connected and self._serial is not None:
  206. try:
  207. line = self._serial.readline()
  208. except:
  209. continue
  210. if not self._firmware_name_requested:
  211. self._firmware_name_requested = True
  212. self.sendCommand("M115")
  213. if b"FIRMWARE_NAME:" in line:
  214. self._setFirmwareName(line)
  215. if self._last_temperature_request is None or time() > self._last_temperature_request + self._timeout:
  216. # Timeout, or no request has been sent at all.
  217. if not self._printer_busy: # Don't flood the printer with temperature requests while it is busy
  218. self.sendCommand("M105")
  219. self._last_temperature_request = time()
  220. if re.search(b"[B|T\d*]: ?\d+\.?\d*", line): # Temperature message. 'T:' for extruder and 'B:' for bed
  221. extruder_temperature_matches = re.findall(b"T(\d*): ?(\d+\.?\d*)\s*\/?(\d+\.?\d*)?", line)
  222. # Update all temperature values
  223. matched_extruder_nrs = []
  224. for match in extruder_temperature_matches:
  225. extruder_nr = 0
  226. if match[0] != b"":
  227. extruder_nr = int(match[0])
  228. if extruder_nr in matched_extruder_nrs:
  229. continue
  230. matched_extruder_nrs.append(extruder_nr)
  231. if extruder_nr >= len(self._printers[0].extruders):
  232. Logger.log("w", "Printer reports more temperatures than the number of configured extruders")
  233. continue
  234. extruder = self._printers[0].extruders[extruder_nr]
  235. if match[1]:
  236. extruder.updateHotendTemperature(float(match[1]))
  237. if match[2]:
  238. extruder.updateTargetHotendTemperature(float(match[2]))
  239. bed_temperature_matches = re.findall(b"B: ?(\d+\.?\d*)\s*\/?(\d+\.?\d*)?", line)
  240. if bed_temperature_matches:
  241. match = bed_temperature_matches[0]
  242. if match[0]:
  243. self._printers[0].updateBedTemperature(float(match[0]))
  244. if match[1]:
  245. self._printers[0].updateTargetBedTemperature(float(match[1]))
  246. if line == b"":
  247. # An empty line means that the firmware is idle
  248. # Multiple empty lines probably means that the firmware and Cura are waiting
  249. # for each other due to a missed "ok", so we keep track of empty lines
  250. self._firmware_idle_count += 1
  251. else:
  252. self._firmware_idle_count = 0
  253. if line.startswith(b"ok") or self._firmware_idle_count > 1:
  254. self._printer_busy = False
  255. self._command_received.set()
  256. if not self._command_queue.empty():
  257. self._sendCommand(self._command_queue.get())
  258. elif self._is_printing:
  259. if self._paused:
  260. pass # Nothing to do!
  261. else:
  262. self._sendNextGcodeLine()
  263. if line.startswith(b"echo:busy:"):
  264. self._printer_busy = True
  265. if self._is_printing:
  266. if line.startswith(b'!!'):
  267. Logger.log('e', "Printer signals fatal error. Cancelling print. {}".format(line))
  268. self.cancelPrint()
  269. elif line.lower().startswith(b"resend") or line.startswith(b"rs"):
  270. # A resend can be requested either by Resend, resend or rs.
  271. try:
  272. self._gcode_position = int(line.replace(b"N:", b" ").replace(b"N", b" ").replace(b":", b" ").split()[-1])
  273. except:
  274. if line.startswith(b"rs"):
  275. # In some cases of the RS command it needs to be handled differently.
  276. self._gcode_position = int(line.split()[1])
  277. def _setFirmwareName(self, name):
  278. new_name = re.findall(r"FIRMWARE_NAME:(.*);", str(name))
  279. if new_name:
  280. self._firmware_name = new_name[0]
  281. Logger.log("i", "USB output device Firmware name: %s", self._firmware_name)
  282. else:
  283. self._firmware_name = "Unknown"
  284. Logger.log("i", "Unknown USB output device Firmware name: %s", str(name))
  285. def getFirmwareName(self):
  286. return self._firmware_name
  287. def pausePrint(self):
  288. self._paused = True
  289. def resumePrint(self):
  290. self._paused = False
  291. 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.
  292. def cancelPrint(self):
  293. self._gcode_position = 0
  294. self._gcode.clear()
  295. self._printers[0].updateActivePrintJob(None)
  296. self._is_printing = False
  297. self._paused = False
  298. # Turn off temperatures, fan and steppers
  299. self._sendCommand("M140 S0")
  300. self._sendCommand("M104 S0")
  301. self._sendCommand("M107")
  302. # Home XY to prevent nozzle resting on aborted print
  303. # Don't home bed because it may crash the printhead into the print on printers that home on the bottom
  304. self.printers[0].homeHead()
  305. self._sendCommand("M84")
  306. def _sendNextGcodeLine(self):
  307. """
  308. Send the next line of g-code, at the current `_gcode_position`, via a
  309. serial port to the printer.
  310. If the print is done, this sets `_is_printing` to `False` as well.
  311. """
  312. try:
  313. line = self._gcode[self._gcode_position]
  314. except IndexError: # End of print, or print got cancelled.
  315. self._printers[0].updateActivePrintJob(None)
  316. self._is_printing = False
  317. return
  318. if ";" in line:
  319. line = line[:line.find(";")]
  320. line = line.strip()
  321. # Don't send empty lines. But we do have to send something, so send M105 instead.
  322. # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
  323. if line == "" or line == "M0" or line == "M1":
  324. line = "M105"
  325. checksum = functools.reduce(lambda x, y: x ^ y, map(ord, "N%d%s" % (self._gcode_position, line)))
  326. self._sendCommand("N%d%s*%d" % (self._gcode_position, line, checksum))
  327. print_job = self._printers[0].activePrintJob
  328. try:
  329. progress = self._gcode_position / len(self._gcode)
  330. except ZeroDivisionError:
  331. # There is nothing to send!
  332. if print_job is not None:
  333. print_job.updateState("error")
  334. return
  335. elapsed_time = int(time() - self._print_start_time)
  336. if print_job is None:
  337. controller = GenericOutputController(self)
  338. controller.setCanUpdateFirmware(True)
  339. print_job = PrintJobOutputModel(output_controller = controller, name = CuraApplication.getInstance().getPrintInformation().jobName)
  340. print_job.updateState("printing")
  341. self._printers[0].updateActivePrintJob(print_job)
  342. print_job.updateTimeElapsed(elapsed_time)
  343. estimated_time = self._print_estimated_time
  344. if progress > .1:
  345. estimated_time = int(self._print_estimated_time * (1 - progress) + elapsed_time)
  346. print_job.updateTimeTotal(estimated_time)
  347. self._gcode_position += 1