USBPrinterOutputDevice.py 16 KB

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