USBPrinterOutputDevice.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 .AvrFirmwareUpdater import AvrFirmwareUpdater
  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 typing import Union, Optional, List, cast
  20. import re
  21. import functools # Used for reduce
  22. import os
  23. catalog = i18nCatalog("cura")
  24. class USBPrinterOutputDevice(PrinterOutputDevice):
  25. def __init__(self, serial_port: str, baud_rate: Optional[int] = None) -> None:
  26. super().__init__(serial_port)
  27. self.setName(catalog.i18nc("@item:inmenu", "USB printing"))
  28. self.setShortDescription(catalog.i18nc("@action:button Preceded by 'Ready to'.", "Print via USB"))
  29. self.setDescription(catalog.i18nc("@info:tooltip", "Print via USB"))
  30. self.setIconName("print")
  31. self._serial = None # type: Optional[Serial]
  32. self._serial_port = serial_port
  33. self._address = serial_port
  34. self._timeout = 3
  35. # List of gcode lines to be printed
  36. self._gcode = [] # type: List[str]
  37. self._gcode_position = 0
  38. self._use_auto_detect = True
  39. self._baud_rate = baud_rate
  40. self._all_baud_rates = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
  41. # Instead of using a timer, we really need the update to be as a thread, as reading from serial can block.
  42. self._update_thread = Thread(target=self._update, daemon=True)
  43. self._last_temperature_request = None # type: Optional[int]
  44. self._is_printing = False # A print is being sent.
  45. ## Set when print is started in order to check running time.
  46. self._print_start_time = None # type: Optional[float]
  47. self._print_estimated_time = None # type: Optional[int]
  48. self._accepts_commands = True
  49. self._paused = False
  50. self.setConnectionText(catalog.i18nc("@info:status", "Connected via USB"))
  51. # Queue for commands that need to be sent.
  52. self._command_queue = Queue() # type: Queue
  53. # Event to indicate that an "ok" was received from the printer after sending a command.
  54. self._command_received = Event()
  55. self._command_received.set()
  56. self._firmware_updater = AvrFirmwareUpdater(self)
  57. CuraApplication.getInstance().getOnExitCallbackManager().addCallback(self._checkActivePrintingUponAppExit)
  58. # This is a callback function that checks if there is any printing in progress via USB when the application tries
  59. # to exit. If so, it will show a confirmation before
  60. def _checkActivePrintingUponAppExit(self) -> None:
  61. application = CuraApplication.getInstance()
  62. if not self._is_printing:
  63. # This USB printer is not printing, so we have nothing to do. Call the next callback if exists.
  64. application.triggerNextExitCheck()
  65. return
  66. application.setConfirmExitDialogCallback(self._onConfirmExitDialogResult)
  67. application.showConfirmExitDialog.emit(catalog.i18nc("@label", "A USB print is in progress, closing Cura will stop this print. Are you sure?"))
  68. def _onConfirmExitDialogResult(self, result: bool) -> None:
  69. if result:
  70. application = CuraApplication.getInstance()
  71. application.triggerNextExitCheck()
  72. @pyqtSlot(str)
  73. def updateFirmware(self, file: Union[str, QUrl]) -> None:
  74. if not self._firmware_updater:
  75. return
  76. self._firmware_updater.updateFirmware(file)
  77. ## Reset USB device settings
  78. #
  79. def resetDeviceSettings(self) -> None:
  80. self._firmware_name = None
  81. ## Request the current scene to be sent to a USB-connected printer.
  82. #
  83. # \param nodes A collection of scene nodes to send. This is ignored.
  84. # \param file_name \type{string} A suggestion for a file name to write.
  85. # \param filter_by_machine Whether to filter MIME types by machine. This
  86. # is ignored.
  87. # \param kwargs Keyword arguments.
  88. def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None, **kwargs):
  89. if self._is_printing:
  90. return # Aleady printing
  91. # cancel any ongoing preheat timer before starting a print
  92. self._printers[0].getController().stopPreheatTimers()
  93. CuraApplication.getInstance().getController().setActiveStage("MonitorStage")
  94. # find the G-code for the active build plate to print
  95. active_build_plate_id = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  96. gcode_dict = getattr(CuraApplication.getInstance().getController().getScene(), "gcode_dict")
  97. gcode_list = gcode_dict[active_build_plate_id]
  98. self._printGCode(gcode_list)
  99. ## Start a print based on a g-code.
  100. # \param gcode_list List with gcode (strings).
  101. def _printGCode(self, gcode_list: List[str]):
  102. self._gcode.clear()
  103. self._paused = False
  104. for layer in gcode_list:
  105. self._gcode.extend(layer.split("\n"))
  106. # Reset line number. If this is not done, first line is sometimes ignored
  107. self._gcode.insert(0, "M110")
  108. self._gcode_position = 0
  109. self._print_start_time = time()
  110. self._print_estimated_time = int(CuraApplication.getInstance().getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.Seconds))
  111. for i in range(0, 4): # Push first 4 entries before accepting other inputs
  112. self._sendNextGcodeLine()
  113. self._is_printing = True
  114. self.writeFinished.emit(self)
  115. def _autoDetectFinished(self, job: AutoDetectBaudJob):
  116. result = job.getResult()
  117. if result is not None:
  118. self.setBaudRate(result)
  119. self.connect() # Try to connect (actually create serial, etc)
  120. def setBaudRate(self, baud_rate: int):
  121. if baud_rate not in self._all_baud_rates:
  122. Logger.log("w", "Not updating baudrate to {baud_rate} as it's an unknown baudrate".format(baud_rate=baud_rate))
  123. return
  124. self._baud_rate = baud_rate
  125. def connect(self):
  126. self._firmware_name = None # after each connection ensure that the firmware name is removed
  127. if self._baud_rate is None:
  128. if self._use_auto_detect:
  129. auto_detect_job = AutoDetectBaudJob(self._serial_port)
  130. auto_detect_job.start()
  131. auto_detect_job.finished.connect(self._autoDetectFinished)
  132. return
  133. if self._serial is None:
  134. try:
  135. self._serial = Serial(str(self._serial_port), self._baud_rate, timeout=self._timeout, writeTimeout=self._timeout)
  136. except SerialException:
  137. Logger.log("w", "An exception occured while trying to create serial connection")
  138. return
  139. container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  140. num_extruders = container_stack.getProperty("machine_extruder_count", "value")
  141. # Ensure that a printer is created.
  142. controller = GenericOutputController(self)
  143. controller.setCanUpdateFirmware(True)
  144. self._printers = [PrinterOutputModel(output_controller=controller, number_of_extruders=num_extruders)]
  145. self._printers[0].updateName(container_stack.getName())
  146. self.setConnectionState(ConnectionState.connected)
  147. self._update_thread.start()
  148. def close(self):
  149. super().close()
  150. if self._serial is not None:
  151. self._serial.close()
  152. # Re-create the thread so it can be started again later.
  153. self._update_thread = Thread(target=self._update, daemon=True)
  154. self._serial = None
  155. ## Send a command to printer.
  156. def sendCommand(self, command: Union[str, bytes]):
  157. if not self._command_received.is_set():
  158. self._command_queue.put(command)
  159. else:
  160. self._sendCommand(command)
  161. def _sendCommand(self, command: Union[str, bytes]):
  162. if self._serial is None or self._connection_state != ConnectionState.connected:
  163. return
  164. new_command = cast(bytes, command) if type(command) is bytes else cast(str, command).encode() # type: bytes
  165. if not new_command.endswith(b"\n"):
  166. new_command += b"\n"
  167. try:
  168. self._command_received.clear()
  169. self._serial.write(new_command)
  170. except SerialTimeoutException:
  171. Logger.log("w", "Timeout when sending command to printer via USB.")
  172. self._command_received.set()
  173. def _update(self):
  174. while self._connection_state == ConnectionState.connected and self._serial is not None:
  175. try:
  176. line = self._serial.readline()
  177. except:
  178. continue
  179. if self._last_temperature_request is None or time() > self._last_temperature_request + self._timeout:
  180. # Timeout, or no request has been sent at all.
  181. self._command_received.set() # We haven't really received the ok, but we need to send a new command
  182. self.sendCommand("M105")
  183. self._last_temperature_request = time()
  184. if self._firmware_name is None:
  185. self.sendCommand("M115")
  186. if re.search(b"[B|T\d*]: ?\d+\.?\d*", line): # Temperature message. 'T:' for extruder and 'B:' for bed
  187. extruder_temperature_matches = re.findall(b"T(\d*): ?(\d+\.?\d*) ?\/?(\d+\.?\d*)?", line)
  188. # Update all temperature values
  189. matched_extruder_nrs = []
  190. for match in extruder_temperature_matches:
  191. extruder_nr = 0
  192. if match[0] != b"":
  193. extruder_nr = int(match[0])
  194. if extruder_nr in matched_extruder_nrs:
  195. continue
  196. matched_extruder_nrs.append(extruder_nr)
  197. if extruder_nr >= len(self._printers[0].extruders):
  198. Logger.log("w", "Printer reports more temperatures than the number of configured extruders")
  199. continue
  200. extruder = self._printers[0].extruders[extruder_nr]
  201. if match[1]:
  202. extruder.updateHotendTemperature(float(match[1]))
  203. if match[2]:
  204. extruder.updateTargetHotendTemperature(float(match[2]))
  205. bed_temperature_matches = re.findall(b"B: ?(\d+\.?\d*) ?\/?(\d+\.?\d*) ?", line)
  206. if bed_temperature_matches:
  207. match = bed_temperature_matches[0]
  208. if match[0]:
  209. self._printers[0].updateBedTemperature(float(match[0]))
  210. if match[1]:
  211. self._printers[0].updateTargetBedTemperature(float(match[1]))
  212. if b"FIRMWARE_NAME:" in line:
  213. self._setFirmwareName(line)
  214. if b"ok" in line:
  215. self._command_received.set()
  216. if not self._command_queue.empty():
  217. self._sendCommand(self._command_queue.get())
  218. if self._is_printing:
  219. if self._paused:
  220. pass # Nothing to do!
  221. else:
  222. self._sendNextGcodeLine()
  223. if self._is_printing:
  224. if line.startswith(b'!!'):
  225. Logger.log('e', "Printer signals fatal error. Cancelling print. {}".format(line))
  226. self.cancelPrint()
  227. elif b"resend" in line.lower() or b"rs" in line:
  228. # A resend can be requested either by Resend, resend or rs.
  229. try:
  230. self._gcode_position = int(line.replace(b"N:", b" ").replace(b"N", b" ").replace(b":", b" ").split()[-1])
  231. except:
  232. if b"rs" in line:
  233. # In some cases of the RS command it needs to be handled differently.
  234. self._gcode_position = int(line.split()[1])
  235. def _setFirmwareName(self, name):
  236. new_name = re.findall(r"FIRMWARE_NAME:(.*);", str(name))
  237. if new_name:
  238. self._firmware_name = new_name[0]
  239. Logger.log("i", "USB output device Firmware name: %s", self._firmware_name)
  240. else:
  241. self._firmware_name = "Unknown"
  242. Logger.log("i", "Unknown USB output device Firmware name: %s", str(name))
  243. def getFirmwareName(self):
  244. return self._firmware_name
  245. def pausePrint(self):
  246. self._paused = True
  247. def resumePrint(self):
  248. self._paused = False
  249. 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.
  250. def cancelPrint(self):
  251. self._gcode_position = 0
  252. self._gcode.clear()
  253. self._printers[0].updateActivePrintJob(None)
  254. self._is_printing = False
  255. self._paused = False
  256. # Turn off temperatures, fan and steppers
  257. self._sendCommand("M140 S0")
  258. self._sendCommand("M104 S0")
  259. self._sendCommand("M107")
  260. # Home XY to prevent nozzle resting on aborted print
  261. # Don't home bed because it may crash the printhead into the print on printers that home on the bottom
  262. self.printers[0].homeHead()
  263. self._sendCommand("M84")
  264. def _sendNextGcodeLine(self):
  265. if self._gcode_position >= len(self._gcode):
  266. self._printers[0].updateActivePrintJob(None)
  267. self._is_printing = False
  268. return
  269. line = self._gcode[self._gcode_position]
  270. if ";" in line:
  271. line = line[:line.find(";")]
  272. line = line.strip()
  273. # Don't send empty lines. But we do have to send something, so send M105 instead.
  274. # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
  275. if line == "" or line == "M0" or line == "M1":
  276. line = "M105"
  277. checksum = functools.reduce(lambda x, y: x ^ y, map(ord, "N%d%s" % (self._gcode_position, line)))
  278. self._sendCommand("N%d%s*%d" % (self._gcode_position, line, checksum))
  279. progress = (self._gcode_position / len(self._gcode))
  280. elapsed_time = int(time() - self._print_start_time)
  281. print_job = self._printers[0].activePrintJob
  282. if print_job is None:
  283. controller = GenericOutputController(self)
  284. controller.setCanUpdateFirmware(True)
  285. print_job = PrintJobOutputModel(output_controller=controller, name=CuraApplication.getInstance().getPrintInformation().jobName)
  286. print_job.updateState("printing")
  287. self._printers[0].updateActivePrintJob(print_job)
  288. print_job.updateTimeElapsed(elapsed_time)
  289. estimated_time = self._print_estimated_time
  290. if progress > .1:
  291. estimated_time = self._print_estimated_time * (1 - progress) + elapsed_time
  292. print_job.updateTimeTotal(estimated_time)
  293. self._gcode_position += 1