USBPrinterOutputDevice.py 23 KB

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