USBPrinterOutputDevice.py 15 KB

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