USBPrinterOutputDevice.py 23 KB

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