PrinterConnection.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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.demon = 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. ## Upload new firmware to machine
  170. # \param filename full path of firmware file to be uploaded
  171. def updateFirmware(self, file_name):
  172. Logger.log("i", "Updating firmware of %s using %s", self._serial_port, file_name)
  173. self._firmware_file_name = file_name
  174. self._update_firmware_thread.start()
  175. @pyqtSlot()
  176. def startPollEndstop(self):
  177. self._poll_endstop = True
  178. self._end_stop_thread.start()
  179. def _pollEndStop(self):
  180. while self._is_connected and self._poll_endstop:
  181. self.sendCommand("M119")
  182. time.sleep(0.5)
  183. ## Private connect function run by thread. Can be started by calling connect.
  184. def _connect(self):
  185. Logger.log("d", "Attempting to connect to %s", self._serial_port)
  186. self._is_connecting = True
  187. programmer = stk500v2.Stk500v2()
  188. try:
  189. programmer.connect(self._serial_port) # Connect with the serial, if this succeeds, it"s an arduino based usb device.
  190. self._serial = programmer.leaveISP()
  191. except ispBase.IspError as e:
  192. Logger.log("i", "Could not establish connection on %s: %s. Device is not arduino based." %(self._serial_port,str(e)))
  193. except Exception as e:
  194. Logger.log("i", "Could not establish connection on %s, unknown reasons. Device is not arduino based." % self._serial_port)
  195. if not self._serial:
  196. self._is_connecting = False
  197. Logger.log("i", "Could not establish connection on %s, unknown reasons.", self._serial_port)
  198. return
  199. # If the programmer connected, we know its an atmega based version. Not all that usefull, but it does give some debugging information.
  200. for baud_rate in self._getBaudrateList(): # Cycle all baud rates (auto detect)
  201. if self._serial is None:
  202. try:
  203. self._serial = serial.Serial(str(self._serial_port), baud_rate, timeout = 3, writeTimeout = 10000)
  204. except serial.SerialException:
  205. Logger.log("i", "Could not open port %s" % self._serial_port)
  206. return
  207. else:
  208. if not self.setBaudRate(baud_rate):
  209. continue # Could not set the baud rate, go to the next
  210. time.sleep(1.5) # Ensure that we are not talking to the bootloader. 1.5 sec seems to be the magic number
  211. sucesfull_responses = 0
  212. timeout_time = time.time() + 5
  213. self._serial.write(b"\n")
  214. self._sendCommand("M105") # Request temperature, as this should (if baudrate is correct) result in a command with "T:" in it
  215. while timeout_time > time.time():
  216. line = self._readline()
  217. if line is None:
  218. self.setIsConnected(False) # Something went wrong with reading, could be that close was called.
  219. return
  220. if b"T:" in line:
  221. self._serial.timeout = 0.5
  222. self._sendCommand("M105")
  223. sucesfull_responses += 1
  224. if sucesfull_responses >= self._required_responses_auto_baud:
  225. self._serial.timeout = 2 #Reset serial timeout
  226. self.setIsConnected(True)
  227. Logger.log("i", "Established printer connection on port %s" % self._serial_port)
  228. return
  229. Logger.log("e", "Baud rate detection for %s failed", self._serial_port)
  230. self.close() # Unable to connect, wrap up.
  231. self.setIsConnected(False)
  232. ## Set the baud rate of the serial. This can cause exceptions, but we simply want to ignore those.
  233. def setBaudRate(self, baud_rate):
  234. try:
  235. self._serial.baudrate = baud_rate
  236. return True
  237. except Exception as e:
  238. return False
  239. def setIsConnected(self, state):
  240. self._is_connecting = False
  241. if self._is_connected != state:
  242. self._is_connected = state
  243. self.connectionStateChanged.emit(self._serial_port)
  244. if self._is_connected:
  245. self._listen_thread.start() #Start listening
  246. else:
  247. Logger.log("w", "Printer connection state was not changed")
  248. connectionStateChanged = Signal()
  249. ## Close the printer connection
  250. def close(self):
  251. if self._connect_thread.isAlive():
  252. try:
  253. self._connect_thread.join()
  254. except Exception as e:
  255. pass # This should work, but it does fail sometimes for some reason
  256. if self._serial is not None:
  257. self.setIsConnected(False)
  258. try:
  259. self._listen_thread.join()
  260. except:
  261. pass
  262. self._serial.close()
  263. self._serial = None
  264. def isConnected(self):
  265. return self._is_connected
  266. ## Directly send the command, withouth checking connection state (eg; printing).
  267. # \param cmd string with g-code
  268. def _sendCommand(self, cmd):
  269. if self._serial is None:
  270. return
  271. if "M109" in cmd or "M190" in cmd:
  272. self._heatup_wait_start_time = time.time()
  273. if "M104" in cmd or "M109" in cmd:
  274. try:
  275. t = 0
  276. if "T" in cmd:
  277. t = int(re.search("T([0-9]+)", cmd).group(1))
  278. self._target_extruder_temperatures[t] = float(re.search("S([0-9]+)", cmd).group(1))
  279. except:
  280. pass
  281. if "M140" in cmd or "M190" in cmd:
  282. try:
  283. self._target_bed_temperature = float(re.search("S([0-9]+)", cmd).group(1))
  284. except:
  285. pass
  286. try:
  287. command = (cmd + "\n").encode()
  288. self._serial.write(b"\n")
  289. self._serial.write(command)
  290. except serial.SerialTimeoutException:
  291. Logger.log("w","Serial timeout while writing to serial port, trying again.")
  292. try:
  293. time.sleep(0.5)
  294. self._serial.write((cmd + "\n").encode())
  295. except Exception as e:
  296. Logger.log("e","Unexpected error while writing serial port %s " % e)
  297. self._setErrorState("Unexpected error while writing serial port %s " % e)
  298. self.close()
  299. except Exception as e:
  300. Logger.log("e","Unexpected error while writing serial port %s" % e)
  301. self._setErrorState("Unexpected error while writing serial port %s " % e)
  302. self.close()
  303. ## Ensure that close gets called when object is destroyed
  304. def __del__(self):
  305. self.close()
  306. def createControlInterface(self):
  307. if self._control_view is None:
  308. path = QUrl.fromLocalFile(os.path.join(PluginRegistry.getInstance().getPluginPath("USBPrinting"), "ControlWindow.qml"))
  309. component = QQmlComponent(Application.getInstance()._engine, path)
  310. self._control_context = QQmlContext(Application.getInstance()._engine.rootContext())
  311. self._control_context.setContextProperty("manager", self)
  312. self._control_view = component.create(self._control_context)
  313. ## Show control interface.
  314. # This will create the view if its not already created.
  315. def showControlInterface(self):
  316. if self._control_view is None:
  317. self.createControlInterface()
  318. self._control_view.show()
  319. ## Send a command to printer.
  320. # \param cmd string with g-code
  321. def sendCommand(self, cmd):
  322. if self.isPrinting():
  323. self._command_queue.put(cmd)
  324. elif self.isConnected():
  325. self._sendCommand(cmd)
  326. ## Set the error state with a message.
  327. # \param error String with the error message.
  328. def _setErrorState(self, error):
  329. self._error_state = error
  330. self.onError.emit()
  331. ## Private function to set the temperature of an extruder
  332. # \param index index of the extruder
  333. # \param temperature recieved temperature
  334. def _setExtruderTemperature(self, index, temperature):
  335. try:
  336. self._extruder_temperatures[index] = temperature
  337. self.extruderTemperatureChanged.emit()
  338. except Exception as e:
  339. pass
  340. ## Private function to set the temperature of the bed.
  341. # As all printers (as of time of writing) only support a single heated bed,
  342. # these are not indexed as with extruders.
  343. def _setBedTemperature(self, temperature):
  344. self._bed_temperature = temperature
  345. self.bedTemperatureChanged.emit()
  346. def requestWrite(self, node):
  347. self.showControlInterface()
  348. def _setEndstopState(self, endstop_key, value):
  349. if endstop_key == b'x_min':
  350. if self._x_min_endstop_pressed != value:
  351. self.endstopStateChanged.emit('x_min', value)
  352. self._x_min_endstop_pressed = value
  353. elif endstop_key == b'y_min':
  354. if self._y_min_endstop_pressed != value:
  355. self.endstopStateChanged.emit('y_min', value)
  356. self._y_min_endstop_pressed = value
  357. elif endstop_key == b'z_min':
  358. if self._z_min_endstop_pressed != value:
  359. self.endstopStateChanged.emit('z_min', value)
  360. self._z_min_endstop_pressed = value
  361. ## Listen thread function.
  362. def _listen(self):
  363. Logger.log("i", "Printer connection listen thread started for %s" % self._serial_port)
  364. temperature_request_timeout = time.time()
  365. ok_timeout = time.time()
  366. while self._is_connected:
  367. line = self._readline()
  368. if line is None:
  369. break # None is only returned when something went wrong. Stop listening
  370. if line.startswith(b"Error:"):
  371. # Oh YEAH, consistency.
  372. # Marlin reports an MIN/MAX temp error as "Error:x\n: Extruder switched off. MAXTEMP triggered !\n"
  373. # But a bed temp error is reported as "Error: Temperature heated bed switched off. MAXTEMP triggered !!"
  374. # So we can have an extra newline in the most common case. Awesome work people.
  375. if re.match(b"Error:[0-9]\n", line):
  376. line = line.rstrip() + self._readline()
  377. # Skip the communication errors, as those get corrected.
  378. 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:
  379. if not self.hasError():
  380. self._setErrorState(line[6:])
  381. elif b" T:" in line or line.startswith(b"T:"): #Temperature message
  382. try:
  383. self._setExtruderTemperature(self._temperature_requested_extruder_index,float(re.search(b"T: *([0-9\.]*)", line).group(1)))
  384. except:
  385. pass
  386. if b"B:" in line: # Check if it"s a bed temperature
  387. try:
  388. self._setBedTemperature(float(re.search(b"B: *([0-9\.]*)", line).group(1)))
  389. except Exception as e:
  390. pass
  391. #TODO: temperature changed callback
  392. elif b"_min" in line or b"_max" in line:
  393. tag, value = line.split(b':', 1)
  394. self._setEndstopState(tag,(b'H' in value or b'TRIGGERED' in value))
  395. if self._is_printing:
  396. if time.time() > temperature_request_timeout: # When printing, request temperature every 5 seconds.
  397. if self._extruder_count > 0:
  398. self._temperature_requested_extruder_index = (self._temperature_requested_extruder_index + 1) % self._extruder_count
  399. self.sendCommand("M105 T%d" % (self._temperature_requested_extruder_index))
  400. else:
  401. self.sendCommand("M105")
  402. temperature_request_timeout = time.time() + 5
  403. if line == b"" and time.time() > ok_timeout:
  404. line = b"ok" # Force a timeout (basicly, send next command)
  405. if b"ok" in line:
  406. ok_timeout = time.time() + 5
  407. if not self._command_queue.empty():
  408. self._sendCommand(self._command_queue.get())
  409. else:
  410. self._sendNextGcodeLine()
  411. elif b"resend" in line.lower() or b"rs" in line: # Because a resend can be asked with "resend" and "rs"
  412. try:
  413. self._gcode_position = int(line.replace(b"N:",b" ").replace(b"N",b" ").replace(b":",b" ").split()[-1])
  414. except:
  415. if b"rs" in line:
  416. self._gcode_position = int(line.split()[1])
  417. else: # Request the temperature on comm timeout (every 2 seconds) when we are not printing.)
  418. if line == b"":
  419. if self._extruder_count > 0:
  420. self._temperature_requested_extruder_index = (self._temperature_requested_extruder_index + 1) % self._extruder_count
  421. self.sendCommand("M105 T%d" % self._temperature_requested_extruder_index)
  422. else:
  423. self.sendCommand("M105")
  424. Logger.log("i", "Printer connection listen thread stopped for %s" % self._serial_port)
  425. ## Send next Gcode in the gcode list
  426. def _sendNextGcodeLine(self):
  427. if self._gcode_position >= len(self._gcode):
  428. return
  429. if self._gcode_position == 100:
  430. self._print_start_time_100 = time.time()
  431. line = self._gcode[self._gcode_position]
  432. if ";" in line:
  433. line = line[:line.find(";")]
  434. line = line.strip()
  435. try:
  436. if line == "M0" or line == "M1":
  437. line = "M105" #Don"t send the M0 or M1 to the machine, as M0 and M1 are handled as an LCD menu pause.
  438. if ("G0" in line or "G1" in line) and "Z" in line:
  439. z = float(re.search("Z([0-9\.]*)", line).group(1))
  440. if self._current_z != z:
  441. self._current_z = z
  442. except Exception as e:
  443. Logger.log("e", "Unexpected error with printer connection: %s" % e)
  444. self._setErrorState("Unexpected error: %s" %e)
  445. checksum = functools.reduce(lambda x,y: x^y, map(ord, "N%d%s" % (self._gcode_position, line)))
  446. self._sendCommand("N%d%s*%d" % (self._gcode_position, line, checksum))
  447. self._gcode_position += 1
  448. self.setProgress(( self._gcode_position / len(self._gcode)) * 100)
  449. self.progressChanged.emit()
  450. ## Set the progress of the print.
  451. # It will be normalized (based on max_progress) to range 0 - 100
  452. def setProgress(self, progress, max_progress = 100):
  453. self._progress = (progress / max_progress) * 100 #Convert to scale of 0-100
  454. self.progressChanged.emit()
  455. ## Cancel the current print. Printer connection wil continue to listen.
  456. @pyqtSlot()
  457. def cancelPrint(self):
  458. self._gcode_position = 0
  459. self.setProgress(0)
  460. self._gcode = []
  461. # Turn of temperatures
  462. self._sendCommand("M140 S0")
  463. self._sendCommand("M104 S0")
  464. self._is_printing = False
  465. ## Check if the process did not encounter an error yet.
  466. def hasError(self):
  467. return self._error_state != None
  468. ## private read line used by printer connection to listen for data on serial port.
  469. def _readline(self):
  470. if self._serial is None:
  471. return None
  472. try:
  473. ret = self._serial.readline()
  474. except Exception as e:
  475. Logger.log("e","Unexpected error while reading serial port. %s" %e)
  476. self._setErrorState("Printer has been disconnected")
  477. self.close()
  478. return None
  479. return ret
  480. ## Create a list of baud rates at which we can communicate.
  481. # \return list of int
  482. def _getBaudrateList(self):
  483. ret = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
  484. return ret