USBPrinterOutputDevice.py 22 KB

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