USBPrinterOutputDevice.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from .avr_isp import stk500v2, ispBase, intelHex
  4. import serial
  5. import threading
  6. import time
  7. import queue
  8. import re
  9. import functools
  10. import os.path
  11. from UM.Application import Application
  12. from UM.Logger import Logger
  13. from UM.PluginRegistry import PluginRegistry
  14. from cura.PrinterOutputDevice import PrinterOutputDevice, ConnectionState
  15. from PyQt5.QtQml import QQmlComponent, QQmlContext
  16. from PyQt5.QtCore import QUrl, pyqtSlot, pyqtSignal
  17. from UM.i18n import i18nCatalog
  18. catalog = i18nCatalog("cura")
  19. class USBPrinterOutputDevice(PrinterOutputDevice):
  20. def __init__(self, serial_port):
  21. super().__init__(serial_port)
  22. self.setName(catalog.i18nc("@item:inmenu", "USB printing"))
  23. self.setShortDescription(catalog.i18nc("@action:button", "Print with USB"))
  24. self.setDescription(catalog.i18nc("@info:tooltip", "Print with USB"))
  25. self.setIconName("print")
  26. self._serial = None
  27. self._serial_port = serial_port
  28. self._error_state = None
  29. self._connect_thread = threading.Thread(target = self._connect)
  30. self._connect_thread.daemon = True
  31. self._end_stop_thread = threading.Thread(target = self._pollEndStop)
  32. self._end_stop_thread.daemon = True
  33. self._poll_endstop = -1
  34. # The baud checking is done by sending a number of m105 commands to the printer and waiting for a readable
  35. # response. If the baudrate is correct, this should make sense, else we get giberish.
  36. self._required_responses_auto_baud = 3
  37. self._listen_thread = threading.Thread(target=self._listen)
  38. self._listen_thread.daemon = True
  39. self._update_firmware_thread = threading.Thread(target= self._updateFirmware)
  40. self._update_firmware_thread.daemon = True
  41. self.firmwareUpdateComplete.connect(self._onFirmwareUpdateComplete)
  42. self._heatup_wait_start_time = time.time()
  43. ## Queue for commands that need to be send. Used when command is sent when a print is active.
  44. self._command_queue = queue.Queue()
  45. self._is_printing = False
  46. ## Set when print is started in order to check running time.
  47. self._print_start_time = None
  48. self._print_start_time_100 = None
  49. ## Keep track where in the provided g-code the print is
  50. self._gcode_position = 0
  51. # List of gcode lines to be printed
  52. self._gcode = []
  53. # Check if endstops are ever pressed (used for first run)
  54. self._x_min_endstop_pressed = False
  55. self._y_min_endstop_pressed = False
  56. self._z_min_endstop_pressed = False
  57. self._x_max_endstop_pressed = False
  58. self._y_max_endstop_pressed = False
  59. self._z_max_endstop_pressed = False
  60. # In order to keep the connection alive we request the temperature every so often from a different extruder.
  61. # This index is the extruder we requested data from the last time.
  62. self._temperature_requested_extruder_index = 0
  63. self._updating_firmware = False
  64. self._firmware_file_name = None
  65. self._control_view = None
  66. onError = pyqtSignal()
  67. firmwareUpdateComplete = pyqtSignal()
  68. endstopStateChanged = pyqtSignal(str ,bool, arguments = ["key","state"])
  69. def _setTargetBedTemperature(self, temperature):
  70. Logger.log("d", "Setting bed temperature to %s", temperature)
  71. self._sendCommand("M140 S%s" % temperature)
  72. def _setTargetHotendTemperature(self, index, temperature):
  73. Logger.log("d", "Setting hotend %s temperature to %s", index, temperature)
  74. self._sendCommand("M104 T%s S%s" % (index, temperature))
  75. def _setHeadPosition(self, x, y , z, speed):
  76. self._sendCommand("G0 X%s Y%s Z%s F%s" % (x, y, z, speed))
  77. def _setHeadX(self, x, speed):
  78. self._sendCommand("G0 X%s F%s" % (x, speed))
  79. def _setHeadY(self, y, speed):
  80. self._sendCommand("G0 Y%s F%s" % (y, speed))
  81. def _setHeadZ(self, z, speed):
  82. self._sendCommand("G0 Y%s F%s" % (z, speed))
  83. def _homeHead(self):
  84. self._sendCommand("G28")
  85. def _homeBed(self):
  86. self._sendCommand("G28 Z")
  87. @pyqtSlot()
  88. def startPrint(self):
  89. self.writeStarted.emit(self)
  90. gcode_list = getattr( Application.getInstance().getController().getScene(), "gcode_list")
  91. self.printGCode(gcode_list)
  92. def _moveHead(self, x, y, z, speed):
  93. self._sendCommand("G91")
  94. self._sendCommand("G0 X%s Y%s Z%s F%s" % (x, y, z, speed))
  95. self._sendCommand("G90")
  96. ## Start a print based on a g-code.
  97. # \param gcode_list List with gcode (strings).
  98. def printGCode(self, gcode_list):
  99. if self._progress or self._connection_state != ConnectionState.connected:
  100. Logger.log("d", "Printer is busy or not connected, aborting print")
  101. self.writeError.emit(self)
  102. return
  103. self._gcode.clear()
  104. for layer in gcode_list:
  105. self._gcode.extend(layer.split("\n"))
  106. # Reset line number. If this is not done, first line is sometimes ignored
  107. self._gcode.insert(0, "M110")
  108. self._gcode_position = 0
  109. self._print_start_time_100 = None
  110. self._is_printing = True
  111. self._print_start_time = time.time()
  112. for i in range(0, 4): # Push first 4 entries before accepting other inputs
  113. self._sendNextGcodeLine()
  114. self.writeFinished.emit(self)
  115. ## Get the serial port string of this connection.
  116. # \return serial port
  117. def getSerialPort(self):
  118. return self._serial_port
  119. ## Try to connect the serial. This simply starts the thread, which runs _connect.
  120. def connect(self):
  121. if not self._updating_firmware and not self._connect_thread.isAlive():
  122. self._connect_thread.start()
  123. ## Private function (threaded) that actually uploads the firmware.
  124. def _updateFirmware(self):
  125. self.setProgress(0, 100)
  126. if self._connection_state != ConnectionState.closed:
  127. self.close()
  128. hex_file = intelHex.readHex(self._firmware_file_name)
  129. if len(hex_file) == 0:
  130. Logger.log("e", "Unable to read provided hex file. Could not update firmware")
  131. return
  132. programmer = stk500v2.Stk500v2()
  133. programmer.progressCallback = self.setProgress
  134. try:
  135. programmer.connect(self._serial_port)
  136. except Exception:
  137. pass
  138. # Give programmer some time to connect. Might need more in some cases, but this worked in all tested cases.
  139. time.sleep(1)
  140. if not programmer.isConnected():
  141. Logger.log("e", "Unable to connect with serial. Could not update firmware")
  142. return
  143. self._updating_firmware = True
  144. try:
  145. programmer.programChip(hex_file)
  146. self._updating_firmware = False
  147. except Exception as e:
  148. Logger.log("e", "Exception while trying to update firmware %s" %e)
  149. self._updating_firmware = False
  150. return
  151. programmer.close()
  152. self.setProgress(100, 100)
  153. self.firmwareUpdateComplete.emit()
  154. ## Upload new firmware to machine
  155. # \param filename full path of firmware file to be uploaded
  156. def updateFirmware(self, file_name):
  157. Logger.log("i", "Updating firmware of %s using %s", self._serial_port, file_name)
  158. self._firmware_file_name = file_name
  159. self._update_firmware_thread.start()
  160. @pyqtSlot()
  161. def startPollEndstop(self):
  162. if self._poll_endstop == -1:
  163. self._poll_endstop = True
  164. self._end_stop_thread.start()
  165. @pyqtSlot()
  166. def stopPollEndstop(self):
  167. self._poll_endstop = False
  168. def _pollEndStop(self):
  169. while self._connection_state == ConnectionState.connected and self._poll_endstop:
  170. self.sendCommand("M119")
  171. time.sleep(0.5)
  172. ## Private connect function run by thread. Can be started by calling connect.
  173. def _connect(self):
  174. Logger.log("d", "Attempting to connect to %s", self._serial_port)
  175. self.setConnectionState(ConnectionState.connecting)
  176. programmer = stk500v2.Stk500v2()
  177. try:
  178. programmer.connect(self._serial_port) # Connect with the serial, if this succeeds, it's an arduino based usb device.
  179. self._serial = programmer.leaveISP()
  180. except ispBase.IspError as e:
  181. Logger.log("i", "Could not establish connection on %s: %s. Device is not arduino based." %(self._serial_port,str(e)))
  182. except Exception as e:
  183. Logger.log("i", "Could not establish connection on %s, unknown reasons. Device is not arduino based." % self._serial_port)
  184. # If the programmer connected, we know its an atmega based version.
  185. # Not all that useful, but it does give some debugging information.
  186. for baud_rate in self._getBaudrateList(): # Cycle all baud rates (auto detect)
  187. Logger.log("d","Attempting to connect to printer with serial %s on baud rate %s", self._serial_port, baud_rate)
  188. if self._serial is None:
  189. try:
  190. self._serial = serial.Serial(str(self._serial_port), baud_rate, timeout = 3, writeTimeout = 10000)
  191. except serial.SerialException:
  192. Logger.log("d", "Could not open port %s" % self._serial_port)
  193. continue
  194. else:
  195. if not self.setBaudRate(baud_rate):
  196. continue # Could not set the baud rate, go to the next
  197. time.sleep(1.5) # Ensure that we are not talking to the bootloader. 1.5 seconds seems to be the magic number
  198. sucesfull_responses = 0
  199. timeout_time = time.time() + 5
  200. self._serial.write(b"\n")
  201. self._sendCommand("M105") # Request temperature, as this should (if baudrate is correct) result in a command with "T:" in it
  202. while timeout_time > time.time():
  203. line = self._readline()
  204. if line is None:
  205. # Something went wrong with reading, could be that close was called.
  206. self.setConnectionState(ConnectionState.closed)
  207. return
  208. if b"T:" in line:
  209. self._serial.timeout = 0.5
  210. sucesfull_responses += 1
  211. if sucesfull_responses >= self._required_responses_auto_baud:
  212. self._serial.timeout = 2 # Reset serial timeout
  213. self.setConnectionState(ConnectionState.connected)
  214. self._listen_thread.start() # Start listening
  215. Logger.log("i", "Established printer connection on port %s" % self._serial_port)
  216. return
  217. self._sendCommand("M105") # Send M105 as long as we are listening, otherwise we end up in an undefined state
  218. Logger.log("e", "Baud rate detection for %s failed", self._serial_port)
  219. self.close() # Unable to connect, wrap up.
  220. self.setConnectionState(ConnectionState.closed)
  221. ## Set the baud rate of the serial. This can cause exceptions, but we simply want to ignore those.
  222. def setBaudRate(self, baud_rate):
  223. try:
  224. self._serial.baudrate = baud_rate
  225. return True
  226. except Exception as e:
  227. return False
  228. ## Close the printer connection
  229. def close(self):
  230. Logger.log("d", "Closing the USB printer connection.")
  231. if self._connect_thread.isAlive():
  232. try:
  233. self._connect_thread.join()
  234. except Exception as e:
  235. Logger.log("d", "PrinterConnection.close: %s (expected)", e)
  236. pass # This should work, but it does fail sometimes for some reason
  237. self._connect_thread = threading.Thread(target = self._connect)
  238. self._connect_thread.daemon = True
  239. self.setConnectionState(ConnectionState.closed)
  240. if self._serial is not None:
  241. try:
  242. self._listen_thread.join()
  243. except:
  244. pass
  245. self._serial.close()
  246. self._listen_thread = threading.Thread(target = self._listen)
  247. self._listen_thread.daemon = True
  248. self._serial = None
  249. ## Directly send the command, withouth checking connection state (eg; printing).
  250. # \param cmd string with g-code
  251. def _sendCommand(self, cmd):
  252. if self._serial is None:
  253. return
  254. if "M109" in cmd or "M190" in cmd:
  255. self._heatup_wait_start_time = time.time()
  256. try:
  257. command = (cmd + "\n").encode()
  258. self._serial.write(b"\n")
  259. self._serial.write(command)
  260. except serial.SerialTimeoutException:
  261. Logger.log("w","Serial timeout while writing to serial port, trying again.")
  262. try:
  263. time.sleep(0.5)
  264. self._serial.write((cmd + "\n").encode())
  265. except Exception as e:
  266. Logger.log("e","Unexpected error while writing serial port %s " % e)
  267. self._setErrorState("Unexpected error while writing serial port %s " % e)
  268. self.close()
  269. except Exception as e:
  270. Logger.log("e","Unexpected error while writing serial port %s" % e)
  271. self._setErrorState("Unexpected error while writing serial port %s " % e)
  272. self.close()
  273. def createControlInterface(self):
  274. if self._control_view is None:
  275. Logger.log("d", "Creating control interface for printer connection")
  276. path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath("USBPrinting"), "ControlWindow.qml"))
  277. component = QQmlComponent(Application.getInstance()._engine, path)
  278. self._control_context = QQmlContext(Application.getInstance()._engine.rootContext())
  279. self._control_context.setContextProperty("manager", self)
  280. self._control_view = component.create(self._control_context)
  281. ## Show control interface.
  282. # This will create the view if its not already created.
  283. def showControlInterface(self):
  284. if self._control_view is None:
  285. self.createControlInterface()
  286. self._control_view.show()
  287. ## Send a command to printer.
  288. # \param cmd string with g-code
  289. def sendCommand(self, cmd):
  290. if self._progress:
  291. self._command_queue.put(cmd)
  292. elif self._connection_state == ConnectionState.connected:
  293. self._sendCommand(cmd)
  294. ## Set the error state with a message.
  295. # \param error String with the error message.
  296. def _setErrorState(self, error):
  297. self._error_state = error
  298. self.onError.emit()
  299. def requestWrite(self, node, file_name = None, filter_by_machine = False):
  300. self.showControlInterface()
  301. def _setEndstopState(self, endstop_key, value):
  302. if endstop_key == b"x_min":
  303. if self._x_min_endstop_pressed != value:
  304. self.endstopStateChanged.emit("x_min", value)
  305. self._x_min_endstop_pressed = value
  306. elif endstop_key == b"y_min":
  307. if self._y_min_endstop_pressed != value:
  308. self.endstopStateChanged.emit("y_min", value)
  309. self._y_min_endstop_pressed = value
  310. elif endstop_key == b"z_min":
  311. if self._z_min_endstop_pressed != value:
  312. self.endstopStateChanged.emit("z_min", value)
  313. self._z_min_endstop_pressed = value
  314. ## Listen thread function.
  315. def _listen(self):
  316. Logger.log("i", "Printer connection listen thread started for %s" % self._serial_port)
  317. temperature_request_timeout = time.time()
  318. ok_timeout = time.time()
  319. while self._connection_state == ConnectionState.connected:
  320. line = self._readline()
  321. if line is None:
  322. break # None is only returned when something went wrong. Stop listening
  323. if time.time() > temperature_request_timeout:
  324. if self._num_extruders > 0:
  325. self._temperature_requested_extruder_index = (self._temperature_requested_extruder_index + 1) % self._num_extruders
  326. self.sendCommand("M105 T%d" % (self._temperature_requested_extruder_index))
  327. else:
  328. self.sendCommand("M105")
  329. temperature_request_timeout = time.time() + 5
  330. if line.startswith(b"Error:"):
  331. # Oh YEAH, consistency.
  332. # Marlin reports a MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
  333. # But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
  334. # So we can have an extra newline in the most common case. Awesome work people.
  335. if re.match(b"Error:[0-9]\n", line):
  336. line = line.rstrip() + self._readline()
  337. # Skip the communication errors, as those get corrected.
  338. if b"Extruder switched off" in line or b"Temperature heated bed switched off" in line or b"Something is wrong, please turn off the printer." in line:
  339. if not self.hasError():
  340. self._setErrorState(line[6:])
  341. elif b" T:" in line or line.startswith(b"T:"): # Temperature message
  342. try:
  343. self._setHotendTemperature(self._temperature_requested_extruder_index, float(re.search(b"T: *([0-9\.]*)", line).group(1)))
  344. except:
  345. pass
  346. if b"B:" in line: # Check if it's a bed temperature
  347. try:
  348. self._setBedTemperature(float(re.search(b"B: *([0-9\.]*)", line).group(1)))
  349. except Exception as e:
  350. pass
  351. #TODO: temperature changed callback
  352. elif b"_min" in line or b"_max" in line:
  353. tag, value = line.split(b":", 1)
  354. self._setEndstopState(tag,(b"H" in value or b"TRIGGERED" in value))
  355. if self._is_printing:
  356. if line == b"" and time.time() > ok_timeout:
  357. line = b"ok" # Force a timeout (basically, send next command)
  358. if b"ok" in line:
  359. ok_timeout = time.time() + 5
  360. if not self._command_queue.empty():
  361. self._sendCommand(self._command_queue.get())
  362. else:
  363. self._sendNextGcodeLine()
  364. elif b"resend" in line.lower() or b"rs" in line: # Because a resend can be asked with "resend" and "rs"
  365. try:
  366. self._gcode_position = int(line.replace(b"N:",b" ").replace(b"N",b" ").replace(b":",b" ").split()[-1])
  367. except:
  368. if b"rs" in line:
  369. self._gcode_position = int(line.split()[1])
  370. else: # Request the temperature on comm timeout (every 2 seconds) when we are not printing.)
  371. if line == b"":
  372. if self._num_extruders > 0:
  373. self._temperature_requested_extruder_index = (self._temperature_requested_extruder_index + 1) % self._num_extruders
  374. self.sendCommand("M105 T%d" % self._temperature_requested_extruder_index)
  375. else:
  376. self.sendCommand("M105")
  377. Logger.log("i", "Printer connection listen thread stopped for %s" % self._serial_port)
  378. ## Send next Gcode in the gcode list
  379. def _sendNextGcodeLine(self):
  380. if self._gcode_position >= len(self._gcode):
  381. return
  382. if self._gcode_position == 100:
  383. self._print_start_time_100 = time.time()
  384. line = self._gcode[self._gcode_position]
  385. if ";" in line:
  386. line = line[:line.find(";")]
  387. line = line.strip()
  388. try:
  389. if line == "M0" or line == "M1":
  390. line = "M105" # Don't send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
  391. if ("G0" in line or "G1" in line) and "Z" in line:
  392. z = float(re.search("Z([0-9\.]*)", line).group(1))
  393. if self._current_z != z:
  394. self._current_z = z
  395. except Exception as e:
  396. Logger.log("e", "Unexpected error with printer connection: %s" % e)
  397. self._setErrorState("Unexpected error: %s" %e)
  398. checksum = functools.reduce(lambda x,y: x^y, map(ord, "N%d%s" % (self._gcode_position, line)))
  399. self._sendCommand("N%d%s*%d" % (self._gcode_position, line, checksum))
  400. self._gcode_position += 1
  401. self.setProgress((self._gcode_position / len(self._gcode)) * 100)
  402. self.progressChanged.emit()
  403. ## Set the progress of the print.
  404. # It will be normalized (based on max_progress) to range 0 - 100
  405. def setProgress(self, progress, max_progress = 100):
  406. self._progress = (progress / max_progress) * 100 # Convert to scale of 0-100
  407. self.progressChanged.emit()
  408. ## Cancel the current print. Printer connection wil continue to listen.
  409. @pyqtSlot()
  410. def cancelPrint(self):
  411. self._gcode_position = 0
  412. self.setProgress(0)
  413. self._gcode = []
  414. # Turn of temperatures
  415. self._sendCommand("M140 S0")
  416. self._sendCommand("M104 S0")
  417. self._is_printing = False
  418. ## Check if the process did not encounter an error yet.
  419. def hasError(self):
  420. return self._error_state is not None
  421. ## private read line used by printer connection to listen for data on serial port.
  422. def _readline(self):
  423. if self._serial is None:
  424. return None
  425. try:
  426. ret = self._serial.readline()
  427. except Exception as e:
  428. Logger.log("e", "Unexpected error while reading serial port. %s" % e)
  429. self._setErrorState("Printer has been disconnected")
  430. self.close()
  431. return None
  432. return ret
  433. ## Create a list of baud rates at which we can communicate.
  434. # \return list of int
  435. def _getBaudrateList(self):
  436. ret = [115200, 250000, 230400, 57600, 38400, 19200, 9600]
  437. return ret
  438. def _onFirmwareUpdateComplete(self):
  439. self._update_firmware_thread.join()
  440. self._update_firmware_thread = threading.Thread(target = self._updateFirmware)
  441. self._update_firmware_thread.daemon = True
  442. self.connect()