USBPrinterOutputDevice.py 16 KB

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