USBPrinterOutputDevice.py 18 KB

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