PrinterConnection.py 24 KB

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