USBPrinterOutputDevice.py 16 KB

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