USBPrinterOutputDevice.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. # Copyright (c) 2016 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 cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
  8. from cura.PrinterOutput.PrinterOutputModel import PrinterOutputModel
  9. from cura.PrinterOutput.PrintJobOutputModel import PrintJobOutputModel
  10. from .AutoDetectBaudJob import AutoDetectBaudJob
  11. from .USBPrinterOutputController import USBPrinterOuptutController
  12. from serial import Serial, SerialException
  13. from threading import Thread
  14. from time import time
  15. from queue import Queue
  16. import re
  17. import functools # Used for reduce
  18. catalog = i18nCatalog("cura")
  19. class USBPrinterOutputDevice(PrinterOutputDevice):
  20. def __init__(self, serial_port, baud_rate = None):
  21. super().__init__(serial_port)
  22. self.setName(catalog.i18nc("@item:inmenu", "USB printing"))
  23. self.setShortDescription(catalog.i18nc("@action:button Preceded by 'Ready to'.", "Print via USB"))
  24. self.setDescription(catalog.i18nc("@info:tooltip", "Print via USB"))
  25. self.setIconName("print")
  26. self._serial = None
  27. self._serial_port = serial_port
  28. self._timeout = 3
  29. # List of gcode lines to be printed
  30. self._gcode = []
  31. self._gcode_position = 0
  32. self._use_auto_detect = True
  33. self._baud_rate = baud_rate
  34. self._all_baud_rates = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
  35. # Instead of using a timer, we really need the update to be as a thread, as reading from serial can block.
  36. self._update_thread = Thread(target=self._update, daemon = True)
  37. self._last_temperature_request = None
  38. self._is_printing = False # A print is being sent.
  39. ## Set when print is started in order to check running time.
  40. self._print_start_time = None
  41. self._print_estimated_time = None
  42. self._accepts_commands = True
  43. self._paused = False
  44. # Queue for commands that need to be send. Used when command is sent when a print is active.
  45. self._command_queue = Queue()
  46. ## Request the current scene to be sent to a USB-connected printer.
  47. #
  48. # \param nodes A collection of scene nodes to send. This is ignored.
  49. # \param file_name \type{string} A suggestion for a file name to write.
  50. # \param filter_by_machine Whether to filter MIME types by machine. This
  51. # is ignored.
  52. # \param kwargs Keyword arguments.
  53. def requestWrite(self, nodes, file_name = None, filter_by_machine = False, file_handler = None, **kwargs):
  54. if self._is_printing:
  55. return # Aleady printing
  56. Application.getInstance().getController().setActiveStage("MonitorStage")
  57. gcode_list = getattr(Application.getInstance().getController().getScene(), "gcode_list")
  58. self._printGCode(gcode_list)
  59. ## Start a print based on a g-code.
  60. # \param gcode_list List with gcode (strings).
  61. def _printGCode(self, gcode_list):
  62. self._gcode.clear()
  63. self._paused = False
  64. for layer in gcode_list:
  65. self._gcode.extend(layer.split("\n"))
  66. # Reset line number. If this is not done, first line is sometimes ignored
  67. self._gcode.insert(0, "M110")
  68. self._gcode_position = 0
  69. self._is_printing = True
  70. self._print_start_time = time()
  71. self._print_estimated_time = int(Application.getInstance().getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.Seconds))
  72. for i in range(0, 4): # Push first 4 entries before accepting other inputs
  73. self._sendNextGcodeLine()
  74. self.writeFinished.emit(self)
  75. def _autoDetectFinished(self, job):
  76. result = job.getResult()
  77. if result is not None:
  78. self.setBaudRate(result)
  79. self.connect() # Try to connect (actually create serial, etc)
  80. def setBaudRate(self, baud_rate):
  81. if baud_rate not in self._all_baud_rates:
  82. Logger.log("w", "Not updating baudrate to {baud_rate} as it's an unknown baudrate".format(baud_rate=baud_rate))
  83. return
  84. self._baud_rate = baud_rate
  85. def connect(self):
  86. if self._baud_rate is None:
  87. if self._use_auto_detect:
  88. auto_detect_job = AutoDetectBaudJob(self._serial_port)
  89. auto_detect_job.start()
  90. auto_detect_job.finished.connect(self._autoDetectFinished)
  91. return
  92. if self._serial is None:
  93. try:
  94. self._serial = Serial(str(self._serial_port), self._baud_rate, timeout=self._timeout, writeTimeout=self._timeout)
  95. except SerialException:
  96. Logger.log("w", "An exception occured while trying to create serial connection")
  97. return
  98. container_stack = Application.getInstance().getGlobalContainerStack()
  99. num_extruders = container_stack.getProperty("machine_extruder_count", "value")
  100. # Ensure that a printer is created.
  101. self._printers = [PrinterOutputModel(output_controller=USBPrinterOuptutController(self), number_of_extruders=num_extruders)]
  102. self.setConnectionState(ConnectionState.connected)
  103. self._update_thread.start()
  104. def sendCommand(self, command):
  105. if self._is_printing:
  106. self._command_queue.put(command)
  107. elif self._connection_state == ConnectionState.connected:
  108. self._sendCommand(command)
  109. def _sendCommand(self, command):
  110. if self._serial is None:
  111. return
  112. if type(command == str):
  113. command = (command + "\n").encode()
  114. if not command.endswith(b"\n"):
  115. command += b"\n"
  116. self._serial.write(b"\n")
  117. self._serial.write(command)
  118. def _update(self):
  119. while self._connection_state == ConnectionState.connected and self._serial is not None:
  120. line = self._serial.readline()
  121. if self._last_temperature_request is None or time() > self._last_temperature_request + self._timeout:
  122. # Timeout, or no request has been sent at all.
  123. self.sendCommand("M105")
  124. self._last_temperature_request = time()
  125. if b"ok T:" in line or line.startswith(b"T:"): # Temperature message
  126. extruder_temperature_matches = re.findall(b"T(\d*): ?([\d\.]+) ?\/?([\d\.]+)?", line)
  127. # Update all temperature values
  128. for match, extruder in zip(extruder_temperature_matches, self._printers[0].extruders):
  129. if match[1]:
  130. extruder.updateHotendTemperature(float(match[1]))
  131. if match[2]:
  132. extruder.updateTargetHotendTemperature(float(match[2]))
  133. bed_temperature_matches = re.findall(b"B: ?([\d\.]+) ?\/?([\d\.]+)?", line)
  134. if bed_temperature_matches:
  135. match = bed_temperature_matches[0]
  136. if match[0]:
  137. self._printers[0].updateBedTemperature(float(match[0]))
  138. if match[1]:
  139. self._printers[0].updateTargetBedTemperature(float(match[1]))
  140. if self._is_printing:
  141. if b"ok" in line:
  142. if not self._command_queue.empty():
  143. self._sendCommand(self._command_queue.get())
  144. elif self._paused:
  145. pass # Nothing to do!
  146. else:
  147. self._sendNextGcodeLine()
  148. elif b"resend" in line.lower() or b"rs" in line:
  149. # A resend can be requested either by Resend, resend or rs.
  150. try:
  151. self._gcode_position = int(line.replace(b"N:", b" ").replace(b"N", b" ").replace(b":", b" ").split()[-1])
  152. except:
  153. if b"rs" in line:
  154. # In some cases of the RS command it needs to be handled differently.
  155. self._gcode_position = int(line.split()[1])
  156. def pausePrint(self):
  157. self._paused = True
  158. def resumePrint(self):
  159. self._paused = False
  160. def cancelPrint(self):
  161. self._gcode_position = 0
  162. self._gcode.clear()
  163. self._printers[0].updateActivePrintJob(None)
  164. self._is_printing = False
  165. self._is_paused = False
  166. # Turn off temperatures, fan and steppers
  167. self._sendCommand("M140 S0")
  168. self._sendCommand("M104 S0")
  169. self._sendCommand("M107")
  170. # Home XY to prevent nozzle resting on aborted print
  171. # Don't home bed because it may crash the printhead into the print on printers that home on the bottom
  172. self.printers[0].homeHead()
  173. self._sendCommand("M84")
  174. def _sendNextGcodeLine(self):
  175. if self._gcode_position >= len(self._gcode):
  176. self._printers[0].updateActivePrintJob(None)
  177. self._is_printing = False
  178. return
  179. line = self._gcode[self._gcode_position]
  180. if ";" in line:
  181. line = line[:line.find(";")]
  182. line = line.strip()
  183. # Don't send empty lines. But we do have to send something, so send M105 instead.
  184. # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
  185. if line == "" or line == "M0" or line == "M1":
  186. line = "M105"
  187. checksum = functools.reduce(lambda x, y: x ^ y, map(ord, "N%d%s" % (self._gcode_position, line)))
  188. self._sendCommand("N%d%s*%d" % (self._gcode_position, line, checksum))
  189. progress = (self._gcode_position / len(self._gcode))
  190. elapsed_time = int(time() - self._print_start_time)
  191. print_job = self._printers[0].activePrintJob
  192. if print_job is None:
  193. print_job = PrintJobOutputModel(output_controller = USBPrinterOuptutController(self), name= Application.getInstance().getPrintInformation().jobName)
  194. print_job.updateState("printing")
  195. self._printers[0].updateActivePrintJob(print_job)
  196. print_job.updateTimeElapsed(elapsed_time)
  197. estimated_time = self._print_estimated_time
  198. if progress > .1:
  199. estimated_time = self._print_estimated_time * (1 - progress) + elapsed_time
  200. print_job.updateTimeTotal(estimated_time)
  201. self._gcode_position += 1