USBPrinterOutputDevice.py 19 KB

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