USBPrinterOutputDevice.py 16 KB

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